@warren-dean/code-kit 0.31.1 → 0.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,159 @@
1
+ // LEAN-10: one worktree per lane, reused by each story the lane builds, with its installs. Claude Code makes
2
+ // a worktree for every agent it starts with `isolation: "worktree"`, and a project's installs in each are
3
+ // gigabytes; a lane runs one story at a time (SCHED-1), so one worktree per lane is enough. code-kit's
4
+ // WorktreeCreate hook gives a lane agent its lane's worktree instead of a new one. The hook is told only
5
+ // the worktree's name, not whose it is, so guard-agent notes the lane as the agent starts (PreToolUse),
6
+ // and the hook takes the note: one lane agent starts at a time, so the note is never another's.
7
+ import { spawnSync } from 'node:child_process';
8
+ import {
9
+ closeSync,
10
+ existsSync,
11
+ mkdirSync,
12
+ openSync,
13
+ readFileSync,
14
+ realpathSync,
15
+ rmSync,
16
+ writeFileSync,
17
+ } from 'node:fs';
18
+ import { dirname, join } from 'node:path';
19
+ import { matchesAny } from './glob.mjs';
20
+ import { WORKTREES_DIR, keepAsPatch } from './worktrees.mjs';
21
+
22
+ /** The lane whose agent starts next, noted by guard-agent for the WorktreeCreate hook. */
23
+ export const NEXT_FILE = '.claude/state/lane-worktree-next.json';
24
+ /** How long a note waits for its worktree: Claude Code makes it within a second or two of the call. */
25
+ export const NEXT_MS = 20_000;
26
+
27
+ const git = (cwd, ...args) => spawnSync('git', ['-C', cwd, ...args], { encoding: 'utf8' });
28
+ const real = (p) => {
29
+ try {
30
+ return realpathSync(p);
31
+ } catch {
32
+ return p;
33
+ }
34
+ };
35
+
36
+ /** The project's main checkout, from any folder in it or its worktrees. */
37
+ export function mainCheckout(dir) {
38
+ const common = git(dir, 'rev-parse', '--path-format=absolute', '--git-common-dir');
39
+ return common.status === 0 ? dirname(common.stdout.trim()) : null;
40
+ }
41
+
42
+ /** A lane's worktree: `.claude/worktrees/lane-<lane>` in the main checkout. */
43
+ export const laneTreePath = (main, lane) => join(main, WORKTREES_DIR, `lane-${lane}`);
44
+
45
+ /** The note, while it's fresh: { lane, story, at }, or null. */
46
+ export function nextLane(main, now = Date.now()) {
47
+ try {
48
+ const n = JSON.parse(readFileSync(join(main, NEXT_FILE), 'utf8'));
49
+ return now - Date.parse(n.at) < NEXT_MS ? n : null;
50
+ } catch {
51
+ return null;
52
+ }
53
+ }
54
+
55
+ /**
56
+ * Notes the lane whose agent starts next, unless another agent's note is still waiting for its worktree:
57
+ * true when noted. Made only where there's none, so of two agents started at once only one is noted.
58
+ */
59
+ export function noteNextLane(main, { lane, story }, now = Date.now()) {
60
+ const file = join(main, NEXT_FILE);
61
+ mkdirSync(dirname(file), { recursive: true });
62
+ for (let tries = 0; tries < 2; tries++) {
63
+ try {
64
+ const fd = openSync(file, 'wx');
65
+ writeFileSync(fd, JSON.stringify({ lane, story, at: new Date(now).toISOString() }));
66
+ closeSync(fd);
67
+ return true;
68
+ } catch {
69
+ if (nextLane(main, now)) return false;
70
+ rmSync(file, { force: true });
71
+ }
72
+ }
73
+ return false;
74
+ }
75
+
76
+ /** Takes back a note whose agent didn't start. */
77
+ export const dropNextLane = (main) => rmSync(join(main, NEXT_FILE), { force: true });
78
+
79
+ /** Takes the note: the lane whose agent this worktree is for, or null. */
80
+ export function takeNextLane(main, now = Date.now()) {
81
+ const n = nextLane(main, now);
82
+ rmSync(join(main, NEXT_FILE), { force: true });
83
+ return n;
84
+ }
85
+
86
+ const registered = (main, dir) =>
87
+ git(main, 'worktree', 'list', '--porcelain')
88
+ .stdout.split('\n')
89
+ .some((l) => l.startsWith('worktree ') && real(l.slice(9)) === real(dir));
90
+
91
+ /**
92
+ * Copies the files `.worktreeinclude` names (ignored files such as `.env`) from the main checkout into a
93
+ * new worktree, as Claude Code does for the worktrees it makes itself, which a WorktreeCreate hook replaces.
94
+ */
95
+ export function copyIncluded(main, dir) {
96
+ if (!existsSync(join(main, '.worktreeinclude'))) return;
97
+ const files = git(
98
+ main,
99
+ 'ls-files',
100
+ '--others',
101
+ '--ignored',
102
+ '--exclude-from=.worktreeinclude',
103
+ ).stdout.split('\n');
104
+ for (const f of files.filter(Boolean)) {
105
+ if (existsSync(join(dir, f))) continue;
106
+ mkdirSync(dirname(join(dir, f)), { recursive: true });
107
+ writeFileSync(join(dir, f), readFileSync(join(main, f)));
108
+ }
109
+ }
110
+
111
+ /**
112
+ * The lane's worktree, ready for its next agent: made the first time; after that, the same folder with its
113
+ * installs, its last story's records kept as a patch (an adapter's anyActor files, which a tool writes at
114
+ * each turn's end) and put back, and HEAD detached at the main checkout's, so the agent makes or switches
115
+ * to its story's branch as its brief says. Null where the last agent left work uncommitted: the agent then
116
+ * gets a worktree of its own, as before, and the lane's stays as it was.
117
+ */
118
+ export function laneTree(main, lane, config, now = Date.now()) {
119
+ const dir = laneTreePath(main, lane);
120
+ const head = git(main, 'rev-parse', 'HEAD').stdout.trim();
121
+ if (!existsSync(dir) || !registered(main, dir)) {
122
+ rmSync(dir, { recursive: true, force: true });
123
+ git(main, 'worktree', 'prune');
124
+ if (git(main, 'worktree', 'add', '--quiet', '--detach', dir, head).status !== 0) return null;
125
+ copyIncluded(main, dir);
126
+ return dir;
127
+ }
128
+ const status = git(dir, 'status', '--porcelain');
129
+ if (status.status !== 0) return null;
130
+ const lines = status.stdout.split('\n').filter(Boolean);
131
+ const records = (l) =>
132
+ l
133
+ .slice(3)
134
+ .split(' -> ')
135
+ .every((f) => matchesAny(f.replace(/^"|"$/g, ''), config?.anyActor ?? []));
136
+ if (lines.some((l) => !records(l))) return null;
137
+ if (lines.length) {
138
+ const branch = git(dir, 'branch', '--show-current').stdout.trim() || null;
139
+ keepAsPatch(main, { path: dir, branch: branch ?? `lane-${lane}` }, now);
140
+ git(dir, 'reset', '--hard', '--quiet');
141
+ git(dir, 'clean', '-fdq');
142
+ }
143
+ if (git(dir, 'switch', '--quiet', '--detach', head).status !== 0) return null;
144
+ return dir;
145
+ }
146
+
147
+ /**
148
+ * The worktree Claude Code would make itself: `.claude/worktrees/<name>` on a new branch
149
+ * `worktree-<name>`, from the remote's default branch where there is one, else HEAD.
150
+ */
151
+ export function plainTree(main, name) {
152
+ const dir = join(main, WORKTREES_DIR, name);
153
+ const remote = git(main, 'rev-parse', '--verify', '--quiet', 'refs/remotes/origin/HEAD');
154
+ const from = remote.status === 0 ? remote.stdout.trim() : 'HEAD';
155
+ const made = git(main, 'worktree', 'add', '--quiet', '-b', `worktree-${name}`, dir, from);
156
+ if (made.status !== 0) return null;
157
+ copyIncluded(main, dir);
158
+ return dir;
159
+ }
@@ -19,6 +19,7 @@ import { isTestFile } from './testfiles.mjs';
19
19
  import { laneClaims } from './laneclaims.mjs';
