loopwright 0.1.11 → 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,12 +19,28 @@ import {
17
19
  readState,
18
20
  realpathLoose,
19
21
  repoRelative,
22
+ settingValue,
20
23
  sha256File,
21
24
  statePath,
22
25
  workingTree,
23
26
  worktreeId,
27
+ writeFileAtomic,
24
28
  writeState,
25
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';
26
44
 
27
45
  const STAGES = ['plan', 'test', 'build', 'review', 'done'];
28
46
  const cwd = process.cwd();
@@ -31,8 +49,8 @@ function fail(msg) {
31
49
  process.stderr.write(msg + '\n');
32
50
  process.exit(1);
33
51
  }
34
- const note = (state, event, detail) => {
35
- (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() });
36
54
  };
37
55
  const out = (v) => process.stdout.write(JSON.stringify(v, null, 2) + '\n');
38
56
 
@@ -61,6 +79,32 @@ function scaffold(dir, withConfig) {
61
79
  if (withConfig && !existsSync(cfg)) copyFileSync(seedConfig(), cfg);
62
80
  }
63
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
+
64
108
  const isMainCheckout = () => gitTopLevel(cwd) === mainWorktreeRoot(cwd);
65
109
 
66
110
  function ctx(create = false) {
@@ -92,7 +136,7 @@ function effortFor(role, badProfile = fail, flagged) {
92
136
  const dir = !name && loopwrightDir(cwd);
93
137
  const state = dir && readState(dir, worktreeId(cwd));
94
138
  if (state?.task && existsSync(join(dir, state.task))) {
95
- 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');
96
140
  if (name === 'pending') name = undefined;
97
141
  }
98
142
  } catch {
@@ -122,16 +166,14 @@ function effortFor(role, badProfile = fail, flagged) {
122
166
  */
123
167
  function setHeader(taskPath, key, value) {
124
168
  try {
125
- const text = readFileSync(taskPath, 'utf8');
126
- const at = text.search(/^## /m);
127
- const split = at === -1 ? text.length : at;
128
- const line = new RegExp(`^${key}:[^\\r\\n]*`, 'm');
129
- const head = text.slice(0, split);
130
- if (!line.test(head)) return `no "${key}:" line`;
131
- 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
+ });
132
173
  return null;
133
174
  } catch (err) {
134
- 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})`;
135
177
  }
136
178
  }
137
179
 
@@ -142,6 +184,174 @@ function headerResult(misses) {
142
184
  return missed.length === 0;
143
185
  }
144
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
+
145
355
  /** The main checkout's config.json, else the seed config. */
146
356
  const readConfig = () => {
147
357
  const main = mainLoopwrightPath(cwd);
@@ -153,20 +363,23 @@ const gitOut = (args) => execFileSync('git', args, { cwd, encoding: 'utf8', stdi
153
363
 
154
364
  /** The worktree a task header names: `worktree: <path> (branch <name>)`. */
155
365
  function namedWorktree(header) {
156
- 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
+ );
157
369
  return m ? { path: resolve(m[1]), branch: m[2] ?? null } : null;
158
370
  }
159
371
 
160
372
  /** Task file fields: status/stage from the header (before the first `## `), title from `# `, goal from `## Goal`. */
161
373
  function readTask(root, rel) {
162
374
  const [head, ...sections] = readFileSync(join(root, rel), 'utf8').split(/^## /m);
163
- 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));
164
377
  return {
165
378
  title: /^# (.*)$/m.exec(head)?.[1].trim() ?? null,
166
- status: /^status:[ \t]*(\S+)/m.exec(head)?.[1] ?? null,
167
- stage: /^stage:[ \t]*(\S+)/m.exec(head)?.[1] ?? null,
379
+ status: settingValue(head, 'status') ?? null,
380
+ stage: settingValue(head, 'stage') ?? null,
168
381
  named: namedWorktree(head),
169
- goal: goal ? goal.replace(/^Goal[ \t]*\r?\n/, '').trim() : '',
382
+ goal: goal ? goal.replace(goalHeading, '').trim() : '',
170
383
  };
171
384
  }
172
385
 
@@ -182,7 +395,11 @@ const listWorktrees = () =>
182
395
 
183
396
  /** A move copies; the source stays, marked so no listing offers it again. */
184
397
  function markMoved(file, to) {
185
- 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
+ );
186
403
  }
