Agentic Software Factory
Agent Guardrails That Hold: Git Worktrees and Deterministic Hooks
Context files guide a coding agent but enforce nothing. Managed settings, fail-closed hooks and one Git worktree per task bind the agent on the workstation, and required CI checks catch what those controls cannot see.
Every coding-agent rollout begins with a context file: conventions, architecture notes, a list of things the agent must never do. Context is how an agent learns a codebase, and it deserves investment. It is also advisory. Claude Code’s own documentation says it “treats CLAUDE.md files as context, not enforced configuration,” and a model in the middle of a failing test run can decide that a rule written there does not apply to the case in front of it. The same is true of an instruction it picks up from a dependency’s README.
The documentation draws the other half of the line too: “Settings rules are enforced by the client regardless of what Claude decides to do.” In the reference design of my book, every rule whose violation must not reach a branch gets a control of that kind, meaning a managed permission rule, a hook or a worktree. Context carries the reasons, so that when a control refuses an action, the agent knows where the legitimate path runs.
Context files are concatenated, so a rule that must prevail goes in managed settings
Claude Code assembles its instructions from several files, and “all discovered files are concatenated into context rather than overriding each other.” No precedence rule settles a conflict between two of them: both reach the model, which picks one. A rule that must prevail therefore belongs in settings, where precedence is defined. For managed settings the permissions documentation is explicit: “no other level, including command line arguments, can override a managed permission rule.”
The organization’s managed settings file carries the rules no repository can relax. An excerpt from the reference file:
{
"permissions": {
"disableBypassPermissionsMode": "disable",
"disableAutoMode": "disable",
"deny": [
"Read(**/.env)",
"Read(**/.env.*)",
"Read(**/secrets/**)",
"Bash(curl *)",
"Bash(wget *)",
"Bash(git push --force *)",
"Bash(git push -f *)"
]
}
}
Each workstation control also has a documented gap, so the design names, for every prohibition, the control that enforces it on the laptop, what that control cannot see, and the backstop that catches the rest.
| Prohibition | Workstation control | Cannot see | Backstop |
|---|---|---|---|
| Editing contract tests | Edit guard refuses Edit and Write | Writes made through the shell | CI sandbox write rules; code-owner review |
Reading secrets and .env files | Managed Read deny rules | Shell readers the rule does not recognize | CI network allowlist; no standing secrets in CI |
| Editing hooks, settings and agent definitions | Edit guard | Shell writes; the developer’s own settings | CI sandbox write rules; code-owner review |
Editing CI definitions and the Makefile | Edit guard | Shell writes | Required jobs read from a platform repository |
| Editing an applied migration | Edit guard checks origin/main | Shell writes; merges not yet fetched | Code-owner review |
| Sharing a checkout between tasks | One worktree per task | Shell writes into the main checkout; a move into a sibling worktree | One branch and one pull request per task |
| Floats for money | None: not a path question | Behavior | Contract suite at the test gate; critic |
Source: Author's reference design, The Enterprise Agentic Software Factory.
Keeping this table in the repository, next to the context file, also shows which prohibitions were left as guidance only, so that choice is reviewed like any other change.
Each task gets its own worktree, branch and pull request
Parallel sessions in one checkout share a working tree, an index and a current branch. When one session switches branch to start a task, another session’s uncommitted edits move with it, and a commit can land carrying half of each change. A Git worktree is a second working directory attached to the same repository, with its own branch and files, and Claude Code creates one per task:
claude --worktree fee-014
# working dir: .claude/worktrees/fee-014/
# branch: worktree-fee-014
“New worktrees branch from the repository’s default branch,” so each task starts from merged code, whatever the engineer happened to have checked out. The worktree directory goes in .gitignore, and gitignored local files are copied in only through an explicit .worktreeinclude list, which never names a secrets file.
Claude Code enforces part of the isolation itself: while a session runs in a worktree, it refuses file edits and Git commands that target the main checkout. The documentation states the limits just as plainly. “None of them tracks which files a shell command writes,” so a cp or a shell redirect into the main checkout is not refused. Sibling worktrees stay reachable, since “Claude can switch directly to another one under .claude/worktrees/.” And choosing “Yes, and don’t ask again” for a command in a worktree session saves the rule to the main checkout’s local settings, so one task’s permanent approval applies to every worktree of the repository. I keep permanent approvals for read-only commands, put anything that writes or reaches the network in the code-owned shared settings, and rely on worktrees to prevent accidental collisions and nothing more. Long unattended work runs in pipelines, where each job has its own checkout, a sandbox and no standing secrets.
Hooks run on every edit because no model decides whether they run
Hooks are commands that Claude Code runs at fixed lifecycle events, with structured input, and whose exit codes the client acts on. Permission rules match the name and arguments of an action; hooks can also run a program against what it contains, such as the resolved path of an edited file or the result of a test suite, and refuse it. The reference repository commits three:
{
"hooks": {
"PreToolUse": [{
"matcher": "Edit|Write",
"hooks": [{
"type": "command",
"command": "bash",
"args": [
"${CLAUDE_PROJECT_DIR}/.claude/hooks/protect-paths.sh"
],
"timeout": 10,
"onFailure": "block"
}]
}],
"PostToolUse": [{
"matcher": "Edit|Write",
"hooks": [{
"type": "command",
"command": "bash",
"args": [
"${CLAUDE_PROJECT_DIR}/.claude/hooks/post-edit.sh"
],
"timeout": 120
}]
}],
"Stop": [{
"hooks": [{
"type": "command",
"command": "bash",
"args": [
"${CLAUDE_PROJECT_DIR}/.claude/hooks/test-gate.sh"
],
"timeout": 900
}]
}]
}
}
| Hook | When it runs | What it does |
|---|---|---|
PreToolUse guard | Before every Edit or Write | Refuses writes to contract tests, secrets files, hooks, settings and agent definitions, CI definitions and applied migrations. Exit code 2 denies the call, and the agent reads the reason from stderr. |
PostToolUse check | After each edit to a Python file | Formats, lints and type-checks. It cannot undo the edit; exit code 2 returns the errors to the agent while the change is fresh. |
Stop test gate | When the agent tries to finish a turn that changed code | Blocks until the unit and contract suites pass, within an attempt budget. A reply that opens with a spec question may end, so a wrong spec goes back to a human. |
Source: Reference configuration, The Enterprise Agentic Software Factory; hook behavior from the Claude Code hooks documentation.
The guard’s denial messages are written for the agent. “Contracts change only through a Spec Gate PR” tells a model in the middle of a task where the legitimate path runs, which is more useful to it than a bare refusal.
The test gate needs its own attempt budget because the built-in loop guard does not cover this case. Claude Code applies an 8-consecutive-continuation cap, and the hooks documentation adds: “The count of consecutive continuations resets each time Claude calls a tool.” An agent that edits code between test runs calls a tool every time, so the cap never trips. My recommended starting budget is five runs: the gate blocks after each of the first four failures and lets the session stop after the fifth with a warning, and the item then goes to an engineer working at Level 2.
The edit guard has to fail closed, and it must resolve paths through Git
The documented default is the risk: “On most events, when a hook fails or times out, Claude Code still carries out the action.” A guard that crashes on a missing jq would let every edit through unchecked while everyone assumed it was working. Setting "onFailure": "block" turns a crash or timeout into a refusal; it requires Claude Code v2.1.295 or later, so the fleet’s minimum version has to be at least that release. A broken guard then refuses every edit until the platform team ships a fix, so the failure stops work in plain sight.
The guard also distrusts the spelling of the path it receives. The hooks documentation says only that Claude Code expands ~ and relative paths before hooks run, so the guard cannot assume that .. segments, symlinks or letter case have been normalized. The script therefore runs under set -euo pipefail, asks Git for the edited file’s path inside its own repository or worktree, and matches its patterns without regard to case. A path through src/../tests/contracts/, a symlinked checkout or a sibling worktree lands on the same pattern as the plain path.
Workstation hooks bind the agent, and required CI checks bind the branch
Three documented behaviors keep the workstation hooks from being the final word on a change.
The test gate fails open. The onFailure field has no effect on Stop hooks, because exit code 2 there “sends Claude back to keep working, and Claude can’t repair a hook that won’t run.” A gate that crashes or reaches its 900-second timeout lets the session end.
Repository hooks can be switched off. The disableAllHooks setting works from user, project and local settings, and only hooks deployed through managed settings resist it. I keep the edit guard in the repository anyway, because protected paths differ from one repository to the next and should change through that repository’s review. A managed SessionStart hook records a user, project or local settings file that disables hooks, which gives the incident process a signal, though it cannot block and cannot see a flag passed inline on the command line.
Shell writes pass the edit guard, as the first exhibit records.
The binding checks therefore run in CI. The required tests check reruns the same suites on the pull request, the jobs that judge a branch are read from a repository the pull request cannot touch, and code-owner review of protected paths catches shell writes the guard never saw.
Source: Author's diagram of the context workbench in The Enterprise Agentic Software Factory.
Hooks are production code running on every engineer’s machine
“Command hooks execute shell commands with your full user permissions.” They should be governed accordingly: owned by the platform team, reviewed, versioned under .claude/, where the edit guard refuses agent edits to hooks, settings and agent definitions, and released through the same canary rings as any other change to the delivery platform.
Each denial is recorded twice. The guard writes it to the system log with the branch and path, and Claude Code’s telemetry counts edit decisions whose source is a hook, so denials per merged pull request can sit on the same scorecard as cost. Repeated denials on one work item are a signal in their own right. My recommended starting threshold is three: denials on contract tests send the item back to the Spec Gate, because the spec or the code is wrong, and denials on guardrail paths go to the platform team, because an agent that keeps reaching for its own guardrails is following a bad instruction or has found a gap.
Hooks and tests form the first of the four verification stations, and the only one that can block an edit while the agent works. They give the same answer every time, which is why a Change Owner can rely on their evidence at the Merge Gate, provided the CI checks that back them are required.