@warren-dean/code-kit 0.22.1 → 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.
@@ -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.
@@ -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({
@@ -82,6 +82,8 @@ function project() {
82
82
  answer: 'Merge',
83
83
  open: new Set<string>(),
84
84
  opened: [] as string[],
85
+ reportFails: false, // report send: GitHub refuses it
86
+ toasts: [] as string[],
85
87
  closed: [] as string[],
86
88
  prompts: [] as string[],
87
89
  acts: [] as string[][],
@@ -216,6 +218,18 @@ function stub(on: any, w: World) {
216
218
  return ran(0, 'Recorded.');
217
219
  }
218
220
  if (sub === 'ask') return ran(0, JSON.stringify(w.questions));
221
+ if (sub === 'worktrees' && argv[3] === 'discard') {
222
+ w.acts.push([...argv.slice(2)]);
223
+ w.next = {
224
+ ...w.next,
225
+ worktrees: (w.next.worktrees ?? []).filter((x: any) => x.branch !== argv[4]),
226
+ };
227
+ return ran(0, `Removed ${argv[4]}'s worktree.`);
228
+ }
229
+ if (sub === 'report' && argv[3] === 'send' && w.reportFails) {
230
+ w.acts.push([...argv.slice(2)]);
231
+ return ran(1, '', "GitHub didn't take it (HTTP 502).");
232
+ }
219
233
  if (sub === 'report' && ['send', 'discard'].includes(argv[3])) {
220
234
  w.acts.push([...argv.slice(2)]);
221
235
  w.reports = w.reports.map((r) =>
@@ -492,6 +506,10 @@ function stub(on: any, w: World) {
492
506
  return { value: undefined };
493
507
  });
494
508
  on('ui.panes', () => ({ value: [...w.open].map((id) => ({ id, title: id, isShown: true })) }));
509
+ on('ui.toast', ($: any, e: any) => {
510
+ w.toasts.push(e.text);
511
+ return { value: undefined };
512
+ });
495
513
  on('ui.open', ($: any, e: any) => {
496
514
  w.opened.push(e.id);
497
515
  w.open.add(e.id);
@@ -1902,8 +1920,83 @@ test('REPORT-3 a bug report an agent drafted waits for the person, who reads it
1902
1920
  await ui.find({ type: 'Text', text: '**What happened:** the card never showed' }),
1903
1921
  ).toBeDefined();
1904
1922
  await press($, 'decide-sendReport', PANE);
1905
- expect(w.acts).toContainEqual(['report', 'send', 'R-1']);
1906
- expect(w.opened).toContain('code-kit-result');
1923
+ expect(w.acts.filter((a: string[]) => a[0] === 'report' && a[1] === 'send')).toEqual([
1924
+ ['report', 'send', 'R-1'],
1925
+ ]);
1926
+ // Sent, it leaves the tab, and the result is a toast, not a pane to close.
1927
+ expect(w.toasts).toEqual([
1928
+ "Sending R-1 to code-kit's GitHub…",
1929
+ 'Filed https://github.com/o/code-kit/issues/9',
1930
+ ]);
1931
+ expect(await ui.find({ type: 'Text', text: '**What happened:** the card never showed' })).toBe(
1932
+ undefined,
1933
+ );
1934
+ expect(w.opened).not.toContain(RESULT);
1935
+ await ui.unmount();
1936
+ });
1937
+
1938
+ test('REPORT-3 a report GitHub refused stays to send again, and says why', async ($, on) => {
1939
+ const w = project();
1940
+ w.reportFails = true;
1941
+ w.reports = [
1942
+ {
1943
+ id: 'R-1',
1944
+ at: '2026-10-13T00:00:00Z',
1945
+ by: 'lead',
1946
+ title: 'Decisions tab misses a held call',
1947
+ fingerprint: 'ck-1',
1948
+ body: '**What happened:** the card never showed',
1949
+ state: 'draft',
1950
+ sent: null,
1951
+ },
1952
+ ];
1953
+ await start($, on, w);
1954
+ const band = await bandUi($);
1955
+ await press($, 'band-openDecision');
1956
+ await band.unmount();
1957
+ const ui = await pane($, PANE);
1958
+ await press($, 'decide-sendReport', PANE);
1959
+ expect(w.opened).toContain(RESULT);
1960
+ const result = await pane($, RESULT);
1961
+ expect(await result.find({ type: 'Text', text: /GitHub didn't take it/ })).toBeDefined();
1962
+ await result.unmount();
1963
+ expect(
1964
+ await ui.find({ type: 'Text', text: '**What happened:** the card never showed' }),
1965
+ ).toBeDefined();
1966
+ await ui.unmount();
1967
+ });
1968
+
1969
+ test('LEAN-8 a merged worktree still holding changes waits for the person, who keeps it or discards it', async ($, on) => {
1970
+ const w = project();
1971
+ w.next = {
1972
+ ...w.next,
1973
+ worktrees: [
1974
+ { branch: 'web/st-2', story: 'ST-2', changes: 2, files: [' M st2.txt', '?? notes.txt'] },
1975
+ { branch: 'api/st-3', story: 'ST-3', changes: 1, files: [' M a.ts'] },
1976
+ ],
1977
+ };
1978
+ await start($, on, w);
1979
+ const band = await bandUi($);
1980
+ expect(
1981
+ await band.find({
1982
+ type: 'Text',
1983
+ text: '2 merged worktrees still hold changes: web/st-2',
1984
+ }),
1985
+ ).toBeDefined();
1986
+ await press($, 'band-openDecision');
1987
+ await band.unmount();
1988
+ const ui = await pane($, PANE);
1989
+ expect(await ui.find({ type: 'Text', text: /\?\? notes\.txt/ })).toBeDefined();
1990
+ await press($, 'decide-discardWorktree', PANE);
1991
+ expect(w.acts).toContainEqual(['worktrees', 'discard', 'web/st-2']);
1992
+ expect(w.opened).not.toContain(RESULT);
1993
+ await press($, 'decide-keepWorktree', PANE);
1994
+ expect(w.acts.filter((a: string[]) => a[0] === 'worktrees')).toEqual([
1995
+ ['worktrees', 'discard', 'web/st-2'],
1996
+ ]);
1997
+ expect((await ui.findAll({ type: 'Text' })).some((t: any) => /api\/st-3/.test(t.text))).toBe(
1998
+ false,
1999
+ );
1907
2000
  await ui.unmount();
1908
2001
  });
1909
2002
 
@@ -2423,6 +2516,28 @@ test('LEAN-5 a lane agent past its context limit is told to wrap up, and its sto
2423
2516
  );
2424
2517
  });
2425
2518
 
2519
+ test('#59 an agent that hands back at its limit a story already merged and done is not carried on', async ($, on) => {
2520
+ const w = project();
2521
+ w.next = { step: 'wait', args: '', then: [] };
2522
+ w.stories = w.stories.map((s: any) => (s.id === 'ST-4' ? { ...s, state: 'done' } : s));
2523
+ w.agents = [
2524
+ { id: 'a1', type: 'web-engineer', description: 'ST-4 booking form', status: 'running' },
2525
+ ];
2526
+ const clock = await start($, on, w);
2527
+ await clock.advance(2000);
2528
+ await request($, 'a1', 300);
2529
+ await $.turn.complete({
2530
+ turnId: 't-a1',
2531
+ agentId: 'a1',
2532
+ answer: 'ST-4: committed, report written.',
2533
+ durationMs: 1,
2534
+ isAborted: false,
2535
+ } as any);
2536
+ await leadTurn($, 't-2');
2537
+ await settle(clock);
2538
+ expect(w.prompts.some((p: string) => /handed ST-4 back/.test(p))).toBe(false);
2539
+ });
2540
+
2426
2541
  test("LEAN-4 past compact.at the lead's context is compacted between turns, without asking", async ($, on) => {
2427
2542
  const w = project();
2428
2543
  const compacted: string[] = [];
@@ -729,6 +729,7 @@ export function bandLines({
729
729
  questions = [],
730
730
  brief = [],
731
731
  reports = [],
732
+ worktrees = [],
732
733
  working = false,
733
734
  task = null,
734
735
  elsewhere = [],
@@ -913,6 +914,15 @@ export function bandLines({
913
914
  { id: 'discardReport', label: 'Discard' },
914
915
  ],
915
916
  });
917
+ // LEAN-8: a merged worktree that still holds uncommitted changes: the person keeps it, or discards them.
918
+ if (worktrees.length && !working)
919
+ lines.push({
920
+ kind: 'worktree',
921
+ text: `${worktrees.length > 1 ? `${worktrees.length} merged worktrees still hold changes: ` : 'A merged worktree still holds changes: '}${worktrees[0].branch}`,
922
+ worktree: worktrees[0],
923
+ worktrees,
924
+ actions: [{ id: 'openDecision', label: 'Look…' }],
925
+ });
916
926
  // LOOP-7: the milestone is done; LOOP-6: the loop's own state, with Pause or Resume.
917
927
  if (loop?.state === 'done')
918
928
  lines.push({