187
404
 
188
405
  const today = () => {
@@ -207,8 +424,14 @@ function writeUnique(dir, base, text) {
207
424
  }
208
425
  }
209
426
 
210
- /** A proposed stub in park's format; `goal` is empty for a stub parked mid-task. */
211
- 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
+ }
212
435
 
213
436
  const refExists = (ref) => {
214
437
  try {
@@ -401,8 +624,16 @@ try {
401
624
  const base = flag(rest, '--base') ?? 'HEAD';
402
625
  const force = rest.includes('--force');
403
626
  if (force) rest.splice(rest.indexOf('--force'), 1);
627
+ const kind = flag(rest, '--kind') ?? 'feature';
628
+ const profile = flag(rest, '--profile');
404
629
  const task = rest[0];
405
- 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(', ')})`);
406
637
  // A task file belongs to the worktree its header names; starting it elsewhere would split its state.
407
638
  const own = loopwrightPath(cwd);
408
639
  const header = own && existsSync(join(own, task)) ? readFileSync(join(own, task), 'utf8').split(/^## /m)[0] : '';
@@ -438,12 +669,79 @@ try {
438
669
  stopBlocks: 0,
439
670
  history: Array.isArray(prior?.history) ? prior.history : [],
440
671
  };
441
- if (force) note(state, 'start', '--force');
442
- 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);
443
682
  writeState(dir, id, state);
683
+ if (title || proposed) refreshTaskFile(file, state);
444
684
  out(state);
445
685
  break;
446
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
+ }
447
745
  case 'stage': {
448
746
  const name = rest[0];
449
747
  if (!STAGES.includes(name)) fail(`loopwright: invalid stage '${name ?? ''}' (one of ${STAGES.join(', ')})`);
@@ -451,9 +749,11 @@ try {
451
749
  state.stage = name;
452
750
  state.stopBlocks = 0;
453
751
  delete state.awaitingUser;
454
- note(state, 'stage', name);
752
+ note(state, 'stage', name, { slice: sliceFor(dir, state, name) });
455
753
  writeState(dir, id, state);
456
- 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 });
457
757
  break;
458
758
  }
459
759
  case 'reopen': {
@@ -475,7 +775,9 @@ try {
475
775
  // Both lines are attempted even if the first misses, so a partial header is still fixed.
476
776
  const set = [setHeader(file, 'stage', target)];
477
777
  if (target === 'plan') set.push(setHeader(file, 'plan', 'draft'));
478
- out({ stage: target, reopened: true, header: headerResult(set) });
778
+ const header = headerResult(set);
779
+ refreshTaskFile(file, state);
780
+ out({ stage: target, reopened: true, header });
479
781
  break;
480
782
  }
481
783
  case 'lock': {
@@ -578,8 +880,9 @@ try {
578
880
  );
579
881
  }
580
882
  delete state.awaitingUser;
581
- note(state, 'verdict', `${result} round ${round}`);
883
+ note(state, 'verdict', `${result} round ${round}`, { slice: sliceFor(dir, state, 'review') });
582
884
  writeState(dir, id, state);
885
+ refreshTaskFile(join(dir, state.task), state);
583
886
  out(state.verdict);
584
887
  break;
585
888
  }
@@ -621,6 +924,7 @@ try {
621
924
  state.awaitingUser = reason;
622
925
  note(state, 'await-user', reason);
623
926
  writeState(dir, id, state);
927
+ refreshTaskFile(join(dir, state.task), state);
624
928
  out(state);
625
929
  break;
626
930
  }
@@ -629,6 +933,7 @@ try {
629
933
  note(state, 'resume', state.awaitingUser ?? '');
630
934
  delete state.awaitingUser;
631
935
  writeState(dir, id, state);
936
+ refreshTaskFile(join(dir, state.task), state);
632
937
  out(state);
633
938
  break;
634
939
  }
@@ -755,8 +1060,7 @@ try {
755
1060
  fail(`loopwright: worktree: ${stubFlag} is not a proposed stub`);
756
1061
  }
757
1062
  let goal = '';
758
- // isatty, not process.stdin.isTTY: touching process.stdin makes a piped fd 0 non-blocking, so a slow writer fails readFileSync with EAGAIN.
759
- if (!source && !isatty(0)) goal = readFileSync(0, 'utf8').trim();
1063
+ if (!source) goal = readInput().trim();
760
1064
  let base = baseFlag;
761
1065
  if (base !== undefined) {
762
1066
  if (base.startsWith('-') || !refExists(base)) fail(`loopwright: worktree: unknown base '${base}'`);
@@ -786,11 +1090,7 @@ try {
786
1090
  copyFileSync(source, join(dir, stub));
787
1091
  markMoved(source, join(dir, stub));
788
1092
  } else {
789
- stub = writeUnique(
790
- dir,
791
- stubBase(title),
792
- stubText([`# ${title}`, '', `kind: ${kind}`, 'status: proposed', 'stage: plan', 'plan: draft'], goal),
793
- );
1093
+ stub = writeUnique(dir, stubBase(title), stubText(title, kind, goal));
794
1094
  }
