loopwright 0.1.6 → 0.1.8

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.
package/README.md CHANGED
@@ -58,7 +58,7 @@ flowchart TD
58
58
  done --> commit(["You commit"])
59
59
  ```
60
60
 
61
- - **Plan** runs in your session. A read-only scout maps the repo, then you answer the high-impact questions one at a time and confirm the plan. Nothing is built before that.
61
+ - **Plan** runs in your session. Plan first restates your goal for you to confirm or correct. A read-only scout then maps the repo, then you answer the high-impact questions one at a time and confirm the plan. Nothing is built before that.
62
62
  - **Test** (standard, large, and every fix): a tester subagent, which never sees the implementation, writes acceptance tests from your confirmed criteria and locks them.
63
63
  - **Build**: an implementer subagent makes the locked tests pass. Small feature tasks skip Test, so the implementer writes the tests; a fix never skips it.
64
64
  - **Review**: a reviewer that starts blind runs your checks, confirms the locked tests are untouched, and reports only proven, high-impact findings. Blocking findings send the task back to Build, up to 3 rounds by default; findings it cannot confirm come to you to fix or dismiss.
@@ -88,7 +88,7 @@ Run a single stage, or the whole loop with `flow`. In Codex, use `$` instead of
88
88
  |---|---|---|---|
89
89
  | Skills install | Supported, tested | WIP: installed, not tested end-to-end | WIP: reads `.agents/skills` |
90
90
  | Subagents (scout, tester, implementer, reviewer) | Supported, tested | WIP: installed, not tested end-to-end | WIP: `.junie/agents` |
91
- | Hook enforcement (locked-test guard, stop gate, context reinjection) | Supported, tested | WIP: installed, not tested end-to-end | Experimental (`--experimental junie-hooks`, Early Access) |
91
+ | Hook enforcement (locked-test guard, stop gate, context reinjection, compaction instructions on Claude Code) | Supported, tested | WIP: installed, not tested end-to-end | Experimental (`--experimental junie-hooks`, Early Access) |
92
92
  | Structured questions | `AskUserQuestion` | Plain-text fallback (numbered options) | Plain-text fallback |
93
93
  | Cross-agent review (as the reviewer) | Supported, tested | WIP: untested | Not supported |
94
94
  | Global install | Supported, tested | WIP: installed, not tested end-to-end | WIP: `~/.junie/agents` |
@@ -13,6 +13,7 @@ The main thread gives you the task file path. Read its acceptance criteria (`AC
13
13
 
14
14
  - Read implementation files only as far as needed to import public interfaces (module paths, exported names, signatures). Do not read or test internals.
15
15
  - Reopened task (the main thread says so and names the scope): you may edit the existing locked tests for the named ACs, then re-lock them. Leave every other locked test untouched.
16
+ - Pulled locked tests (the main thread lists the files from `pulledLocks`): check each still tests its acceptance criteria, edit only what the pull broke, then re-lock only those files. Leave every other locked test untouched.
16
17
  - Re-dispatched during Test-stage verification (the main thread names the problem, e.g. comments restating a test name): you may edit and re-lock your own tests; this is the same re-lock as a reopen, before Build.
17
18
  - Read `{{LW_HOME}}/prompts/standards.md` and follow it in the tests you write.
18
19
  - Write only test files (and fixtures they need). Do not create or edit implementation code, not even stubs.
@@ -78,17 +78,21 @@ function requireState() {
78
78
  return { dir, id, state };
79
79
  }
80
80
 
81
- /** Effort for a role: the task header's `profile:`, else the manifest's recorded profile, else balanced. */
82
- function effortFor(role) {
81
+ /**
82
+ * Effort for a role: a `--profile` name, else the task header's `profile:` (`pending` means not chosen yet), else the manifest's recorded profile, else balanced.
83
+ * An unknown profile goes to `badProfile`, which fails by default; if it returns, there is no effort.
84
+ */
85
+ function effortFor(role, badProfile = fail, flagged) {
83
86
  if (!Object.hasOwn(PROFILES.balanced, role))
84
87
  fail(`loopwright: usage: effort <${Object.keys(PROFILES.balanced).join('|')}>`);
85
88
  // Works before `start` (Plan's scout spawn): no task or repo state just means no header.
86
- let name;
89
+ let name = flagged;
87
90
  try {
88
- const dir = loopwrightDir(cwd);
91
+ const dir = !name && loopwrightDir(cwd);
89
92
  const state = dir && readState(dir, worktreeId(cwd));
90
93
  if (state?.task && existsSync(join(dir, state.task))) {
91
94
  name = /^profile:\s*(\S+)\s*$/m.exec(readFileSync(join(dir, state.task), 'utf8').split(/^## /m)[0])?.[1];
95
+ if (name === 'pending') name = undefined;
92
96
  }
93
97
  } catch {
94
98
  // Unreadable task or state: fall through to the manifest profile.
@@ -104,11 +108,46 @@ function effortFor(role) {
104
108
  }
105
109
  }
106
110
  name ??= 'balanced';
107
- if (!Object.hasOwn(PROFILES, name))
108
- fail(`loopwright: unknown profile '${name}' (allowed: ${Object.keys(PROFILES).join(', ')})`);
111
+ if (!Object.hasOwn(PROFILES, name)) {
112
+ badProfile(`loopwright: unknown profile '${name}' (allowed: ${Object.keys(PROFILES).join(', ')})`);
113
+ return undefined;
114
+ }
109
115
  return PROFILES[name][role];
110
116
  }
111
117
 
118
+ /**
119
+ * Set `key: value` in the task file header (the text before the first `## `). The body is never touched,
120
+ * and the file's line endings are kept. Returns null when written, else why not (nothing is written then).
121
+ */
122
+ function setHeader(taskPath, key, value) {
123
+ 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));
131
+ return null;
132
+ } catch (err) {
133
+ return err.code === 'ENOENT' ? 'task file missing' : `cannot write "${key}:" (${err.code ?? err.message})`;
134
+ }
135
+ }
136
+
137
+ /** A missed header write is a warning, never a failure: state is already saved. Returns whether every write landed. */
138
+ function headerResult(misses) {
139
+ const missed = [...new Set(misses.filter(Boolean))];
140
+ if (missed.length) process.stderr.write(`loopwright: task file header not updated (${missed.join('; ')})\n`);
141
+ return missed.length === 0;
142
+ }
143
+
144
+ /** The main checkout's config.json, else the seed config. */
145
+ const readConfig = () => {
146
+ const main = mainLoopwrightPath(cwd);
147
+ const file = main && join(main, 'config.json');
148
+ return JSON.parse(readFileSync(file && existsSync(file) ? file : seedConfig(), 'utf8'));
149
+ };
150
+
112
151
  const gitOut = (args) => execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
113
152
 
114
153
  /** The worktree a task header names: `worktree: <path> (branch <name>)`. */
@@ -179,6 +218,166 @@ const refExists = (ref) => {
179
218
  }
180
219
  };
181
220
 
221
+ /**
222
+ * Re-locks and restarts that the history flags for the user's attention, and the ones an `accept-locks` took out.
223
+ * Re-locking an existing lock after a build could launder an implementer's edit; first-time locks in later slices are legitimate.
224
+ * A reopen covers re-locks until the next Build starts, but only when the history reads
225
+ * await-user, resume, reopen with nothing between (the pair the skills run around the user's answer
226
+ * to going back); any other reopen is ignored. A faked triple is not detected.
227
+ * An acceptance covers only what was flagged when it ran: a later re-lock or forced restart flags again.
228
+ */
229
+ function lockFlags(history = []) {
230
+ const lockedAfterBuild = [];
231
+ const relockedAfterReopen = [];
232
+ const accepted = [];
233
+ const seen = new Map();
234
+ let reopenReason = null;
235
+ let prev = null;
236
+ let prev2 = null;
237
+ let built = false;
238
+ let forcedRestartAfterBuild = false;
239
+ const unaccept = (match) => {
240
+ const i = accepted.findIndex(match);
241
+ if (i !== -1) accepted.splice(i, 1);
242
+ };
243
+ for (const e of history) {
244
+ const sanctioned = prev2 === 'await-user' && prev === 'resume';
245
+ prev2 = prev;
246
+ prev = e.event;
247
+ if (e.event === 'stage' && e.detail === 'build') {
248
+ for (const p of seen.keys()) seen.set(p, true);
249
+ reopenReason = null;
250
+ built = true;
251
+ }
252
+ if (e.event === 'reopen' && sanctioned) reopenReason = e.reason ?? '';
253
+ if (built && e.event === 'start' && e.detail === '--force') {
254
+ forcedRestartAfterBuild = true;
255
+ unaccept((a) => a.restart);
256
+ }
257
+ if (e.event === 'accept-locks') {
258
+ if (e.detail === '--restart') {
259
+ forcedRestartAfterBuild = false;
260
+ accepted.push({ restart: true, reason: e.reason });
261
+ } else {
262
+ const i = lockedAfterBuild.indexOf(e.detail);
263
+ if (i !== -1) lockedAfterBuild.splice(i, 1);
264
+ accepted.push({ path: e.detail, reason: e.reason });
265
+ }
266
+ }
267
+ if (e.event !== 'lock') continue;
268
+ if (seen.get(e.detail) === true) {
269
+ if (reopenReason !== null) {
270
+ if (!relockedAfterReopen.some((r) => r.path === e.detail))
271
+ relockedAfterReopen.push({ path: e.detail, reason: reopenReason });
272
+ } else {
273
+ unaccept((a) => a.path === e.detail);
274
+ if (!lockedAfterBuild.includes(e.detail)) lockedAfterBuild.push(e.detail);
275
+ }
276
+ }
277
+ seen.set(e.detail, false);
278
+ }
279
+ return { lockedAfterBuild, relockedAfterReopen, forcedRestartAfterBuild, accepted };
280
+ }
281
+
282
+ const isAncestor = (a, b) => {
283
+ try {
284
+ gitOut(['merge-base', '--is-ancestor', a, b]);
285
+ return true;
286
+ } catch {
287
+ return false;
288
+ }
289
+ };
290
+
291
+ /**
292
+ * Locked tests out of step with their lock that the pulled commits from..to touched: the ones on the upstream
293
+ * branch, never the task's local-only commits. A repo without an upstream branch counts every commit.
294
+ */
295
+ function pulledLockedTests(state, from, to) {
296
+ const top = gitTopLevel(cwd);
297
+ const stale = (state.lockedTests ?? []).filter((l) => {
298
+ const abs = resolve(top, l.path);
299
+ return existsSync(abs) && sha256File(abs) !== l.sha256;
300
+ });
301
+ if (!stale.length) return undefined;
302
+ try {
303
+ // Lock paths are lower-cased on win32 (repoRelative), git prints the tracked case.
304
+ const fold = (p) => (process.platform === 'win32' ? p.toLowerCase() : p);
305
+ const lines = (args) => gitOut(args).split('\n').filter(Boolean);
306
+ const upstream = ['@{u}', 'origin/HEAD'].find(refExists);
307
+ let commits = lines(['rev-list', `${from}..${to}`]);
308
+ if (upstream) {
309
+ const onUpstream = new Set(lines(['rev-list', `${from}..${upstream}`]));
310
+ commits = commits.filter((c) => onUpstream.has(c));
311
+ }
312
+ const names = (args) =>
313
+ gitOut(['-c', 'core.quotePath=false', ...args])
314
+ .split('\0')
315
+ .filter(Boolean)
316
+ .map(fold);
317
+ // `--cc` lists a merge commit's own edits (conflict resolutions) only, never what its second parent brings in:
318
+ // the commits that merge brought are listed on their own. `-m` would list every file the mainline changed since
319
+ // the merged branch forked, from before the base too. A file the pulled commits changed and then reverted is
320
+ // dropped by the net diff from..to.
321
+ const touched = new Set(
322
+ commits.length ? names(['log', '--cc', '--no-walk', '--name-only', '--format=', '-z', ...commits]) : [],
323
+ );
324
+ const net = new Set(names(['diff', '--name-only', '-z', from, to]));
325
+ return stale.filter((l) => touched.has(fold(l.path)) && net.has(fold(l.path))).map((l) => l.path);
326
+ } catch (err) {
327
+ process.stderr.write(`loopwright: cannot diff the previous base (${err.message.split('\n')[0]}); no pulledLocks\n`);
328
+ return undefined;
329
+ }
330
+ }
331
+
332
+ /** The answered HEAD when it sits on the way from the base to `to`: those commits stay in the review. */
333
+ const keptHead = (state, to) =>
334
+ state.answeredHead && isAncestor(state.baseCommit, state.answeredHead) && isAncestor(state.answeredHead, to)
335
+ ? state.answeredHead
336
+ : undefined;
337
+
338
+ /**
339
+ * HEAD past the base with at least one commit already on the upstream branch (else origin/HEAD), and not yet
340
+ * answered. Once answered, only the commits made since that answer are checked, and `keptEarlier` says the
341
+ * answered commits stay in the review. `localOnly` lists the short shas of the commits that exist only locally
342
+ * (the task's own work, so the branch holds both kinds); a merge commit holds no work of its own and never counts.
343
+ */
344
+ function movedHead(state) {
345
+ try {
346
+ const to = gitOut(['rev-parse', 'HEAD']);
347
+ if (to === state.baseCommit || to === state.answeredHead) return undefined;
348
+ const upstream = ['@{u}', 'origin/HEAD'].find(refExists);
349
+ if (!upstream) return undefined;
350
+ const kept = keptHead(state, to);
351
+ const keptEarlier = Boolean(kept);
352
+ const range = `${kept ?? state.baseCommit}..`;
353
+ const lines = (args) => gitOut(args).split('\n').filter(Boolean);
354
+ const onUpstream = new Set(lines(['rev-list', `${range}${upstream}`]));
355
+ const commits = lines(['log', '--format=%H %s', `${range}HEAD`]);
356
+ if (!commits.some((c) => onUpstream.has(c.split(' ')[0]))) return undefined;
357
+ const localOnly = lines(['rev-list', '--no-merges', `${range}HEAD`])
358
+ .filter((c) => !onUpstream.has(c))
359
+ .map((c) => c.slice(0, 7));
360
+ return {
361
+ from: state.baseCommit,
362
+ to,
363
+ commits,
364
+ ...(keptEarlier && { keptEarlier }),
365
+ ...(localOnly.length && { localOnly }),
366
+ };
367
+ } catch {
368
+ return undefined;
369
+ }
370
+ }
371
+
372
+ /** How many commits the task already has since its base, so a later pull is known to sit on top of them. */
373
+ function ownCommits(state) {
374
+ try {
375
+ return Number(gitOut(['rev-list', '--count', `${state.baseCommit}..HEAD`])) || undefined;
376
+ } catch {
377
+ return undefined;
378
+ }
379
+ }
380
+
182
381
  const [cmd, ...rest] = process.argv.slice(2);
