Skip to content

Commit 88c83ca

Browse files
cliffhallclaude
andcommitted
docs: all work in a fresh worktree, with the session started inside it
Widens the modelcontextprotocol#5138 worktree rule from PR branches to all work, and adds the session-start requirement: Claude Code loads AGENTS.md and the skills once, from where the session starts, so a stale checkout means stale rules for the whole run. A SessionStart hook (scripts/session-instructions-check.mjs) checks it at every start. Closes modelcontextprotocol#5167 Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: cliffhall <[email protected]>
1 parent f18beb7 commit 88c83ca

6 files changed

Lines changed: 439 additions & 11 deletions

File tree

‎.claude/settings.json‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
{
2+
"hooks": {
3+
"SessionStart": [
4+
{
5+
"hooks": [
6+
{
7+
"type": "command",
8+
"command": "node \"$CLAUDE_PROJECT_DIR/scripts/session-instructions-check.mjs\"",
9+
"timeout": 30
10+
}
11+
]
12+
}
13+
]
14+
}
15+
}

‎.claude/skills/pr-flow/SKILL.md‎

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -40,12 +40,11 @@ gh issue edit <N> --repo modelcontextprotocol/servers --add-assignee @me
4040
## 2. Branch
4141

4242
`v2/<type>/<N>-<slug>`, cut from **`origin/v2/main`** into a **new git
43-
worktree**, never by switching branches in the primary checkout. Several agent
44-
sessions work this repo on one machine at once and share the primary checkout:
45-
a `git switch` there moves the branch out from under every other session using
46-
it, and carries one task's uncommitted edits, `dist/` output and
47-
`node_modules` into another's. A worktree per issue gives each task its own
48-
tree and leaves the primary checkout alone.
43+
worktree**, never by switching branches in the primary checkout. The rule, and
44+
the check that this session's own instructions are current, is `AGENTS.md`
45+
**Issue-driven work style** (all work in a worktree freshly cut from
46+
`origin/v2/main`). If that check, or the `SessionStart` hook, said `STALE`,
47+
stop here: a fresh branch does not refresh the rules this session loaded.
4948

5049
Run it from the primary checkout. The worktree is a **sibling** directory named
5150
for the checkout plus the issue number (`servers` → `../servers-4810`), never a

‎.claude/skills/release/SKILL.md‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,21 @@ Release whose commit is not on `main`.
1919
environment deployments are a maintainer's acts. So is merging any PR. Prepare,
2020
verify and recommend; do not perform those.
2121

