@warren-dean/code-kit 0.22.0 → 0.23.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.
@@ -388,7 +388,11 @@ function requestRecords(root) {
388
388
  export const readRequests = (root) => requestRecords(root).filter((r) => !r.drop);
389
389
 
390
390
  /** CARD-7: whether a request was dropped (the person dismissed it, or the lead said it's no longer needed). */
391
- const droppedIn = (drops, r) => drops.some((d) => d.of === r.at && sameRequest(d, r));
391
+ // A drop written before drops carried the request's session (code-kit issue #78) matches it whatever its session.
392
+ const droppedIn = (drops, r) =>
393
+ drops.some(
394
+ (d) => d.of === r.at && sameRequest('session' in d ? d : { ...d, session: r.session }, r),
395
+ );
392
396
 
393
397
  /**
394
398
  * CARD-7: drops open requests: `which` is a request's number in `openRequests`' order (1 is the
@@ -409,7 +413,7 @@ export function dropRequests(root, which, { by, reason = null }, now = Date.now(
409
413
  for (const r of picked)
410
414
  appendFileSync(
411
415
  file,
412
- `${JSON.stringify({ drop: true, of: r.at, actor: r.actor, names: r.names, what: r.what, by, reason, at: new Date(now).toISOString() })}\n`,
416
+ `${JSON.stringify({ drop: true, of: r.at, actor: r.actor, session: r.session ?? null, names: r.names, what: r.what, by, reason, at: new Date(now).toISOString() })}\n`,
413
417
  );
414
418
  return { ok: true, dropped: picked };
415
419
  }
@@ -849,8 +853,12 @@ function specCheckProblem(rel, root) {
849
853
  return null; // not a git worktree: nothing to key the report on
850
854
  }
851
855
  if (rel === report) return null;
852
- const file = join(root, report);
853
- if (existsSync(file) && /\|\s*Requirement\s*\|/i.test(readFileSync(file, 'utf8'))) return null;
856
+ // In the worktree, or in the main checkout, where it's kept when a worktree goes (#55).
857
+ const read = (dir) => {
858
+ const file = join(dir, report);
859
+ return existsSync(file) && /\|\s*Requirement\s*\|/i.test(readFileSync(file, 'utf8'));
860
+ };
861
+ if (read(root) || read(projectWorktrees(root)[0] ?? root)) return null;
854
862
  return `Run the spec-check skill before writing code on this branch. Save its report (the requirement table, questions and recommendation) to ${report}, then continue.`;
855
863
  }
856
864
 
@@ -164,6 +164,27 @@ function currentBranchOf(root) {
164
164
  }
165
165
  }
166
166
 
167
+ // The runtime's own noise, which says nothing about whether the check passed (#57).
168
+ const NOISE = [
169
+ /^\(node:\d+\) \[?\w*\]? ?(DeprecationWarning|ExperimentalWarning|Warning)\b/,
170
+ /^\(Use `node --trace-(deprecation|warnings) /,
171
+ /^\s*$/,
172
+ ];
173
+ const FAILING = /\b(fail(ed|ing|s)?|error|✗|✘|×|expected|received|assert|panic|traceback)\b/i;
174
+
175
+ /**
176
+ * What a failed check printed, as the lead needs it (#57): the runtime's warnings left out, the lines
177
+ * that name a failure first (up to 20), then the last 20 lines.
178
+ */
179
+ export function failureOutput(output) {
180
+ const lines = String(output ?? '')
181
+ .split('\n')
182
+ .filter((l) => !NOISE.some((re) => re.test(l)));
183
+ const tail = lines.slice(-20);
184
+ const named = lines.filter((l) => FAILING.test(l) && !tail.includes(l)).slice(0, 20);
185
+ return [...named, ...(named.length ? ['…'] : []), ...tail].join('\n');
186
+ }
187
+
167
188
  /**
168
189
  * The files changed, every problem with the branch, grouped as { ownership, protected, layers,
169
190
  * baseline, design, tests, regression, standards, checks }, and the checks `skipped` because a tool isn't
@@ -301,6 +322,7 @@ export function verifyBranch({
301
322
  if (fix) found.regression.push(...proveFix({ root, from, base, changed, config, fix }));
302
323
 
303
324
  let skipped = [];
325
+ let unfinished = false;
304
326
  if (checks) {
305
327
  const actor = lane
306
328
  ? { kind: 'lane', lane, label: `${lane} lane branch` }
@@ -308,13 +330,10 @@ export function verifyBranch({
308
330
  const ran = runChecks(config, changed, root, actor);
309
331
  skipped = ran.skipped;
310
332
  const { failure } = ran;
311
- if (failure)
312
- found.checks.push(
313
- `${failure.title}\n${String(failure.output ?? '')
314
- .split('\n')
315
- .slice(-40)
316
- .join('\n')}`.trim(),
317
- );
333
+ if (failure) {
334
+ found.checks.push(`${failure.title}\n${failureOutput(failure.output)}`.trim());
335
+ unfinished = Boolean(failure.timedOut);
336
+ }
318
337
  }
319
- return { changed, found, skipped };
338
+ return { changed, found, skipped, unfinished };
320
339
  }
@@ -0,0 +1,286 @@
1
+ // The project's worktrees, and taking away the ones that are done (docs/specs/20-lean-lead.md, LEAN-6 and
2
+ // LEAN-8). Every lane agent works in a worktree of its own, each with its own install, so a project that
3
+ // merges a few stories a day gains a gigabyte or more of checkouts a day unless they go as their work
4
+ // merges. A worktree goes once its branch's own commits are merged and it holds nothing uncommitted, and
5
+ // no agent is still at work in it; one that's merged but still holds changes is the person's to decide,
6
+ // and what it held is kept as a patch. code-kit's own leftovers go too: a temporary merge checkout an
7
+ // interrupted merge left, a worktree whose folder is gone, and folders under .claude/worktrees git no
8
+ // longer knows.
9
+ import { spawnSync } from 'node:child_process';
10
+ import {
11
+ copyFileSync,
12
+ existsSync,
13
+ mkdirSync,
14
+ readdirSync,
15
+ realpathSync,
16
+ rmSync,
17
+ statSync,
18
+ writeFileSync,
19
+ } from 'node:fs';
20
+ import { tmpdir } from 'node:os';
21
+ import { basename, dirname, join } from 'node:path';
22
+ import { laneClaims } from './laneclaims.mjs';
23
+ import { storyOfBranch } from './teamfacts.mjs';
24
+
25
+ export const WORKTREES_DIR = '.claude/worktrees';
26
+ export const DISCARDED_DIR = '.claude/state/discarded';
27
+ /** A temporary merge checkout this old belongs to a merge that didn't finish. */
28
+ export const TEMP_MERGE_MS = 30 * 60_000;
29
+ const TEMP_MERGE = /^code-kit-merge-/;
30
+
31
+ const git = (cwd, ...args) => spawnSync('git', ['-C', cwd, ...args], { encoding: 'utf8' });
32
+ const real = (p) => {
33
+ try {
34
+ return realpathSync(p);
35
+ } catch {
36
+ return p;
37
+ }
38
+ };
39
+ const alive = (pid) => {
40
+ try {
41
+ process.kill(pid, 0);
42
+ return true;
43
+ } catch (e) {
44
+ return e.code === 'EPERM';
45
+ }
46
+ };
47
+
48
+ /** The base branch's ref a worktree's branch is merged into: the first protected branch, or its remote. */
49
+ export function baseRef(root, config) {
50
+ const name = config.branches?.protected?.[0];
51
+ if (!name) return null;
52
+ return (
53
+ [name, `origin/${name}`].find(
54
+ (r) => git(root, 'rev-parse', '--verify', '--quiet', r).status === 0,
55
+ ) ?? null
56
+ );
57
+ }
58
+
59
+ /**
60
+ * Whether the branch has commits of its own: a branch made from the base for an agent just dispatched
61
+ * is contained in the base too, but its work hasn't started, let alone merged (code-kit issue #61).
62
+ */
63
+ function hasOwnCommits(root, branch) {
64
+ const log = git(root, 'reflog', 'show', '--format=%gs', `refs/heads/${branch}`);
65
+ if (log.status !== 0 || !log.stdout.trim()) return true; // no reflog: judged by the base alone
66
+ return log.stdout
67
+ .trim()
68
+ .split('\n')
69
+ .some((l) => !/^branch: Created from /.test(l));
70
+ }
71
+
72
+ /**
73
+ * LEAN-6: each worktree but the main checkout: { path, branch, story, merged, clean, changes, report,
74
+ * kind, missing, locked: { reason, pid, live } | null, agentAtWork }. `kind` is `agent` (under
75
+ * .claude/worktrees), `merge` (a temporary merge checkout) or `other` (one the person made). `clean` and
76
+ * `changes` are null where they weren't read: an unmerged worktree stays whatever it holds (cleanOf reads it).
77
+ */
78
+ export function worktrees(root, config, now = Date.now()) {
79
+ const list = git(root, 'worktree', 'list', '--porcelain');
80
+ if (list.status !== 0) return [];
81
+ const main = list.stdout.split('\n\n')[0];
82
+ const mainPath = /^worktree (.+)$/m.exec(main)?.[1] ?? root;
83
+ const from = baseRef(root, config);
84
+ const claims = laneClaims(mainPath, now).filter((c) => !c.stale);
85
+ const agents = real(join(mainPath, WORKTREES_DIR));
86
+ const temp = real(tmpdir());
87
+ return list.stdout
88
+ .split('\n\n')
89
+ .filter(Boolean)
90
+ .slice(1)
91
+ .map((block) => {
92
+ const path = /^worktree (.+)$/m.exec(block)?.[1];
93
+ const branch = /^branch refs\/heads\/(.+)$/m.exec(block)?.[1] ?? null;
94
+ const lockLine = /^locked(?: (.*))?$/m.exec(block);
95
+ const pid = Number(/\bpid (\d+)/.exec(lockLine?.[1] ?? '')?.[1]) || null;
96
+ const missing = !existsSync(path);
97
+ const where = real(path);
98
+ const kind = where.startsWith(`${agents}/`)
99
+ ? 'agent'
100
+ : where.startsWith(`${temp}/`) && TEMP_MERGE.test(basename(path))
101
+ ? 'merge'
102
+ : 'other';
103
+ const story = branch ? storyOfBranch(branch) : null;
104
+ const merged = Boolean(
105
+ branch &&
106
+ from &&
107
+ spawnSync('git', ['merge-base', '--is-ancestor', branch, from], { cwd: root }).status ===
108
+ 0 &&
109
+ hasOwnCommits(root, branch),
110
+ );
111
+ // Read only where it decides anything: an unmerged worktree stays whatever it holds.
112
+ const status =
113
+ missing || (!merged && kind !== 'other') ? null : git(path, 'status', '--porcelain');
114
+ const changes =
115
+ status?.status === 0 ? status.stdout.split('\n').filter(Boolean).length : null;
116
+ const lane = branch?.includes('/') ? branch.split('/')[0] : null;
117
+ const report = branch ? `.claude/state/reports/${branch.replace(/[^\w.-]+/g, '_')}.md` : null;
118
+ return {
119
+ path,
120
+ branch,
121
+ story,
122
+ kind,
123
+ missing,
124
+ merged,
125
+ clean: changes === null ? null : changes === 0,
126
+ changes,
127
+ // What it holds, as git status words it: the first ten.
128
+ files: status?.status === 0 ? status.stdout.split('\n').filter(Boolean).slice(0, 10) : [],
129
+ report: report && !missing && existsSync(join(path, report)) ? report : null,
130
+ locked: lockLine
131
+ ? { reason: lockLine[1] ?? null, pid, live: pid ? alive(pid) : true }
132
+ : null,
133
+ // A lane's agent still holds its claim on this story: it may yet commit here.
134
+ agentAtWork: Boolean(
135
+ lane && claims.some((c) => c.lane === lane && (c.story ?? null) === (story ?? c.story)),
136
+ ),
137
+ age: missing ? null : now - statSync(path).mtimeMs,
138
+ };
139
+ });
140
+ }
141
+
142
+ /** Whether a worktree holds nothing uncommitted, read now where worktrees() didn't. */
143
+ export function cleanOf(w) {
144
+ if (w.clean !== null) return w.clean;
145
+ if (w.missing) return true;
146
+ const status = git(w.path, 'status', '--porcelain');
147
+ return status.status === 0 && !status.stdout.trim();
148
+ }
149
+
150
+ /** Why a worktree stays, in words, or null when it's done with and can go. */
151
+ export function keptBecause(w) {
152
+ if (w.missing) return null;
153
+ if (w.kind === 'merge') return w.age < TEMP_MERGE_MS ? 'a merge may be using it now' : null;
154
+ if (w.kind === 'other') return "it isn't one code-kit made; release it by name if it's done";
155
+ if (w.locked && !w.locked.pid)
156
+ return `it's locked${w.locked.reason ? ` (${w.locked.reason})` : ''}`;
157
+ if (!w.branch) return 'it has no branch checked out';
158
+ if (!w.merged) return "its branch isn't merged";
159
+ if (w.agentAtWork) return "its lane's agent is still at work on it";
160
+ if (!w.clean)
161
+ return `it's merged, but holds ${w.changes} uncommitted change${w.changes === 1 ? '' : 's'}`;
162
+ return null;
163
+ }
164
+
165
+ /** Folders under .claude/worktrees that no worktree is registered at: what a removal left behind. */
166
+ export function strayFolders(root, list) {
167
+ const dir = join(root, WORKTREES_DIR);
168
+ let names = [];
169
+ try {
170
+ names = readdirSync(dir, { withFileTypes: true })
171
+ .filter((d) => d.isDirectory())
172
+ .map((d) => d.name);
173
+ } catch {
174
+ return [];
175
+ }
176
+ const known = new Set(list.map((w) => real(w.path)));
177
+ return names
178
+ .map((n) => join(dir, n))
179
+ .filter((p) => !known.has(real(p)) && !existsSync(join(p, '.git')));
180
+ }
181
+
182
+ /**
183
+ * A worktree's report moved to the main checkout, so the next agent on its story still reads it, and its
184
+ * spec-check report, so that agent can carry on writing code on the branch (#55).
185
+ */
186
+ function keepReport(root, w) {
187
+ const keep = (rel) => {
188
+ if (!rel || !existsSync(join(w.path, rel))) return;
189
+ mkdirSync(dirname(join(root, rel)), { recursive: true });
190
+ copyFileSync(join(w.path, rel), join(root, rel));
191
+ };
192
+ keep(w.report);
193
+ if (w.branch) keep(`.claude/state/spec-check/${w.branch.replace(/[^\w.-]+/g, '_')}.md`);
194
+ }
195
+
196
+ /**
197
+ * Removes one worktree, its report kept and its branch left. A lock held by Claude Code for an agent
198
+ * that has finished (its lane's claim on the story ended) doesn't keep it: `force` removes it anyway.
199
+ */
200
+ export function removeWorktree(root, w, { force = false } = {}) {
201
+ if (w.missing) return { ok: true };
202
+ keepReport(root, w);
203
+ const locked = Boolean(w.locked);
204
+ const args = [
205
+ 'worktree',
206
+ 'remove',
207
+ ...(force || locked ? ['--force'] : []),
208
+ ...(locked ? ['--force'] : []),
209
+ w.path,
210
+ ];
211
+ const removed = git(root, ...args);
212
+ return removed.status === 0 ? { ok: true } : { ok: false, why: removed.stderr.trim() };
213
+ }
214
+
215
+ /**
216
+ * LEAN-8: takes away every worktree that's done with (keptBecause is null), git's records of worktrees
217
+ * whose folders are gone, and the stray folders. Returns { removed: [label], kept: [{ label, why }] }.
218
+ */
219
+ export function pruneWorktrees(root, config, now = Date.now()) {
220
+ const list = worktrees(root, config, now);
221
+ const removed = [];
222
+ const kept = [];
223
+ for (const w of list) {
224
+ const label = w.branch ?? w.path;
225
+ const why = keptBecause(w);
226
+ if (why) {
227
+ kept.push({ label, why, branch: w.branch, changes: w.changes, kind: w.kind });
228
+ continue;
229
+ }
230
+ if (w.missing) continue;
231
+ const r = removeWorktree(root, w, { force: w.kind === 'merge' });
232
+ if (r.ok) removed.push(`${label}${w.report ? ` (its report kept at ${w.report})` : ''}`);
233
+ else
234
+ kept.push({
235
+ label,
236
+ why: `git wouldn't remove it: ${r.why.split('\n')[0]}`,
237
+ branch: w.branch,
238
+ });
239
+ }
240
+ if (list.some((w) => w.missing)) {
241
+ git(root, 'worktree', 'prune');
242
+ for (const w of list.filter((x) => x.missing))
243
+ removed.push(`${w.branch ?? w.path} (its folder was gone)`);
244
+ }
245
+ for (const p of strayFolders(root, list)) {
246
+ rmSync(p, { recursive: true, force: true });
247
+ removed.push(`${p.slice(root.length + 1)} (left behind, not a worktree)`);
248
+ }
249
+ return { removed, kept };
250
+ }
251
+
252
+ /**
253
+ * LEAN-8: the person discards a merged worktree that still holds changes. What it held is kept first,
254
+ * as a patch under .claude/state/discarded, with the files nobody had added; then it goes.
255
+ */
256
+ export function discardWorktree(root, config, branch, now = Date.now()) {
257
+ const w = worktrees(root, config, now).find((x) => x.branch === branch || x.path === branch);
258
+ if (!w) return { ok: false, why: `No worktree has ${branch} checked out.` };
259
+ if (!w.merged)
260
+ return {
261
+ ok: false,
262
+ why: `${branch} isn't merged, so its worktree is work in progress: release it once it's committed.`,
263
+ };
264
+ if (w.agentAtWork)
265
+ return {
266
+ ok: false,
267
+ why: `The ${branch.split('/')[0]} lane's agent is still at work on ${branch}.`,
268
+ };
269
+ let patch = null;
270
+ if (!w.clean) {
271
+ git(w.path, 'add', '-A');
272
+ const diff = spawnSync('git', ['-C', w.path, 'diff', '--cached', '--binary', 'HEAD'], {
273
+ encoding: 'utf8',
274
+ maxBuffer: 256 * 1024 * 1024,
275
+ });
276
+ patch = join(
277
+ DISCARDED_DIR,
278
+ `${branch.replace(/[^\w.-]+/g, '_')}-${new Date(now).toISOString().replace(/[:.]/g, '-')}.patch`,
279
+ );
280
+ mkdirSync(join(root, DISCARDED_DIR), { recursive: true });
281
+ writeFileSync(join(root, patch), diff.stdout ?? '');
282
+ }
283
+ const r = removeWorktree(root, w, { force: true });
284
+ if (!r.ok) return { ok: false, why: `git wouldn't remove it: ${r.why.split('\n')[0]}` };
285
+ return { ok: true, patch, report: w.report };
286
+ }
@@ -20,6 +20,7 @@ export const DECISION_KINDS = new Set([
20
20
  'question',
21
21
  'brief',
22
22
  'report',
23
+ 'worktree',
23
24
  'waiting',
24
25
  ]);
25
26
 
@@ -56,6 +57,9 @@ const EFFECT = {
56
57
  sendReport:
57
58
  "Files it on code-kit's GitHub under your account (a comment instead, if it's filed already).",
58
59
  discardReport: "It's not sent, and goes.",
60
+ keepWorktree: 'It stays as it is, and comes back next session.',
61
+ discardWorktree:
62
+ 'The worktree goes. What it held is kept as a patch under .claude/state/discarded, to apply again if you need it.',
59
63
  };
60
64
 
61
65
  /**
@@ -89,6 +93,12 @@ function eachDecision(line) {
89
93
  }));
90
94
  if (line.kind === 'report')
91
95
  return (line.reports ?? [line.report]).map((r) => ({ ...line, text: r.title, report: r }));
96
+ if (line.kind === 'worktree')
97
+ return (line.worktrees ?? [line.worktree]).map((w) => ({
98
+ ...line,
99
+ text: `${w.branch} is merged, and its worktree holds uncommitted changes`,
100
+ worktree: w,
101
+ }));
92
102
  return [line];
93
103
  }
94
104
 
@@ -121,6 +131,11 @@ function optionsOf(line) {
121
131
  { id: 'sendReport', label: 'Send' },
122
132
  { id: 'discardReport', label: 'Discard' },
123
133
  ];
134
+ if (line.kind === 'worktree')
135
+ return [
136
+ { id: 'discardWorktree', label: 'Discard' },
137
+ { id: 'keepWorktree', label: 'Keep' },
138
+ ];
124
139
  // LOOP-11: what the lead waits on, read from its reply: its answers, or the person's own words.
125
140
  if (line.kind === 'waiting' && line.waiting.kind === 'person' && line.waiting.question)
126
141
  return [
@@ -148,6 +163,7 @@ const TAG = {
148
163
  question: 'question',
149
164
  brief: 'your brief',
150
165
  report: 'bug report',
166
+ worktree: 'worktree',
151
167
  waiting: 'the lead',
152
168
  };
153
169
 
@@ -195,6 +211,11 @@ function headlineOf(line, story) {
195
211
  };
196
212
  if (line.kind === 'report')
197
213
  return { headline: line.report.title, sub: "drafted by an agent, for code-kit's GitHub" };
214
+ if (line.kind === 'worktree')
215
+ return {
216
+ headline: `${line.worktree.branch}'s worktree still holds ${line.worktree.changes} uncommitted change${line.worktree.changes === 1 ? '' : 's'}`,
217
+ sub: 'its branch is merged',
218
+ };
198
219
  if (line.kind === 'waiting' && line.waiting.question)
199
220
  return { headline: line.waiting.question, sub: 'from the lead, which waits on it' };
200
221
  return { headline: line.text, sub: story ? `${story.id} ${story.title ?? ''}` : '' };
@@ -244,6 +265,8 @@ function whyOf(line, check) {
244
265
  return 'You stopped the lead mid-turn, so the loop leaves the lead to you until you say.';
245
266
  if (line.kind === 'waiting' && line.waiting.kind === 'blocked')
246
267
  return "The lead was asked to take this step and didn't, so the loop won't ask again until you say.";
268
+ if (line.kind === 'worktree')
269
+ return "Its branch is merged, but something in its worktree was changed and never committed. Only you can tell whether that's work or leftovers, and the worktree holds a full install, so it takes disk space until it goes.";
247
270
  if (line.kind === 'report')
248
271
  return "code-kit got in an agent's way. It's sent under your GitHub account to a public repository, so read what it says first.";
249
272
  return null;
@@ -347,7 +370,10 @@ export function decisionCards(lines, context = {}) {
347
370
  (line.question?.blocks ? `${line.question.story} waits on your answer.` : null) ??
348
371
  (line.waiting?.label ? `The loop's last step: ${line.waiting.label}` : null) ??
349
372
  (line.denial ? clip(line.denial.command ?? line.denial.what, 400) : null) ??
350
- (line.report ? line.report.body : null),
373
+ (line.report ? line.report.body : null) ??
374
+ (line.worktree?.files?.length
375
+ ? `${line.worktree.files.join('\n')}${line.worktree.changes > line.worktree.files.length ? `\n… and ${line.worktree.changes - line.worktree.files.length} more` : ''}`
376
+ : null),
351
377
  settled,
352
378
  why: whyOf(line, check),
353
379
  options: optionsOf(line).map((a) => ({
@@ -100,6 +100,8 @@ let reviewing = new Set(); // stories the person asked the lead to review (ACT-3
100
100
  let reviewTurn = null; // 'next' until the lead's review turn starts, then its id
101
101
  let approving = null; // the open Approve… confirmation: { request, reason, error }
102
102
  let result = null; // what the last merge reported
103
+ // REPORT-3: the reports a Send is filing now, off the band and the Decisions tab until it's done.
104
+ const sendingReports = new Set();
103
105
  let notice = null; // why the person's last act failed
104
106
  let teamSince = null; // TEAM-6: since you last looked, as read when the Team pane's tab opened
105
107
  let teamUi = { ...DEFAULT_TEAM_UI }; // TEAM-7: the Team pane's own state
@@ -116,6 +118,7 @@ const present = new Map(); // agent id (or 'main') → its presence for a hosted
116
118
  const held = new Map(); // tool_use_id → a call held for the person (HOLD-2)
117
119
  const denied = new Map(); // tool_use_id → a call Claude Code's own permission check refused (PERM-1)
118
120
  const briefLater = new Set(); // the brief's questions the person put off this session (ASK-4)
121
+ const worktreesKept = new Set(); // merged worktrees the person chose to keep this session (LEAN-8)
119
122
  let answering = null; // the open Answer… box: { kind: 'question' | 'brief', question, id?, path?, text, error }
120
123
  let where = null; // { cli, cwd, interactive }, from session start
121
124
  // The lead loop (spec 05): what it did, and what it waits on.
@@ -325,7 +328,7 @@ export function register(on) {
325
328
  ? ((await json('adapters', '--session', session)) ?? [])
326
329
  : [];
327
330
  // TEAM-7: the team's claims, intents and pull requests, where the project is a team's.
328
- const team = valid && check.team ? await json('team') : null;
331
+ const team = valid && check.team ? await json('team', '--session', session) : null;
329
332
  // ASK-2: the lead's questions waiting for the person; REPORT-3: bug reports waiting to be sent.
330
333
  const questions = !valid
331
334
  ? []
@@ -333,7 +336,9 @@ export function register(on) {
333
336
  ? mine('answer')
334
337
  : ((await json('ask')) ?? []).filter((q) => q.state === 'open');
335
338
  const reports = valid
336
- ? ((await json('report')) ?? []).filter((r) => r.state === 'draft')
339
+ ? ((await json('report')) ?? []).filter(
340
+ (r) => r.state === 'draft' && !sendingReports.has(r.id),
341
+ )
337
342
  : [];
338
343
  // TEAM-12: the plan mirrored onto the team's Project board, at most every 10 minutes, in the
339
344
  // background: a slow GitHub never holds up the band.
@@ -370,6 +375,8 @@ export function register(on) {
370
375
  reports,
371
376
  // ASK-4: the brief's open questions, less those put off this session.
372
377
  brief: (nextStep?.brief ?? []).filter((b) => !briefLater.has(b.question)),
378
+ // LEAN-8: merged worktrees still holding changes, less those kept this session.
379
+ worktrees: (nextStep?.worktrees ?? []).filter((w) => !worktreesKept.has(w.branch)),
373
380
  base: status?.base ?? null,
374
381
  // SESS-3, SESS-4: a working session's band holds its own, and its task.
375
382
  working: role === 'working',
@@ -745,16 +752,55 @@ export function register(on) {
745
752
  },
746
753
  // REPORT-3: the person sends a drafted report to code-kit's GitHub, or discards it.
747
754
  sendReport: async (line) => {
748
- const ran = await $.process.run(['node', cli, 'report', 'send', line.report.id], {
755
+ const { id } = line.report;
756
+ if (sendingReports.has(id)) return;
757
+ sendingReports.add(id);
758
+ await act.reload();
759
+ await $.ui.toast(`Sending ${id} to code-kit's GitHub…`);
760
+ try {
761
+ const ran = await $.process.run(['node', cli, 'report', 'send', id], {
762
+ cwd,
763
+ timeoutMs: 120000,
764
+ });
765
+ const text = `${ran.stdout}${ran.stderr}`.trim();
766
+ if (ran.exitCode === 0) await $.ui.toast(text);
767
+ else {
768
+ result = { ok: false, title: 'Report not sent', text };
769
+ await $.ui.open({ id: RESULT_ID, title: 'Report', focus: true, closeOnEscape: true });
770
+ }
771
+ } finally {
772
+ sendingReports.delete(id);
773
+ await act.reload();
774
+ }
775
+ },
776
+ // LEAN-8: the person keeps a merged worktree that still holds changes, or discards them.
777
+ keepWorktree: (line) => {
778
+ worktreesKept.add(line.worktree.branch);
779
+ model = {
780
+ ...model,
781
+ worktrees: (model.worktrees ?? []).filter((w) => w.branch !== line.worktree.branch),
782
+ };
783
+ $.ui.invalidate('ui.render');
784
+ },
785
+ discardWorktree: async (line) => {
786
+ const { branch } = line.worktree;
787
+ worktreesKept.add(branch);
788
+ model = {
789
+ ...model,
790
+ worktrees: (model.worktrees ?? []).filter((w) => w.branch !== branch),
791
+ };
792
+ $.ui.invalidate('ui.render');
793
+ const ran = await $.process.run(['node', cli, 'worktrees', 'discard', branch], {
749
794
  cwd,
750
795
  timeoutMs: 120000,
751
796
  });
752
- result = {
753
- ok: ran.exitCode === 0,
754
- title: ran.exitCode === 0 ? 'Report sent' : 'Report not sent',
755
- text: `${ran.stdout}${ran.stderr}`.trim(),
756
- };
757
- await $.ui.open({ id: RESULT_ID, title: 'Report', focus: true, closeOnEscape: true });
797
+ const text = `${ran.stdout}${ran.stderr}`.trim();
798
+ if (ran.exitCode === 0) await $.ui.toast(text);
799
+ else {
800
+ worktreesKept.delete(branch);
801
+ result = { ok: false, title: 'Worktree not removed', text };
802
+ await $.ui.open({ id: RESULT_ID, title: 'Worktree', focus: true, closeOnEscape: true });
803
+ }
758
804
  await act.reload();
759
805
  },
760
806
  discardReport: async (line) => {
@@ -1462,6 +1508,11 @@ export function register(on) {
1462
1508
  // LOOP-11: the lead's last reply first: one that waits on the person holds every step.
1463
1509
  await act.hear();
1464
1510
  if (loop.waiting && ['person', 'stopped'].includes(loop.waiting.kind)) return;
1511
+ // #59: a restart or hand-back for a story that has since merged is stale, and goes unasked.
1512
+ const finished = new Set(
1513
+ (model.state?.stories ?? []).filter((s) => s.state === 'done').map((s) => s.id),
1514
+ );
1515
+ loop.pending = loop.pending.filter((p) => !finished.has(p.story));
1465
1516
  if (loop.pending.length) {
1466
1517
  const { story, prompt } = loop.pending.shift();
1467
1518
  // Until the person has chosen how hands-off the loop is, or under propose, a restart is offered
@@ -2244,10 +2295,10 @@ export function register(on) {
2244
2295
  const a = activityOf(e.agentId, await $.clock.now());
2245
2296
  a.handedBack = true;
2246
2297
  // LEAN-5: an agent that handed back at its limit: the lead carries its story on with a fresh one.
2247
- if (a.overflow && !a.continued && act) {
2298
+ const story = (model.state?.stories ?? []).find((s) => s.id === a.story);
2299
+ if (a.overflow && !a.continued && act && story?.state !== 'done') {
2248
2300
  a.continued = true;
2249
2301
  const agent = agentsSeen.get(e.agentId);
2250
- const story = (model.state?.stories ?? []).find((s) => s.id === a.story);
2251
2302
  loop.pending.push({
2252
2303
  story: a.story,
2253
2304
  prompt: continuePrompt({