A main worktree keeps no committable change: a mod that refuses or reverts changes git would commit in <project>/worktrees/main, leaves gitignored files free…

A Claude Code mod that enforces the golden rule: a main worktree keeps no committable change. Every change to what main tracks is made in a dedicated worktree on its own branch and reaches main only through a pull request. The mod runs inside Claude Code on every tool call, for the main conversation and every subagent.
A main worktree is a git working tree whose folder is named main, in practice <project>/worktrees/main. A committable change is anything git status there would show: a tracked file modified or deleted, a new file git does not ignore, a staged change, or main's HEAD or branch moved.
Nothing else is governed. Gitignored files in main (vendor/, node_modules/, the files folder, a local DDEV setup) change freely, so main can run as a dev instance: DDEV, Composer, npm, Drush and database imports just work. Folders outside a main worktree, dot folders included, are not touched.
| Layer | What happens |
|---|---|
| Rule in context | The rule is added to every system prompt (personal account). On a Team seat, where Claude Code's built-in guard keeps mods out of the system prompt, a short form rides on each prompt and each subagent's prompt. |
| Edit, Write, NotebookEdit | Refused when the destination (symlinks followed, any letter case) is a file the main worktree could commit, or the git metadata of a repository that has one, with the git worktree add command to use instead. A gitignored, untracked file is allowed (git check-ignore, with the person's global excludes, as git status sees it). |
| Bash and Monitor | Every command runs through hooks/sandbox/run.py, which knows the shell's real working directory. Before: pushes to main, and git commands in a main worktree that would move its HEAD or branch (commit, merge or pull without --ff-only, rebase, reset to another commit, checkout or switch to another branch, renaming or deleting main, stash pop/apply), are refused. Around a command run in or naming a main worktree: git status before and after; a move of main's HEAD or branch is undone unless it is a fast-forward to what the hosted remote's main holds (git ls-remote origin); every tracked file the command changed is restored from HEAD, every new unignored file is deleted, and the command reports it and exits non-zero. A file that was already changed before the command is left alone and reported. |
| Pushes | From a governed repository, git push to main in any spelling, gh pr merge --admin, and API writes to refs/heads/main are refused. Repositories without a main worktree are left alone. Branch protection on the host is the real enforcement. |
| MCP tools | A tool whose path arguments land on a committable file in main is refused, unless mcpReadTools in hooks/policy.json lists it as read-only. |
| Other plugins | Their $.fs.write is judged like Write; their $.process.run/spawn go through the same bootstrap. |
| Self-protection | The plugin's own files and ~/.claude/hooks/golden-rule.sh cannot be edited; a command naming them is refused, and a command that changed them anyway is reported. A command that switches the plugin off or uninstalls it has that put back; /config rows about hooks or plugins are refused unless the person changes them. A command that removes or moves a main worktree folder or its .git is refused. |
Every gate fails closed: a guard that throws refuses the call.
/golden-rule shows what is guarded and recent refusals.
git -C <project>/worktrees/main fetch origin
git -C <project>/worktrees/main worktree add ../<topic> -b feature/<topic> --no-track origin/main
# work, commit, then
git push origin HEAD:feature/<topic>
gh pr create --head feature/<topic>
Keep main current with git -C <project>/worktrees/main pull --ff-only.
/usr/bin/python3, /usr/bin/git, Claude Code 2.1.287 or later.~/<folder>/<project>/worktrees/main, set in hooks/policy.json), and anywhere a command runs or names.claude plugin test . # hook decisions, mocked engine
zsh tests/e2e/run.zsh # the real bootstrap against fixture repositories
zsh tests/live/run.zsh <out> # the mod in a real headless session (uses the model)hooks/mod/register.ts 390 lines1// The golden rule mod: a main worktree keeps no committable change, and work reaches main only through a
2// pull request. Every gate fails closed (its .catch refuses); the shell layer hands each command to
3// hooks/sandbox/run.py, which refuses pushes to main and git commands that move main's HEAD, and puts back
4// any committable change a command made in a main worktree.
5// Plan: ~/Tools/CLAUDE-PLUGINS/plans/2026-10-06-golden-rule-mod.md.
6
7import type { EngineInterface, Register } from 'claude-code'
8
9import {
10 type GitDirs, type Io, type Policy, expandHome, gitDirsOf, governedGitPath, isGuardPath, isIdentityPath, isSettingsFile,
11 mainWorktreeOf, normalize, pathLiterals, placed, relativeMainTokens,
12} from './paths'
13import { RULE, SECTION_ID, SHORT_RULE } from './rule'
14import { wrapArgv, wrapCommand } from './shell'
15
16const NAME = 'golden-rule'
17
18export type Refusal = { at: string; tool: string; what: string; why: string }
19type Settings = { enabledPlugins?: Record<string, unknown>; disableAllHooks?: unknown }
20type Registry = { plugins?: Record<string, unknown> }
21
22let policy: Policy | undefined
23let home = ''
24// Whether prompt.compose reached the system prompt in this load. On a Team seat the built-in guard skips
25// it, so the short rule rides on each prompt and on each subagent's prompt instead.
26let composed = false
27// The command each wrapped call must arrive with at the shell, by tool call id, for the final check.
28const expected = new Map<string, string>()
29// The guard's own paths as written and as resolved, and every known main worktree's git directories.
30let guardRoots: string[] = []
31let gitDirs: GitDirs[] = []
32
33function io($: EngineInterface): Io {
34 return {
35 // Only "not there" reads as absent. A link that exists but leads nowhere (or nowhere the engine can
36 // name) cannot be placed, so it throws, as does any other failure: the gate's .catch refuses.
37 realPath: path => $.fs.stat(path, { resolve: true }).then(
38 stat => {
39 if (stat.realPath === undefined) throw new Error(`${path} cannot be resolved (a link that leads nowhere)`)
40 return stat.realPath
41 },
42 (error: unknown) => {
43 if (/ENOENT|not found|no such/i.test(String(error))) return undefined
44 throw error
45 },
46 ),
47 exists: path => $.fs.exists(path),
48 }
49}
50
51async function setup($: EngineInterface): Promise<Policy> {
52 if (!policy) {
53 home = (await $.env.get('HOME')) ?? ''
54 if (!home) throw new Error('HOME is not set')
55 const rules = JSON.parse(await $.fs.read(`${$.plugin.root}/hooks/policy.json`)) as Policy
56 const written = [$.plugin.root, ...rules.guardFiles.map(file => normalize(expandHome(file, home)))]
57 const resolved = await Promise.all(written.map(path => io($).realPath(path)))
58 guardRoots = [...new Set([...written, ...resolved.filter((path): path is string => path !== undefined)])]
59 policy = rules
60 gitDirs = await knownGitDirs($, await guarded($))
61 }
62 return policy
63}
64
65const readText = ($: EngineInterface) => (path: string): Promise<string | undefined> =>
66 $.fs.stat(path).then(stat => (stat.kind === 'file' ? $.fs.read(path) : undefined), () => undefined)
67
68async function knownGitDirs($: EngineInterface, roots: readonly string[]): Promise<GitDirs[]> {
69 const out: GitDirs[] = []
70 for (const root of roots) out.push(await gitDirsOf(root, readText($), io($)))
71 return out
72}
73
74async function refuse($: EngineInterface, tool: string, what: string, why: string): Promise<{ deny: string }> {
75 const log = ((await $.store.get('refusals').catch(() => undefined)) as Refusal[] | undefined) ?? []
76 const at = new Date(await $.clock.now()).toISOString()
77 await $.store.set('refusals', [...log, { at, tool, what: what.slice(0, 200), why }].slice(-50)).catch(() => undefined)
78 $.ui.toast(`golden rule refused ${tool}: ${why.split('.')[0]}`)
79 return { deny: `golden-rule: ${why}` }
80}
81
82/** Whether a real path in a main worktree is a gitignored, untracked file, which nothing could commit
83 * (hooks/sandbox/committable.py). Anything but a clear yes, a failure included, keeps the path protected. */
84async function isIgnored($: EngineInterface, root: string, real: string): Promise<boolean> {
85 const done = await $.process.run(['/usr/bin/python3', '-I', '-B', '-X', 'pycache_prefix=/var/empty/golden-rule', `${$.plugin.root}/hooks/sandbox/committable.py`, 'check', root, real], { timeoutMs: 20_000 })
86 .catch(() => undefined)
87 return done?.exitCode === 0
88}
89
90const worktreeHint = (root: string): string =>
91 `Make this change in a sibling worktree: git -C ${root} worktree add ../<topic> -b feature/<topic> --no-track origin/main`
92
93/** Why writing `text` (when known) to `path` is refused, or undefined when it is allowed. */
94async function judgeWrite($: EngineInterface, path: string, text?: string): Promise<string | undefined> {
95 const rules = await setup($)
96 const cwd = await $.session.cwd()
97 const spelled = normalize(expandHome(path, home), cwd)
98 if (isIdentityPath(spelled)) return `${path} names a file by its identity (/.vol), which the guard cannot place; use its real path.`
99 const real = await placed(path, cwd, home, io($))
100 if (isIdentityPath(real)) return `${path} lands on a file-identity path (${real}), which the guard cannot place; use its real path.`
101 const root = await mainWorktreeOf(real, io($))
102 if (root && !(await isIgnored($, root, real))) return `${real} is a file the main worktree ${root} could commit; main keeps no committable change. ${worktreeHint(root)}`
103 const owner = governedGitPath(real, gitDirs)
104 if (owner) return `${real} is git metadata of the main worktree ${owner.root}; only git itself writes there.`
105 if (isGuardPath([spelled, real], guardRoots, rules)) return `${real} belongs to the golden rule's guard, which a session never changes.`
106 if (text !== undefined && switchesOff(text, rules.pluginId) && (isSettingsFile(spelled) || isSettingsFile(real) || await isWatchedSettings($, real))) {
107 return `that change to ${real} would switch the golden rule guard off, which a session never does.`
108 }
109 return undefined
110}
111
112// ---- Settings and the plugin registry ---------------------------------------------------------------
113
114/** Whether a real path is where one of the watched settings files resolves to now (a settings file may be a
115 * link to a file named anything, and may be retargeted during the session). */
116async function isWatchedSettings($: EngineInterface, real: string): Promise<boolean> {
117 const { settings } = await watchedFiles($)
118 for (const path of settings) {
119 const resolved = await io($).realPath(path).catch(() => undefined)
120 if (resolved !== undefined && resolved.toLowerCase() === real.toLowerCase()) return true
121 }
122 return false
123}
124
125function parse(text: string | undefined): unknown {
126 if (text === undefined) return undefined
127 try {
128 return JSON.parse(text)
129 } catch {
130 return undefined
131 }
132}
133
134function disables(json: unknown, pluginId: string): boolean {
135 if (typeof json !== 'object' || json === null) return false
136 const settings = json as Settings
137 return settings.disableAllHooks === true || settings.enabledPlugins?.[pluginId] === false
138}
139
140/** Whether a settings file's proposed text switches the plugin off. Text that is not JSON is judged by
141 * its words, since Claude Code may still read a settings file a later write repairs. */
142function switchesOff(text: string, pluginId: string): boolean {
143 const json = parse(text)
144 if (json !== undefined) return disables(json, pluginId)
145 const id = pluginId.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
146 return /"disableAllHooks"\s*:\s*true/.test(text) || new RegExp(`"${id}"\\s*:\\s*false`).test(text)
147}
148
149/** The text an Edit would leave in a file, from its current text. */
150function edited(current: string, oldString: string, newString: string, all: boolean): string {
151 return all ? current.split(oldString).join(newString) : current.replace(oldString, () => newString)
152}
153
154/** Every Claude configuration folder this session's settings and registry live in. */
155async function configDirs($: EngineInterface): Promise<string[]> {
156 const configured = await $.env.get('CLAUDE_CONFIG_DIR')
157 return [...new Set([configured, `${home}/.claude`, `${home}/.claude-work`].filter((dir): dir is string => Boolean(dir)))]
158}
159
160async function watchedFiles($: EngineInterface): Promise<{ settings: string[]; registries: string[] }> {
161 const dirs = await configDirs($)
162 const cwd = await $.session.cwd()
163 return {
164 settings: [...dirs.flatMap(dir => [`${dir}/settings.json`, `${dir}/settings.local.json`]), `${cwd}/.claude/settings.json`, `${cwd}/.claude/settings.local.json`],
165 registries: dirs.map(dir => `${dir}/plugins/installed_plugins.json`),
166 }
167}
168
169async function snapshot($: EngineInterface): Promise<Map<string, string | undefined>> {
170 const { settings, registries } = await watchedFiles($)
171 const out = new Map<string, string | undefined>()
172 for (const path of [...settings, ...registries]) out.set(path, await $.fs.read(path).catch(() => undefined))
173 return out
174}
175
176/** Undoes a command's switching the guard off or uninstalling it: only the keys that do it. */
177async function restore($: EngineInterface, before: Map<string, string | undefined>): Promise<string[]> {
178 const rules = await setup($)
179 const { settings, registries } = await watchedFiles($)
180 const restored: string[] = []
181 const indentOf = (text: string): string => /\n( +)"/.exec(text)?.[1] ?? ' '
182 for (const path of settings) {
183 const now = await $.fs.read(path).catch(() => undefined)
184 const was = parse(before.get(path)) as Settings | undefined
185 const json = parse(now) as Settings | undefined
186 if (now === undefined || !json || !disables(json, rules.pluginId) || disables(was, rules.pluginId)) continue
187 if (json.enabledPlugins?.[rules.pluginId] === false) {
188 if (was?.enabledPlugins && rules.pluginId in was.enabledPlugins) json.enabledPlugins[rules.pluginId] = was.enabledPlugins[rules.pluginId]
189 else delete json.enabledPlugins[rules.pluginId]
190 }
191 if (json.disableAllHooks === true && was?.disableAllHooks !== true) delete json.disableAllHooks
192 await $.fs.write(path, `${JSON.stringify(json, null, indentOf(now))}\n`)
193 restored.push(path)
194 }
195 for (const path of registries) {
196 const was = parse(before.get(path)) as Registry | undefined
197 const now = await $.fs.read(path).catch(() => undefined)
198 const json = (parse(now) ?? {}) as Registry
199 const entry = was?.plugins?.[rules.pluginId]
200 if (entry === undefined || json.plugins?.[rules.pluginId] !== undefined) continue
201 json.plugins = { ...json.plugins, [rules.pluginId]: entry }
202 await $.fs.write(path, `${JSON.stringify(json, null, indentOf(now ?? before.get(path) ?? ''))}\n`)
203 restored.push(path)
204 }
205 return restored
206}
207
208// ---- Strings inside a tool's arguments ---------------------------------------------------------------
209
210const bytes = (text: string): number => new TextEncoder().encode(text).length
211
212/** Whether a string is within macOS's limits for a path (PATH_MAX 1,024, NAME_MAX 255, no NUL). */
213export function couldBePath(text: string): boolean {
214 return text.length > 0 && !text.includes('\0') && bytes(text) <= 1024 && text.split('/').every(name => bytes(name) <= 255)
215}
216
217function strings(value: unknown): string[] {
218 if (typeof value === 'string') return [value]
219 if (Array.isArray(value)) return value.flatMap(strings)
220 if (typeof value === 'object' && value !== null) return Object.values(value).flatMap(strings)
221 return []
222}
223
224// ---- Status and the /golden-rule command -------------------------------------------------------------
225
226/** Every main worktree in the person's project folders: each container's children with worktrees/main. */
227async function guarded($: EngineInterface): Promise<string[]> {
228 const rules = await setup($)
229 const containers: string[] = []
230 for (const container of rules.containers) {
231 const path = expandHome(container, home)
232 if (!path.endsWith('/*')) containers.push(path)
233 else for (const entry of await $.fs.list(path.slice(0, -2)).catch(() => [])) if (entry.kind === 'dir') containers.push(`${path.slice(0, -2)}/${entry.name}`)
234 }
235 const roots: string[] = []
236 for (const folder of containers) {
237 for (const entry of await $.fs.list(folder).catch(() => [])) {
238 const root = `${folder}/${entry.name}/worktrees/main`
239 if (entry.kind === 'dir' && await $.fs.exists(`${root}/.git`).catch(() => false)) roots.push(root)
240 }
241 }
242 return roots
243}
244
245async function showStatus($: EngineInterface): Promise<void> {
246 const count = (await guarded($)).length
247 $.ui.status(`golden rule: ${count} main worktrees guarded${composed ? '' : ' (rule on each prompt)'}`)
248}
249
250async function report($: EngineInterface): Promise<string> {
251 const roots = await guarded($)
252 const refusals = (((await $.store.get('refusals').catch(() => undefined)) as Refusal[] | undefined) ?? []).slice(-10)
253 return [
254 `Golden rule: a main worktree keeps no committable change. ${roots.length} main worktrees guarded:`,
255 ` ${roots.map(root => root.split('/').slice(-3, -2)[0]).join(', ')}`,
256 refusals.length > 0 ? 'Recent refusals:' : 'No refusals yet.',
257 ...refusals.map(entry => ` ${entry.at} ${entry.tool}: ${entry.why.split('.')[0]}`),
258 `Rule as the model reads it: ${composed ? 'system prompt' : 'a short form on each prompt (the system prompt is not open to mods on this account)'}.`,
259 ].join('\n')
260}
261
262export const register: Register = on => {
263 on('session.start', async ($, e, next) => {
264 await setup($)
265 await showStatus($).catch(() => undefined)
266 await $.command.register({ name: 'golden-rule', description: 'Golden rule: what is guarded and recent refusals' }).catch(() => undefined)
267 return next(e)
268 })
269
270 on('command.run', { command: 'golden-rule' }, async $ => ({ text: await report($) }))
271
272 // ---- Layer 1: the rule is always in context ----
273 on('prompt.compose', async ($, e, next) => {
274 const composedPrompt = await next(e)
275 composed = true
276 if (composedPrompt.sections.some(section => section.id === SECTION_ID)) return composedPrompt
277 return { sections: [...composedPrompt.sections, { id: SECTION_ID, text: RULE, scope: 'session' as const }] }
278 })
279
280 on('prompt.submit', async ($, e, next) =>
281 composed ? next(e) : next({ ...e, context: [...(e.context ?? []), SHORT_RULE] }),
282 ).catch(($, e, next) => next(e))
283
284 // ---- Layer 2: structured tools ----
285 on('tool.call', { tool: ['Edit', 'Write', 'NotebookEdit'] }, async ($, e, next) => {
286 let path: string
287 let text: string | undefined
288 if (e.tool === 'NotebookEdit') path = e.notebook_path
289 else if (e.tool === 'Write') [path, text] = [e.file_path, e.content]
290 else {
291 path = e.file_path
292 const current = await $.fs.read(path).catch(() => undefined)
293 text = current === undefined ? undefined : edited(current, e.old_string, e.new_string, e.replace_all === true)
294 }
295 const why = await judgeWrite($, path, text)
296 return why ? refuse($, e.tool, path, why) : next(e)
297 }).catch(($, e, next) => (next.called ? next(e) : { deny: 'golden-rule: the edit guard failed, so this edit was not made.' }))
298
299 // A subagent's prompt carries the short rule where the system prompt cannot (a Team seat).
300 on('tool.call', { tool: 'Agent' }, async ($, e, next) =>
301 composed || typeof e.prompt !== 'string' ? next(e) : next({ ...e, prompt: `${SHORT_RULE}\n\n${e.prompt}` }),
302 ).catch(($, e, next) => next(e))
303
304 // ---- Layer 3: every command runs sandboxed ----
305 on('tool.call', { tool: ['Bash', 'Monitor'] }, async ($, e, next) => {
306 if (typeof e.command !== 'string') return next(e)
307 const rules = await setup($)
308 const before = await snapshot($)
309 const wrapped = wrapCommand($.plugin.root, e.command)
310 if (e.tool_use_id) expected.set(e.tool_use_id, wrapped)
311 const result = await next({ ...e, command: wrapped })
312 if (e.tool_use_id) expected.delete(e.tool_use_id)
313 let restored: string[]
314 try {
315 restored = await restore($, before)
316 } catch (error) {
317 await refuse($, e.tool, e.command, `the guard could not check whether that command switched it off (${String(error).slice(0, 120)}).`)
318 return { deny: 'golden-rule: the command ran, but the guard could not confirm it is still switched on; tell Chris.' }
319 }
320 if (restored.length === 0) return result
321 await refuse($, e.tool, e.command, `that command switched the golden rule guard off in ${restored.join(', ')}; the setting was put back.`)
322 return { deny: `golden-rule: that command switched the guard off (${rules.pluginId}); the setting was put back. A session never disables the guard.` }
323 }).catch(($, e, next) => (next.called ? next(e) : { deny: `golden-rule: the shell guard failed (${next.error.kind}), so this command was not run.` }))
324
325 // The last word on what runs, beneath every plugin's rewrite: exactly the wrapped command, or nothing
326 // (skipped on a Team seat by the built-in guard).
327 on('classic.PreToolUse', async ($, e, next) => {
328 if ((e.tool === 'Bash' || e.tool === 'Monitor') && typeof e.command === 'string') {
329 const want = e.tool_use_id ? expected.get(e.tool_use_id) : undefined
330 if (want === undefined ? !e.command.startsWith('__gr=$(/usr/bin/mktemp -t golden-rule)') : e.command !== want) {
331 return { deny: 'golden-rule: this command was changed on its way to the shell after the guard wrapped it, so it was not run.' }
332 }
333 }
334 return next(e)
335 }).catch(($, e, next) => (next.called ? next(e) : { deny: 'golden-rule: the final command check failed, so this command was not run.' }))
336
337 // ---- Layer 4: MCP tools that name a main worktree ----
338 // Every string argument is judged as a path where it could be one: whole (a path with spaces), each path
339 // token inside it, and a bare relative name against the session's folder. A destination split across
340 // arguments or computed by the server cannot be seen; that residual is documented.
341 on('tool.call', { tool: /^mcp__/ }, async ($, e, next) => {
342 const tool = String(e.tool)
343 const rules = await setup($)
344 if (rules.mcpReadTools.some(pattern => new RegExp(pattern).test(tool))) return next(e)
345 const texts = strings(Object.fromEntries(Object.entries(e).filter(([key]) => key !== 'tool' && key !== 'tool_use_id' && key !== 'agentId')))
346 // Every string that could name a file is placed as a path, links followed, and judged by where it
347 // lands: a destination reached through a link into main is caught, and ordinary text lands nowhere
348 // protected. A string past the system's path limits (1,024 bytes, 255 per name) cannot be a
349 // destination and is not placed, so long content never fails the call.
350 // A bare relative word (no slash) is a path only when it names something that exists: otherwise every
351 // sentence sent from a session inside main would read as a new file there.
352 const cwd = await $.session.cwd()
353 const whole: string[] = []
354 for (const text of texts.filter(couldBePath)) {
355 if (/^[~/]/.test(text) || text.includes('/') || await io($).realPath(normalize(text, cwd)).catch(() => undefined) !== undefined) whole.push(text)
356 }
357 for (const path of [...new Set([...whole, ...texts.flatMap(pathLiterals), ...texts.flatMap(relativeMainTokens)])].filter(couldBePath)) {
358 const why = await judgeWrite($, path)
359 if (why) return refuse($, tool, path, `${why} (MCP tools are refused for main worktrees unless listed as read-only in policy.json)`)
360 }
361 return next(e)
362 }).catch(($, e, next) => (next.called ? next(e) : { deny: 'golden-rule: the MCP guard failed, so this call was not made.' }))
363
364 // ---- Layer 5: other plugins' files and processes ----
365 on('fs.write', async ($, e, next) => {
366 if (next.origin.plugin === NAME) return next(e)
367 const why = await judgeWrite($, e.path, e.text)
368 return why ? { deny: `golden-rule (refusing ${next.origin.plugin}): ${why}` } : next(e)
369 }).catch(($, e, next) => (next.called ? next(e) : { deny: 'golden-rule: the file guard failed, so this write was not made.' }))
370
371 on('process.run', async ($, e, next) =>
372 next.origin.plugin === NAME ? next(e) : next({ ...e, argv: wrapArgv($.plugin.root, e.argv) }),
373 ).catch(($, e, next) => (next.called ? next(e) : { deny: 'golden-rule: the process guard failed, so this program was not started.' }))
374
375 on('process.spawn', async function* ($, e, next) {
376 return yield* next(next.origin.plugin === NAME ? e : { ...e, argv: wrapArgv($.plugin.root, e.argv) })
377 }).catch(async function* ($, e, next) {
378 if (next.called) return yield* next(e)
379 return { deny: 'golden-rule: the process guard failed, so this program was not started.' }
380 })
381
382 // ---- Settings rows that would switch hooks or plugins off ----
383 // The person's own changes in the menu pass; a plugin's are refused for hook and plugin rows.
384 on('config.set', async ($, e, next) =>
385 e.origin.kind !== 'composer' && /hook|plugin|golden/i.test(e.key)
386 ? { deny: 'golden-rule: a plugin never changes hook or plugin settings; Chris can change this in /config himself.' }
387 : next(e),
388 ).catch(($, e, next) => (next.called ? next(e) : { deny: 'golden-rule: the settings guard failed, so this setting was not changed.' }))
389}
390hooks/mod/paths.ts 145 lines1// Where a path lands, and whether that is a main worktree, its git metadata, or one of the guard's own
2// files. Pure functions over a small file-system view, so tests can run them without the engine.
3
4export type Policy = {
5 containers: string[]
6 guardFiles: string[]
7 guardPatterns: string[]
8 mcpReadTools: string[]
9 pluginId: string
10}
11
12/** The file-system answers the decisions need. `realPath` is undefined only for a path that is not there. */
13export type Io = {
14 realPath: (path: string) => Promise<string | undefined>
15 exists: (path: string) => Promise<boolean>
16}
17
18export function expandHome(path: string, home: string): string {
19 if (path === '~') return home
20 return path.startsWith('~/') ? `${home}${path.slice(1)}` : path
21}
22
23/** Collapses `.`, `..` and repeated slashes without touching the disk. Relative paths join `cwd`. */
24export function normalize(path: string, cwd = '/'): string {
25 const parts: string[] = []
26 for (const part of (path.startsWith('/') ? path : `${cwd}/${path}`).split('/')) {
27 if (part === '' || part === '.') continue
28 if (part === '..') parts.pop()
29 else parts.push(part)
30 }
31 return `/${parts.join('/')}`
32}
33
34export const parentOf = (path: string): string => path.slice(0, path.lastIndexOf('/')) || '/'
35export const baseOf = (path: string): string => path.slice(path.lastIndexOf('/') + 1)
36// macOS volumes are case-insensitive by default: `MAIN` and `.GIT` name the same folders.
37const named = (path: string, name: string): boolean => baseOf(path).toLowerCase() === name
38
39/** Every directory from `path` up to the root, nearest first. */
40export function ancestorsOf(path: string): string[] {
41 const out: string[] = []
42 for (let at = path; ; at = parentOf(at)) {
43 out.push(at)
44 if (at === '/') return out
45 }
46}
47
48/**
49 * Where a path a tool names would land, resolved the way the file system walks it: component by
50 * component, each existing one replaced by its real path before the next `..` is applied (so
51 * `link/../x` lands beside the link's target, not beside the link). Past the first component that does
52 * not exist the rest is joined as written. A file-system error other than "not there" propagates, so the
53 * calling gate's `.catch` refuses instead of judging a path it could not place.
54 */
55export async function placed(path: string, cwd: string, home: string, io: Io): Promise<string> {
56 const expanded = expandHome(path, home)
57 let at = expanded.startsWith('/') ? '/' : (await io.realPath(cwd)) ?? normalize(cwd)
58 let exists = true
59 for (const part of expanded.split('/')) {
60 if (part === '' || part === '.') continue
61 if (part === '..') {
62 at = parentOf(at)
63 continue
64 }
65 const next = at === '/' ? `/${part}` : `${at}/${part}`
66 const real = exists ? await io.realPath(next) : undefined
67 if (real === undefined) exists = false
68 at = real ?? next
69 }
70 return at
71}
72
73/** A spelling that reaches a file by its identity (`/.vol/<device>/<inode>`), which no path check can judge. */
74export const isIdentityPath = (path: string): boolean => /^\/\.vol(\/|$)/i.test(path)
75
76/**
77 * The main worktree a real path is inside, if any: the nearest ancestor that is a working-tree root named
78 * `main` (any case). A repository nested inside a main worktree stays inside it; a feature worktree nested
79 * inside a project root that merely has `main` checked out is not inside one, since that root is not
80 * named `main`.
81 */
82export async function mainWorktreeOf(real: string, io: Io): Promise<string | undefined> {
83 for (const dir of ancestorsOf(real)) {
84 if (named(dir, 'main') && await io.exists(`${dir}/.git`)) return dir
85 }
86 return undefined
87}
88
89/** A main worktree's git directories as git lays them out: its own (`gitdir`) and the shared one. */
90export type GitDirs = { root: string; gitdir: string; common: string }
91
92/**
93 * Where a main worktree keeps its git metadata: a `.git` folder, or a `.git` file naming a directory
94 * elsewhere (a linked worktree under any administrative id, a separate git dir, a bare repository's
95 * worktree), whose `commondir` names the shared directory.
96 */
97export async function gitDirsOf(root: string, read: (path: string) => Promise<string | undefined>, io: Io): Promise<GitDirs> {
98 const marker = `${root}/.git`
99 const text = await read(marker)
100 if (text === undefined) {
101 const real = (await io.realPath(marker)) ?? marker
102 return { root, gitdir: real, common: real }
103 }
104 const pointer = /^gitdir: (.+)$/m.exec(text)?.[1]?.trim()
105 if (!pointer) throw new Error(`cannot read ${marker}`)
106 const gitdir = (await io.realPath(normalize(pointer, root))) ?? normalize(pointer, root)
107 const commondir = (await read(`${gitdir}/commondir`))?.trim()
108 const common = commondir ? (await io.realPath(normalize(commondir, gitdir))) ?? normalize(commondir, gitdir) : gitdir
109 return { root, gitdir, common }
110}
111
112/** Which main worktree's git metadata a real path is inside, if any. Git writes there itself; a session's
113 * Edit or Write never needs to. */
114export function governedGitPath(real: string, dirs: readonly GitDirs[]): GitDirs | undefined {
115 const path = real.toLowerCase()
116 return dirs.find(({ gitdir, common }) => [gitdir, common].some(dir => path === dir.toLowerCase() || path.startsWith(`${dir.toLowerCase()}/`)))
117}
118
119const lower = (path: string): string => path.toLowerCase()
120
121/** Whether a path is one of the guard's own files, or a place that would load a new hooks module.
122 * `roots` holds the guard's paths both as written and resolved, and callers pass both spellings. */
123export function isGuardPath(paths: readonly string[], roots: readonly string[], policy: Policy): boolean {
124 const guarded = roots.map(lower)
125 return paths.some(candidate => {
126 const path = lower(candidate)
127 return guarded.some(root => path === root || path.startsWith(`${root}/`))
128 || policy.guardPatterns.some(pattern => new RegExp(pattern, 'i').test(candidate))
129 })
130}
131
132/** Settings files that could switch a plugin off, in any Claude configuration folder (`~/.claude-work` too). */
133export const isSettingsFile = (real: string): boolean => /\/\.claude[^/]*\/settings(\.local)?\.json$/i.test(real)
134
135/** Absolute, home-relative and relative path tokens in a command or a tool's string arguments. */
136export function pathLiterals(text: string): string[] {
137 return [...text.matchAll(/(?:^|[\s"'`=:(])((?:~|\/)[^\s"'`;|&()<>]*)/g)].map(match => match[1]).filter(path => path.length > 1)
138}
139
140/** Relative tokens that name a `main` folder (`../main/README.md`), resolved later against the working directory. */
141export function relativeMainTokens(text: string): string[] {
142 return [...text.matchAll(/[^\s"'`;|&()<>]+/g)].map(match => match[0])
143 .filter(token => /(^|\/)main(\/|$)/i.test(token) && !/^[~/-]/.test(token))
144}
145hooks/mod/rule.ts 30 lines1// The golden rule as the model reads it, written from Chris's decisions, not older wording.
2
3export const SECTION_ID = 'golden-rule'
4
5export const RULE = `# The golden rule (enforced by the golden-rule mod)
6
7A main worktree keeps no committable change. Every change is made in a dedicated worktree on its own branch
8and reaches \`main\` only through a pull request.
9
10- A main worktree is a git working tree whose folder is named \`main\`, in practice
11 \`<project>/worktrees/main\`. A committable change is anything \`git status\` there would show: a tracked
12 file modified or deleted, a new file git does not ignore, a staged change, or main's HEAD or branch moved.
13- Everything else is free. Run the main worktree as a dev instance (DDEV, Composer, npm, Drush, database
14 imports): gitignored files there (vendor/, node_modules/, the files folder, local DDEV setup) may change.
15 Folders outside a main worktree, dot folders included, are not governed.
16- If a shell command changes a committable file in main, the guard restores it from HEAD (or deletes the new
17 file) after the command and says so. Edit and Write into such a file are refused. Git commands that would
18 move main's HEAD (commit, merge, rebase, reset to another commit, checkout or switch to another branch,
19 pull without --ff-only) are refused. Pushing to main is refused.
20- To change something main tracks, create a sibling worktree without asking:
21 \`git -C <project>/worktrees/main fetch origin\`, then
22 \`git -C <project>/worktrees/main worktree add ../<topic> -b feature/<topic> --no-track origin/main\`.
23 Work, commit and push there: \`git push origin HEAD:feature/<topic>\`, then \`gh pr create --head feature/<topic>\`.
24- When the guard refuses or reverts something, move the work to a worktree. Never route around the guard,
25 edit its files, or switch it off.`
26
27export const SHORT_RULE = `Golden rule (enforced): a main worktree (<project>/worktrees/main) keeps no committable change (anything git status would show, or HEAD moved). Gitignored files there, and everything outside it, are free: running main as a dev instance is fine.
28Change tracked files in a sibling worktree: git -C <project>/worktrees/main worktree add ../<topic> -b feature/<topic> --no-track origin/main. Changes reach main only by pull request.
29Shell changes to committable files in main are reverted after the command. Never route around or disable the guard.`
30hooks/mod/shell.ts 44 lines1// The shell side of the guard: wrapping a command so the bootstrap runs it inside the sandbox. The
2// bootstrap (hooks/sandbox/run.py) also refuses pushes to main, since only it knows the shell's real
3// working directory and so whether the repository is governed.
4
5function b64(text: string): string {
6 let binary = ''
7 for (const byte of new TextEncoder().encode(text)) binary += String.fromCharCode(byte)
8 return btoa(binary)
9}
10
11const quote = (text: string): string => `'${text.replace(/'/g, `'\\''`)}'`
12
13/** A heredoc delimiter that is no line of the command, so the body ends where the command does. */
14export function delimiterFor(command: string): string {
15 const lines = new Set(command.split('\n'))
16 let delimiter = 'GOLDEN_RULE_EOF'
17 for (let n = 1; lines.has(delimiter); n++) delimiter = `GOLDEN_RULE_EOF_${n}`
18 return delimiter
19}
20
21/**
22 * The command the Bash tool actually runs. The bootstrap computes the sandbox profile from the shell's
23 * real working directory, runs the model's command inside it, and writes the child's final directory
24 * to a file, so `cd` carries over to the next call; the exit status passes through.
25 *
26 * The command travels verbatim as the body of a quoted heredoc: the outer shell expands nothing in
27 * it, and every other plugin's PreToolUse hook, which runs after this rewrite, reads the command as
28 * the model wrote it rather than an encoding of it.
29 */
30export function wrapCommand(pluginRoot: string, command: string): string {
31 const delimiter = delimiterFor(command)
32 return [
33 `__gr=$(/usr/bin/mktemp -t golden-rule); /usr/bin/python3 -I -B -X pycache_prefix=/var/empty/golden-rule ${quote(`${pluginRoot}/hooks/sandbox/run.py`)} --stdin --state "$__gr" <<'${delimiter}'`,
34 command,
35 delimiter,
36 ['__s=$?', '[ -s "$__gr" ] && cd "$(/bin/cat "$__gr")" 2>/dev/null', '/bin/rm -f "$__gr"', '(exit $__s)'].join('; '),
37 ].join('\n')
38}
39
40/** Another plugin's `$.process.run`/`spawn` argument vector, run through the same bootstrap. */
41export function wrapArgv(pluginRoot: string, argv: readonly string[]): string[] {
42 return ['/usr/bin/python3', '-I', '-B', '-X', 'pycache_prefix=/var/empty/golden-rule', `${pluginRoot}/hooks/sandbox/run.py`, '--argv', b64(JSON.stringify(argv))]
43}
44