Skip to content

Commit 98a6717

Browse files
authored
Merge pull request #5219 from modelcontextprotocol/v2/docs/5167-fresh-worktree-sessions
docs: all work in a fresh worktree, with the session started inside it
2 parents f18beb7 + 69d5326 commit 98a6717

6 files changed

Lines changed: 542 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: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,24 @@ 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, **from the session-start revision, not `HEAD`**: this flow moves
36+
between worktrees (step 4e moves the verification worktree onto a newer
37+
candidate), and a newer worktree's `HEAD` says nothing about the rules this
38+
session loaded. The hook prints that revision and the re-check command.
39+
2240
## The shape
2341

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

‎AGENTS.md‎

Lines changed: 47 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,53 @@ 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; the `:/`
527+
anchors the paths at the repository root, so the check means the same
528+
from any directory. **If it is stale, stop and ask for a session started
529+
in a fresh worktree**, rather than continuing on rules you cannot trust.
530+
531+
- The `SessionStart` hook in `.claude/settings.json`
532+
(`scripts/session-instructions-check.mjs`) runs that check at every
533+
session start and prints its verdict into the session, with a note when
534+
the session started in the primary checkout. A `STALE` line from it is
535+
the same stop.
536+
- **A long session re-checks after `v2/main` moves under it**, for
537+
example after its own PRs merge, **from the revision it started at, not
538+
from `HEAD`**: once the session moves into a newer worktree, that
539+
worktree's `HEAD` can match `origin/v2/main` while the rules the session
540+
holds are still the old ones. The hook prints the session-start revision
541+
and the exact re-check command; without the hook, record
542+
`git rev-parse HEAD` in the starting checkout before anything else, and
543+
put it in place of `HEAD` above.
501544
- **When work begins**, assign the issue to yourself, set Status to
502545
**In Progress**, and create a branch named
503546
`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
547+
`v2/fix/4810-filesystem-symlink-escape`) from `origin/v2/main`, in a new
548+
worktree under the rule above. Remove the worktree once the PR merges or is
549+
closed. The recipe is the `pr-flow` skill (step 2, and step 10 for the
508550
removal).
509551
- **When work is complete**, run the checks under
510552
[Before pushing](#before-pushing), open a PR against `v2/main` labeled `v2`
Lines changed: 192 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,192 @@
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+
/**
38+
* The paths Claude Code loads its instructions from at session start, as
39+
* pathspecs anchored at the repository root (`:/`), so the same check means
40+
* the same thing run from `src/git` as from the root.
41+
*/
42+
export const INSTRUCTION_PATHS = [":/AGENTS.md", ":/.claude/"];
43+
44+
/**
45+
* Pure: the command that re-checks, later in the session, the instructions
46+
* loaded at `startSha`. It names the session-start revision rather than
47+
* `HEAD`: once the session moves into a newer worktree, that worktree's
48+
* `HEAD` can match `origin/v2/main` while the rules the session holds are
49+
* still the ones it started with.
50+
*
51+
* @param {string} startSha
52+
*/
53+
export function recheckCommand(startSha) {
54+
const paths = INSTRUCTION_PATHS.map((p) => `'${p}'`).join(" ");
55+
return `git fetch origin v2/main && git diff --quiet ${startSha}...${BASE} -- ${paths} || echo STALE`;
56+
}
57+
58+
/** How long the fetch may take before the check falls back to the local ref. */
59+
export const FETCH_TIMEOUT_MS = 15_000;
60+
61+
/** How many changed paths a STALE report names before summarizing the rest. */
62+
export const MAX_NAMED = 5;
63+
64+
/**
65+
* Pure: the lines to print, from what the checks found.
66+
*
67+
* @param {{
68+
* fetched: boolean,
69+
* baseSha: string | null,
70+
* startSha: string | null,
71+
* stale: boolean,
72+
* changed: string[],
73+
* primary: boolean,
74+
* }} state
75+
* @returns {string[]}
76+
*/
77+
export function report({
78+
fetched,
79+
baseSha,
80+
startSha,
81+
stale,
82+
changed,
83+
primary,
84+
}) {
85+
const lines = [];
86+
if (!fetched)
87+
lines.push(
88+
`session-instructions-check: could not fetch ${BASE}; checking against the copy already on disk.`,
89+
);
90+
if (baseSha === null) {
91+
lines.push(
92+
`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.`,
93+
);
94+
} else if (stale) {
95+
const named =
96+
changed.length > MAX_NAMED
97+
? `${changed.slice(0, MAX_NAMED).join(", ")} and ${changed.length - MAX_NAMED} more`
98+
: changed.join(", ");
99+
lines.push(
100+
`STALE: this session's instructions differ from ${BASE} (${baseSha.slice(0, 8)}). ` +
101+
`${BASE} has changed ${named} since this checkout's HEAD branched from it, ` +
102+
"and Claude Code loaded AGENTS.md and the skills from this checkout at session start. " +
103+
"Stop, and ask for a session started in a worktree freshly cut from origin/v2/main " +
104+
"(AGENTS.md, Issue-driven work style), rather than continuing on rules that cannot be trusted.",
105+
);
106+
} else {
107+
lines.push(
108+
`session-instructions-check: AGENTS.md and .claude/ match ${BASE} (${baseSha.slice(0, 8)}).`,
109+
);
110+
}
111+
if (!stale && startSha !== null)
112+
lines.push(
113+
`session-instructions-check: this session loaded its instructions at ${startSha}. ` +
114+
"Re-check from that revision, not from HEAD, after v2/main moves or the session changes " +
115+
`checkout: ${recheckCommand(startSha)}`,
116+
);
117+
if (primary)
118+
lines.push(
119+
"session-instructions-check: this session started in the primary checkout, which concurrent " +
120+
"sessions share. Do the work in a git worktree freshly cut from origin/v2/main, never here " +
121+
"(AGENTS.md, Issue-driven work style).",
122+
);
123+
return lines;
124+
}
125+
126+
function git(args, cwd, opts = {}) {
127+
const r = spawnSync("git", args, { cwd, encoding: "utf8", ...opts });
128+
return { status: r.error ? -1 : r.status, stdout: r.stdout ?? "" };
129+
}
130+
131+
/**
132+
* Run the checks in the repository at `cwd`.
133+
*
134+
* @param {{ cwd: string, fetch?: boolean }} opts
135+
* @returns {string[]} the lines to print
136+
*/
137+
export function checkSession({ cwd, fetch = true }) {
138+
const fetched =
139+
!fetch ||
140+
git(["fetch", "--quiet", "origin", "v2/main"], cwd, {
141+
timeout: FETCH_TIMEOUT_MS,
142+
}).status === 0;
143+
const resolved = git(
144+
["rev-parse", "--verify", "--quiet", `${BASE}^{commit}`],
145+
cwd,
146+
);
147+
const baseSha = resolved.status === 0 ? resolved.stdout.trim() : null;
148+
const head = git(["rev-parse", "--verify", "--quiet", "HEAD"], cwd);
149+
const startSha = head.status === 0 ? head.stdout.trim() : null;
150+
151+
let changed = [];
152+
if (baseSha !== null) {
153+
const diff = git(
154+
["diff", "--name-only", `HEAD...${BASE}`, "--", ...INSTRUCTION_PATHS],
155+
cwd,
156+
);
157+
// No merge base (an unrelated history) also lands here, as a failed
158+
// diff: the instructions cannot be shown current, so they count as stale.
159+
changed =
160+
diff.status === 0
161+
? diff.stdout.split("\n").filter(Boolean)
162+
: ["(no common history with HEAD)"];
163+
}
164+
165+
// In a linked worktree the git dir is `.git/worktrees/<name>`, apart from
166+
// the common dir; in the primary checkout the two are the same.
167+
const dirs = git(
168+
["rev-parse", "--path-format=absolute", "--git-dir", "--git-common-dir"],
169+
cwd,
170+
).stdout.split("\n");
171+
const primary = dirs.length >= 2 && dirs[0] !== "" && dirs[0] === dirs[1];
172+
173+
return report({
174+
fetched,
175+
baseSha,
176+
startSha,
177+
stale: changed.length > 0,
178+
changed,
179+
primary,
180+
});
181+
}
182+
183+
if (
184+
process.argv[1] &&
185+
import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href
186+
) {
187+
const repoRoot = path.resolve(
188+
path.dirname(fileURLToPath(import.meta.url)),
189+
"..",
190+
);
191+
console.log(checkSession({ cwd: repoRoot }).join("\n"));
192+
}

0 commit comments

Comments
 (0)