183
382
  try {
184
383
  switch (cmd) {
@@ -200,11 +399,23 @@ try {
200
399
  const { dir, id } = ctx(true);
201
400
  const prior = readState(dir, id);
202
401
  if (!force && prior) fail('loopwright: task already active (run lw.mjs done first, or start --force)');
402
+ const baseCommit = gitOut(['rev-parse', base]);
403
+ const baseMoved = prior?.baseCommit !== baseCommit;
404
+ // Locked tests out of step with their lock now that the base moves, that the commits it moves over touched:
405
+ // the pull's files, fixed here so a later edit of a test that matched its lock is never taken for a pull.
406
+ const pulledSnapshot = baseMoved
407
+ ? prior?.baseCommit && pulledLockedTests(prior, prior.baseCommit, baseCommit)
408
+ : prior?.pulledSnapshot;
203
409
  const state = {
204
410
  version: 1,
205
411
  task,
206
412
  stage: 'plan',
207
- baseCommit: gitOut(['rev-parse', base]),
413
+ baseCommit,
414
+ // The locked tests a pull changed, and where in the history the base moved, so a re-lock after it counts
415
+ // as handled; both kept across restarts that leave the base alone.
416
+ pulledSnapshot: pulledSnapshot?.length ? pulledSnapshot : undefined,
417
+ baseMovedAt: baseMoved ? (prior?.history?.length ?? 0) : prior.baseMovedAt,
418
+ answeredHead: prior?.answeredHead,
208
419
  worktree: gitTopLevel(cwd),
209
420
  branch: gitOut(['rev-parse', '--abbrev-ref', 'HEAD']),
210
421
  // A forced restart keeps the audit trail and the lock records, so a locked test edited
@@ -229,7 +440,7 @@ try {
229
440
  delete state.awaitingUser;
230
441
  note(state, 'stage', name);
231
442
  writeState(dir, id, state);
232
- out(state);
443
+ out({ stage: name, header: headerResult([setHeader(join(dir, state.task), 'stage', name)]) });
233
444
  break;
234
445
  }
235
446
  case 'reopen': {
@@ -246,7 +457,11 @@ try {
246
457
  note(state, 'reopen', target);
247
458
  state.history.at(-1).reason = reason;
248
459
  writeState(dir, id, state);
249
- out(state);
460
+ const file = join(dir, state.task);
461
+ // Both lines are attempted even if the first misses, so a partial header is still fixed.
462
+ const set = [setHeader(file, 'stage', target)];
463
+ if (target === 'plan') set.push(setHeader(file, 'plan', 'draft'));
464
+ out({ stage: target, reopened: true, header: headerResult(set) });
250
465
  break;
251
466
  }
252
467
  case 'lock': {
@@ -279,42 +494,50 @@ try {
279
494
  else if (sha256File(abs) !== l.sha256) changed.push(l.path);
280
495
  }
281
496
  const ok = changed.length === 0 && missing.length === 0;
282
- // Re-locking an existing lock after a build could launder an implementer's edit; first-time locks in later slices are legitimate.
283
- // A reopen covers re-locks until the next Build starts, but only when the history reads
284
- // await-user, resume, reopen with nothing between (the pair the skills run around the user's answer
285
- // to going back); any other reopen is ignored. A faked triple is not detected.
286
- const lockedAfterBuild = [];
287
- const relockedAfterReopen = [];
288
- const seen = new Map();
289
- let reopenReason = null;
290
- let prev = null;
291
- let prev2 = null;
292
- for (const e of state.history ?? []) {
293
- const sanctioned = prev2 === 'await-user' && prev === 'resume';
294
- prev2 = prev;
295
- prev = e.event;
296
- if (e.event === 'stage' && e.detail === 'build') {
297
- for (const p of seen.keys()) seen.set(p, true);
298
- reopenReason = null;
299
- }
300
- if (e.event === 'reopen' && sanctioned) reopenReason = e.reason ?? '';
301
- if (e.event !== 'lock') continue;
302
- if (seen.get(e.detail) === true) {
303
- if (reopenReason !== null) {
304
- if (!relockedAfterReopen.some((r) => r.path === e.detail))
305
- relockedAfterReopen.push({ path: e.detail, reason: reopenReason });
306
- } else if (!lockedAfterBuild.includes(e.detail)) lockedAfterBuild.push(e.detail);
307
- }
308
- seen.set(e.detail, false);
497
+ const { lockedAfterBuild, relockedAfterReopen, forcedRestartAfterBuild, accepted } = lockFlags(state.history);
498
+ out({ ok, changed, missing, lockedAfterBuild, relockedAfterReopen, forcedRestartAfterBuild, accepted });
499
+ process.exit(ok ? 0 : 1);
500
+ break;
501
+ }
502
+ case 'accept-locks': {
503
+ // Takes re-locks and a forced restart that a decision covers, or that the user dismissed, out of check-locks.
504
+ const usage = 'loopwright: usage: accept-locks --reason "<text>" [--restart] [<path>...]';
505
+ const reason = flag(rest, '--reason')?.trim();
506
+ if (!reason) fail(`loopwright: accept-locks requires --reason <text>\n${usage}`);
507
+ const restart = rest.includes('--restart');
508
+ if (restart) rest.splice(rest.indexOf('--restart'), 1);
509
+ if (!restart && rest.length === 0) fail(`loopwright: accept-locks needs a path or --restart\n${usage}`);
510
+ const { dir, id, state } = requireState();
511
+ const flags = lockFlags(state.history);
512
+ const items = [...rest.map((p) => repoRelative(cwd, p)), ...(restart ? ['--restart'] : [])];
513
+ const flagged = (item) =>
514
+ item === '--restart' ? flags.forcedRestartAfterBuild : flags.lockedAfterBuild.includes(item);
515
+ const accepted = items.filter(flagged);
516
+ for (const item of accepted) {
517
+ note(state, 'accept-locks', item);
518
+ state.history.at(-1).reason = reason;
309
519
  }
310
- let built = false;
311
- let forcedRestartAfterBuild = false;
312
- for (const e of state.history ?? []) {
313
- if (e.event === 'stage' && e.detail === 'build') built = true;
314
- if (built && e.event === 'start' && e.detail === '--force') forcedRestartAfterBuild = true;
520
+ if (accepted.length) writeState(dir, id, state);
521
+ out({ accepted, notFlagged: items.filter((item) => !flagged(item)) });
522
+ break;
523
+ }
524
+ case 'keep-base': {
525
+ // Records the current HEAD as answered, so `brief` stops reporting headMoved until HEAD moves again.
526
+ // `--pulled`: some of those commits are pulled, so the locked tests they changed are recorded as after a base move.
527
+ const reason = flag(rest, '--reason')?.trim();
528
+ if (!reason) fail('loopwright: keep-base requires --reason <text>');
529
+ const { dir, id, state } = requireState();
530
+ const head = gitOut(['rev-parse', 'HEAD']);
531
+ if (rest.includes('--pulled')) {
532
+ const files = pulledLockedTests(state, keptHead(state, head) ?? state.baseCommit, head);
533
+ state.pulledSnapshot = files?.length ? files : undefined;
534
+ state.baseMovedAt = state.history.length;
315
535
  }
316
- out({ ok, changed, missing, lockedAfterBuild, relockedAfterReopen, forcedRestartAfterBuild });
317
- process.exit(ok ? 0 : 1);
536
+ state.answeredHead = head;
537
+ note(state, 'keep-base', state.answeredHead);
538
+ state.history.at(-1).reason = reason;
539
+ writeState(dir, id, state);
540
+ out({ answeredHead: state.answeredHead });
318
541
  break;
319
542
  }
320
543
  case 'fingerprint': {
@@ -550,15 +773,79 @@ try {
550
773
  out({ carried });
551
774
  break;
552
775
  }
553
- case 'config': {
554
- const main = mainLoopwrightPath(cwd);
555
- const file = main && join(main, 'config.json');
556
- out(JSON.parse(readFileSync(file && existsSync(file) ? file : seedConfig(), 'utf8')));
776
+ case 'config':
777
+ out(readConfig());
778
+ break;
779
+ case 'brief': {
780
+ // One call for a stage's setup: what `dir`, `status`, `config` and `effort <role>` told it, minus the history.
781
+ // A bad profile or an unreadable config.json costs only that field (warned on stderr), not the whole brief.
782
+ const warn = (msg) => process.stderr.write(`${msg}\n`);
783
+ const effort =
784
+ rest[0] === undefined ? undefined : effortFor(rest[0], (msg) => warn(`${msg}; brief has no effort`));
785
+ const dir = loopwrightDir(cwd);
786
+ const state = dir && readState(dir, worktreeId(cwd));
787
+ const history = state?.history ?? [];
788
+ // A reopen counts until the next Build or Review: Review sends a pulled test back to Test and goes on to
789
+ // pass without a Build, and that reopen must not scope the next slice's Test.
790
+ const lastScoped = history.findLastIndex(
791
+ (e) => e.event === 'stage' && (e.detail === 'build' || e.detail === 'review'),
792
+ );
793
+ const reopen = history.findLast((e, i) => e.event === 'reopen' && i > lastScoped);
794
+ let cfg;
795
+ try {
796
+ cfg = readConfig();
797
+ } catch (err) {
798
+ warn(`loopwright: config.json unreadable (${err.message}); brief uses the default config`);
799
+ cfg = JSON.parse(readFileSync(fileURLToPath(new URL('./default-config.json', import.meta.url)), 'utf8'));
800
+ }
801
+ const { maxFixRounds, crossAgentReview, docsDir, models } = cfg;
802
+ const flags = lockFlags(history);
803
+ const flaggedLocks =
804
+ flags.lockedAfterBuild.length || flags.forcedRestartAfterBuild
805
+ ? { lockedAfterBuild: flags.lockedAfterBuild, forcedRestartAfterBuild: flags.forcedRestartAfterBuild }
806
+ : undefined;
807
+ const top = state?.pulledSnapshot?.length && gitTopLevel(cwd);
808
+ const relocked = new Set(
809
+ history
810
+ .slice(state?.baseMovedAt ?? 0)
811
+ .filter((e) => e.event === 'lock')
812
+ .map((e) => e.detail),
813
+ );
814
+ const pulledLocks = (state?.lockedTests ?? [])
815
+ .filter((l) => {
816
+ const abs = top && resolve(top, l.path);
817
+ return (
818
+ abs &&
819
+ state.pulledSnapshot.includes(l.path) &&
820
+ !relocked.has(l.path) &&
821
+ existsSync(abs) &&
822
+ sha256File(abs) !== l.sha256
823
+ );
824
+ })
825
+ .map((l) => l.path);
826
+ out({
827
+ dir,
828
+ task: state?.task ?? null,
829
+ stage: state?.stage,
830
+ baseCommit: state?.baseCommit,
831
+ lockedTests: state?.lockedTests,
832
+ verdict: state?.verdict,
833
+ awaitingUser: state?.awaitingUser,
834
+ flaggedLocks,
835
+ pulledLocks: pulledLocks.length ? pulledLocks : undefined,
836
+ headMoved: state && movedHead(state),
837
+ ownCommits: state ? ownCommits(state) : undefined,
838
+ reopened: reopen ? { target: reopen.detail, reason: reopen.reason } : null,
839
+ config: { maxFixRounds, crossAgentReview, docsDir, crossAgentReviewer: models?.crossAgentReviewer },
840
+ effort,
841
+ });
557
842
  break;
558
843
  }
559
- case 'effort':
560
- process.stdout.write(effortFor(rest[0]) + '\n');
844
+ case 'effort': {
845
+ const profile = flag(rest, '--profile');
846
+ process.stdout.write(effortFor(rest[0], fail, profile) + '\n');
561
847
  break;
848
+ }
562
849
  case 'park': {
563
850
  // Captures work found mid-task as a proposed stub. Reads state only to find the active task; never writes it.
564
851
  const usage = 'loopwright: usage: park "<title>" [--blocks] [--kind feature|fix]';
@@ -705,7 +992,7 @@ try {
705
992
  }
706
993
  default:
707
994
  fail(
708
- 'loopwright: usage: lw.mjs <dir|start|stage|reopen|lock|check-locks|fingerprint|verdict|await-user|resume|park|explore|status|config|tasks|adopt|worktree|carry|effort|done>',
995
+ '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>',
709
996
  );
710
997
  }
711
998
  } catch (err) {
@@ -0,0 +1,31 @@
1
+ #!/usr/bin/env node
2
+ // PreCompact hook (Claude Code only): tell compaction what the summary must keep while a task is active.
3
+ // https://code.claude.com/docs/en/hooks.md (PreCompact output): exit 0 with stdout uses the stdout as instructions for the compaction summary.
4
+ import { allow, exitIfHooksOff, failOpen, loopwrightDir, readState, readStdinJson, worktreeId } from './lib.mjs';
5
+
6
+ exitIfHooksOff();
7
+
8
+ try {
9
+ const input = await readStdinJson();
10
+ const cwd = input.project_path || input.cwd || process.cwd();
11
+ const dir = loopwrightDir(cwd);
12
+ if (!dir) allow();
13
+ const state = readState(dir, worktreeId(cwd));
14
+ if (!state) allow();
15
+
16
+ const lines = [`loopwright task in progress: ${state.task} (stage: ${state.stage}).`];
17
+ if (state.awaitingUser) lines.push(`Waiting on the user: ${state.awaitingUser}`);
18
+ lines.push(
19
+ 'Keep in the summary, word for word where it is a quote:',
20
+ '- the task file path and the stage;',
21
+ '- any question the user has not answered yet, with its options;',
22
+ '- unresolved review findings, verbatim;',
23
+ '- the implementer report, if a second review pass is still due;',
24
+ '- any user decision that is not yet written in the task file.',
25
+ 'After compaction, re-read the task file before continuing.',
26
+ );
27
+ process.stdout.write(lines.join('\n') + '\n');
28
+ allow();
29
+ } catch (err) {
30
+ failOpen(err);
31
+ }
@@ -6,11 +6,12 @@ State tool: `node "{{LW_HOME}}/hooks/lw.mjs" <cmd>`, run from the task's worktre
6
6
 
7
7
  ## 0. Locked tests (always first)
8
8
 
9
- Run `node "{{LW_HOME}}/hooks/lw.mjs" check-locks`. It prints `{ok, changed, missing, lockedAfterBuild, relockedAfterReopen, forcedRestartAfterBuild}` and exits 1 when `ok` is false.
9
+ Run `node "{{LW_HOME}}/hooks/lw.mjs" check-locks`. It prints `{ok, changed, missing, lockedAfterBuild, relockedAfterReopen, forcedRestartAfterBuild, accepted}` and exits 1 when `ok` is false.
10
10
  - `ok` is false → one Blocking finding per path in `changed` and `missing` (expectation: locked acceptance tests are unchanged; proof: the check-locks output).
11
- - `lockedAfterBuild` is non-empty → one Undecided finding per path (expectation: "acceptance test re-locked after Build began; user must confirm"; proof: the check-locks output).
11
+ - `lockedAfterBuild` is non-empty (paths not accepted) → one Undecided finding per path (expectation: "acceptance test re-locked after Build began; user must confirm"; proof: the check-locks output).
12
12
  - `relockedAfterReopen` is non-empty → information, not a finding: the user sent the task back through `lw.mjs reopen` and the tester re-locked these paths (`check-locks` counts only a reopen directly after an `await-user` and `resume` pair, so a reopen without the user's answer shows up under `lockedAfterBuild`). These re-locks are expected; do not report them.
13
- - `forcedRestartAfterBuild` is true → one Undecided finding (expectation: "task state was force-restarted after Build began; user must confirm locked tests"; proof: the check-locks output).
13
+ - `accepted` is non-empty → information, not a finding: a decision in the task file or the user already accepted these re-locks (`{path, reason}`) or the forced restart (`{restart: true, reason}`). Do not report them.
14
+ - `forcedRestartAfterBuild` is true (a restart not accepted) → one Undecided finding (expectation: "task state was force-restarted after Build began; user must confirm locked tests"; proof: the check-locks output).
14
15
  - The command errors (e.g. no active task) → one Blocking finding with the error text as proof.
15
16
 
16
17
  ## Inputs
@@ -9,19 +9,25 @@ The implementer subagent writes the code. This thread dispatches it and hands th
9
9
  ## Setup
10
10
 
11
11
  1. Run every loopwright command from the worktree root: `cd "$(git rev-parse --show-toplevel)"`.
12
- 2. `node "{{LW_HOME}}/hooks/lw.mjs" dir` → `<lw>` (`null` inside a git repo → no task has started here yet; `lw.mjs start` creates `.loopwright/` with the first task, so continue and the next step reports "no active task". Not a git repo → tell the user loopwright must run inside a git repo, stop).
13
- 3. `node "{{LW_HOME}}/hooks/lw.mjs" status` → `task` (relative to `<lw>`) and `lockedTests`. "no active task" → point the user to `/loopwright-plan` or `/loopwright-flow`, stop.
12
+ 2. `node "{{LW_HOME}}/hooks/lw.mjs" brief implementer` → `dir` (`<lw>`), `task` (relative to `<lw>`), `stage`, `lockedTests`, `effort`. `dir` `null` inside a git repo → no task has started here yet; `lw.mjs start` creates `.loopwright/` with the first task, so continue and `task: null` reports "no active task". Not a git repo → tell the user loopwright must run inside a git repo, stop.
13
+ 3. `task: null` → "no active task": point the user to `/loopwright-plan` or `/loopwright-flow`, stop.
14
14
  4. Read the task file header (`tier`, `checks`).
15
15
  - Header not `plan: confirmed` → stop; the plan is not confirmed yet, point the user to `/loopwright-plan`.
16
16
  - `standard` or `large` with no `lockedTests` (or, large, the current slice is still `[todo]`) → run `/loopwright-test` first.
17
17
  - `kind: fix` with no `lockedTests`, at any tier including small → run `/loopwright-test` first; a fix is never built without a locked repro test.
18
18
  - `large` → the current slice is the first `S<n> [tested]` line; build only that slice. Every slice `[passed]` → this is a whole-branch fix round; no slice limit.
19
- 5. Upstream check. Skip this check on a fix round (called with Review findings). Otherwise run `GIT_TERMINAL_PROMPT=0 git fetch --quiet` (never prompts for credentials; failure, e.g. offline or no auth → skip). List `git log --oneline HEAD..@{u}`; with no upstream, use `HEAD..origin/HEAD`; with neither, skip. For `large`, check before each slice's first Build. If the new commits touch the task's files or feature, or a sibling repo the task touches, run `node "{{LW_HOME}}/hooks/lw.mjs" await-user "upstream changed"`, show them to the user and ask whether to pull first or stop (someone may already have done this work) before spawning the implementer. After the answer, run `node "{{LW_HOME}}/hooks/lw.mjs" resume` and record it as a decision `D<n> [asked]`. If the user pulled, rebase the review scope so pulled commits are not judged as this task's change: run `node "{{LW_HOME}}/hooks/lw.mjs" start <task> --force --base HEAD` (keeps locks and history, resets the stage to plan), then `node "{{LW_HOME}}/hooks/lw.mjs" stage build`, and update `base commit` in the task file header to the new HEAD. Otherwise continue.
19
+ 5. Moved branch. Skip this on a fix round (called with Review findings). `headMoved` in `brief` (new commits since the base commit, at least one already on the upstream branch, and not answered yet for this HEAD) → run `node "{{LW_HOME}}/hooks/lw.mjs" await-user "branch moved"`, list the commits to the user and ask one question: are they pulled commits (leave them out of the review) or this task's own commits (keep them in)? After the answer run `node "{{LW_HOME}}/hooks/lw.mjs" resume` and record it as a decision `D<n> [asked]`.
20
+ - `headMoved.keptEarlier` → an earlier answer kept commits in the review, so the branch holds both kinds whatever the answer: list only the new commits, and a 'pulled' answer takes the keep-base path below, with the both-kinds notice.
21
+ - `headMoved.localOnly` → the listed short shas exist only locally, so they are the task's own work and the branch holds both kinds whatever the answer: a 'pulled' answer takes the keep-base path below, with the both-kinds notice. Never judge this from the commit subjects.
22
+ - Pulled → run `node "{{LW_HOME}}/hooks/lw.mjs" start <task> --force --base HEAD && node "{{LW_HOME}}/hooks/lw.mjs" stage build` as one call, update `base commit` in the task file header to the new HEAD, then run `node "{{LW_HOME}}/hooks/lw.mjs" accept-locks --restart --reason "<the decision in words>"`.
23
+ - This task's own commits, or a branch holding both kinds → run `node "{{LW_HOME}}/hooks/lw.mjs" keep-base --reason "<the decision in words>"`; the base stays. Both kinds: add `--pulled` to that command, so the locked tests the new commits changed show in `pulledLocks` (step 7), and tell the user the pulled commits stay in the review, because the base cannot move past the task's own commits.
24
+ 6. Upstream check. Skip this check on a fix round (called with Review findings). Otherwise run `GIT_TERMINAL_PROMPT=0 git fetch --quiet` (never prompts for credentials; failure, e.g. offline or no auth → skip). List `git log --oneline HEAD..@{u}`; with no upstream, use `HEAD..origin/HEAD`; with neither, skip. For `large`, check before each slice's first Build. If the new commits touch the task's files or feature, or a sibling repo the task touches, run `node "{{LW_HOME}}/hooks/lw.mjs" await-user "upstream changed"`, show them to the user and ask whether to pull first or stop (someone may already have done this work) before spawning the implementer. Before asking, run `brief` and note whether `ownCommits` is present (the task already has commits since its base, answered as its own or only local). After the answer, run `node "{{LW_HOME}}/hooks/lw.mjs" resume` and record it as a decision `D<n> [asked]`. If the user pulled and `ownCommits` was present, the base stays: run `node "{{LW_HOME}}/hooks/lw.mjs" keep-base --pulled --reason "<the pull decision in words>"` instead of the restart below, tell the user the pulled commits stay in the review (the base cannot move past the task's own commits), and go to step 7. If it pulled and `ownCommits` was absent, rebase the review scope so pulled commits are not judged as this task's change: run `node "{{LW_HOME}}/hooks/lw.mjs" start <task> --force --base HEAD && node "{{LW_HOME}}/hooks/lw.mjs" stage build` as one call (`start` keeps locks and history and resets the stage to plan; `stage build` sets it back), and update `base commit` in the task file header to the new HEAD, then run `node "{{LW_HOME}}/hooks/lw.mjs" accept-locks --restart --reason "<the pull decision in words>"` (the pull is the approved restart, so it is not raised again in Review). Otherwise continue.
25
+ 7. After a pull (step 5 or 6), run `brief` again, as in step 2. `pulledLocks` present (a pulled commit changed those locked tests) → before the implementer runs, send only the listed files to Test: `node "{{LW_HOME}}/hooks/lw.mjs" reopen test "<the pull decision in words>"` when Build has begun, `node "{{LW_HOME}}/hooks/lw.mjs" stage test` otherwise, then run `/loopwright-test` for those files. After the tester re-locked them, run `node "{{LW_HOME}}/hooks/lw.mjs" accept-locks --reason "<the pull decision in words>" <path>…` with the `pulledLocks` paths, so the re-locks are accepted under the pull decision, and continue with Steps.
20
26
 
21
27
  ## Steps
22
28
 
23
- 1. `node "{{LW_HOME}}/hooks/lw.mjs" stage build`, and set `stage: build` in the task file header.
24
- 2. Now spawn the `loopwright-implementer` subagent and wait for its result. On Claude Code pass `effort` = the output of `node "{{LW_HOME}}/hooks/lw.mjs" effort implementer` on the spawn; if the spawn rejects `effort`, fall back to spawning without it (the agent file's effort applies). The prompt contains only:
29
+ 1. `node "{{LW_HOME}}/hooks/lw.mjs" stage build` (it updates the task file header `stage:` line; if it prints `"header": false`, set that line by hand).
30
+ 2. Now spawn the `loopwright-implementer` subagent and wait for its result. On Claude Code pass `effort` = the `effort` from `brief` on the spawn; if `brief` has no `effort` (it warns on stderr) or the spawn rejects `effort`, spawn without it (the agent file's effort applies). The prompt contains only:
25
31
  - the absolute task file path (`<lw>/<task>`);
26
32
  - large tier: "Implement slice S<n> only.";
27
33
  - small feature (no locked tests): "This task has no locked acceptance tests. Write tests covering each acceptance criterion (AC…) as part of your change.";
@@ -29,7 +35,7 @@ The implementer subagent writes the code. This thread dispatches it and hands th
29
35
  Never paste chat history, your own summary of the decisions, or design ideas; the task file is the source.
30
36
  3. Keep the implementer report verbatim in this conversation; a two-pass review needs it.
31
37
  Fix task: write the report's `Root cause:` line to `## Root cause` in the task file. A root cause that differs from the plan's hypothesis is a `Deviation`, handled in step 4.
32
- 4. `Deviations` not "none" → run `node "{{LW_HOME}}/hooks/lw.mjs" await-user "deviations in build"` (so the stop gate lets you end the turn), then show each to the user before Review, one at a time (Claude: `AskUserQuestion`; Codex: numbered text, then end the turn). After the answers, run `node "{{LW_HOME}}/hooks/lw.mjs" resume`. The user either accepts it (write a new decision `D<n> [asked]` to the task file), wants it fixed (run `node "{{LW_HOME}}/hooks/lw.mjs" stage build` first, so a `reopen` the implementer runs on its own does not directly follow the `resume` and is not counted as the user's choice; then spawn the `loopwright-implementer` subagent and wait for its result again, with the deviation as the finding), or wants to go back: offer that when the deviation needs a changed decision or locked test. Going back: directly after `resume`, run `node "{{LW_HOME}}/hooks/lw.mjs" reopen <plan|test> "<reason>"`, set `stage: <plan|test>` in the task file header (for plan also `plan: draft`), record the decision, and continue with `/loopwright-plan` or `/loopwright-test` as the target says.
38
+ 4. `Deviations` not "none" → run `node "{{LW_HOME}}/hooks/lw.mjs" await-user "deviations in build"` (so the stop gate lets you end the turn), then show each to the user before Review, one at a time (Claude: `AskUserQuestion`; Codex: numbered text, then end the turn). After the answers, run `node "{{LW_HOME}}/hooks/lw.mjs" resume`. The user either accepts it (write a new decision `D<n> [asked]` to the task file), wants it fixed (run `node "{{LW_HOME}}/hooks/lw.mjs" stage build` first, so a `reopen` the implementer runs on its own does not directly follow the `resume` and is not counted as the user's choice; then spawn the `loopwright-implementer` subagent and wait for its result again, with the deviation as the finding), or wants to go back: offer that when the deviation needs a changed decision or locked test. Going back: directly after `resume`, run `node "{{LW_HOME}}/hooks/lw.mjs" reopen <plan|test> "<reason>"` (it sets the header `stage:` line, and `plan: draft` for plan; if it prints `"header": false`, set those lines by hand), record the decision, and continue with `/loopwright-plan` or `/loopwright-test` as the target says.
33
39
  5. Go straight to `/loopwright-review`. The stop gate blocks ending the turn in Build without a passing review.
34
40
 
35
41
  ## Rules
@@ -9,19 +9,19 @@ Done runs in this main thread; do not spawn the subagents here. You propose; the
9
9
  ## Setup
10
10
 
11
11
  1. Run every loopwright command from the worktree root: `cd "$(git rev-parse --show-toplevel)"`.
12
- 2. `node "{{LW_HOME}}/hooks/lw.mjs" dir` → `<lw>` (`null` inside a git repo → no task has started here yet; `lw.mjs start` creates `.loopwright/` with the first task, so continue and the next step reports "no active task". Not a git repo → tell the user loopwright must run inside a git repo, stop). Read `docsDir` from `node "{{LW_HOME}}/hooks/lw.mjs" config` (the main checkout's config; default `docs/agents`).
13
- 3. `node "{{LW_HOME}}/hooks/lw.mjs" status` → `task`, `verdict`. Then `node "{{LW_HOME}}/hooks/lw.mjs" fingerprint`.
12
+ 2. `node "{{LW_HOME}}/hooks/lw.mjs" brief` → `dir` (`<lw>`), `task`, `verdict`, `config.docsDir` (the main checkout's config; default `docs/agents`). `dir` `null` inside a git repo → no task has started here yet; `lw.mjs start` creates `.loopwright/` with the first task, so continue and `task: null` reports "no active task". Not a git repo → tell the user loopwright must run inside a git repo, stop.
13
+ 3. `task: null` → "no active task": stop. Then `node "{{LW_HOME}}/hooks/lw.mjs" fingerprint`.
14
14
  - No `verdict.pass: true`, or its `fingerprint` differs from the current one → the code changed since review or never passed: run `/loopwright-review` first. Continue only if the user explicitly says so, and note it in the review log.
15
- 4. `node "{{LW_HOME}}/hooks/lw.mjs" stage done`, and set `stage: done` in the task file header.
15
+ 4. `node "{{LW_HOME}}/hooks/lw.mjs" stage done` (it updates the task file header `stage:` line; if it prints `"header": false`, set that line by hand).
16
16
 
17
17
  ## 1. Knowledge (AGENTS.md)
18
18
 
19
- From the task file (decisions, overrides, review log) and what this task taught you, find durable cross-task knowledge: conventions, "we don't do X here", gotchas a future task would hit. Not task history, not what the code or README already says. A fact already stated in the repo docs or the contract (spec, schema, config) is not added: link instead of restating.
19
+ From the task file (decisions, overrides, review log, and `## Notes for Done` when present, written before a fresh-context reset) and what this task taught you, find durable cross-task knowledge: conventions, "we don't do X here", gotchas a future task would hit. Not task history, not what the code or README already says. A fact already stated in the repo docs or the contract (spec, schema, config) is not added: link instead of restating.
20
20
  - Write concepts, not file paths; one line per entry.
21
21
  - An entry that needs more than ~3 lines goes to `docs/agents/<topic>.md` (the configured `docsDir`), plus one line in AGENTS.md: "Read `docs/agents/<topic>.md` when <situation>."
22
22
  - Prune: AGENTS.md or docs entries this task showed to be stale or wrong → propose an edit or removal.
23
23
  - No AGENTS.md → propose creating one with the first entry.
24
- Propose each change individually, with the exact text, and wait for approval (Claude: `AskUserQuestion`; Codex: numbered text). Apply only approved changes. Nothing worth adding → say so.
24
+ Notes from `## Notes for Done` are candidates, not approved entries: each goes through the user like the rest. Propose each change individually, with the exact text, and wait for approval (Claude: `AskUserQuestion`; Codex: numbered text). Apply only approved changes. Nothing worth adding → say so.
25
25
 
26
26
  If `CLAUDE.md` exists and has no line `@AGENTS.md`, propose adding that import line instead of copying content into CLAUDE.md. Never duplicate AGENTS.md content elsewhere.
27
27
 
@@ -37,7 +37,7 @@ Never write task ids (AC, D, S shorthands) into tests, code, comments, commit me
37
37
 
38
38
  Draft both and show them to the user:
39
39
  - Commit: imperative subject ≤ 72 chars; body says why, the key decisions, and the rejected options with the reason.
40
- - PR: summary of intent; decisions and rejected options; notable assumptions the reviewer should know; how it was verified (check commands, acceptance tests, review rounds from the log). Do not list the diff file by file. Run `node "{{LW_HOME}}/hooks/lw.mjs" check-locks`; when `relockedAfterReopen` is non-empty, add a section listing each locked test changed after a reopen with its reason.
40
+ - PR: summary of intent; decisions and rejected options; notable assumptions the reviewer should know; how it was verified (check commands, acceptance tests, review rounds from the log). Do not list the diff file by file. Run `node "{{LW_HOME}}/hooks/lw.mjs" check-locks`; when `relockedAfterReopen` is non-empty, add a section listing each locked test changed after a reopen with its reason; when `accepted` is non-empty, list each accepted re-lock or restart with its reason in that section too.
41
41
  - A `## Follow-ups` section for every kind of task, listing the parked stubs by title and any follow-ups in the task file (still no task paths or ids).
42
42
  - Fix tasks (`kind: fix`): the PR also states the root cause in one line (from `## Root cause`), the repro test name(s) with "failed before, passes after", and the follow-ups from `## Follow-ups`.
43
43
 
@@ -33,7 +33,7 @@ First step, before any question or message: if `node "{{LW_HOME}}/hooks/lw.mjs"
33
33
  ## Steps
34
34
 
35
35
  1. Input: a bug description, issue text, or a path to a log or report. None given → ask the user for one.
36
- 2. Follow `loopwright-plan` with `kind: fix` (`/loopwright-plan` in Claude Code, `$loopwright-plan` in Codex). The plan skill's fix rules apply: the scout reads the report first, the user is asked once for missing evidence, and the root-cause hypothesis is confirmed with the user.
36
+ 2. Follow `loopwright-plan` with `kind: fix` (`/loopwright-plan` in Claude Code, `$loopwright-plan` in Codex). The plan skill's fix rules apply: the goal is restated and confirmed first (with the effort profile), then the scout reads the report, the user is asked once for missing evidence, and the root-cause hypothesis is confirmed with the user.
37
37
  3. Continue as `/loopwright-flow` does: Test runs at every tier, then Build, Review and Done. `/loopwright-flow` resumes a fix task like any other.
38
38
 
39
39
  ## Rules
@@ -48,9 +48,11 @@ Follow each stage skill in turn (Claude Code `/loopwright-<stage>`, Codex `$loop
48
48
  - standard (and any fix): `loopwright-plan` → `loopwright-test` → `loopwright-build` → `loopwright-review` → `loopwright-done`
49
49
  - large: `loopwright-plan` → for each slice in order: `loopwright-test` → `loopwright-build` → `loopwright-review` → then one whole-branch `loopwright-review` → `loopwright-done`
50
50
  - A fix (`kind: fix` in the task file header; set by `/loopwright-fix`, or by Plan after the user agrees to run a bug-like goal as a fix) runs `loopwright-test` at every tier: a small fix is never built without a locked repro test. Large keeps its slice loop.
51
- - Going back is the user's choice only: at a deviation, or an undecided review finding, run `node "{{LW_HOME}}/hooks/lw.mjs" reopen <plan|test> "<reason>"` (plan or test; accepted only after Build began) and set `stage: <plan|test>` in the task file header (for plan also `plan: draft`), then follow the stage skill it names. Locked tests may then be edited by the tester in Test and are re-locked.
51
+ - Going back is the user's choice only: at a deviation, or an undecided review finding, run `node "{{LW_HOME}}/hooks/lw.mjs" reopen <plan|test> "<reason>"` (plan or test; accepted only after Build began; it sets the header `stage:` line, and `plan: draft` for plan; if it prints `"header": false`, set those lines by hand), then follow the stage skill it names. Locked tests may then be edited by the tester in Test and are re-locked.
52
52
  - A failed review returns to `loopwright-build` and then `loopwright-review`, up to the task's fix-round cap.
53
53
 
54
+ A "fresh context" answer (at the plan confirmation, or at a slice boundary) ends the turn after the stage is advanced; the next session resumes from `status` and the task file, as in Resume.
55
+
54
56
  Exploring is not a stage of the loop: to understand an unfamiliar codebase before any task, run `loopwright-explore` (`/loopwright-explore [folder]`).
55
57
 
56
58
  Work found along the way that does not belong in the task goes to `loopwright-park` (`/loopwright-park`), which leaves the current task unchanged.
@@ -59,8 +61,10 @@ When a stage says to spawn the `loopwright-<role>` subagent, spawn the subagent
59
61
 
60
62
  ## Gates: stop and wait for the user
61
63
 
62
- - each high-impact question, the "run this as a fix?" question for a bug-like goal, the low-impact batch, the tier/settings proposal, and the final plan confirmation;
64
+ - the goal restatement and the effort profile (one prompt) before the scout, each high-impact question, the "run this as a fix?" question for a bug-like goal, the low-impact batch, the tier/settings proposal, and the final plan confirmation;
65
+ - the slice-boundary question after a large-tier slice review passes while a `[todo]` slice remains (continue here or in a fresh context);
63
66
  - tester `Uncovered`/`Needs` items and implementer `Deviations`;
67
+ - the moved-branch question at the start of Build and Review, when the branch has new commits that are already on the upstream branch (pulled commits, or this task's own);
64
68
  - fixes: the no-repro gate (no locked repro test: provide evidence, find the faulty unit, or stop; never continue without one) and, after the final passing review (whole-branch for large), the sibling gate (include siblings in this fix or list them as follow-ups);
65
69
  - each undecided review finding, and the fix-round cap being reached;
66
70
  - each AGENTS.md / docs change, and the commit message and PR draft.
@@ -38,18 +38,19 @@ First step, before any question or message: if `node "{{LW_HOME}}/hooks/lw.mjs"
38
38
 
39
39
  ## Parked stubs
40
40
 
41
- Invoked without a goal (and no active task) → run `grep -l "^status: proposed" <lw>/tasks/*.md` and list the stubs `/loopwright-park` left, one line each (title, `kind`, `found while`, `blocks`). Offer: start one, drop one, or a new task. Drop → set `status: dropped` in the stub; never delete it. Start → treat the stub as an imported spec: run `start tasks/<stub>.md`, and fill that same file in place (status `active`, the Plan template's header lines and sections) instead of creating a second file. Keep its `kind`, `found while` and `blocks` lines. Its `## Goal` is confirmed with the batch; its `## Evidence` is a lead for the scout, not a verified fact.
41
+ Invoked without a goal (and no active task) → run `grep -l "^status: proposed" <lw>/tasks/*.md` and list the stubs `/loopwright-park` left, one line each (title, `kind`, `found while`, `blocks`). Offer: start one, drop one, or a new task. Drop → set `status: dropped` in the stub; never delete it. Start → treat the stub as an imported spec: run `start tasks/<stub>.md`, and fill that same file in place (status `active`, the Plan template's header lines and sections) instead of creating a second file. Keep its `kind`, `found while` and `blocks` lines. Unlike an imported spec, its goal is confirmed before the scout (section 1); its `## Evidence` is a lead for the scout, not a verified fact.
42
42
 
43
43
  ## 1. Input
44
44
 
45
45
  - A goal in the user's words, or a path to an imported spec/plan (e.g. from superpowers).
46
+ - Restate the goal first, on every task with a typed goal, a bug report or a parked stub's goal, before the scout runs. Say in your own plain words what the user wants and what will change, and ask it as one question in the format of section 4: the user must confirm or correct it before you go on. In the same prompt as the restatement, ask which effort profile the task runs at (lean: trivial or mechanical; balanced: most tasks; thorough: cross-module or risky; deep: major refactors), the recommended profile first. The recommendation is your best guess from the restatement, and `balanced` when it does not show the size; the user has the last say and may confirm or change it. A corrected restatement asks both again. A goal with more than one reading lists the readings as options in the same question. Never skip it because the goal looks clear or obvious. A bug is restated in one sentence, observed and expected; its evidence intake stays after the scout. An imported spec skips the restatement but still gets the profile question on its own before its scout; a reopened plan skips both and asks nothing about the profile, since its header already has one. The confirmed restatement becomes the task file's `## Goal` paragraph and is recorded as an `[asked]` decision once the task file exists. No `await-user` here: no task state exists yet.
46
47
  - Called from `/loopwright-fix` → `kind: fix`; read "Fix tasks" below. Otherwise `kind: feature`.
47
- - A goal that looks like a bug, without `/loopwright-fix` → never switch silently. Ask one question first (format of section 4), recommendation first: "Run this as a fix (repro test first)?" Yes → `kind: fix`; no → `kind: feature`. Record the answer as a decision once the task file exists.
48
+ - A goal that looks like a bug, without `/loopwright-fix` → never switch silently. After the restatement, ask one question (format of section 4), recommendation first: "Run this as a fix (repro test first)?" Yes → `kind: fix`; no → `kind: feature`. Record the answer as a decision once the task file exists.
48
49
  - Imported spec: read it fully. Do not interview from scratch; run the assumption pass over it. What the spec states explicitly becomes a decision tagged `batch-confirmed` once the user confirms the batch; what it leaves implicit goes in the ledger.
49
50
 
50
51
  ## 2. Scout
51
52
 
52
- Before writing any assumption, spawn the `loopwright-scout` subagent and wait for its result. Give it only the goal text or the spec path (a fix: the bug report text, and "Fix tasks: report the fix inputs"). On Claude Code pass `effort` = the output of `node "{{LW_HOME}}/hooks/lw.mjs" effort scout` on the spawn; if the spawn rejects `effort`, fall back to spawning without it (the agent file's effort applies).
53
+ Only after the restatement is confirmed, and before writing any assumption, spawn the `loopwright-scout` subagent and wait for its result. Give it the goal text plus the confirmed restatement, or the spec path (a fix: the bug report text, and "Fix tasks: report the fix inputs"). On Claude Code pass `effort` = the output of `node "{{LW_HOME}}/hooks/lw.mjs" effort scout --profile <chosen profile>` on the first spawn (follow-up scouts below use plain `lw.mjs" effort scout`, which reads the header); if the spawn rejects `effort`, fall back to spawning without it (the agent file's effort applies).
53
54
  Never ask the user a question the repo can answer. If the scout report leaves a repo fact open, look it up yourself or spawn the `loopwright-scout` subagent and wait for its result again with that one question.
54
55
 
55
56
  ## 3. Assumption ledger
@@ -59,7 +60,7 @@ List every assumption you would otherwise make silently, one line each: `A<n> [h
59
60
  - **low-impact**: everything else (internal naming, file placement following an existing pattern, minor edge-case choices).
60
61
  - Cover: scope in/out, behavior and edge cases, interfaces and paths, error handling, compatibility, how it is tested (no test runner in the repo → high-impact), docs to update, extending an existing mechanism (the scout's `Mechanisms` line) vs adding something new. Behavior that differs by environment, deployment or tenant is high-impact unless it extends a mechanism the scout found.
61
62
 
62
- Show the user the whole ledger in one compact message, then run `node "{{LW_HOME}}/hooks/lw.mjs" start tasks/<file>.md` (path relative to `<lw>`; if `dir` printed `null`, this creates `.loopwright/`, so run `dir` again for `<lw>`) and create the task file (see Task file) with status `active`, stage `plan` and `plan: draft`. Copy `baseCommit`, `worktree` and `branch` from its output into the header. Put every unresolved ledger line under `## Open questions` with `— pending`; move each to Decisions or Assumptions as it is resolved, so a resumed session knows what is still open. Starting early lets the hooks restore this task after compaction; it builds nothing.
63
+ Show the user the whole ledger in one compact message, then run `node "{{LW_HOME}}/hooks/lw.mjs" start tasks/<file>.md` (path relative to `<lw>`; if `dir` printed `null`, this creates `.loopwright/`, so run `dir` again for `<lw>`) and create the task file (see Task file) with status `active`, stage `plan` and `plan: draft`, and the profile chosen before the scout in `profile:`. Copy `baseCommit`, `worktree` and `branch` from its output into the header. Put every unresolved ledger line under `## Open questions` with `— pending`; move each to Decisions or Assumptions as it is resolved, so a resumed session knows what is still open. Starting early lets the hooks restore this task after compaction; it builds nothing.
63
64
 
64
65
  ## 4. High-impact questions, one at a time
65
66
 
@@ -78,7 +79,7 @@ Write the result immediately: accepted → `[batch-confirmed]`, changed by the u
78
79
 
79
80
  In one message, propose and explain each in one line:
80
81
  - **tier**: `small` (one area, few files, low risk; no acceptance-test stage for features, the implementer writes tests for every AC; a fix always runs Test), `standard` (default; tests first, then build), `large` (several separable parts; split into ordered slices, each run Test → Build → Review, then one whole-branch review).
81
- - **profile**: `lean` (trivial or mechanical), `balanced` (default; most tasks), `thorough` (cross-module work, risky changes), `deep` (major refactors, complex redesigns). It sets subagent effort for the task; the user confirms. Written as `profile: <name>` in the header; Test, Build and Review read it via `lw.mjs effort <role>`.
82
+ - **profile**: `lean` (trivial or mechanical), `balanced` (default; most tasks), `thorough` (cross-module work, risky changes), `deep` (major refactors, complex redesigns). It sets subagent effort for the task. It is pre-filled with the profile chosen before the scout; say so when the scout's findings suggest a different one. The user confirms or changes it. Written as `profile: <name>` in the header; Test, Build and Review read it via `lw.mjs brief <role>`.
82
83
  - **two-pass** review on/off: on when the implementer's claims matter beyond what tests show (performance, migrations, concurrency, external APIs); otherwise off.
83
84
  - **fix-round cap**: default `maxFixRounds` from config; may be lower for small tasks.
84
85
  - **check commands**: exact lint / typecheck / test commands from the scout report.
@@ -88,7 +89,13 @@ The user confirms or edits each item; write the outcome to the header and sectio
88
89
  ## 7. Confirm
89
90
 
90
91
  Show the task file path and a short summary (tier, decisions count, ACs). Ask for explicit confirmation. Until the user confirms, keep editing the plan; never start Test or Build.
92
+ Safe point: for tier standard or large (fixes of those tiers included) and a task that was not reopened, the confirmation offers three answers: confirm and continue here; confirm and continue in a fresh context; keep editing. The small tier and a reopened task (Build has begun, so findings and the implementer report live in this conversation) keep the two answers confirm and keep editing, with no fresh-context offer. Give the reason in one sentence, stated as a tradeoff: later turns re-read the whole conversation, so a fresh context saves tokens when much of the task remains (a large task, a long plan conversation), but the new session rewrites the cache, which can cost more than it saves on a short task; nothing is lost either way because the task file holds the plan.
91
93
  On explicit confirmation, set the header line to `plan: confirmed` (Test and Build refuse to run without it). Then, unless the task was reopened (keep its base commit so the review scope stays whole), if `git rev-parse HEAD` differs from the recorded base commit, rerun `node "{{LW_HOME}}/hooks/lw.mjs" start tasks/<file>.md --force` and update the header. Then the next stage is `/loopwright-test` (standard, large, and every fix) or `/loopwright-build` (small feature); under `/loopwright-flow`, return to the flow.
94
+ On "confirm and continue in a fresh context", after the `plan: confirmed` step and the base-commit rerun above, in this order:
95
+ 1. Append `## Notes for Done` to the task file (add to it if it exists): up to five lines of things learned so far that Done may propose for `AGENTS.md`.
96
+ 2. Re-read the task file and write any decision made in this conversation that it is missing.
97
+ 3. Run `node "{{LW_HOME}}/hooks/lw.mjs" stage test` (it updates the header), so the next session resumes at Test and not at this confirmation.
98
+ 4. Tell the user what to type, by tool: Claude Code "`/clear`, then `/loopwright-flow`" (`/compact` also works and keeps a summary); Codex and Junie: start a new session and run the flow. End the turn. If the user's next message arrives in the same session, continue with `/loopwright-test` as usual.
92
99
 
93
100
  ## Fix tasks
94
101
 
@@ -9,19 +9,26 @@ Reviewers judge in their own context. This thread dispatches them, merges their
9
9
  ## Setup
10
10
 
11
11
  1. Run every loopwright command from the worktree root: `cd "$(git rev-parse --show-toplevel)"`.
12
- 2. `node "{{LW_HOME}}/hooks/lw.mjs" dir` → `<lw>` (`null` inside a git repo → no task has started here yet; `lw.mjs start` creates `.loopwright/` with the first task, so continue and the next step reports "no active task". Not a git repo → tell the user loopwright must run inside a git repo, stop).
13
- 3. `node "{{LW_HOME}}/hooks/lw.mjs" status` → `task` (relative to `<lw>`) and `baseCommit`. "no active task" → point the user to `/loopwright-flow`, stop.
14
- 4. Read the task file header (`tier`, `two-pass`, `fix-round cap`) and `node "{{LW_HOME}}/hooks/lw.mjs" config` (`crossAgentReview`, `models.crossAgentReviewer`; missing → `off`).
12
+ 2. `node "{{LW_HOME}}/hooks/lw.mjs" brief reviewer` → `dir` (`<lw>`), `task` (relative to `<lw>`), `baseCommit`, `config` (`crossAgentReview`, `crossAgentReviewer` = `models.crossAgentReviewer`; missing → `off`), `effort`. `dir` `null` inside a git repo → no task has started here yet; `lw.mjs start` creates `.loopwright/` with the first task, so continue and `task: null` reports "no active task". Not a git repo → tell the user loopwright must run inside a git repo, stop.
13
+ 3. `task: null` → "no active task": point the user to `/loopwright-flow`, stop.
14
+ 4. Read the task file header (`tier`, `two-pass`, `fix-round cap`).
15
15
  5. Scope: small/standard → the task. Large → the first `S<n> [tested]` slice, or `whole` once every slice is `[passed]`.
16
16
  6. Round `n` = number of `- R` lines in `## Review log` for this scope after the last `- Scope change:` line (all of them if there is none) + 1.
17
+ 7. Moved branch. `headMoved` in `brief` (new commits since the base commit, at least one already on the upstream branch, and not answered yet for this HEAD) → run `node "{{LW_HOME}}/hooks/lw.mjs" await-user "branch moved"`, list the commits to the user and ask one question: are they pulled commits (leave them out of the review) or this task's own commits (keep them in)? After the answer run `node "{{LW_HOME}}/hooks/lw.mjs" resume` and record it as a decision `D<n> [asked]`.
18
+ - `headMoved.keptEarlier` → an earlier answer kept commits in the review, so the branch holds both kinds whatever the answer: list only the new commits, and a 'pulled' answer takes the keep-base path below, with the both-kinds notice.
19
+ - `headMoved.localOnly` → the listed short shas exist only locally, so they are the task's own work and the branch holds both kinds whatever the answer: a 'pulled' answer takes the keep-base path below, with the both-kinds notice. Never judge this from the commit subjects.
20
+ - Pulled → run `node "{{LW_HOME}}/hooks/lw.mjs" start <task> --force --base HEAD && node "{{LW_HOME}}/hooks/lw.mjs" stage build` as one call (Passes step 1 sets the stage to review), update `base commit` in the task file header to the new HEAD, run `node "{{LW_HOME}}/hooks/lw.mjs" accept-locks --restart --reason "<the decision in words>"`, then run `brief reviewer` again (the base commit changed).
21
+ - This task's own commits, or a branch holding both kinds → run `node "{{LW_HOME}}/hooks/lw.mjs" keep-base --reason "<the decision in words>"`; the base stays. Both kinds: add `--pulled` to that command, so the locked tests the new commits changed show in `pulledLocks` (run `brief reviewer` again, then step 8), and tell the user the pulled commits stay in the review, because the base cannot move past the task's own commits.
22
+ 8. `pulledLocks` in `brief` (a pulled commit changed those locked tests) → before the first reviewer is spawned, send only the listed files to Test: `node "{{LW_HOME}}/hooks/lw.mjs" reopen test "<the pull decision in words>"` when Build has begun, `node "{{LW_HOME}}/hooks/lw.mjs" stage test` otherwise, then run `/loopwright-test` for those files. After the tester re-locked them, run `node "{{LW_HOME}}/hooks/lw.mjs" accept-locks --reason "<the pull decision in words>" <path>…` with the `pulledLocks` paths, so the re-locks are accepted under the pull decision, and continue with step 9 and the Passes.
23
+ 9. `flaggedLocks` in `brief` (present only while a re-lock or forced restart is flagged and not accepted) → before the first reviewer is spawned, compare each item with the task file's decisions. A decision covers an item when it names the test file, the return to Test, or the pull. Covered → run `node "{{LW_HOME}}/hooks/lw.mjs" accept-locks --reason "<that decision in words>" [--restart] [<path>…]` without asking the user (paths for `lockedAfterBuild`, `--restart` for `forcedRestartAfterBuild`). No decision covers an item → leave it to the reviewer, unchanged.
17
24
 
18
25
  ## Passes
19
26
 
20
- 1. `node "{{LW_HOME}}/hooks/lw.mjs" stage review`, and set `stage: review` in the header.
21
- 2. **Blind pass.** Now spawn the `loopwright-reviewer` subagent and wait for its result. Give it only: the absolute task file path, the base commit, and "Follow `{{LW_HOME}}/prompts/reviewer.md`. Blind pass." Large tier: add "Scope: slice S<n> (its ACs; earlier slices passed)" or "Scope: whole-branch review of all slices". Never include the implementer report, chat history or your opinion. On Claude Code pass `effort` = the output of `node "{{LW_HOME}}/hooks/lw.mjs" effort reviewer` on the spawn; if the spawn rejects `effort`, fall back to spawning without it (the agent file's effort applies). Use the same effort for the second pass.
27
+ 1. `node "{{LW_HOME}}/hooks/lw.mjs" stage review` (it updates the task file header `stage:` line; if it prints `"header": false`, set that line by hand).
28
+ 2. **Blind pass.** Now spawn the `loopwright-reviewer` subagent and wait for its result. Give it only: the absolute task file path, the base commit, and "Follow `{{LW_HOME}}/prompts/reviewer.md`. Blind pass." Large tier: add "Scope: slice S<n> (its ACs; earlier slices passed)" or "Scope: whole-branch review of all slices". Never include the implementer report, chat history or your opinion. On Claude Code pass `effort` = the `effort` from `brief` on the spawn; if `brief` has no `effort` (it warns on stderr) or the spawn rejects `effort`, spawn without it (the agent file's effort applies). Use the same effort for the second pass.
22
29
  3. **Second pass** (only if `two-pass: on`). Now spawn the `loopwright-reviewer` subagent and wait for its result, with the task file path, the base commit, "Follow `{{LW_HOME}}/prompts/reviewer.md`. Second pass.", and then "Verify the claims in this implementer report:" with the report verbatim. Report no longer available → skip and note it in the log line.
23
30
  4. **Cross-agent pass** (only if `crossAgentReview` is not `off`). `command -v <claude|codex>` fails → skip, note it. Otherwise, from the worktree root, set `PROMPT="Follow {{LW_HOME}}/prompts/reviewer.md. Task file: <abs path>. Base commit: <sha>. Blind pass."` and run (`LOOPWRIGHT_HOOKS=off` keeps loopwright's own hooks, such as the stop gate, out of the headless reviewer session):
24
- - claude (omit `--model` when the model is `inherit`; add one `"Bash(<cmd>:*)"` per check command in the task header; the `lw.mjs` entries allow only the read-only `status`, `check-locks` and `fingerprint`, in the quoted form the reviewer prompt uses and unquoted; the prompt must come after `--` because the tool flags take several values; `<effort>` is the output of `lw.mjs effort reviewer`; omit `--effort` if that command fails):
31
+ - claude (omit `--model` when the model is `inherit`; add one `"Bash(<cmd>:*)"` per check command in the task header; the `lw.mjs` entries allow only the read-only `status`, `check-locks` and `fingerprint`, in the quoted form the reviewer prompt uses and unquoted; the prompt must come after `--` because the tool flags take several values; `<effort>` is the `effort` from `brief`; omit `--effort` if it is missing):
25
32
  `LOOPWRIGHT_HOOKS=off claude -p --model <crossAgentReviewer.claude> --effort <effort> --output-format json --json-schema "$(cat "{{LW_HOME}}/schemas/verdict.json")" --allowedTools "Read" "Grep" "Glob" "Bash(git diff:*)" "Bash(git status:*)" "Bash(git log:*)" 'Bash(node "{{LW_HOME}}/hooks/lw.mjs" status)' 'Bash(node "{{LW_HOME}}/hooks/lw.mjs" check-locks)' 'Bash(node "{{LW_HOME}}/hooks/lw.mjs" fingerprint)' "Bash(node {{LW_HOME}}/hooks/lw.mjs status)" "Bash(node {{LW_HOME}}/hooks/lw.mjs check-locks)" "Bash(node {{LW_HOME}}/hooks/lw.mjs fingerprint)" "Bash(<check command>:*)" --disallowedTools "Edit" "Write" "MultiEdit" "NotebookEdit" -- "$PROMPT"`
26
33
  The verdict is the top-level `structured_output` field.
27
34
  - codex (best effort, untested; omit `-m` when the model is `inherit`): `OUT="$(mktemp)"; LOOPWRIGHT_HOOKS=off codex exec --sandbox read-only --output-schema "{{LW_HOME}}/schemas/verdict.json" -o "$OUT" -m <crossAgentReviewer.codex> "$PROMPT"`, then read the verdict from `$OUT`.
@@ -35,12 +42,12 @@ Human gates: before you ask the user anything in this stage (an undecided findin
35
42
  Merge all passes: union of `blocking`, union of `undecided` (drop exact duplicates by location and expectation), sum of `droppedCount`. Decide from the arrays, not from the `pass` fields.
36
43
 
37
44
  - **Blocking** present → `node "{{LW_HOME}}/hooks/lw.mjs" verdict fail --round <n>`. Fix rounds used = n − 1. If that reaches or exceeds the `fix-round cap`, stop: show every open finding and let the user decide (raise the cap, fix by hand, or accept). Otherwise show the findings briefly and run `/loopwright-build` with the Blocking findings verbatim; then review again (round n + 1). Undecided findings of this round are only counted; the next round re-checks them.
38
- - Only **Undecided** → present each to the user, one at a time (Claude: `AskUserQuestion`; Codex: numbered text), with its location, expectation and proof; options: fix or dismiss. Record each answer under the round's log line: ` - U<k> <location>: fix|dismissed — <user's reason>`. Any "fix" → `verdict fail --round <n>` and Build with those findings, same cap rule. All dismissed → pass.
39
- - An undecided finding the user wants resolved by changing the plan or a locked test (not just the code) → offer to go back: after `verdict fail --round <n>`, `await-user` and the answer's `resume`, run `node "{{LW_HOME}}/hooks/lw.mjs" reopen <plan|test> "<reason>"` with the user's reason, set `stage: <plan|test>` in the task file header (for plan also `plan: draft`), then continue with `/loopwright-plan` or `/loopwright-test`. Run it only after the user chooses it.
45
+ - Only **Undecided** → present each to the user, one at a time (Claude: `AskUserQuestion`; Codex: numbered text), with its location, expectation and proof; options: fix or dismiss. Record each answer under the round's log line: ` - U<k> <location>: fix|dismissed — <user's reason>`. Any "fix" → `verdict fail --round <n>` and Build with those findings, same cap rule. A dismissed re-lock or restart finding also runs `node "{{LW_HOME}}/hooks/lw.mjs" accept-locks --reason "<user's reason>" [--restart] [<path>…]`, so it is not asked again for that re-lock or restart. Every other Undecided finding is asked as above, each round. All dismissed → pass.
46
+ - An undecided finding the user wants resolved by changing the plan or a locked test (not just the code) → offer to go back: after `verdict fail --round <n>`, `await-user` and the answer's `resume`, run `node "{{LW_HOME}}/hooks/lw.mjs" reopen <plan|test> "<reason>"` with the user's reason (it sets the header `stage:` line, and `plan: draft` for plan; if it prints `"header": false`, set those lines by hand), then continue with `/loopwright-plan` or `/loopwright-test`. Run it only after the user chooses it.
40
47
  - Nothing open → `node "{{LW_HOME}}/hooks/lw.mjs" verdict pass --round <n>`.
41
48
  - Fix tasks, sibling gate: asked once, at the final pass (the task review for small/standard, the whole-branch review for large), never after a slice review. A passing slice review only records its merged `siblings` (union from all passes, dropping exact duplicates by `path` and `line`) as ` - Sibling <path>:<line> — <why>` lines under its log line, then the slice loop goes on.
42
- - At the final pass, take the merged `siblings` of this verdict plus every `Sibling` line after the last `- Scope change:` line, dropping duplicates by `path` and `line`. Non-empty → run `node "{{LW_HOME}}/hooks/lw.mjs" await-user "siblings of the fixed bug"` after the `verdict` command (the verdict clears the wait), list each sibling (`path:line`, why), then ask one question for the batch, recommendation first: include the siblings (also fix them), or list them as follow-ups. After the answer run `node "{{LW_HOME}}/hooks/lw.mjs" resume`.
43
- - Include → append `- Scope change: siblings included` to the review log, run `node "{{LW_HOME}}/hooks/lw.mjs" reopen plan "include siblings in the fix"`, set `stage: plan` and `plan: draft` in the task file header, then continue with `/loopwright-plan` (one `[repro]` criterion per sibling; Test locks the new repro tests and existing locks stay; Build and Review run again with a fresh fix-round budget, because rounds are counted after the scope change).
49
+ - At the final pass, take the merged `siblings` of this verdict plus every `Sibling` line after the last `- Scope change:` line, dropping duplicates by `path` and `line`. Non-empty → run `node "{{LW_HOME}}/hooks/lw.mjs" verdict pass --round <n> && node "{{LW_HOME}}/hooks/lw.mjs" await-user "siblings of the fixed bug"` as one call, in this order because the verdict clears the wait; list each sibling (`path:line`, why), then ask one question for the batch, recommendation first: include the siblings (also fix them), or list them as follow-ups. After the answer run `node "{{LW_HOME}}/hooks/lw.mjs" resume`.
50
+ - Include → append `- Scope change: siblings included` to the review log, run `node "{{LW_HOME}}/hooks/lw.mjs" reopen plan "include siblings in the fix"` (it sets the header `stage:` and `plan: draft` lines; if it prints `"header": false`, set them by hand), then continue with `/loopwright-plan` (one `[repro]` criterion per sibling; Test locks the new repro tests and existing locks stay; Build and Review run again with a fresh fix-round budget, because rounds are counted after the scope change).
44
51
  - No (follow-ups only) → write the siblings under `## Follow-ups` in the task file (`path:line — why`) and go to `/loopwright-done`.
45
52
 
46
53
  Once the outcome is known (after the user's undecided answers) and before the verdict command, append one line to `## Review log`, followed by its `U<k>` lines if any:
@@ -50,5 +57,10 @@ Large tier: `- R<n> S<k>: …` for a slice, `- R<n> whole: …` for the whole-br
50
57
  ## After a pass
51
58
 
52
59
  - small/standard → `/loopwright-done`.
53
- - large → mark the slice `S<n> [passed]`; next `[todo]` slice → `/loopwright-test`. When the last slice passes, run this skill again with scope `whole` (the diff against the base commit, all ACs); its fixes go through Build without new tests. Whole-branch pass → `/loopwright-done`.
60
+ - large → mark the slice `S<n> [passed]`; a `[todo]` slice remains → ask the question below, then `/loopwright-test` (or the fresh-context steps). When the last slice passes, run this skill again with scope `whole` (the diff against the base commit, all ACs); its fixes go through Build without new tests. Whole-branch pass → `/loopwright-done`.
61
+ - Large, after marking the slice `[passed]`, and a [todo] slice remains: ask one question, continue here or continue in a fresh context, with the reason in one sentence, stated as a tradeoff: later turns re-read the whole conversation, so a fresh context saves tokens when much of the task remains (several slices left), but the new session rewrites the cache, which can cost more than it saves when little remains; nothing is lost either way because the task file holds the plan. Not asked after the last slice, after a whole-branch review, or on a small or standard task. Run `node "{{LW_HOME}}/hooks/lw.mjs" await-user "<reason>"` before asking and `resume` after the answer. On "continue in a fresh context", in this order:
62
+ 1. Append `## Notes for Done` to the task file (add to it if it exists): up to five lines of things learned so far that Done may propose for `AGENTS.md`.
63
+ 2. Re-read the task file and write any decision made in this conversation that it is missing.
64
+ 3. Run `node "{{LW_HOME}}/hooks/lw.mjs" stage test` (it updates the header; if it prints `"header": false`, set the `stage:` line by hand), so the next session resumes at the next slice's Test and not in Review with no slice in scope.
65
+ 4. Tell the user what to type, by tool: Claude Code "`/clear`, then `/loopwright-flow`" (`/compact` also works and keeps a summary); Codex and Junie: start a new session and run the flow. End the turn. If the user's next message arrives in the same session, continue with `/loopwright-test` as usual.
54
66
  - Any code edit after a pass makes the verdict stale; review again.
@@ -9,35 +9,36 @@ The tester writes acceptance tests from the confirmed ACs and locks them. This t
9
9
  ## Setup
10
10
 
11
11
  1. Run every loopwright command from the worktree root: `cd "$(git rev-parse --show-toplevel)"`.
12
- 2. `node "{{LW_HOME}}/hooks/lw.mjs" dir` → `<lw>` (`null` inside a git repo → no task has started here yet; `lw.mjs start` creates `.loopwright/` with the first task, so continue and the next step reports "no active task". Not a git repo → tell the user loopwright must run inside a git repo, stop).
13
- 3. `node "{{LW_HOME}}/hooks/lw.mjs" status` → `task` (path relative to `<lw>`). "no active task" → stop and point the user to `/loopwright-plan` or `/loopwright-flow`.
12
+ 2. `node "{{LW_HOME}}/hooks/lw.mjs" brief tester` → `dir` (`<lw>`), `task` (path relative to `<lw>`), `stage`, `lockedTests`, `reopened`, `pulledLocks`, `effort`. `dir` `null` inside a git repo → no task has started here yet; `lw.mjs start` creates `.loopwright/` with the first task, so continue and `task: null` reports "no active task". Not a git repo → tell the user loopwright must run inside a git repo, stop.
13
+ 3. `task: null` → "no active task": stop and point the user to `/loopwright-plan` or `/loopwright-flow`.
14
14
  4. Read the task file header.
15
15
  - `tier: small` and `kind` feature (or no `kind`) → there is no Test stage; say so and go to `/loopwright-build`. `kind: fix` at tier small → Test runs: a fix is never built without a locked repro test.
16
16
  - Header not `plan: confirmed` (or no ACs, or ACs without an interface) → stop; point the user to `/loopwright-plan`.
17
- - Reopened task (`status` `history` has a `reopen` event after the last `stage build` event; that event's `reason` says why) → the scope is the ACs the reason and the task file's added or changed ACs name, in whichever slices hold them (a `[tested]` or `[passed]` slice included), not the first `[todo]` slice. Existing locked tests for those ACs may be edited and re-locked.
17
+ - `pulledLocks` present (a pull the user approved changed locked tests) → the scope is the files in `pulledLocks`, not the ACs below: the tester checks each listed file still tests its acceptance criteria, edits only what the pull broke, and re-locks it; every other locked test stays untouched.
18
+ - Reopened task (`reopened` is not `null`; its `reason` says why) → the scope is the ACs the reason and the task file's added or changed ACs name, in whichever slices hold them (a `[tested]` or `[passed]` slice included), not the first `[todo]` slice. Existing locked tests for those ACs may be edited and re-locked.
18
19
  - `tier: large`, not reopened → the current slice is the first `S<n> [todo]` line; test only its ACs.
19
20
 
20
21
  ## Steps
21
22
 
22
- 1. `node "{{LW_HOME}}/hooks/lw.mjs" stage test`, and set `stage: test` in the task file header.
23
- 2. Now spawn the `loopwright-tester` subagent and wait for its result. Give it only the absolute task file path (`<lw>/<task>`) and, for large tier, "Write tests only for slice S<n>: AC…". Reopened: "Reopened task: the reason is … Write or edit tests only for AC…; existing locked tests for them may be edited and re-locked." No chat history, no implementation hints. On Claude Code pass `effort` = the output of `node "{{LW_HOME}}/hooks/lw.mjs" effort tester` on the spawn; if the spawn rejects `effort`, fall back to spawning without it (the agent file's effort applies).
23
+ 1. `node "{{LW_HOME}}/hooks/lw.mjs" stage test` (it updates the task file header `stage:` line; if it prints `"header": false`, set that line by hand).
24
+ 2. Now spawn the `loopwright-tester` subagent and wait for its result. Give it only the absolute task file path (`<lw>/<task>`) and, for large tier, "Write tests only for slice S<n>: AC…". `pulledLocks`: "A pull changed these locked tests: <paths>. Check each still tests its acceptance criteria, edit only what the pull broke, and re-lock them; leave every other locked test untouched." Reopened: "Reopened task: the reason is … Write or edit tests only for AC…; existing locked tests for them may be edited and re-locked." No chat history, no implementation hints. On Claude Code pass `effort` = the `effort` from `brief` on the spawn; if `brief` has no `effort` (it warns on stderr) or the spawn rejects `effort`, spawn without it (the agent file's effort applies).
24
25
  Fix tasks: also say the task is a fix whose `## Bug report` it must read, and name any existing test the scout or the user found already failing with the reported symptom.
25
26
  3. Verify the report:
26
- - `node "{{LW_HOME}}/hooks/lw.mjs" status` → `lockedTests` must contain every test file and fixture the report lists. A reported file missing from the locks → run `node "{{LW_HOME}}/hooks/lw.mjs" lock <file>` yourself.
27
+ - `node "{{LW_HOME}}/hooks/lw.mjs" brief tester` → `lockedTests` must contain every test file and fixture the report lists. A reported file missing from the locks → run `node "{{LW_HOME}}/hooks/lw.mjs" lock <file>` yourself.
27
28
  - Every in-scope AC has a test, and each failure excerpt shows the expected reason (missing behavior, missing module/export at the named path), not a syntax or setup error. Reopened: an edited or re-locked test for behavior Build already implemented may pass; the report must say so, and a pass is accepted only when the test checks the changed contract. Otherwise spawn the `loopwright-tester` subagent and wait for its result again, naming the problem.
28
29
  - Read the new test files. Comments or doc blocks that restate a test name or an acceptance criterion break the standards: spawn the `loopwright-tester` subagent and wait for its result again, naming the files, before Build; it may edit and re-lock its own tests for this.
29
30
  - Fix tasks: compare each repro failure excerpt with the `observed` line in `## Bug report`. A different error type or message, or a different wrong output, is a mismatch (the test does not match the reported symptom): send the tester back with the mismatch described, via the same spawn rule. A `[regression]` test is expected to pass; one that fails is a `Needs` item.
30
- - Fix tasks, no repro (the tester locked no `[repro]` test and `Needs` says it could not reproduce): run `node "{{LW_HOME}}/hooks/lw.mjs" await-user "no repro for the reported bug"`, show the tester's `Needs` (what it tried, what happened, what evidence is missing), then ask one question, recommendation first. After the answer run `node "{{LW_HOME}}/hooks/lw.mjs" resume`, then `node "{{LW_HOME}}/hooks/lw.mjs" stage test`, so a `reopen` by a subagent you spawn next does not directly follow the `resume`.
31
+ - Fix tasks, no repro (the tester locked no `[repro]` test and `Needs` says it could not reproduce): run `node "{{LW_HOME}}/hooks/lw.mjs" await-user "no repro for the reported bug"`, show the tester's `Needs` (what it tried, what happened, what evidence is missing), then ask one question, recommendation first. After the answer run `node "{{LW_HOME}}/hooks/lw.mjs" resume && node "{{LW_HOME}}/hooks/lw.mjs" stage test` as one call, so a `reopen` by a subagent you spawn next does not directly follow the `resume`.
31
32
  - (a) Provide the missing evidence: add it to `## Bug report`, dispatch the tester again.
32
33
  - (b) Find the faulty unit: spawn the `loopwright-scout` subagent and wait for its result, asking it to investigate the internals and name a suspect unit and why. The user confirms or corrects the unit. Then add a `[repro]` criterion at that unit's interface to the task file (`[asked]` decision) and dispatch the tester again.
33
34
  - (c) Stop the task: set `status: stopped` in the task file header and run `node "{{LW_HOME}}/hooks/lw.mjs" done` (the task file stays).
34
35
  If (a) and (b) both fail, the task stops the same way, with what was tried recorded in the task file and an honest next step for the user (for example a normal `/loopwright-flow` task to add logging around the suspected code). No repro, no fix: there is no option to continue without a repro, and Build never starts.
35
36
  - `Uncovered` or `Needs` not empty → show those items to the user, one at a time. The answer may change an AC or a decision: write it to the task file (`[asked]`), then dispatch the tester again.
36
- 4. Write the test file next to each AC line (`— test: <file>`). Large tier: change the slice (reopened: every slice in scope) to `S<n> [tested]`.
37
+ 4. Write the test file next to each AC line (`— test: <file>`). `pulledLocks`: leave the slice markers alone. Large tier otherwise: change the slice (reopened: every slice in scope) to `S<n> [tested]`.
37
38
  5. Tell the user in a few lines: test files, ACs covered, locked paths. Then the next stage is `/loopwright-build`.
38
39
 
39
40
  ## Rules
40
41
 
41
42
  - Never write task ids (AC, D, S shorthands) into tests, code, comments, commit messages or PR drafts.
42
- - Lock only in this stage, and only the tests for this stage's scope (the task, or the current slice). Never re-lock an existing locked test, except after a reopen (the user chose to go back), where the tester may edit and re-lock the tests in the reopened scope, or when this stage's verification re-dispatches the tester before Build. Outside a reopen, if one is wrong, tell the user and let them decide.
43
+ - Lock only in this stage, and only the tests for this stage's scope (the task, or the current slice). Never re-lock an existing locked test, except after a reopen (the user chose to go back), where the tester may edit and re-lock the tests in the reopened scope, or after a pull the user approved, where it may re-lock the files in `pulledLocks` and no others, or when this stage's verification re-dispatches the tester before Build. Outside a reopen, if one is wrong, tell the user and let them decide.
43
44
  - Do not read the implementation to judge the tests; the ACs are the contract.
package/dist/cli.js CHANGED
@@ -413,7 +413,11 @@ function hookSpecs(tool) {
413
413
  event: "SessionStart",
414
414
  matcher: "compact",
415
415
  script: "reinject-context.mjs"
416
- }
416
+ },
417
+ ...tool === "claude" ? [{
418
+ event: "PreCompact",
419
+ script: "precompact-instructions.mjs"
420
+ }] : []
417
421
  ];
418
422
  }
419
423
  function hookCommand(tool, targets, script) {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "loopwright",
3
3
  "author": "Xuan Son Trinh",
4
- "version": "0.1.6",
4
+ "version": "0.1.8",
5
5
  "description": "Agent workflow installer for Claude Code, Codex and Junie",
6
6
  "type": "module",
7
7
  "bin": {