20
20
  import { keptBecause, worktrees } from './worktrees.mjs';
21
21
  import { ciFindings } from './ci.mjs';
22
+ import { costReport, infraFiles, money } from './costs.mjs';
22
23
  import { storyModels } from './dispatches.mjs';
23
24
  import { pickPerLane } from './schedule.mjs';
24
25
  import { reconcileAll } from './events.mjs';
@@ -78,6 +79,43 @@ export function readBrief(root, config) {
78
79
  return { path, status: status ?? null, openQuestions: open.map((q) => q.question), open };
79
80
  }
80
81
 
82
+ /**
83
+ * Spec 29: the running budget and the cost register, as next's attention. A project with infrastructure
84
+ * and no budget is asked for one (COST-6); with one, an estimate over it goes to the person with options
85
+ * (COST-5), and the register's other problems are named (COST-3).
86
+ */
87
+ export function costAttention(root, config) {
88
+ const some = (files) => `${files.slice(0, 3).join(', ')}${files.length > 3 ? ', …' : ''}`;
89
+ if (!config.cost) {
90
+ const infra = infraFiles(root);
91
+ return infra.length
92
+ ? [
93
+ `No running budget is set, and the project has infrastructure (${some(infra)}). Ask the person how much a month each environment may cost and the load to plan for; /code-kit:init records it, and the lead then costs what's built in the register.`,
94
+ ]
95
+ : [];
96
+ }
97
+ const report = costReport(root, config);
98
+ const infra = config.cost.paths.length ? infraFiles(root, config.cost.paths) : [];
99
+ if (!report.exists)
100
+ return infra.length
101
+ ? [
102
+ `There is no cost register (${report.file}) for the project's infrastructure (${some(infra)}). Cost it there, a row per paid thing with its monthly estimate and where the price came from; \`code-kit cost\` adds it up against the budget.`,
103
+ ]
104
+ : [];
105
+ const words = [];
106
+ const over = report.environments.filter((e) => e.over > 0);
107
+ if (over.length)
108
+ words.push(
109
+ `The running cost is over the budget: ${over.map((e) => `${e.name} ${money(e.total, config.cost.currency)} a month against ${money(e.budget, config.cost.currency)}`).join(', ')}. Bring the person options that fit (smaller sizes, cheaper tiers or providers, fewer environments, less at launch), each with what it gives up, and let them decide.`,
110
+ );
111
+ const other = report.problems.length - over.length;
112
+ if (other > 0)
113
+ words.push(
114
+ `${report.file} has ${other} problem${other === 1 ? '' : 's'} (\`code-kit cost\` says which): an estimate that isn't a number, a row without where its price came from, or one for an environment the budget doesn't name.`,
115
+ );
116
+ return words;
117
+ }
118
+
81
119
  const hasMarkdown = (dir) => {
82
120
  try {
83
121
  return readdirSync(dir, { recursive: true }).some((f) => String(f).endsWith('.md'));
@@ -196,7 +234,9 @@ export function nextStep(root, base) {
196
234
  attention.push(
197
235
  `${leftovers} worktree${leftovers === 1 ? ' is' : 's are'} done with; \`code-kit worktrees prune\` removes them, keeping their reports.`,
198
236
  );
199
- const holding = trees.filter((w) => w.kind === 'agent' && w.merged && !w.clean && !w.agentAtWork);
237
+ const holding = trees.filter(
238
+ (w) => w.kind === 'agent' && w.merged && w.changes > 0 && !w.agentAtWork,
239
+ );
200
240
  holdingTrees = holding.map((w) => ({
201
241
  branch: w.branch,
202
242
  story: w.story,
@@ -388,6 +428,7 @@ export function nextStep(root, base) {
388
428
  `${ci.length} thing${ci.length === 1 ? '' : 's'} in the project's CI (${files.join(', ')}) ${ci.length === 1 ? 'runs' : 'run'} once per story or without a time limit; \`code-kit ci check\` says what, and the fix for the person to approve.`,
389
429
  );
390
430
  }
431
+ attention.push(...costAttention(root, config));
391
432
  const instructions = instructionsState(root, config);
392
433
  const behind = instructions.filter((f) => ['stale', 'legacy'].includes(f.state));
393
434
  // A file with no code-kit part may be one the project keeps without it: said, not insisted on.
@@ -46,8 +46,10 @@ export function maskQuotes(text) {
46
46
  }
47
47
 
48
48
  const SEPARATOR = /[;&|\n()`]/;
49
+ // A quoted value is taken whole: unquoted, a value stops at a quote, so `CK="node x"` with nothing after it
50
+ // is never read as `CK="node` running `x"`.
49
51
  const LEADING =
50
- /^(?:(?:[A-Za-z_]\w*=(?:"[^"]*"|'[^']*'|\S*)\s+)|(?:sudo|exec|time|command|nohup|env)\s+|!\s+)+/;
52
+ /^(?:(?:[A-Za-z_]\w*=(?:"[^"]*"|'[^']*'|[^\s"']*)\s+)|(?:sudo|exec|time|command|nohup|env)\s+|!\s+)+/;
51
53
 
52
54
  /**
53
55
  * The simple commands `cmd` runs, in order: split at `;`, `&`, `|`, newlines, parentheses and
@@ -162,6 +164,74 @@ function sedPrints(text) {
162
164
  return scripts.length > 0 && scripts.every((s) => SED_PRINTS.test(s));
163
165
  }
164
166
 
167
+ /**
168
+ * Where a command sends its output: each `>` or `>>` redirect's target as written, quotes off (`2>&1`
169
+ * and /dev/null left out), and the command without them. Null for a read-write redirect (`<>`).
170
+ */
171
+ export function outputRedirects(cmd) {
172
+ const text = withoutHarmlessRedirects(cmd);
173
+ const code = maskQuotes(text);
174
+ if (/<>/.test(code)) return null;
175
+ const targets = [];
176
+ let rest = '';
177
+ let at = 0;
178
+ for (const m of code.matchAll(/(?:\d+|&)?>>?\|?\s*/g)) {
179
+ const from = m.index + m[0].length;
180
+ const word = code.slice(from).match(/^[^\s;&|<>()]*/)[0];
181
+ targets.push(text.slice(from, from + word.length).replace(/^(['"])(.*)\1$/s, '$2'));
182
+ rest += `${text.slice(at, m.index)} `;
183
+ at = from + word.length;
184
+ }
185
+ return { targets, rest: rest + text.slice(at) };
186
+ }
187
+
188
+ // One or more sed substitutions (`s/a/b/g`, `s|a|b|`; `;` between them), with no flag that writes a
189
+ // file (`w`) or runs a command (`e`).
190
+ function onlySubstitutes(script) {
191
+ const s = script.trim();
192
+ let i = 0;
193
+ while (i < s.length) {
194
+ const d = s[i + 1];
195
+ if (s[i] !== 's' || !d || /[\s\\]/.test(d)) return false;
196
+ let j = i + 2;
197
+ for (let parts = 0; parts < 2; j++) {
198
+ if (j >= s.length) return false;
199
+ if (s[j] === '\\') j++;
200
+ else if (s[j] === d) parts++;
201
+ }
202
+ j += s.slice(j).match(/^[gIip\d]*\s*/)[0].length;
203
+ if (j < s.length && s[j] !== ';') return false;
204
+ i = j + 1;
205
+ while (s[i] === ' ') i++;
206
+ }
207
+ return s.length > 0;
208
+ }
209
+
210
+ /**
211
+ * The files a `sed -i` edits in place when every script only substitutes (onlySubstitutes), or null
212
+ * for any other sed: `-i`, `-i.bak` and BSD's `-i ''`, with `-e`, `-E` and `-r` beside them.
213
+ */
214
+ export function sedInPlaceFiles(text) {
215
+ if (!/^sed\s/.test(text) || /[`$<>]/.test(maskQuotes(text))) return null;
216
+ const words = wordsOf(text).slice(1);
217
+ const scripts = [];
218
+ const files = [];
219
+ let inPlace = false;
220
+ for (let i = 0; i < words.length; i++) {
221
+ const w = words[i];
222
+ if (w === '-i' || w === '--in-place') {
223
+ inPlace = true;
224
+ if (words[i + 1] === '') i++;
225
+ } else if (/^-i\.?\w*$|^--in-place=/.test(w)) inPlace = true;
226
+ else if (w === '-e' || w === '--expression') scripts.push(words[++i] ?? '');
227
+ else if (/^-[Er]+$/.test(w)) continue;
228
+ else if (w.startsWith('-')) return null;
229
+ else files.push(w);
230
+ }
231
+ if (!scripts.length && files.length) scripts.push(files.shift());
232
+ return inPlace && files.length && scripts.every(onlySubstitutes) ? files : null;
233
+ }
234
+
165
235
  /** Whether an awk command only prints: -F and -v only, and no redirect, pipe, system() or getline. */
166
236
  function awkPrints(text) {
167
237
  const words = wordsOf(text).slice(1);
@@ -234,7 +304,45 @@ export function unreadNames(cmd, pattern) {
234
304
  if (andOr) i++;
235
305
  }
236
306
  }
237
- return parts.filter((p) => pattern.test(p) && !readsOnly(p));
307
+ // The commit hook appends to the log before the command runs: a restore beside a commit could drop that.
308
+ const restores = !runs(
309
+ cmd,
310
+ new RegExp(String.raw`^${GIT}(?:commit|merge|revert|cherry-pick|rebase|am|pull)(?![\w-])`),
311
+ );
312
+ return parts.filter(
313
+ (p) => pattern.test(p) && !readsOnly(p) && !(restores && restoresFromHead(p, pattern)),
314
+ );
315
+ }
316
+
317
+ // git restore's flags that keep its source the last commit (or the index), and change nothing else.
318
+ const RESTORE_FLAG = /^(?:--staged|-S|--worktree|-W|-SW|-WS|--source=HEAD|-q|--quiet|--)$/;
319
+
320
+ /**
321
+ * Whether `part` only puts a file `pattern` names back as the last commit (or the index) has it:
322
+ * `git restore [--staged] [--worktree] <file>` or `git checkout [HEAD] -- <file>`. That can lose only
323
+ * what isn't committed, never what the history holds, as after `git revert --no-commit` took a file's
324
+ * committed lines out.
325
+ */
326
+ export function restoresFromHead(part, pattern) {
327
+ const pieces = commandsOf(part);
328
+ if (pieces.length !== 1 || /[|<>`$]/.test(codeOf(part))) return false;
329
+ const words = wordsOf(pieces[0].text);
330
+ if (words[0] !== 'git' || words.length < 3) return false;
331
+ const file = words.at(-1);
332
+ if (!pattern.test(file) || /[*?[]/.test(file)) return false;
333
+ const flags = words.slice(2, -1);
334
+ if (words[1] === 'restore') {
335
+ for (let i = 0; i < flags.length; i++) {
336
+ if ((flags[i] === '-s' || flags[i] === '--source') && flags[i + 1] === 'HEAD') i++;
337
+ else if (!RESTORE_FLAG.test(flags[i])) return false;
338
+ }
339
+ return true;
340
+ }
341
+ if (words[1] === 'checkout')
342
+ return (
343
+ flags.join(' ') === '--' || flags.join(' ') === 'HEAD --' || flags.join(' ') === '-q HEAD --'
344
+ );
345
+ return false;
238
346
  }
239
347
 
240
348
  // What may come before a command it runs: a package runner (`npx`, `pnpm exec`, `uv run`…) or a wrapper
@@ -7,6 +7,7 @@ import { join } from 'node:path';
7
7
  import { BASELINE_FILE, loadBaseline, newProblems } from './baseline.mjs';
8
8
  import { runChecks } from './checks.mjs';
9
9
  import { CONFIG_FILE } from './config.mjs';
10
+ import { COST_APPROVAL, overBudget, overWords, registerFile } from './costs.mjs';
10
11
  import { isDependencyFile } from './dependencies.mjs';
11
12
  import { entryProblems, freshEntries, readRegister, statesWithoutEvidence } from './designs.mjs';
12
13
  import { evidenceRecords } from './reviews.mjs';
@@ -117,7 +118,9 @@ function logEntries(root, base) {
117
118
  if (added === null)
118
119
  return {
119
120
  entries: [],
120
- problems: [`${APPROVAL_LOG} was edited, not appended to; it is append-only.`],
121
+ problems: [
122
+ `${APPROVAL_LOG} was edited, not appended to; it is append-only. An entry it has where the branch left the base is gone or changed, as a \`git revert\` of a commit that logged approvals leaves it. Take that commit out of the branch and make it again without the log's change: \`git revert --no-commit <commit>\`, then \`git restore --staged --worktree ${APPROVAL_LOG}\`, then commit.`,
123
+ ],
121
124
  };
122
125
  const entries = [];
123
126
  const problems = [];
@@ -237,6 +240,7 @@ export function verifyBranch({
237
240
  tests: [],
238
241
  regression: [],
239
242
  standards: [],
243
+ cost: [],
240
244
  checks: [],
241
245
  };
242
246
  const { entries, problems: logProblems } = logEntries(root, from);
@@ -402,6 +406,29 @@ export function verifyBranch({
402
406
  );
403
407
  }
404
408
 
409
+ // COST-4: a branch that changes the infrastructure says in the register what that costs. COST-5: one
410
+ // that takes an environment past its budget carries the person's cost approval, which the commit logs.
411
+ if (config.cost) {
412
+ const register = registerFile(config);
413
+ const infra = changed.filter((f) => matchesAny(f, config.cost.paths));
414
+ if (infra.length && !changed.includes(register))
415
+ found.cost.push(
416
+ `${infra.slice(0, 3).join(', ')}${infra.length > 3 ? `, and ${infra.length - 3} more,` : ''} changed the infrastructure, but ${register} didn't change. Say there what the change costs a month: a new or changed row for each paid thing it adds or resizes, or a Basis saying why the cost didn't move.`,
417
+ );
418
+ if (changed.includes(register)) {
419
+ const over = overBudget(
420
+ showAt(root, from, register),
421
+ showAt(root, 'HEAD', register),
422
+ config.cost,
423
+ );
424
+ const approved = entries.some((e) => e.file === register && e.approval === COST_APPROVAL);
425
+ if (over.length && !approved)
426
+ found.cost.push(
427
+ `${register}: ${overWords(over, config.cost.currency)}. Going past the budget is the person's call: bring them options that fit, each with what it gives up, and the cost of this one; their cost approval is recorded in ${APPROVAL_LOG} by the commit.`,
428
+ );
429
+ }
430
+ }
431
+
405
432
  // REG-1: a fix's tests fail without it, as the bug.
406
433
  const fix = fixes ? fixOf(root, branch ?? currentBranchOf(root), config) : null;
407
434
  if (fix) found.regression.push(...proveFix({ root, from, base, changed, config, fix }));
@@ -19,15 +19,20 @@ import {
19
19
  } from 'node:fs';
20
20
  import { tmpdir } from 'node:os';
21
21
  import { basename, dirname, join } from 'node:path';
22
- import { pruneLogs, readEvents } from './events.mjs';
22
+ import { pruneLogs, readEvents, stopped } from './events.mjs';
23
+ import { sessions } from './sessions.mjs';
23
24
  import { laneClaims } from './laneclaims.mjs';
24
25
  import { storyOfBranch } from './teamfacts.mjs';
26
+ import { CHECKOUTS_DIR } from './checkout.mjs';
27
+ import { matchesAny } from './glob.mjs';
25
28
 
26
29
  export const WORKTREES_DIR = '.claude/worktrees';
27
30
  export const DISCARDED_DIR = '.claude/state/discarded';
28
31
  /** A temporary merge checkout this old belongs to a merge that didn't finish. */
29
32
  export const TEMP_MERGE_MS = 30 * 60_000;
30
33
  const TEMP_MERGE = /^code-kit-merge-/;
34
+ // A temporary checkout made beside the kept ones while another run holds the kept one.
35
+ const TEMP_CHECKOUT = /^code-kit-(merge|fix)-/;
31
36
 
32
37
  const git = (cwd, ...args) => spawnSync('git', ['-C', cwd, ...args], { encoding: 'utf8' });
33
38
  const real = (p) => {
@@ -109,10 +114,16 @@ export function worktrees(root, config, now = Date.now(), cwd = cwdNow()) {
109
114
  const where = real(path);
110
115
  const here = Boolean(cwd && (cwd === where || cwd.startsWith(`${where}/`)));
111
116
  const kind = where.startsWith(`${agents}/`)
112
- ? 'agent'
113
- : where.startsWith(`${temp}/`) && TEMP_MERGE.test(basename(path))
114
- ? 'merge'
115
- : 'other';
117
+ ? // LEAN-10: a lane's own worktree, reused by each of its stories (lanetrees.mjs).
118
+ /^lane-/.test(basename(path))
119
+ ? 'lane'
120
+ : 'agent'
121
+ : // MQ-9: code-kit's kept checkout, reused by each merge with its installs.
122
+ where.startsWith(`${real(CHECKOUTS_DIR)}/`) && !TEMP_CHECKOUT.test(basename(path))
123
+ ? 'kept'
124
+ : where.startsWith(`${temp}/`) && TEMP_MERGE.test(basename(path))
125
+ ? 'merge'
126
+ : 'other';
116
127
  const story = branch ? storyOfBranch(branch) : null;
117
128
  const merged = Boolean(
118
129
  branch &&
@@ -126,8 +137,16 @@ export function worktrees(root, config, now = Date.now(), cwd = cwdNow()) {
126
137
  // Read only where it decides anything: an unmerged worktree stays whatever it holds.
127
138
  const status =
128
139
  missing || (!merged && kind !== 'other') ? null : git(path, 'status', '--porcelain');
129
- const changes =
130
- status?.status === 0 ? status.stdout.split('\n').filter(Boolean).length : null;
140
+ // LEAN-9: a tool's own records (an adapter's anyActor files, written at each turn's end) are no
141
+ // one's work in progress: they're kept as a patch when the worktree goes, and don't keep it.
142
+ const lines = status?.status === 0 ? status.stdout.split('\n').filter(Boolean) : null;
143
+ const recordsOnly = (l) =>
144
+ l
145
+ .slice(3)
146
+ .split(' -> ')
147
+ .every((f) => matchesAny(f.replace(/^"|"$/g, ''), config?.anyActor ?? []));
148
+ const changes = lines ? lines.filter((l) => !recordsOnly(l)).length : null;
149
+ const records = lines ? lines.filter(recordsOnly).length : 0;
131
150
  const lane = branch?.includes('/') ? branch.split('/')[0] : null;
132
151
  const report = branch ? `.claude/state/reports/${branch.replace(/[^\w.-]+/g, '_')}.md` : null;
133
152
  return {
@@ -137,8 +156,9 @@ export function worktrees(root, config, now = Date.now(), cwd = cwdNow()) {
137
156
  kind,
138
157
  missing,
139
158
  merged,
140
- clean: changes === null ? null : changes === 0,
159
+ clean: changes === null ? null : changes === 0 && records === 0,
141
160
  changes,
161
+ records,
142
162
  // What it holds, as git status words it: the first ten.
143
163
  files: status?.status === 0 ? status.stdout.split('\n').filter(Boolean).slice(0, 10) : [],
144
164
  report: report && !missing && existsSync(join(path, report)) ? report : null,
@@ -160,18 +180,30 @@ export const BUSY_MS = 3 * 60_000;
160
180
 
161
181
  /**
162
182
  * LEAN-6: whether a lane agent is still at work on a worktree's story, by the story's event log (spec
163
- * 26): its lane's last act is still open, or came within BUSY_MS, with no hand-back or stop after it. Releasing
183
+ * 26): its lane's last act is still open (and its agent hasn't stopped), or came within BUSY_MS, with no
184
+ * hand-back or stop after it. Releasing
164
185
  * a worktree under a running agent takes its git away mid-step. Only the branch's own lane counts: the
165
186
  * lead's helpers (a reviewer, a security reviewer) act on the story too, but never commit on its branch.
166
187
  */
167
- export function agentBusy(root, w, now = Date.now()) {
188
+ export function agentBusy(root, w, config = {}, now = Date.now()) {
168
189
  if (!w.story || !w.branch?.includes('/')) return false;
169
190
  const lane = w.branch.split('/')[0];
170
- const last = readEvents(root, w.story)
171
- .filter((e) => e.actor === lane && e.agent)
172
- .at(-1);
191
+ const events = readEvents(root, w.story);
192
+ const last = events.filter((e) => e.actor === lane && e.agent).at(-1);
173
193
  if (!last || ['handback', 'stopped'].includes(last.kind)) return false;
174
- return last.phase === 'start' || now - Date.parse(last.at) < BUSY_MS;
194
+ if (last.phase !== 'start') return now - Date.parse(last.at) < BUSY_MS;
195
+ // An act still open: its agent is at work, unless it was stopped mid-call and the act left open for good.
196
+ // That's settled as reconcile settles it: code-kit reconciled the act, or its session ended, it handed
197
+ // back, or it's older than the stall restart (DUR-4, LOOP-3).
198
+ if (last.act && events.some((e) => e.kind === 'reconciled' && e.target === last.act))
199
+ return false;
200
+ const liveSessions = new Set(
201
+ sessions(root, now)
202
+ .filter((s) => s.live)
203
+ .map((s) => s.id),
204
+ );
205
+ const restartMs = (config.harness?.stall?.restartMinutes ?? 10) * 60_000;
206
+ return !stopped(last, events, { liveSessions, restartMs, now });
175
207
  }
176
208
 
177
209
  /** Whether a worktree holds nothing uncommitted, read now where worktrees() didn't. */
@@ -186,6 +218,10 @@ export function cleanOf(w) {
186
218
  export function keptBecause(w) {
187
219
  if (w.missing) return null;
188
220
  if (w.kind === 'merge') return w.age < TEMP_MERGE_MS ? 'a merge may be using it now' : null;
221
+ if (w.kind === 'lane')
222
+ return `it's the ${basename(w.path).slice(5)} lane's worktree, kept with its installs for the lane's next story`;
223
+ if (w.kind === 'kept')
224
+ return "it's code-kit's own checkout for merges and fix checks, kept with its installs so each one doesn't copy them again";
189
225
  if (w.kind === 'other') return "it isn't one code-kit made; release it by name if it's done";
190
226
  // A merge run from inside a lane's worktree mustn't take away the folder its own shell is in.
191
227
  if (w.here)
@@ -195,7 +231,7 @@ export function keptBecause(w) {
195
231
  if (!w.branch) return 'it has no branch checked out';
196
232
  if (!w.merged) return "its branch isn't merged";
197
233
  if (w.agentAtWork) return "its lane's agent is still at work on it";
198
- if (!w.clean)
234
+ if (!w.clean && w.changes > 0)
199
235
  return `it's merged, but holds ${w.changes} uncommitted change${w.changes === 1 ? '' : 's'}`;
200
236
  return null;
201
237
  }
@@ -237,6 +273,12 @@ function keepReport(root, w) {
237
273
  */
238
274
  export function removeWorktree(root, w, { force = false } = {}) {
239
275
  if (w.missing) return { ok: true };
276
+ // LEAN-10: a lane's worktree stays for its next story: it only lets go of the branch.
277
+ if (w.kind === 'lane') {
278
+ keepReport(root, w);
279
+ const freed = git(w.path, 'switch', '--quiet', '--detach');
280
+ return freed.status === 0 ? { ok: true } : { ok: false, why: freed.stderr.trim() };
281
+ }
240
282
  keepReport(root, w);
241
283
  const locked = Boolean(w.locked);
242
284
  const args = [
@@ -261,6 +303,16 @@ export function pruneWorktrees(root, config, now = Date.now()) {
261
303
  for (const w of list) {
262
304
  const label = w.branch ?? w.path;
263
305
  const why = keptBecause(w);
306
+ // LEAN-10: a lane's worktree stays; once its story is merged and it holds nothing, it lets go of the
307
+ // branch, so the branch can be checked out elsewhere and the lane's next agent starts clean.
308
+ if (w.kind === 'lane' && w.branch && w.merged && w.changes === 0 && !w.agentAtWork && !w.here) {
309
+ if (w.records > 0) {
310
+ keepAsPatch(root, w, now);
311
+ git(w.path, 'reset', '--hard', '--quiet');
312
+ }
313
+ keepReport(root, w);
314
+ git(w.path, 'switch', '--quiet', '--detach');
315
+ }
264
316
  if (why) {
265
317
  kept.push({
266
318
  label,
@@ -274,8 +326,13 @@ export function pruneWorktrees(root, config, now = Date.now()) {
274
326
  continue;
275
327
  }
276
328
  if (w.missing) continue;
277
- const r = removeWorktree(root, w, { force: w.kind === 'merge' });
278
- if (r.ok) removed.push(`${label}${w.report ? ` (its report kept at ${w.report})` : ''}`);
329
+ // LEAN-9: a tool's records it holds are kept as a patch first, as a discard keeps what it held.
330
+ const patch = w.records > 0 ? keepAsPatch(root, w, now) : null;
331
+ const r = removeWorktree(root, w, { force: w.kind === 'merge' || Boolean(patch) });
332
+ if (r.ok)
333
+ removed.push(
334
+ `${label}${w.report ? ` (its report kept at ${w.report})` : ''}${patch ? ` (the tool records it held kept as ${patch})` : ''}`,
335
+ );
279
336
  else
280
337
  kept.push({
281
338
  label,
@@ -298,6 +355,22 @@ export function pruneWorktrees(root, config, now = Date.now()) {
298
355
  return { removed, kept };
299
356
  }
300
357
 
358
+ /** What a worktree holds uncommitted, kept as a patch under .claude/state/discarded: its path there. */
359
+ export function keepAsPatch(root, w, now) {
360
+ git(w.path, 'add', '-A');
361
+ const diff = spawnSync('git', ['-C', w.path, 'diff', '--cached', '--binary', 'HEAD'], {
362
+ encoding: 'utf8',
363
+ maxBuffer: 256 * 1024 * 1024,
364
+ });
365
+ const patch = join(
366
+ DISCARDED_DIR,
367
+ `${(w.branch ?? basename(w.path)).replace(/[^\w.-]+/g, '_')}-${new Date(now).toISOString().replace(/[:.]/g, '-')}.patch`,
368
+ );
369
+ mkdirSync(join(root, DISCARDED_DIR), { recursive: true });
370
+ writeFileSync(join(root, patch), diff.stdout ?? '');
371
+ return patch;
372
+ }
373
+
301
374
  /**
302
375
  * LEAN-8: the person discards a merged worktree that still holds changes. What it held is kept first,
303
376
  * as a patch under .claude/state/discarded, with the files nobody had added; then it goes.
@@ -315,20 +388,7 @@ export function discardWorktree(root, config, branch, now = Date.now()) {
315
388
  ok: false,
316
389
  why: `The ${branch.split('/')[0]} lane's agent is still at work on ${branch}.`,
317
390
  };
318
- let patch = null;
319
- if (!w.clean) {
320
- git(w.path, 'add', '-A');
321
- const diff = spawnSync('git', ['-C', w.path, 'diff', '--cached', '--binary', 'HEAD'], {
322
- encoding: 'utf8',
323
- maxBuffer: 256 * 1024 * 1024,
324
- });
325
- patch = join(
326
- DISCARDED_DIR,
327
- `${branch.replace(/[^\w.-]+/g, '_')}-${new Date(now).toISOString().replace(/[:.]/g, '-')}.patch`,
328
- );
329
- mkdirSync(join(root, DISCARDED_DIR), { recursive: true });
330
- writeFileSync(join(root, patch), diff.stdout ?? '');
331
- }
391
+ const patch = w.clean ? null : keepAsPatch(root, w, now);
332
392
  const r = removeWorktree(root, w, { force: true });
333
393
  if (!r.ok) return { ok: false, why: `git wouldn't remove it: ${r.why.split('\n')[0]}` };
334
394
  return { ok: true, patch, report: w.report };