loopwright 0.1.10 → 0.1.12

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.
@@ -7,7 +7,9 @@ import { execFileSync } from 'node:child_process';
7
7
  import { isatty } from 'node:tty';
8
8
  import { fileURLToPath } from 'node:url';
9
9
  import {
10
+ ICON_PREFIX,
10
11
  PROFILES,
12
+ TASK_FILE_ICONS,
11
13
  fingerprint,
12
14
  gitTopLevel,
13
15
  loopwrightDir,
@@ -17,11 +19,28 @@ import {
17
19
  readState,
18
20
  realpathLoose,
19
21
  repoRelative,
22
+ settingValue,
20
23
  sha256File,
21
24
  statePath,
25
+ workingTree,
22
26
  worktreeId,
27
+ writeFileAtomic,
23
28
  writeState,
24
29
  } from './lib.mjs';
30
+ import {
31
+ ENTRY_NAMES,
32
+ SECTION_NAMES,
33
+ SETTING_KEYS,
34
+ addEntry,
35
+ editEntry,
36
+ fenced,
37
+ fillTask,
38
+ header,
39
+ markEntry,
40
+ setSetting,
41
+ skeleton,
42
+ writeSection,
43
+ } from './task-file.mjs';
25
44
 
26
45
  const STAGES = ['plan', 'test', 'build', 'review', 'done'];
27
46
  const cwd = process.cwd();
@@ -30,8 +49,8 @@ function fail(msg) {
30
49
  process.stderr.write(msg + '\n');
31
50
  process.exit(1);
32
51
  }
33
- const note = (state, event, detail) => {
34
- (state.history ??= []).push({ event, detail, at: new Date().toISOString() });
52
+ const note = (state, event, detail, extra) => {
53
+ (state.history ??= []).push({ event, detail, ...extra, at: new Date().toISOString() });
35
54
  };
36
55
  const out = (v) => process.stdout.write(JSON.stringify(v, null, 2) + '\n');
37
56
 
@@ -60,6 +79,32 @@ function scaffold(dir, withConfig) {
60
79
  if (withConfig && !existsSync(cfg)) copyFileSync(seedConfig(), cfg);
61
80
  }
62
81
 
82
+ /** Stdin as LF text; empty when there is none. isatty, not process.stdin.isTTY: touching process.stdin makes a piped fd 0 non-blocking, so a slow writer fails readFileSync with EAGAIN. */
83
+ const readInput = () => (isatty(0) ? '' : readFileSync(0, 'utf8')).replace(/\r\n/g, '\n');
84
+ const inputLines = () =>
85
+ readInput()
86
+ .split('\n')
87
+ .map((l) => l.trimEnd())
88
+ .filter(Boolean);
89
+
90
+ /** The task file a writer command edits: the `--file <path under .loopwright>` (a stub, another task), else the active task. */
91
+ function writerTarget(cmd, args) {
92
+ const named = flag(args, '--file');
93
+ const dir = loopwrightPath(cwd);
94
+ const task = named ?? (dir && readState(dir, worktreeId(cwd))?.task);
95
+ if (!task) fail(`loopwright: ${cmd} needs an active task or --file`);
96
+ const file = resolve(dir, task);
97
+ if (!existsSync(file)) fail(`loopwright: ${cmd}: ${task} not found`);
98
+ return file;
99
+ }
100
+
101
+ /** Replace a task file with `change(text)`: read and written with its own line endings, in one rename. */
102
+ function rewriteTask(file, change) {
103
+ const raw = readFileSync(file, 'utf8');
104
+ const next = change(raw.replace(/\r\n/g, '\n'));
105
+ writeFileAtomic(file, raw.includes('\r\n') ? next.replace(/\n/g, '\r\n') : next);
106
+ }
107
+
63
108
  const isMainCheckout = () => gitTopLevel(cwd) === mainWorktreeRoot(cwd);
64
109
 
65
110
  function ctx(create = false) {
@@ -91,7 +136,7 @@ function effortFor(role, badProfile = fail, flagged) {
91
136
  const dir = !name && loopwrightDir(cwd);
92
137
  const state = dir && readState(dir, worktreeId(cwd));
93
138
  if (state?.task && existsSync(join(dir, state.task))) {
94
- name = /^profile:\s*(\S+)\s*$/m.exec(readFileSync(join(dir, state.task), 'utf8').split(/^## /m)[0])?.[1];
139
+ name = settingValue(readFileSync(join(dir, state.task), 'utf8').split(/^## /m)[0], 'profile');
95
140
  if (name === 'pending') name = undefined;
96
141
  }
97
142
  } catch {
@@ -121,16 +166,14 @@ function effortFor(role, badProfile = fail, flagged) {
121
166
  */
122
167
  function setHeader(taskPath, key, value) {
123
168
  try {
124
- const text = readFileSync(taskPath, 'utf8');
125
- const at = text.search(/^## /m);
126
- const split = at === -1 ? text.length : at;
127
- const line = new RegExp(`^${key}:[^\\r\\n]*`, 'm');
128
- const head = text.slice(0, split);
129
- if (!line.test(head)) return `no "${key}:" line`;
130
- writeFileSync(taskPath, head.replace(line, () => `${key}: ${value}`) + text.slice(split));
169
+ rewriteTask(taskPath, (t) => {
170
+ if (!new RegExp(`^${ICON_PREFIX}${key}:`, 'm').test(header(t))) throw new Error(`no "${key}:" line`);
171
+ return setSetting(t, key, value);
172
+ });
131
173
  return null;
132
174
  } catch (err) {
133
- return err.code === 'ENOENT' ? 'task file missing' : `cannot write "${key}:" (${err.code ?? err.message})`;
175
+ if (!err.code) return err.message;
176
+ return err.code === 'ENOENT' ? 'task file missing' : `cannot write "${key}:" (${err.code})`;
134
177
  }
135
178
  }
136
179
 
@@ -141,6 +184,174 @@ function headerResult(misses) {
141
184
  return missed.length === 0;
142
185
  }
143
186
 
187
+ const PROGRESS_OPEN = '<!-- loopwright progress: written by the state tool, edits are overwritten -->';
188
+ const PROGRESS_CLOSE = '<!-- /loopwright progress -->';
189
+ // Markers only count at a line start, so a decision that quotes them in running text is never taken for the block.
190
+ const PROGRESS_BLOCK = /^<!-- loopwright progress[^\r\n]*-->[\s\S]*?^<!-- \/loopwright progress -->/m;
191
+
192
+ const SLICE_ENTRY = new RegExp(`^- (S\\d+) ${ICON_PREFIX}\\[(todo|tested|passed)\\][ \\t]*(.*)$`, 'gm');
193
+ const WHOLE_BRANCH = 'whole branch';
194
+
195
+ /** The slice a stage works on, picked like the stage skills do: Test the first todo, Build and Review the first tested, none left open → the whole branch. */
196
+ function currentSlice(text, stage) {
197
+ const slices = [...text.matchAll(SLICE_ENTRY)];
198
+ if (!['test', 'build', 'review'].includes(stage) || !slices.length) return undefined;
199
+ const open =
200
+ slices.find((m) => m[2] === (stage === 'test' ? 'todo' : 'tested')) ?? slices.find((m) => m[2] !== 'passed');
201
+ return open ? open[1] : WHOLE_BRANCH;
202
+ }
203
+
204
+ /** The slice to record on a stage or verdict event; none when the task has no Slices list. */
205
+ const sliceFor = (dir, state, stage) =>
206
+ existsSync(join(dir, state.task)) ? currentSlice(readFileSync(join(dir, state.task), 'utf8'), stage) : undefined;
207
+
208
+ const sliceName = (label) => (/^S\d+$/.test(label) ? `slice ${label.slice(1)}` : label);
209
+ const capital = (s) => s[0].toUpperCase() + s.slice(1);
210
+
211
+ /** Trail steps from the history since the task started. The last one stands for the current stage. */
212
+ function trailSteps(history, state, finished) {
213
+ const steps = [];
214
+ for (const e of history) {
215
+ const last = steps.at(-1);
216
+ if (e.event === 'reopen') steps.push({ stage: e.detail, back: true });
217
+ else if (e.event === 'verdict' && last?.stage === 'review') last.pass = e.detail.startsWith('pass');
218
+ else if (e.event === 'stage' && e.detail !== 'plan') {
219
+ const same = last?.stage === e.detail && last.pass === undefined && (last.back || last.slice === e.slice);
220
+ if (!same) steps.push({ stage: e.detail, slice: e.slice });
221
+ }
222
+ }
223
+ const want = finished ? 'done' : state.stage;
224
+ if (want !== 'plan' && steps.at(-1)?.stage !== want) steps.push({ stage: want });
225
+ return steps;
226
+ }
227
+
228
+ /** The progress block lines: a Now line, then the step trail. Facts come from what the tool recorded in the history. */
229
+ function progressLines(state, text) {
230
+ const { finished: done, failed, running, paused, back } = TASK_FILE_ICONS.progress;
231
+ const head = text.split(/^## /m)[0];
232
+ const all = state.history ?? [];
233
+ // A forced restart of the same task keeps the trail; only a start of another task begins an empty one.
234
+ const starts = all.flatMap((e, i) => (e.event === 'start' ? [{ i, task: e.task ?? e.detail }] : []));
235
+ let first = starts.length - 1;
236
+ while (first > 0 && starts[first].task === starts[first - 1].task) first--;
237
+ const history = all.slice(first < 0 ? 0 : starts[first].i + 1);
238
+ const finished = history.at(-1)?.event === 'done';
239
+ const steps = trailSteps(history, state, finished);
240
+ const mark = (s, isLast) => {
241
+ if (s.pass === false) return failed;
242
+ if (!isLast || finished) return done;
243
+ return s.pass ? done : state.awaitingUser ? paused : running;
244
+ };
245
+ const shown = steps.map(
246
+ (s, i) => `${s.back ? `${back} ` : ''}${capital(s.stage)} ${mark(s, i === steps.length - 1)}`,
247
+ );
248
+ const trail = [];
249
+ let label;
250
+ steps.forEach((s, i) => {
251
+ label = s.slice ?? label;
252
+ let line = trail.find((t) => t.label === label);
253
+ if (!line) trail.push((line = { label, steps: [] }));
254
+ line.steps.push(shown[i]);
255
+ });
256
+ const planMark = steps.length ? done : state.awaitingUser ? paused : running;
257
+ const sliced = trail.some((t) => t.label);
258
+ const lines = sliced
259
+ ? [
260
+ `Plan ${planMark}`,
261
+ ...trail.map(
262
+ (t) =>
263
+ `${t.label ? `${TASK_FILE_ICONS.headings.Slices} **${sliceName(t.label)}:** ` : ''}${t.steps.join(' → ')}`,
264
+ ),
265
+ ]
266
+ : [[`Plan ${planMark}`, ...shown].join(' → ')];
267
+
268
+ const slices = [...text.matchAll(SLICE_ENTRY)];
269
+ const tail = steps.at(-1);
270
+ // After a passing review the Now line keeps naming that slice until the next Test starts.
271
+ const current = finished ? undefined : currentSlice(text, state.stage);
272
+ const passed =
273
+ current !== WHOLE_BRANCH && tail?.stage === 'review' && tail.pass && state.stage === 'review'
274
+ ? tail.slice
275
+ : undefined;
276
+ const live = finished ? undefined : (passed ?? current);
277
+ const at = slices.findIndex((m) => m[1] === live);
278
+ const title = at === -1 ? '' : slices[at][3].replace(/ — [^—]*$/, '');
279
+ const where =
280
+ live === WHOLE_BRANCH ? `, ${WHOLE_BRANCH}` : at === -1 ? '' : `, slice ${at + 1} of ${slices.length} (${title})`;
281
+ const verdicts = history.filter((e) => e.event === 'verdict');
282
+ const own = verdicts.filter((e) => e.slice === live);
283
+ const cap = Number(settingValue(head, 'fix-round cap')) || 0;
284
+ const prev = verdicts.findLast((e) => e.slice && e.slice !== live && e.detail.startsWith('pass'));
285
+ const prevRounds = prev ? verdicts.filter((e) => e.slice === prev.slice && e.detail.startsWith('fail')).length : 0;
286
+ const facts = [
287
+ state.stage === 'build' && own.at(-1)?.detail.startsWith('fail')
288
+ ? `fix round ${own.filter((e) => e.detail.startsWith('fail')).length}${cap ? ` of ${cap}` : ''}`
289
+ : null,
290
+ state.awaitingUser ? `waiting for you (${state.awaitingUser})` : null,
291
+ prev
292
+ ? `${sliceName(prev.slice)} passed ${prevRounds ? `after ${prevRounds} fix round${prevRounds === 1 ? '' : 's'}` : 'with no fix rounds'}`
293
+ : null,
294
+ ].filter(Boolean);
295
+ const now = finished
296
+ ? `**All stages finished** ${done}`
297
+ : `**Now: ${capital(state.stage)}${where}**${facts.map((f) => ` · ${f}`).join('')} ${state.awaitingUser ? paused : running}`;
298
+ return [now, '', ...lines.map((l) => `${l} `)];
299
+ }
300
+
301
+ /** Settings lines, known headings and tagged lines with a missing or wrong icon get the one from TASK_FILE_ICONS. Text is never reflowed. */
302
+ function repairIcons(text) {
303
+ const { settings, headings, tags } = TASK_FILE_ICONS;
304
+ const at = text.search(/^## /m);
305
+ const split = at === -1 ? text.length : at;
306
+ return (
307
+ text
308
+ .slice(0, split)
309
+ .replace(new RegExp(`^${ICON_PREFIX}([a-z][a-z -]*):`, 'gm'), (all, key) =>
310
+ Object.hasOwn(settings, key) ? `${settings[key]} ${key}:` : all,
311
+ ) +
312
+ text
313
+ .slice(split)
314
+ .replace(new RegExp(`^## ${ICON_PREFIX}(.+?)(?=[ \\t]*$)`, 'gm'), (all, name) =>
315
+ Object.hasOwn(headings, name) ? `## ${headings[name]} ${name}` : all,
316
+ )
317
+ .replace(new RegExp(`^(- [ADS]\\d+) ${ICON_PREFIX}\\[([a-z-]+)\\]`, 'gm'), (all, id, tag) =>
318
+ Object.hasOwn(tags, tag) ? `${id} ${tags[tag]} [${tag}]` : all,
319
+ )
320
+ );
321
+ }
322
+
323
+ /** The task text with its progress block rewritten (inserted under the title when missing), and icons repaired in a file with the fenced settings block. */
324
+ function withProgress(text, state) {
325
+ const eol = text.includes('\r\n') ? '\r\n' : '\n';
326
+ const block = [PROGRESS_OPEN, ...progressLines(state, text), PROGRESS_CLOSE].join(eol);
327
+ const afterTitle = /^# [^\r\n]*(?:\r?\n)+/.exec(text)?.[0].length ?? 0;
328
+ const next = PROGRESS_BLOCK.test(text)
329
+ ? text.replace(PROGRESS_BLOCK, () => block)
330
+ : `${text.slice(0, afterTitle)}${block}${eol}${eol}${text.slice(afterTitle)}`;
331
+ return fenced(next) ? repairIcons(next) : next;
332
+ }
333
+
334
+ /** Write the progress block into the task file. A failure is a warning only: state is already saved. */
335
+ function refreshTaskFile(taskPath, state) {
336
+ try {
337
+ const text = readFileSync(taskPath, 'utf8');
338
+ const next = withProgress(text, state);
339
+ if (next !== text) writeFileAtomic(taskPath, next);
340
+ } catch (err) {
341
+ // A missing file is already reported by the header write.
342
+ if (err.code !== 'ENOENT')
343
+ process.stderr.write(`loopwright: task file progress list not updated (${err.code ?? err.message})\n`);
344
+ }
345
+ }
346
+
347
+ /** A writer command's edit; the active task's progress block is rewritten in the same write, any other file keeps its block. */
348
+ function editTask(file, change) {
349
+ const dir = loopwrightPath(cwd);
350
+ const state = dir && readState(dir, worktreeId(cwd));
351
+ const active = state?.task && resolve(dir, state.task) === file;
352
+ rewriteTask(file, (t) => (active ? withProgress(change(t), state) : change(t)));
353
+ }
354
+
144
355
  /** The main checkout's config.json, else the seed config. */
145
356
  const readConfig = () => {
146
357
  const main = mainLoopwrightPath(cwd);
@@ -152,20 +363,23 @@ const gitOut = (args) => execFileSync('git', args, { cwd, encoding: 'utf8', stdi
152
363
 
153
364
  /** The worktree a task header names: `worktree: <path> (branch <name>)`. */
154
365
  function namedWorktree(header) {
155
- const m = /^worktree:[ \t]*(.+?)(?:[ \t]+\(branch[ \t]+(.*?)\))?[ \t]*$/m.exec(header);
366
+ const m = new RegExp(`^${ICON_PREFIX}worktree:[ \\t]*(.+?)(?:[ \\t]+\\(branch[ \\t]+(.*?)\\))?[ \\t]*$`, 'm').exec(
367
+ header,
368
+ );
156
369
  return m ? { path: resolve(m[1]), branch: m[2] ?? null } : null;
157
370
  }
158
371
 
159
372
  /** Task file fields: status/stage from the header (before the first `## `), title from `# `, goal from `## Goal`. */
160
373
  function readTask(root, rel) {
161
374
  const [head, ...sections] = readFileSync(join(root, rel), 'utf8').split(/^## /m);
162
- const goal = sections.find((s) => /^Goal[ \t]*\r?\n/.test(s));
375
+ const goalHeading = new RegExp(`^${ICON_PREFIX}Goal[ \\t]*\\r?\\n`);
376
+ const goal = sections.find((s) => goalHeading.test(s));
163
377
  return {
164
378
  title: /^# (.*)$/m.exec(head)?.[1].trim() ?? null,
165
- status: /^status:[ \t]*(\S+)/m.exec(head)?.[1] ?? null,
166
- stage: /^stage:[ \t]*(\S+)/m.exec(head)?.[1] ?? null,
379
+ status: settingValue(head, 'status') ?? null,
380
+ stage: settingValue(head, 'stage') ?? null,
167
381
  named: namedWorktree(head),
168
- goal: goal ? goal.replace(/^Goal[ \t]*\r?\n/, '').trim() : '',
382
+ goal: goal ? goal.replace(goalHeading, '').trim() : '',
169
383
  };
170
384
  }
171
385
 
@@ -181,7 +395,11 @@ const listWorktrees = () =>
181
395
 
182
396
  /** A move copies; the source stays, marked so no listing offers it again. */
183
397
  function markMoved(file, to) {
184
- writeFileSync(file, readFileSync(file, 'utf8').replace(/^status:.*$/m, `status: moved\nmoved to: ${to}`));
398
+ const status = new RegExp(`^(${ICON_PREFIX})status:.*$`, 'm');
399
+ writeFileAtomic(
400
+ file,
401
+ readFileSync(file, 'utf8').replace(status, (_, icon) => `${icon}status: moved\nmoved to: ${to}`),
402
+ );
185
403
  }
186
404
 
187
405
  const today = () => {
@@ -206,8 +424,14 @@ function writeUnique(dir, base, text) {
206
424
  }
207
425
  }
208
426
 
209
- /** A proposed stub in park's format; `goal` is empty for a stub parked mid-task. */
210
- const stubText = (header, goal = '') => `${header.join('\n')}\n\n## Goal\n${goal ? `${goal}\n` : ''}\n## Evidence\n`;
427
+ /** A proposed stub in park's format, settings in a yaml fence with their icons; `goal` is empty for a stub parked mid-task. */
428
+ function stubText(title, kind, goal = '', links = {}) {
429
+ const { settings, headings } = TASK_FILE_ICONS;
430
+ const lines = Object.entries({ kind, status: 'proposed', stage: 'plan', plan: 'draft', ...links }).map(
431
+ ([key, value]) => `${settings[key]} ${key}: ${value}`,
432
+ );
433
+ return `# ${title}\n\n\`\`\`yaml\n${lines.join('\n')}\n\`\`\`\n\n## ${headings.Goal} Goal\n\n${goal ? `${goal}\n\n` : ''}## ${headings.Evidence} Evidence\n`;
434
+ }
211
435
 
212
436
  const refExists = (ref) => {
213
437
  try {
@@ -378,6 +602,18 @@ function ownCommits(state) {
378
602
  }
379
603
  }
380
604
 
605
+ /** The verdict's snapshot of the reviewed code, while its git tree still exists; else undefined. */
606
+ function usableSnapshot(state) {
607
+ const tree = state?.reviewed?.tree;
608
+ if (typeof tree !== 'string' || !/^[0-9a-f]{40,64}$/.test(tree)) return undefined;
609
+ try {
610
+ gitOut(['cat-file', '-e', `${tree}^{tree}`]);
611
+ return state.reviewed;
612
+ } catch {
613
+ return undefined;
614
+ }
615
+ }
616
+
381
617
  const [cmd, ...rest] = process.argv.slice(2);
382
618
  try {
383
619
  switch (cmd) {
@@ -388,8 +624,16 @@ try {
388
624
  const base = flag(rest, '--base') ?? 'HEAD';
389
625
  const force = rest.includes('--force');
390
626
  if (force) rest.splice(rest.indexOf('--force'), 1);
627
+ const kind = flag(rest, '--kind') ?? 'feature';
628
+ const profile = flag(rest, '--profile');
391
629
  const task = rest[0];
392
- if (!task) fail('loopwright: usage: start <task-rel-path> [--base <sha>] [--force]');
630
+ if (!task)
631
+ fail(
632
+ 'loopwright: usage: start <task-rel-path> [--base <sha>] [--force] [--kind feature|fix] [--profile <name>]',
633
+ );
634
+ if (kind !== 'feature' && kind !== 'fix') fail(`loopwright: start: kind must be feature or fix, not '${kind}'`);
635
+ if (profile !== undefined && !Object.hasOwn(PROFILES, profile))
636
+ fail(`loopwright: unknown profile '${profile}' (allowed: ${Object.keys(PROFILES).join(', ')})`);
393
637
  // A task file belongs to the worktree its header names; starting it elsewhere would split its state.
394
638
  const own = loopwrightPath(cwd);
395
639
  const header = own && existsSync(join(own, task)) ? readFileSync(join(own, task), 'utf8').split(/^## /m)[0] : '';
@@ -425,12 +669,79 @@ try {
425
669
  stopBlocks: 0,
426
670
  history: Array.isArray(prior?.history) ? prior.history : [],
427
671
  };
428
- if (force) note(state, 'start', '--force');
429
- else note(state, 'start', task);
672
+ note(state, 'start', force ? '--force' : task, { task });
673
+ // A file that is missing (the title comes on stdin) or a proposed stub becomes a task file at Plan; any other
674
+ // file is left alone except for the base commit line of a forced restart.
675
+ const file = join(dir, task);
676
+ const fill = { profile, worktree: `${state.worktree} (branch ${state.branch})`, base: baseCommit };
677
+ const title = existsSync(file) ? '' : readInput().split('\n')[0].trim();
678
+ const proposed = settingValue(header, 'status') === 'proposed';
679
+ if (title) writeFileAtomic(file, fillTask(skeleton(title, kind), fill));
680
+ else if (proposed) rewriteTask(file, (t) => fillTask(t, fill));
681
+ else if (force) setHeader(file, 'base commit', baseCommit);
430
682
  writeState(dir, id, state);
683
+ if (title || proposed) refreshTaskFile(file, state);
431
684
  out(state);
432
685
  break;
433
686
  }
687
+ case 'set': {
688
+ const file = writerTarget('set', rest);
689
+ const unset = rest.includes('--unset');
690
+ if (unset) rest.splice(rest.indexOf('--unset'), 1);
691
+ const [key, value, ...more] = rest;
692
+ if (!SETTING_KEYS.includes(key))
693
+ fail(`loopwright: set: unknown setting '${key ?? ''}' (one of ${SETTING_KEYS.join(', ')})`);
694
+ if (unset !== (value === undefined) || more.length)
695
+ fail('loopwright: usage: set <key> <value> | set <key> --unset [--file <path>]');
696
+ editTask(file, (t) => setSetting(t, key, unset ? null : value));
697
+ break;
698
+ }
699
+ case 'add': {
700
+ const file = writerTarget('add', rest);
701
+ const opts = Object.fromEntries(
702
+ ['tag', 'interface', 'test', 'scope', 'resolves'].map((name) => [name, flag(rest, `--${name}`)]),
703
+ );
704
+ for (const name of Object.keys(opts)) if (opts[name] === undefined) delete opts[name];
705
+ const [type, ...more] = rest;
706
+ if (!ENTRY_NAMES.includes(type) || more.length)
707
+ fail(`loopwright: add: unknown entry type '${rest.join(' ')}' (one of ${ENTRY_NAMES.join(', ')})`);
708
+ let id;
709
+ const input = inputLines();
710
+ editTask(file, (t) => {
711
+ const added = addEntry(t, type, opts, input);
712
+ id = added.id;
713
+ return added.text;
714
+ });
715
+ out({ id });
716
+ break;
717
+ }
718
+ case 'mark': {
719
+ const file = writerTarget('mark', rest);
720
+ editTask(file, (t) => markEntry(t, rest[0], rest[1]));
721
+ break;
722
+ }
723
+ case 'edit': {
724
+ const file = writerTarget('edit', rest);
725
+ const opts = { interface: flag(rest, '--interface'), test: flag(rest, '--test') };
726
+ if (opts.interface === undefined && opts.test === undefined) {
727
+ opts.text = inputLines()[0];
728
+ if (opts.text === undefined) fail('loopwright: edit needs the new text on stdin, or --interface or --test');
729
+ }
730
+ editTask(file, (t) => editEntry(t, rest[0], opts));
731
+ break;
732
+ }
733
+ case 'section': {
734
+ const file = writerTarget('section', rest);
735
+ const set = rest.includes('--set');
736
+ const append = rest.includes('--append');
737
+ const [name] = rest.filter((a) => a !== '--set' && a !== '--append');
738
+ if (!SECTION_NAMES.includes(name))
739
+ fail(`loopwright: section: unknown section '${name ?? ''}' (one of ${SECTION_NAMES.join(', ')})`);
740
+ if (set === append) fail('loopwright: section needs one of --set or --append');
741
+ const body = readInput().replace(/^\n+/, '').trimEnd();
742
+ editTask(file, (t) => writeSection(t, name, body, append));
743
+ break;
744
+ }
434
745
  case 'stage': {
435
746
  const name = rest[0];
436
747
  if (!STAGES.includes(name)) fail(`loopwright: invalid stage '${name ?? ''}' (one of ${STAGES.join(', ')})`);
@@ -438,9 +749,11 @@ try {
438
749
  state.stage = name;
439
750
  state.stopBlocks = 0;
440
751
  delete state.awaitingUser;
441
- note(state, 'stage', name);
752
+ note(state, 'stage', name, { slice: sliceFor(dir, state, name) });
442
753
  writeState(dir, id, state);
443
- out({ stage: name, header: headerResult([setHeader(join(dir, state.task), 'stage', name)]) });
754
+ const header = headerResult([setHeader(join(dir, state.task), 'stage', name)]);
755
+ refreshTaskFile(join(dir, state.task), state);
756
+ out({ stage: name, header });
444
757
  break;
445
758
  }
446
759
  case 'reopen': {
@@ -454,6 +767,7 @@ try {
454
767
  state.stage = target;
455
768
  state.stopBlocks = 0;
456
769
  delete state.awaitingUser;
770
+ delete state.reviewed;
457
771
  note(state, 'reopen', target);
458
772
  state.history.at(-1).reason = reason;
459
773
  writeState(dir, id, state);
@@ -461,7 +775,9 @@ try {
461
775
  // Both lines are attempted even if the first misses, so a partial header is still fixed.
462
776
  const set = [setHeader(file, 'stage', target)];
463
777
  if (target === 'plan') set.push(setHeader(file, 'plan', 'draft'));
464
- out({ stage: target, reopened: true, header: headerResult(set) });
778
+ const header = headerResult(set);
779
+ refreshTaskFile(file, state);
780
+ out({ stage: target, reopened: true, header });
465
781
  break;
466
782
  }
467
783
  case 'lock': {
@@ -554,12 +870,53 @@ try {
554
870
  fail('loopwright: verdict requires --round <n>');
555
871
  const { dir, id, state } = requireState();
556
872
  state.verdict = { pass: result === 'pass', fingerprint: fingerprint(cwd, state.baseCommit), round };
873
+ // The reviewed code as a git tree, so the next round can look only at what changed since (review-diff).
874
+ try {
875
+ state.reviewed = { tree: workingTree(cwd), round };
876
+ } catch (err) {
877
+ delete state.reviewed;
878
+ process.stderr.write(
879
+ `loopwright: reviewed snapshot not recorded (${err instanceof Error ? err.message : String(err)})\n`,
880
+ );
881
+ }
557
882
  delete state.awaitingUser;
558
- note(state, 'verdict', `${result} round ${round}`);
883
+ note(state, 'verdict', `${result} round ${round}`, { slice: sliceFor(dir, state, 'review') });
559
884
  writeState(dir, id, state);
885
+ refreshTaskFile(join(dir, state.task), state);
560
886
  out(state.verdict);
561
887
  break;
562
888
  }
889
+ case 'review-diff': {
890
+ const stat = rest.includes('--stat');
891
+ if (stat) rest.splice(rest.indexOf('--stat'), 1);
892
+ const { state } = requireState();
893
+ const snapshot = usableSnapshot(state);
894
+ if (!snapshot) fail('loopwright: no reviewed snapshot; run a full review');
895
+ // Numstat, not stat: git cuts long paths to `...` when stdout is not a terminal, and the paths are reused.
896
+ // Stdout streams straight through, so a large diff never fills a buffer. Paths are relative to the worktree root.
897
+ execFileSync(
898
+ 'git',
899
+ [
900
+ '--no-pager',
901
+ '-c',
902
+ 'core.quotePath=false',
903
+ 'diff',
904
+ '--src-prefix=a/',
905
+ '--dst-prefix=b/',
906
+ '--no-color',
907
+ '--no-ext-diff',
908
+ '--no-textconv',
909
+ '--no-renames',
910
+ ...(stat ? ['--numstat'] : []),
911
+ snapshot.tree,
912
+ workingTree(cwd),
913
+ '--',
914
+ ...rest,
915
+ ],
916
+ { cwd: gitTopLevel(cwd), stdio: ['ignore', 'inherit', 'pipe'] },
917
+ );
918
+ break;
919
+ }
563
920
  case 'await-user': {
564
921
  const reason = rest.join(' ').trim();
565
922
  if (!reason) fail('loopwright: usage: await-user <reason>');
@@ -567,6 +924,7 @@ try {
567
924
  state.awaitingUser = reason;
568
925
  note(state, 'await-user', reason);
569
926
  writeState(dir, id, state);
927
+ refreshTaskFile(join(dir, state.task), state);
570
928
  out(state);
571
929
  break;
572
930
  }
@@ -575,6 +933,7 @@ try {
575
933
  note(state, 'resume', state.awaitingUser ?? '');
576
934
  delete state.awaitingUser;
577
935
  writeState(dir, id, state);
936
+ refreshTaskFile(join(dir, state.task), state);
578
937
  out(state);
579
938
  break;
580
939
  }
@@ -701,8 +1060,7 @@ try {
701
1060
  fail(`loopwright: worktree: ${stubFlag} is not a proposed stub`);
702
1061
  }
703
1062
  let goal = '';
704
- // isatty, not process.stdin.isTTY: touching process.stdin makes a piped fd 0 non-blocking, so a slow writer fails readFileSync with EAGAIN.
705
- if (!source && !isatty(0)) goal = readFileSync(0, 'utf8').trim();
1063
+ if (!source) goal = readInput().trim();
706
1064
  let base = baseFlag;
707
1065
  if (base !== undefined) {
708
1066
  if (base.startsWith('-') || !refExists(base)) fail(`loopwright: worktree: unknown base '${base}'`);
@@ -732,11 +1090,7 @@ try {
732
1090
  copyFileSync(source, join(dir, stub));
733
1091
  markMoved(source, join(dir, stub));
734
1092
  } else {
735
- stub = writeUnique(
736
- dir,
737
- stubBase(title),
738
- stubText([`# ${title}`, '', `kind: ${kind}`, 'status: proposed', 'stage: plan', 'plan: draft'], goal),
739
- );
1093
+ stub = writeUnique(dir, stubBase(title), stubText(title, kind, goal));
740
1094
  }
741
1095
  const hook = join('.agents', 'loopwright', 'hooks', 'lw.mjs');
742
1096
  out({
@@ -830,6 +1184,7 @@ try {
830
1184
  baseCommit: state?.baseCommit,
831
1185
  lockedTests: state?.lockedTests,
832
1186
  verdict: state?.verdict,
1187
+ reviewed: usableSnapshot(state) ? { round: state.reviewed.round } : undefined,
833
1188
  awaitingUser: state?.awaitingUser,
834
1189
  flaggedLocks,
835
1190
  pulledLocks: pulledLocks.length ? pulledLocks : undefined,
@@ -868,26 +1223,16 @@ try {
868
1223
  const foundWhile = active && existsSync(join(dir, active)) ? active : null;
869
1224
  if (active && !foundWhile)
870
1225
  process.stderr.write(`loopwright: warning: active task file ${active} is missing; follow-up not linked\n`);
871
- const header = [`# ${title}`, '', `kind: ${kind}`, 'status: proposed', 'stage: plan', 'plan: draft'];
872
- if (foundWhile) header.push(`found while: ${foundWhile}`);
873
- if (blocks && foundWhile) header.push(`blocks: ${foundWhile}`);
874
- const stub = writeUnique(dir, stubBase(title), stubText(header));
875
- if (foundWhile) {
876
- const line = `- ${title} — ${stub}${blocks ? ' [blocking]' : ''}`;
877
- const file = join(dir, foundWhile);
878
- const body = readFileSync(file, 'utf8');
879
- const m = /^## Follow-ups[ \t]*$/m.exec(body);
880
- let next;
881
- if (!m) next = body.replace(/\n*$/, '\n') + `\n## Follow-ups\n${line}\n`;
882
- else {
883
- const start = m.index + m[0].length;
884
- const end = body.slice(start).search(/^## /m);
885
- const stop = end === -1 ? body.length : start + end;
886
- const section = body.slice(start, stop).replace(/\s*$/, '');
887
- next = body.slice(0, start) + section + `\n${line}\n` + (end === -1 ? '' : '\n') + body.slice(stop);
888
- }
889
- writeFileSync(file, next);
890
- }
1226
+ const links = {
1227
+ ...(foundWhile && { 'found while': foundWhile }),
1228
+ ...(blocks && foundWhile && { blocks: foundWhile }),
1229
+ };
1230
+ const stub = writeUnique(dir, stubBase(title), stubText(title, kind, '', links));
1231
+ if (foundWhile)
1232
+ rewriteTask(
1233
+ join(dir, foundWhile),
1234
+ (t) => addEntry(t, 'followup', {}, [`${title} — ${stub}${blocks ? ' [blocking]' : ''}`]).text,
1235
+ );
891
1236
  out({ stub, foundWhile, blocks: Boolean(blocks && foundWhile) });
892
1237
  break;
893
1238
  }
@@ -992,13 +1337,14 @@ try {
992
1337
  state.stage = 'done';
993
1338
  note(state, 'done', state.task);
994
1339
  writeState(dir, id, state);
1340
+ refreshTaskFile(join(dir, state.task), state);
995
1341
  unlinkSync(statePath(dir, id));
996
1342
  out(state);
997
1343
  break;
998
1344
  }
999
1345
  default:
1000
1346
  fail(
1001
- 'loopwright: usage: lw.mjs <dir|start|stage|reopen|lock|check-locks|accept-locks|keep-base|fingerprint|verdict|await-user|resume|park|explore|status|config|brief|tasks|adopt|worktree|carry|effort|done>',
1347
+ 'loopwright: usage: lw.mjs <dir|start|set|add|mark|edit|section|stage|reopen|lock|check-locks|accept-locks|keep-base|fingerprint|verdict|review-diff|await-user|resume|park|explore|status|config|brief|tasks|adopt|worktree|carry|effort|done>',
1002
1348
  );
1003
1349
  }
1004
1350
  } catch (err) {