forked from gastownhall/gastown
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstaller.go
More file actions
270 lines (234 loc) · 9.37 KB
/
installer.go
File metadata and controls
270 lines (234 loc) · 9.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
// Package hooks provides a generic hook/settings installer for all agent runtimes.
//
// Instead of per-agent packages (claude/, gemini/, cursor/, etc.) each containing
// near-identical boilerplate, this package embeds all agent templates and provides
// a single generic installer that reads template metadata from AgentPresetInfo.
package hooks
import (
"bytes"
"embed"
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"github.com/steveyegge/gastown/internal/hookutil"
)
//go:embed templates/*
var templateFS embed.FS
// InstallForRole provisions hook/settings files for an agent based on its preset config.
// It creates the file if it does not exist, or overwrites if the existing file contains
// known stale patterns (e.g., legacy "export PATH=" format). Otherwise it does not
// overwrite — this is the safe path for session startup, where Claude's settings.json
// may have been customized by syncTarget (base + role overrides merge) and must not
// be clobbered.
//
// For explicit sync operations that should update stale files, use SyncForRole.
//
// Parameters:
// - provider: the preset's HooksProvider (e.g., "claude", "gemini").
// - settingsDir: the gastown-managed parent (used by agents with --settings flag).
// - workDir: the agent's working directory.
// - role: the Gas Town role (e.g., "polecat", "crew", "witness").
// - hooksDir/hooksFile: from the preset's HooksDir and HooksSettingsFile.
//
// Template resolution:
// - Role-aware agents (have both autonomous and interactive templates):
// templates/<provider>/settings-autonomous.json + settings-interactive.json
// or templates/<provider>/hooks-autonomous.json + hooks-interactive.json
// - Role-agnostic agents (single template): templates/<provider>/<hooksFile>
//
// The install directory is settingsDir for agents that support --settings (useSettingsDir=true),
// or workDir for all others.
func InstallForRole(provider, settingsDir, workDir, role, hooksDir, hooksFile string, useSettingsDir bool) error {
if provider == "" || hooksDir == "" || hooksFile == "" {
return nil
}
targetPath := installTargetPath(settingsDir, workDir, hooksDir, hooksFile, useSettingsDir)
if existing, err := os.ReadFile(targetPath); err == nil {
if !needsUpgrade(existing) {
return nil // File exists and is current — don't overwrite
}
// Stale file detected — fall through to overwrite with current template
}
return writeTemplate(provider, role, hooksDir, hooksFile, targetPath)
}
// needsUpgrade returns true if an existing hooks file contains stale patterns
// that should be replaced by the current template. This allows the installer
// to auto-upgrade hooks from earlier versions without requiring manual intervention.
func needsUpgrade(content []byte) bool {
// Stale pattern: export PATH=... && gt — replaced by {{GT_BIN}} in current templates.
// The PATH export breaks Gemini CLI's hook runner which expands $PATH into
// an enormous string. Also catches files missing GT_HOOK_SOURCE env vars.
return bytes.Contains(content, []byte(`export PATH=`))
}
// SyncResult describes what SyncForRole did.
type SyncResult int
const (
SyncUnchanged SyncResult = iota // File already matches template
SyncCreated // File did not exist, created
SyncUpdated // File existed but content differed, updated
)
// SyncForRole compares the deployed hook/settings file against the current template
// and overwrites if content differs. Returns what action was taken.
//
// This is the explicit sync path used by "gt hooks sync" for template-based agents
// (OpenCode, Copilot, Pi, OMP, etc.). It should NOT be used for agents whose settings
// are managed by the JSON merge path (Claude), as that would clobber merged overrides.
func SyncForRole(provider, settingsDir, workDir, role, hooksDir, hooksFile string, useSettingsDir bool) (SyncResult, error) {
if provider == "" || hooksDir == "" || hooksFile == "" {
return SyncUnchanged, nil
}
targetPath := installTargetPath(settingsDir, workDir, hooksDir, hooksFile, useSettingsDir)
content, err := resolveAndSubstitute(provider, hooksFile, role)
if err != nil {
return 0, err
}
fileExisted := false
if existing, err := os.ReadFile(targetPath); err == nil {
fileExisted = true
if isSettingsFile(hooksFile) {
// JSON files: use structural comparison to tolerate whitespace differences.
if TemplateContentEqual(existing, content) {
return SyncUnchanged, nil
}
} else {
if bytes.Equal(existing, content) {
return SyncUnchanged, nil
}
}
}
if err := os.MkdirAll(filepath.Dir(targetPath), 0755); err != nil {
return 0, fmt.Errorf("creating hooks directory: %w", err)
}
perm := os.FileMode(0644)
if isSettingsFile(hooksFile) {
perm = 0600
}
if err := os.WriteFile(targetPath, content, perm); err != nil {
return 0, fmt.Errorf("writing hooks file: %w", err)
}
if fileExisted {
return SyncUpdated, nil
}
return SyncCreated, nil
}
// installTargetPath computes the full path for a hook/settings file.
func installTargetPath(settingsDir, workDir, hooksDir, hooksFile string, useSettingsDir bool) string {
installDir := workDir
if useSettingsDir {
installDir = settingsDir
}
return filepath.Join(installDir, hooksDir, hooksFile)
}
// resolveAndSubstitute resolves the template and performs {{GT_BIN}} substitution.
func resolveAndSubstitute(provider, hooksFile, role string) ([]byte, error) {
content, err := resolveTemplate(provider, hooksFile, role)
if err != nil {
return nil, fmt.Errorf("resolving template for %s: %w", provider, err)
}
if bytes.Contains(content, []byte("{{GT_BIN}}")) {
gtBin := resolveGTBinary()
content = bytes.ReplaceAll(content, []byte("{{GT_BIN}}"), []byte(gtBin))
}
return content, nil
}
// writeTemplate resolves a template, substitutes placeholders, and writes it to targetPath.
//
//nolint:unparam // hooksDir kept for API symmetry with InstallForRole
func writeTemplate(provider, role, hooksDir, hooksFile, targetPath string) error {
content, err := resolveAndSubstitute(provider, hooksFile, role)
if err != nil {
return err
}
if err := os.MkdirAll(filepath.Dir(targetPath), 0755); err != nil {
return fmt.Errorf("creating hooks directory: %w", err)
}
perm := os.FileMode(0644)
if isSettingsFile(hooksFile) {
perm = 0600
}
if err := os.WriteFile(targetPath, content, perm); err != nil {
return fmt.Errorf("writing hooks file: %w", err)
}
return nil
}
// resolveTemplate finds the right template for a provider+role combination.
func resolveTemplate(provider, hooksFile, role string) ([]byte, error) {
// Determine role type
autonomous := hookutil.IsAutonomousRole(role)
// Try role-aware naming conventions
if autonomous {
for _, pattern := range roleAwarePatterns("autonomous", hooksFile) {
path := fmt.Sprintf("templates/%s/%s", provider, pattern)
if content, err := templateFS.ReadFile(path); err == nil {
return content, nil
}
}
} else {
for _, pattern := range roleAwarePatterns("interactive", hooksFile) {
path := fmt.Sprintf("templates/%s/%s", provider, pattern)
if content, err := templateFS.ReadFile(path); err == nil {
return content, nil
}
}
}
// Fall back to single template (role-agnostic agents)
path := fmt.Sprintf("templates/%s/%s", provider, hooksFile)
content, err := templateFS.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("no template found for provider %q file %q: %w", provider, hooksFile, err)
}
return content, nil
}
// roleAwarePatterns generates candidate template filenames for role-aware agents.
// Given roleType "autonomous" and hooksFile "settings.json", it tries:
// - settings-autonomous.json
// - hooks-autonomous.json
func roleAwarePatterns(roleType, hooksFile string) []string {
ext := filepath.Ext(hooksFile)
base := hooksFile[:len(hooksFile)-len(ext)]
return []string{
base + "-" + roleType + ext, // settings-autonomous.json
"hooks-" + roleType + ext, // hooks-autonomous.json
"settings-" + roleType + ext, // settings-autonomous.json (fallback)
}
}
// isSettingsFile returns true for files that may contain sensitive role config.
func isSettingsFile(name string) bool {
return filepath.Ext(name) == ".json"
}
// resolveGTBinary returns the absolute path to the gt binary.
// Tries os.Executable() first (most reliable when running as gt), then
// falls back to exec.LookPath for PATH-based discovery. If both fail,
// returns "gt" and hopes the runtime PATH has it.
func resolveGTBinary() string {
if exe, err := os.Executable(); err == nil {
return exe
}
if path, err := exec.LookPath("gt"); err == nil {
return path
}
return "gt"
}
// ComputeExpectedTemplate returns the expected file content for a template-based
// provider (e.g., gemini) with {{GT_BIN}} resolved to the actual gt binary path.
// This is used by the doctor hooks-sync check to compare installed files against
// current templates.
func ComputeExpectedTemplate(provider, hooksFile, role string) ([]byte, error) {
return resolveAndSubstitute(provider, hooksFile, role)
}
// TemplateContentEqual compares two JSON byte slices for structural equality
// by normalizing whitespace. Returns true if they represent the same JSON.
func TemplateContentEqual(expected, actual []byte) bool {
var e, a interface{}
if err := json.Unmarshal(expected, &e); err != nil {
return false
}
if err := json.Unmarshal(actual, &a); err != nil {
return false
}
ej, _ := json.Marshal(e)
aj, _ := json.Marshal(a)
return string(ej) == string(aj)
}