@warren-dean/code-kit 0.31.1 → 0.32.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
+ }
@@ -196,7 +196,9 @@ export function nextStep(root, base) {
196
196
  attention.push(
197
197
  `${leftovers} worktree${leftovers === 1 ? ' is' : 's are'} done with; \`code-kit worktrees prune\` removes them, keeping their reports.`,
198
198
  );
199
- const holding = trees.filter((w) => w.kind === 'agent' && w.merged && !w.clean && !w.agentAtWork);
199
+ const holding = trees.filter(
200
+ (w) => w.kind === 'agent' && w.merged && w.changes > 0 && !w.agentAtWork,
201
+ );
200
202
  holdingTrees = holding.map((w) => ({
201
203
  branch: w.branch,
202
204
  story: w.story,
@@ -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);
@@ -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 };
@@ -719,13 +719,9 @@ export function board(view, els, on) {
719
719
  ],
720
720
  });
721
721
 
722
- // --- Needs you (UI-3) ---
723
- const openAt = Math.min(
724
- Math.max(0, sel?.kind === 'need' ? Number(sel.id) : (ui.need ?? 0)),
725
- Math.max(0, needs.length - 1),
726
- );
727
- const buttonsOf = (line) =>
728
- line.actions.map((a) =>
722
+ // A need's own buttons, and a decision's Decide…, where a line has room for them (the inline layout).
723
+ const buttonsOf = (line) => [
724
+ ...line.actions.map((a) =>
729
725
  Button({
730
726
  key: `need-${a.id}`,
731
727
  label: a.hotkey ? `${a.hotkey} ${a.label}` : a.label,
@@ -733,7 +729,23 @@ export function board(view, els, on) {
733
729
  variant: isNote(line) ? undefined : 'primary',
734
730
  onPress: () => on.onNeed(a.id, line),
735
731
  }),
736
- );
732
+ ),
733
+ ...(isNote(line)
734
+ ? []
735
+ : [
736
+ Button({
737
+ key: 'need-decide',
738
+ label: 'Decide…',
739
+ hotkey: 'd',
740
+ plain: true,
741
+ onPress: () => on.onDecide(0, line),
742
+ }),
743
+ ]),
744
+ ];
745
+
746
+ // --- Needs you (UI-3, DECIDE-5) ---
747
+ // One line each, the same height whichever is chosen, so the list never jumps: a decision opens in the
748
+ // Decide pane, all of it; a note keeps its own buttons on its line.
737
749
  const needsPanel = needs.length
738
750
  ? Box({
739
751
  key: 'panel-needs',
@@ -748,54 +760,7 @@ export function board(view, els, on) {
748
760
  ),
749
761
  ...needs.map((line, i) => {
750
762
  const chosen = sel?.kind === 'need' && Number(sel.id) === i;
751
- if (i === openAt)
752
- return Box({
753
- key: `need-open`,
754
- flexDirection: 'column',
755
- borderStyle: 'round',
756
- borderColor: isNote(line) ? 'gray' : 'yellow',
757
- paddingX: 1,
758
- children: [
759
- Box({
760
- flexDirection: 'row',
761
- columnGap: 1,
762
- children: [
763
- text(needWord(line), {
764
- color: isNote(line) ? undefined : 'yellow',
765
- dimColor: isNote(line),
766
- }),
767
- Box({
768
- flexShrink: 1,
769
- children: [text(line.text, { bold: true, wrap: 'wrap' })],
770
- }),
771
- ],
772
- }),
773
- ...(line.context
774
- ? [text(line.context, { dimColor: true, wrap: 'truncate-end' })]
775
- : []),
776
- Box({
777
- key: 'need-buttons',
778
- flexDirection: 'row',
779
- columnGap: 1,
780
- flexWrap: 'wrap',
781
- children: [
782
- ...buttonsOf(line),
783
- ...(isNote(line)
784
- ? []
785
- : [
786
- Button({
787
- key: 'need-why',
788
- label: 'Why…',
789
- plain: true,
790
- ...(chosen ? { autoFocus: true } : {}),
791
- onPress: () => on.onDecide(i, line),
792
- }),
793
- ]),
794
- ],
795
- }),
796
- ],
797
- });
798
- // One line each: what it is (pressed to open it in its place), then its words, cut to fit.
763
+ const note = isNote(line);
799
764
  return Box({
800
765
  key: `need-row-${i}`,
801
766
  flexDirection: 'row',
@@ -805,18 +770,29 @@ export function board(view, els, on) {
805
770
  key: `need-line-${i}`,
806
771
  label: `${chosen ? '›' : ' '} ${needWord(line)}`,
807
772
  plain: true,
808
- ...(isNote(line) ? { dimColor: true } : {}),
809
- onPress: () => on.onSelect({ kind: 'need', id: String(i) }),
773
+ ...(note ? { dimColor: true } : { color: 'yellow' }),
774
+ onPress: () =>
775
+ note ? on.onSelect({ kind: 'need', id: String(i) }) : on.onDecide(i, line),
810
776
  }),
811
777
  Box({
812
778
  flexShrink: 1,
813
779
  children: [
814
780
  text(line.text, {
815
781
  wrap: 'truncate-end',
816
- ...(isNote(line) ? { dimColor: true } : {}),
782
+ ...(note ? { dimColor: true } : chosen ? { bold: true } : {}),
817
783
  }),
818
784
  ],
819
785
  }),
786
+ ...(note
787
+ ? line.actions.map((a) =>
788
+ Button({
789
+ key: `need-${i}-${a.id}`,
790
+ label: a.label,
791
+ plain: true,
792
+ onPress: () => on.onNeed(a.id, line),
793
+ }),
794
+ )
795
+ : []),
820
796
  ],
821
797
  });
822
798
  }),
@@ -1137,7 +1113,7 @@ export function board(view, els, on) {
1137
1113
  // The rows the cards have: the pane's, less what the other panels and the keys take, and the
1138
1114
  // gaps between them; in the wide layout, the Lanes column's, under Build.
1139
1115
  const buildRows = (progress ? 4 : 3) + (state.planGaps ? 1 : 0);
1140
- const needsRows = needs.length ? 1 + 4 + (needs[openAt]?.context ? 1 : 0) + needs.length - 1 : 0;
1116
+ const needsRows = needs.length ? 1 + needs.length : 0;
1141
1117
  const queueRows = open.length ? 1 + open.length + settled.length : 0;
1142
1118
  const logRows = 1 + log.length;
1143
1119
  const panels = 3 + (needs.length ? 1 : 0) + (open.length ? 1 : 0);
@@ -1434,6 +1410,7 @@ export function board(view, els, on) {
1434
1410
  key: 'inline-need',
1435
1411
  flexDirection: 'row',
1436
1412
  columnGap: 1,
1413
+ flexWrap: 'wrap',
1437
1414
  children: [
1438
1415
  Box({
1439
1416
  flexShrink: 1,
@@ -1561,7 +1538,7 @@ export function bandOf(view, els, onAction) {
1561
1538
  : [
1562
1539
  Button({
1563
1540
  key: 'band-decide',
1564
- label: columns < 60 ? 'Why…' : 'Why, and what each choice does',
1541
+ label: 'Decide…',
1565
1542
  hotkey: 'd',
1566
1543
  plain: true,
1567
1544
  onPress: () => onAction('decide', first),