795
1095
  const hook = join('.agents', 'loopwright', 'hooks', 'lw.mjs');
796
1096
  out({
@@ -923,26 +1223,16 @@ try {
923
1223
  const foundWhile = active && existsSync(join(dir, active)) ? active : null;
924
1224
  if (active && !foundWhile)
925
1225
  process.stderr.write(`loopwright: warning: active task file ${active} is missing; follow-up not linked\n`);
926
- const header = [`# ${title}`, '', `kind: ${kind}`, 'status: proposed', 'stage: plan', 'plan: draft'];
927
- if (foundWhile) header.push(`found while: ${foundWhile}`);
928
- if (blocks && foundWhile) header.push(`blocks: ${foundWhile}`);
929
- const stub = writeUnique(dir, stubBase(title), stubText(header));
930
- if (foundWhile) {
931
- const line = `- ${title} — ${stub}${blocks ? ' [blocking]' : ''}`;
932
- const file = join(dir, foundWhile);
933
- const body = readFileSync(file, 'utf8');
934
- const m = /^## Follow-ups[ \t]*$/m.exec(body);
935
- let next;
936
- if (!m) next = body.replace(/\n*$/, '\n') + `\n## Follow-ups\n${line}\n`;
937
- else {
938
- const start = m.index + m[0].length;
939
- const end = body.slice(start).search(/^## /m);
940
- const stop = end === -1 ? body.length : start + end;
941
- const section = body.slice(start, stop).replace(/\s*$/, '');
942
- next = body.slice(0, start) + section + `\n${line}\n` + (end === -1 ? '' : '\n') + body.slice(stop);
943
- }
944
- writeFileSync(file, next);
945
- }
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
+ );
946
1236
  out({ stub, foundWhile, blocks: Boolean(blocks && foundWhile) });
947
1237
  break;
948
1238
  }
@@ -1047,13 +1337,14 @@ try {
1047
1337
  state.stage = 'done';
1048
1338
  note(state, 'done', state.task);
1049
1339
  writeState(dir, id, state);
1340
+ refreshTaskFile(join(dir, state.task), state);
1050
1341
  unlinkSync(statePath(dir, id));
1051
1342
  out(state);
1052
1343
  break;
1053
1344
  }
1054
1345
  default:
1055
1346
  fail(
1056
- 'loopwright: usage: lw.mjs <dir|start|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>',
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>',
1057
1348
  );
1058
1349
  }
1059
1350
  } catch (err) {
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- // PreToolUse hook (Claude Code only): send an AskUserQuestion back for a rewrite when it holds a bare loopwright label.
3
- // https://code.claude.com/docs/en/hooks.md (PreToolUse): tool_input.questions[] has question, header, options[].label and .description; exit 2 sends stderr to Claude.
2
+ // PreToolUse hook (Claude Code only): send an AskUserQuestion back for a rewrite when it holds a bare task id.
3
+ // https://code.claude.com/docs/en/hooks.md (PreToolUse): tool_input.questions[] has question, header, options[].label and .description.
4
4
  import { readFileSync } from 'node:fs';
5
5
  import { join } from 'node:path';
6
6
  import {
@@ -18,9 +18,6 @@ import {
18
18
 
19
19
  // Two denials in a row, then the question goes through, so a stubborn one never loops.
20
20
  const CAP = 2;
21
- // Words only loopwright uses; common words with a loopwright meaning (tier, slice, lock) are left to the rules file.
22
- // The closing \b keeps everyday words out ("fix rounding", "two passwords", "stop gateway").
23
- const PHRASES = /\b(?:stop[- ]gates?|re-?lock(?:s|ed|ing)?|fix[- ]rounds?|two[- ]pass|acceptance criteri(?:a|on))\b/gi;
24
21
  // Text after a plain description: in brackets, parentheses or backticks.
25
22
  const LABELLED = /\([^)]*\)|\[[^\]]*\]|`[^`]*`/g;
26
23
 
@@ -51,7 +48,7 @@ try {
51
48
  for (const text of texts) {
52
49
  if (typeof text !== 'string') continue;
53
50
  const bare = text.replace(LABELLED, ' ');
54
- const terms = [...new Set([...(ids ? bare.matchAll(ids) : []), ...bare.matchAll(PHRASES)].map((m) => m[0]))];
51
+ const terms = [...new Set([...(ids ? bare.matchAll(ids) : [])].map((m) => m[0]))];
55
52
  if (terms.length) found.push(`- "${text}": ${terms.join(', ')}`);
56
53
  }
57
54
 
@@ -66,12 +63,11 @@ try {
66
63
  state.questionBlocks = blocks + 1;
67
64
  writeState(dir, id, state);
68
65
  deny(
69
- '',
70
- '',
66
+ 'PreToolUse',
71
67
  [
72
- 'loopwright: this question has loopwright labels the user has not met, so it was not shown:',
68
+ 'loopwright: this question was not shown because it names task ids the user has never seen:',
73
69
  ...found,
74
- `Say each one in everyday words first and put the label in brackets after it, as in ${USER_MESSAGES_RULES}. Then ask again.`,
70
+ `Rewrite it so each id is described in plain words first and the id is only a bracketed pointer, as in ${USER_MESSAGES_RULES}. Then ask again.`,
75
71
  ].join('\n'),
76
72
  );
77
73
  } catch (err) {
@@ -3,6 +3,7 @@
3
3
  import { existsSync, readFileSync } from 'node:fs';
4
4
  import { join } from 'node:path';
5
5
  import {
6
+ ICON_PREFIX,
6
7
  USER_MESSAGES_RULES,
7
8
  allow,
8
9
  exitIfHooksOff,
@@ -10,6 +11,7 @@ import {
10
11
  loopwrightDir,
11
12
  readState,
12
13
  readStdinJson,
14
+ settingValue,
13
15
  worktreeId,
14
16
  } from './lib.mjs';
15
17
 
@@ -21,9 +23,14 @@ const NEXT = {
21
23
  done: 'Run /loopwright-done.',
22
24
  };
23
25
 
26
+ function headingAt(lines, name) {
27
+ const heading = new RegExp(`^#{1,6}\\s*${ICON_PREFIX}${name}\\b`, 'i');
28
+ return lines.findIndex((l) => heading.test(l.trim()));
29
+ }
30
+
24
31
  function goalParagraph(text) {
25
32
  const lines = text.split(/\r?\n/);
26
- const i = lines.findIndex((l) => /^#{1,6}\s*goal\b/i.test(l.trim()));
33
+ const i = headingAt(lines, 'goal');
27
34
  if (i === -1) return [];
28
35
  const out = [];
29
36
  for (const l of lines.slice(i + 1)) {
@@ -40,7 +47,7 @@ function goalParagraph(text) {
40
47
  // First non-empty line under `## Root cause`; one line keeps the 40-line cap for the decisions.
41
48
  function rootCauseLine(text) {
42
49
  const lines = text.split(/\r?\n/);
43
- const i = lines.findIndex((l) => /^#{1,6}\s*root cause\b/i.test(l.trim()));
50
+ const i = headingAt(lines, 'root cause');
44
51
  if (i === -1) return null;
45
52
  for (const l of lines.slice(i + 1)) {
46
53
  if (/^#{1,6}\s/.test(l)) return null;
@@ -64,7 +71,7 @@ try {
64
71
  const file = join(dir, String(state.task));
65
72
  if (existsSync(file)) {
66
73
  const text = readFileSync(file, 'utf8');
67
- const fix = /^kind:\s*fix\s*$/im.test(text);
74
+ const fix = settingValue(text, 'kind') === 'fix';
68
75
  if (fix) lines.push('kind: fix');
69
76
  lines.push(...goalParagraph(text));
70
77
  const root = fix ? rootCauseLine(text) : null;