22+
## 0. Check this session's instructions first
23+
24+
A release is the longest-running session and the costliest to get wrong, and
25+
it follows this skill and `AGENTS.md` exactly as they were when the session
26+
started. Before step 1, run the staleness check in `AGENTS.md`
27+
**Issue-driven work style** (all work in a worktree freshly cut from
28+
`origin/v2/main`), whatever the `SessionStart` hook printed: the hook ran when
29+
the session began, and this check runs now.
30+
31+
On `STALE`, or a `STALE` line from the `SessionStart` hook, **stop** and ask
32+
for a session started in a fresh worktree. The v2.0.0 release ran its first
33+
three steps on a `release` skill 447 commits out of date (#5167). Re-run the
34+
check after each preparation PR merges, since `v2/main` moves under the
35+
session.
36+
2237
## The shape
2338

2439
One **release issue**, up to three **preparation PRs** on `v2/main`, one

‎AGENTS.md‎

Lines changed: 40 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -51,11 +51,13 @@ servers/
5151
│ ├── git/ Py mcp-server-git PyPI Git repository operations
5252
│ └── time/ Py mcp-server-time PyPI Time and timezone conversion
5353
├── .claude/skills/ On-demand procedures (see the Skills index above)
54+
├── .claude/settings.json The SessionStart hook that checks this session's instructions are current
5455
├── .changeset/ Pending changesets for the TypeScript servers, and the changesets config
5556
├── scripts/ The pre-push gate (gate-lease, smoke-servers, validate-py, coverage-py, interface-diff), its guards (verify-*),
5657
│ the skills tooling, release tooling (npm-publish-guard, prepare-python-release,
5758
│ pack-and-verify, release-manifest, release-notes), and the issue-filing sweeps
58-
│ (dependency-refresh, dependabot-alerts, sdk-watch)
59+
│ (dependency-refresh, dependabot-alerts, sdk-watch), and the session-start
60+
│ instructions check (session-instructions-check)
5961
├── docs/ Design documents; quality-gate.md is the gate's reference (stages, CI vs local, the lease);
6062
│ contribution-model.md holds the outside-PR backlog plan; ai-software-factory.md is the
6163
│ overview of how the rules, skills, gates and sweeps fit together
@@ -498,13 +500,46 @@ here.
498500
- **`Done` means the work shipped**: its PR merged, or it is a parent whose last
499501
sub-issue closed. A duplicate, won't-fix, not-planned or superseded issue
500502
shipped nothing, so its card is **deleted** rather than moved to Done.
503+
- **All work happens in a git worktree freshly cut from `origin/v2/main`, and
504+
the agent session runs inside it.** Not only PR branches: release
505+
verification, audits, triage, investigation and anything else done in a
506+
checkout. `git fetch origin` first, then `git worktree add` from
507+
`origin/v2/main`: a new branch for PR work, `--detach` for work that
508+
commits nothing. Never work in the primary checkout, which concurrent agent
509+
sessions share, and never in an existing worktree without first confirming
510+
it is at the current `origin/v2/main`.
511+
- **Start the session in that worktree.** Claude Code loads this file and
512+
`.claude/skills/` from the directory the session starts in, once, at
513+
session start; a worktree created later does not change what was loaded.
514+
A session started in a stale checkout follows stale rules for its whole
515+
run, however fresh the branches it cuts are (the v2.0.0 release did,
516+
#5167). A session that finds itself elsewhere checks before doing
517+
anything:
518+
519+
```sh
520+
git fetch origin v2/main
521+
git diff --quiet HEAD...origin/v2/main -- AGENTS.md .claude/ \
522+
|| echo "STALE: instructions differ from origin/v2/main"
523+
```
524+
525+
The three dots compare against where `HEAD` branched from `v2/main`, so
526+
a branch's own edits to the instructions do not read as stale. **If it is
527+
stale, stop and ask for a session started in a fresh worktree**, rather
528+
than continuing on rules you cannot trust.
529+
530+
- The `SessionStart` hook in `.claude/settings.json`
531+
(`scripts/session-instructions-check.mjs`) runs that check at every
532+
session start and prints its verdict into the session, with a note when
533+
the session started in the primary checkout. A `STALE` line from it is
534+
the same stop.
535+
- **A long session re-checks after `v2/main` moves under it**, for
536+
example after its own PRs merge.
501537
- **When work begins**, assign the issue to yourself, set Status to
502538
**In Progress**, and create a branch named
503539
`v2/<type>/<ISSUE_NUMBER>-<slug>` (for example
504-
`v2/fix/4810-filesystem-symlink-escape`) from `origin/v2/main`, **in a new
505-
git worktree**: never by switching branches in the primary checkout, which
506-
concurrent agent sessions share. Remove the worktree once the PR merges or
507-
is closed. The recipe is the `pr-flow` skill (step 2, and step 10 for the
540+
`v2/fix/4810-filesystem-symlink-escape`) from `origin/v2/main`, in a new
541+
worktree under the rule above. Remove the worktree once the PR merges or is
542+
closed. The recipe is the `pr-flow` skill (step 2, and step 10 for the
508543
removal).
509544
- **When work is complete**, run the checks under
510545
[Before pushing](#before-pushing), open a PR against `v2/main` labeled `v2`
Lines changed: 157 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,157 @@
1+
#!/usr/bin/env node
2+
// SessionStart hook: warns an agent session whose instructions are stale, or
3+
// which started in the primary checkout (#5167).
4+
//
5+
// Claude Code loads `AGENTS.md` and `.claude/skills/` from the directory a
6+
// session starts in, once, at session start. A worktree created later does not
7+
// change what was loaded, so a session started in a stale checkout follows
8+
// stale rules for its whole run, however fresh the branches it cuts are. The
9+
// v2.0.0 release session did exactly that (#5159): it started in a primary
10+
// checkout 447 commits behind `origin/v2/main` and ran three steps on a
11+
// superseded `release` skill.
12+
//
13+
// So `.claude/settings.json` runs this at session start. It fetches
14+
// `origin/v2/main` and asks whether `v2/main` has changed the instructions
15+
// since this checkout's HEAD branched from it:
16+
//
17+
// git diff --quiet HEAD...origin/v2/main -- AGENTS.md .claude/
18+
//
19+
// The three dots matter. They diff the merge base against `origin/v2/main`,
20+
// so a branch that edits the instructions itself (a PR like the one that
21+
// added this file) is not reported stale for its own edits, while a checkout
22+
// that lacks any instruction change `v2/main` has made is.
23+
//
24+
// The hook never blocks the session and never fails it: whatever it prints is
25+
// added to the session's context, and the rule in `AGENTS.md` (Issue-driven
26+
// work style) says what the session does about it. A failed fetch (offline, a
27+
// lock held by another session's fetch) is reported, and the check runs
28+
// against the `origin/v2/main` already on disk rather than not at all.
29+
30+
import { spawnSync } from "node:child_process";
31+
import path from "node:path";
32+
import { fileURLToPath, pathToFileURL } from "node:url";
33+
34+
/** The branch whose instructions a session must be running. */
35+
export const BASE = "origin/v2/main";
36+
37+
/** The paths Claude Code loads its instructions from at session start. */
38+
export const INSTRUCTION_PATHS = ["AGENTS.md", ".claude/"];
39+
40+
/** How long the fetch may take before the check falls back to the local ref. */
41+
export const FETCH_TIMEOUT_MS = 15_000;
42+
43+
/** How many changed paths a STALE report names before summarizing the rest. */
44+
export const MAX_NAMED = 5;
45+
46+
/**
47+
* Pure: the lines to print, from what the checks found.
48+
*
49+
* @param {{
50+
* fetched: boolean,
51+
* baseSha: string | null,
52+
* stale: boolean,
53+
* changed: string[],
54+
* primary: boolean,
55+
* }} state
56+
* @returns {string[]}
57+
*/
58+
export function report({ fetched, baseSha, stale, changed, primary }) {
59+
const lines = [];
60+
if (!fetched)
61+
lines.push(
62+
`session-instructions-check: could not fetch ${BASE}; checking against the copy already on disk.`,
63+
);
64+
if (baseSha === null) {
65+
lines.push(
66+
`session-instructions-check: cannot resolve ${BASE}, so whether this session's AGENTS.md and skills are current is UNKNOWN. Run \`git fetch origin v2/main\` and re-check before doing anything.`,
67+
);
68+
} else if (stale) {
69+
const named =
70+
changed.length > MAX_NAMED
71+
? `${changed.slice(0, MAX_NAMED).join(", ")} and ${changed.length - MAX_NAMED} more`
72+
: changed.join(", ");
73+
lines.push(
74+
`STALE: this session's instructions differ from ${BASE} (${baseSha.slice(0, 8)}). ` +
75+
`${BASE} has changed ${named} since this checkout's HEAD branched from it, ` +
76+
"and Claude Code loaded AGENTS.md and the skills from this checkout at session start. " +
77+
"Stop, and ask for a session started in a worktree freshly cut from origin/v2/main " +
78+
"(AGENTS.md, Issue-driven work style), rather than continuing on rules that cannot be trusted.",
79+
);
80+
} else {
81+
lines.push(
82+
`session-instructions-check: AGENTS.md and .claude/ match ${BASE} (${baseSha.slice(0, 8)}).`,
83+
);
84+
}
85+
if (primary)
86+
lines.push(
87+
"session-instructions-check: this session started in the primary checkout, which concurrent " +
88+
"sessions share. Do the work in a git worktree freshly cut from origin/v2/main, never here " +
89+
"(AGENTS.md, Issue-driven work style).",
90+
);
91+
return lines;
92+
}
93+
94+
function git(args, cwd, opts = {}) {
95+
const r = spawnSync("git", args, { cwd, encoding: "utf8", ...opts });
96+
return { status: r.error ? -1 : r.status, stdout: r.stdout ?? "" };
97+
}
98+
99+
/**
100+
* Run the checks in the repository at `cwd`.
101+
*
102+
* @param {{ cwd: string, fetch?: boolean }} opts
103+
* @returns {string[]} the lines to print
104+
*/
105+
export function checkSession({ cwd, fetch = true }) {
106+
const fetched =
107+
!fetch ||
108+
git(["fetch", "--quiet", "origin", "v2/main"], cwd, {
109+
timeout: FETCH_TIMEOUT_MS,
110+
}).status === 0;
111+
const resolved = git(
112+
["rev-parse", "--verify", "--quiet", `${BASE}^{commit}`],
113+
cwd,
114+
);
115+
const baseSha = resolved.status === 0 ? resolved.stdout.trim() : null;
116+
117+
let changed = [];
118+
if (baseSha !== null) {
119+
const diff = git(
120+
["diff", "--name-only", `HEAD...${BASE}`, "--", ...INSTRUCTION_PATHS],
121+
cwd,
122+
);
123+
// No merge base (an unrelated history) also lands here, as a failed
124+
// diff: the instructions cannot be shown current, so they count as stale.
125+
changed =
126+
diff.status === 0
127+
? diff.stdout.split("\n").filter(Boolean)
128+
: ["(no common history with HEAD)"];
129+
}
130+
131+
// In a linked worktree the git dir is `.git/worktrees/<name>`, apart from
132+
// the common dir; in the primary checkout the two are the same.
133+
const dirs = git(
134+
["rev-parse", "--path-format=absolute", "--git-dir", "--git-common-dir"],
135+
cwd,
136+
).stdout.split("\n");
137+
const primary = dirs.length >= 2 && dirs[0] !== "" && dirs[0] === dirs[1];
138+
139+
return report({
140+
fetched,
141+
baseSha,
142+
stale: changed.length > 0,
143+
changed,
144+
primary,
145+
});
146+
}
147+
148+
if (
149+
process.argv[1] &&
150+
import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href
151+
) {
152+
const repoRoot = path.resolve(
153+
path.dirname(fileURLToPath(import.meta.url)),
154+
"..",
155+
);
156+
console.log(checkSession({ cwd: repoRoot }).join("\n"));
157+
}

0 commit comments

Comments
 (0)