loopwright 0.1.5 → 0.1.6

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.
@@ -22,7 +22,7 @@ The main thread gives you the task file path, and on a fix round the reviewer's
22
22
 
23
23
  - Follow `AGENTS.md` and the `docs/agents/` docs it links, and the patterns of nearby code (error handling, naming, layout, test style).
24
24
  - Prefer the simplest code path that does the job. Reuse existing helpers before adding new ones.
25
- - Comments explain why, briefly. State each rationale in exactly one place. Never restate what the code does.
25
+ - Read `{{LW_HOME}}/prompts/standards.md` and follow it, including its comment rule.
26
26
 
27
27
  ## Steps
28
28
 
@@ -30,7 +30,8 @@ The main thread gives you the task file path, and on a fix round the reviewer's
30
30
  2. Read the locked tests and the code they exercise.
31
31
  3. Implement. Add unit tests for logic the acceptance tests do not pin down (edge cases, error paths), in new or existing non-locked test files.
32
32
  4. Run the task's check commands (lint, typecheck, tests). Fix until they pass. Do not mark a check as passing that you did not run.
33
- 5. On a fix round, address each Blocking finding; if you disagree with one, say why with proof instead of changing code.
33
+ 5. Simplify pass: read your diff against the base commit (`baseCommit` in `status`) and apply the standards: cut what is redundant, remove wrappers and duplicated docs. If anything changed, rerun the checks.
34
+ 6. On a fix round, address each Blocking finding; if you disagree with one, say why with proof instead of changing code.
34
35
 
35
36
  ## Fix tasks
36
37
 
@@ -100,6 +100,8 @@ Return plain text, at most ~60 lines, one line per item, each with `path` or `pa
100
100
  Relevant files: path — role in the goal
101
101
  Standards: rule — source path
102
102
  Conventions: convention — example path:line
103
+ Mechanisms: existing config, registry or helper this goal could extend instead of adding new code — path:line
104
+ Layers: layers or boundaries the repo docs define for the code the goal touches — doc path
103
105
  Checks: test (all) / test (one file) / lint / format / typecheck — exact command, or "none found"
104
106
  Tests: runner, location and style of existing tests near the goal
105
107
  Risks: risk — evidence path:line
@@ -13,6 +13,8 @@ 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
+ - 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
+ - Read `{{LW_HOME}}/prompts/standards.md` and follow it in the tests you write.
16
18
  - Write only test files (and fixtures they need). Do not create or edit implementation code, not even stubs.
17
19
  - Use the repo's existing test runner, file layout and test style. Do not add a test framework or dependency.
18
20
  - Never write task ids (AC, D, S shorthands) into tests, code, comments, commit messages or PR drafts. Task ids live only in the task file.
@@ -25,8 +27,9 @@ The main thread gives you the task file path. Read its acceptance criteria (`AC
25
27
  3. Confirm each test fails for the expected reason: the behavior is missing or wrong (assertion failure, missing export). A syntax error, a typo, an import path the task file does not name, or a crashing setup is the wrong reason; fix the test and rerun.
26
28
  Reopened task: a test you edited for behavior the implementation already has may pass now; that is fine when it checks the changed contract. Say which tests pass and why in `Run`.
27
29
  When the module or interface the task file names does not exist yet, import it from that path. "Module not found" or a missing export at that path is the expected failure; one file-level excerpt covers every AC in that file. If the task file names no module path or interface for an AC, stop and report it under Needs.
28
- 4. Run the task's format check (its format command from `checks`) on your test files and fix what it reports; they must be clean before the lock step. No format command in the checks → skip. Accept lint errors that come only from the missing module (it does not exist yet) and list them in `Run`.
29
- 5. When every test fails for the right reason (reopened: or passes for the reason given in `Run`), lock them:
30
+ 4. Standards pass: reread your test files against `{{LW_HOME}}/prompts/standards.md`. Remove comments and doc blocks that restate a test name or an acceptance criterion, and helpers that have one call site and do not name a step the reader would otherwise have to decode. Then rerun the tests (steps 2-3) to confirm they still fail for the right reason.
31
+ 5. Run the task's format check (its format command from `checks`) on your test files and fix what it reports; they must be clean before the lock step. No format command in the checks → skip. Accept lint errors that come only from the missing module (it does not exist yet) and list them in `Run`.
32
+ 6. When every test fails for the right reason (reopened: or passes for the reason given in `Run`), lock them:
30
33
  `node "{{LW_HOME}}/hooks/lw.mjs" lock <test-file> [<test-file>…]`
31
34
  Lock every acceptance test file and fixture you wrote. Locking only works in stage `test`; if it errors, report the error.
32
35
 
@@ -1,11 +1,15 @@
1
1
  #!/usr/bin/env node
2
2
  // PreToolUse guard: block edits to locked acceptance tests during the build stage.
3
+ import { existsSync } from 'node:fs';
4
+ import { dirname, isAbsolute, resolve } from 'node:path';
3
5
  import {
4
6
  allow,
5
7
  exitIfHooksOff,
6
8
  deny,
7
9
  failOpen,
10
+ gitTopLevel,
8
11
  loopwrightDir,
12
+ realpathLoose,
9
13
  readState,
10
14
  readStdinJson,
11
15
  repoRelative,
@@ -22,17 +26,31 @@ function patchPaths(command) {
22
26
  return out;
23
27
  }
24
28
 
29
+ /** Top-level of the worktree holding abs (via its nearest existing folder); null outside git. */
30
+ function ownerTop(abs) {
31
+ let cur = dirname(abs);
32
+ while (!existsSync(cur) && dirname(cur) !== cur) cur = dirname(cur);
33
+ try {
34
+ return gitTopLevel(cur);
35
+ } catch {
36
+ return null;
37
+ }
38
+ }
39
+
40
+ /** Locked test paths of the task building in the worktree at top; empty unless it is in build. */
41
+ function lockedTests(top) {
42
+ const dir = loopwrightDir(top);
43
+ const state = dir && readState(dir, worktreeId(top));
44
+ if (!state || state.stage !== 'build' || !Array.isArray(state.lockedTests)) return new Set();
45
+ return new Set(state.lockedTests.map((l) => l.path));
46
+ }
47
+
25
48
  exitIfHooksOff();
26
49
 
27
50
  try {
28
51
  const input = await readStdinJson();
29
52
  // Junie runs hooks from ~/.junie and reports the repo as project_path.
30
53
  const cwd = input.project_path || input.cwd || process.cwd();
31
- const dir = loopwrightDir(cwd);
32
- if (!dir) allow();
33
- const state = readState(dir, worktreeId(cwd));
34
- if (!state || state.stage !== 'build' || !Array.isArray(state.lockedTests) || state.lockedTests.length === 0) allow();
35
-
36
54
  const ti = input.tool_input ?? {};
37
55
  const raw =
38
56
  input.tool_name === 'apply_patch'
@@ -40,11 +58,18 @@ try {
40
58
  : ti.file_path && input.tool_name !== 'Read' // Junie fires PreToolUse for reads too; only edits are guarded
41
59
  ? [ti.file_path]
42
60
  : [];
43
- const locked = new Set(state.lockedTests.map((l) => l.path));
61
+ // A file is locked by the session worktree's task or by its own worktree's, which need not match: check both.
62
+ const lockedByTop = new Map();
44
63
  for (const p of raw) {
45
- const rel = repoRelative(cwd, p);
46
- if (locked.has(rel))
47
- deny('', '', `loopwright: ${rel} is a locked acceptance test. Ask the user before changing it.`);
64
+ const abs = realpathLoose(isAbsolute(p) ? resolve(p) : resolve(cwd, p));
65
+ for (const top of new Set([cwd, ownerTop(abs) ?? cwd])) {
66
+ if (!lockedByTop.has(top)) lockedByTop.set(top, lockedTests(top));
67
+ const locked = lockedByTop.get(top);
68
+ if (locked.size === 0) continue;
69
+ const rel = repoRelative(top, abs);
70
+ if (locked.has(rel))
71
+ deny('', '', `loopwright: ${rel} is a locked acceptance test. Ask the user before changing it.`);
72
+ }
48
73
  }
49
74
  allow();
50
75
  } catch (err) {
@@ -38,8 +38,17 @@ export function mainWorktreeRoot(cwd) {
38
38
  return gitTopLevel(cwd);
39
39
  }
40
40
 
41
- /** Main-worktree .loopwright path (whether or not it exists); null outside git. */
41
+ /** This worktree's .loopwright path (tasks and state live per worktree; whether or not it exists); null outside git. */
42
42
  export function loopwrightPath(cwd) {
43
+ try {
44
+ return join(gitTopLevel(cwd), '.loopwright');
45
+ } catch {
46
+ return null;
47
+ }
48
+ }
49
+
50
+ /** The main checkout's .loopwright path, where config.json and manifest.json live once; null outside git. */
51
+ export function mainLoopwrightPath(cwd) {
43
52
  try {
44
53
  return join(mainWorktreeRoot(cwd), '.loopwright');
45
54
  } catch {
@@ -47,7 +56,7 @@ export function loopwrightPath(cwd) {
47
56
  }
48
57
  }
49
58
 
50
- /** Main-worktree .loopwright directory if it exists; null outside git or if absent. */
59
+ /** This worktree's .loopwright directory if it exists; null outside git or if absent. */
51
60
  export function loopwrightDir(cwd) {
52
61
  const dir = loopwrightPath(cwd);
53
62
  return dir && existsSync(dir) ? dir : null;
@@ -2,8 +2,9 @@
2
2
  // Loopwright state tool. Usage: node lw.mjs <cmd> [args]
3
3
  import { copyFileSync, existsSync, readFileSync, readdirSync, mkdirSync, unlinkSync, writeFileSync } from 'node:fs';
4
4
  import { homedir } from 'node:os';
5
- import { isAbsolute, join, relative, resolve, sep } from 'node:path';
5
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
6
6
  import { execFileSync } from 'node:child_process';
7
+ import { isatty } from 'node:tty';
7
8
  import { fileURLToPath } from 'node:url';
8
9
  import {
9
10
  PROFILES,
@@ -11,7 +12,10 @@ import {
11
12
  gitTopLevel,
12
13
  loopwrightDir,
13
14
  loopwrightPath,
15
+ mainLoopwrightPath,
16
+ mainWorktreeRoot,
14
17
  readState,
18
+ realpathLoose,
15
19
  repoRelative,
16
20
  sha256File,
17
21
  statePath,
@@ -40,27 +44,30 @@ function flag(args, name) {
40
44
  return v;
41
45
  }
42
46
 
43
- /** Create <main worktree>/.loopwright/ (global installs, fresh clones). Config seeds from ~/.config/loopwright/config.json, else the default. */
44
- function scaffold(dir) {
47
+ /** Config a fresh install starts from: the user's, else the shipped default. */
48
+ const seedConfig = () => {
49
+ const user = join(homedir(), '.config', 'loopwright', 'config.json');
50
+ return existsSync(user) ? user : fileURLToPath(new URL('./default-config.json', import.meta.url));
51
+ };
52
+
53
+ /** Create <worktree>/.loopwright/ (global installs, fresh clones, new worktrees). Only the main checkout holds config.json. */
54
+ function scaffold(dir, withConfig) {
45
55
  mkdirSync(join(dir, 'tasks'), { recursive: true });
46
56
  mkdirSync(join(dir, 'state'), { recursive: true });
47
57
  const ignore = join(dir, '.gitignore');
48
58
  if (!existsSync(ignore)) writeFileSync(ignore, '*\n');
49
59
  const cfg = join(dir, 'config.json');
50
- if (existsSync(cfg)) return;
51
- const user = join(homedir(), '.config', 'loopwright', 'config.json');
52
- copyFileSync(existsSync(user) ? user : fileURLToPath(new URL('./default-config.json', import.meta.url)), cfg);
60
+ if (withConfig && !existsSync(cfg)) copyFileSync(seedConfig(), cfg);
53
61
  }
54
62
 
63
+ const isMainCheckout = () => gitTopLevel(cwd) === mainWorktreeRoot(cwd);
64
+
55
65
  function ctx(create = false) {
56
- let dir = loopwrightDir(cwd);
57
- if (!dir) {
58
- const path = loopwrightPath(cwd);
59
- if (!path) fail('loopwright: no .loopwright directory found (not inside a git repository)');
60
- if (!create) fail('loopwright: no active task (no .loopwright directory yet; lw.mjs start creates it)');
61
- scaffold(path);
62
- dir = path;
63
- } else if (create) scaffold(dir); // idempotent: seeds a config.json missing from an existing .loopwright/
66
+ const dir = loopwrightPath(cwd);
67
+ if (!dir) fail('loopwright: no .loopwright directory found (not inside a git repository)');
68
+ if (!existsSync(dir) && !create)
69
+ fail('loopwright: no active task (no .loopwright directory yet; lw.mjs start creates it)');
70
+ if (create) scaffold(dir, isMainCheckout()); // idempotent: seeds a config.json missing from an existing main .loopwright/
64
71
  return { dir, id: worktreeId(cwd) };
65
72
  }
66
73
 
@@ -77,9 +84,8 @@ function effortFor(role) {
77
84
  fail(`loopwright: usage: effort <${Object.keys(PROFILES.balanced).join('|')}>`);
78
85
  // Works before `start` (Plan's scout spawn): no task or repo state just means no header.
79
86
  let name;
80
- let dir = null;
81
87
  try {
82
- dir = loopwrightDir(cwd);
88
+ const dir = loopwrightDir(cwd);
83
89
  const state = dir && readState(dir, worktreeId(cwd));
84
90
  if (state?.task && existsSync(join(dir, state.task))) {
85
91
  name = /^profile:\s*(\S+)\s*$/m.exec(readFileSync(join(dir, state.task), 'utf8').split(/^## /m)[0])?.[1];
@@ -87,8 +93,9 @@ function effortFor(role) {
87
93
  } catch {
88
94
  // Unreadable task or state: fall through to the manifest profile.
89
95
  }
90
- // Repo manifest first, then the global one (global installs record it under ~/.config/loopwright).
91
- for (const m of [dir && join(dir, 'manifest.json'), join(homedir(), '.config', 'loopwright', 'manifest.json')]) {
96
+ // Main checkout's manifest first (it exists once), then the global one (global installs record it under ~/.config/loopwright).
97
+ const main = mainLoopwrightPath(cwd);
98
+ for (const m of [main && join(main, 'manifest.json'), join(homedir(), '.config', 'loopwright', 'manifest.json')]) {
92
99
  if (name || !m || !existsSync(m)) continue;
93
100
  try {
94
101
  name = JSON.parse(readFileSync(m, 'utf8')).options?.profile;
@@ -104,6 +111,74 @@ function effortFor(role) {
104
111
 
105
112
  const gitOut = (args) => execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
106
113
 
114
+ /** The worktree a task header names: `worktree: <path> (branch <name>)`. */
115
+ function namedWorktree(header) {
116
+ const m = /^worktree:[ \t]*(.+?)(?:[ \t]+\(branch[ \t]+(.*?)\))?[ \t]*$/m.exec(header);
117
+ return m ? { path: resolve(m[1]), branch: m[2] ?? null } : null;
118
+ }
119
+
120
+ /** Task file fields: status/stage from the header (before the first `## `), title from `# `, goal from `## Goal`. */
121
+ function readTask(root, rel) {
122
+ const [head, ...sections] = readFileSync(join(root, rel), 'utf8').split(/^## /m);
123
+ const goal = sections.find((s) => /^Goal[ \t]*\r?\n/.test(s));
124
+ return {
125
+ title: /^# (.*)$/m.exec(head)?.[1].trim() ?? null,
126
+ status: /^status:[ \t]*(\S+)/m.exec(head)?.[1] ?? null,
127
+ stage: /^stage:[ \t]*(\S+)/m.exec(head)?.[1] ?? null,
128
+ named: namedWorktree(head),
129
+ goal: goal ? goal.replace(/^Goal[ \t]*\r?\n/, '').trim() : '',
130
+ };
131
+ }
132
+
133
+ /** `git worktree list`: the main checkout first, then linked worktrees. A missing folder is still listed. */
134
+ const listWorktrees = () =>
135
+ gitOut(['worktree', 'list', '--porcelain'])
136
+ .split(/\r?\n\r?\n/)
137
+ .filter(Boolean)
138
+ .map((b) => ({
139
+ path: resolve(/^worktree (.+)$/m.exec(b)[1]),
140
+ branch: /^branch refs\/heads\/(.+)$/m.exec(b)?.[1] ?? null,
141
+ }));
142
+
143
+ /** A move copies; the source stays, marked so no listing offers it again. */
144
+ function markMoved(file, to) {
145
+ writeFileSync(file, readFileSync(file, 'utf8').replace(/^status:.*$/m, `status: moved\nmoved to: ${to}`));
146
+ }
147
+
148
+ const today = () => {
149
+ const d = new Date();
150
+ const p2 = (n) => String(n).padStart(2, '0');
151
+ return `${d.getFullYear()}-${p2(d.getMonth() + 1)}-${p2(d.getDate())}`;
152
+ };
153
+
154
+ /** File name (no extension) for a stub: date plus the title with spaces and path characters dashed. */
155
+ const stubBase = (title) => `${today()}-${title.replace(/\s+/g, '-').replace(/[\\/:*?"<>|]/g, '-')}`;
156
+
157
+ /** Write `tasks/<base>.md`, adding `-2`, `-3`... on a name collision; returns the path relative to `dir`. */
158
+ function writeUnique(dir, base, text) {
159
+ for (let n = 1; ; n++) {
160
+ const rel = `tasks/${base}${n === 1 ? '' : `-${n}`}.md`;
161
+ try {
162
+ writeFileSync(join(dir, rel), text, { flag: 'wx' });
163
+ return rel;
164
+ } catch (err) {
165
+ if (err.code !== 'EEXIST') throw err;
166
+ }
167
+ }
168
+ }
169
+
170
+ /** A proposed stub in park's format; `goal` is empty for a stub parked mid-task. */
171
+ const stubText = (header, goal = '') => `${header.join('\n')}\n\n## Goal\n${goal ? `${goal}\n` : ''}\n## Evidence\n`;
172
+
173
+ const refExists = (ref) => {
174
+ try {
175
+ gitOut(['rev-parse', '--verify', '--quiet', `${ref}^{commit}`]);
176
+ return true;
177
+ } catch {
178
+ return false;
179
+ }
180
+ };
181
+
107
182
  const [cmd, ...rest] = process.argv.slice(2);
108
183
  try {
109
184
  switch (cmd) {
@@ -116,6 +191,12 @@ try {
116
191
  if (force) rest.splice(rest.indexOf('--force'), 1);
117
192
  const task = rest[0];
118
193
  if (!task) fail('loopwright: usage: start <task-rel-path> [--base <sha>] [--force]');
194
+ // A task file belongs to the worktree its header names; starting it elsewhere would split its state.
195
+ const own = loopwrightPath(cwd);
196
+ const header = own && existsSync(join(own, task)) ? readFileSync(join(own, task), 'utf8').split(/^## /m)[0] : '';
197
+ const named = namedWorktree(header)?.path;
198
+ if (named && realpathLoose(named) !== realpathLoose(gitTopLevel(cwd)))
199
+ fail(`loopwright: ${task} belongs to the worktree ${named}; start it there`);
119
200
  const { dir, id } = ctx(true);
120
201
  const prior = readState(dir, id);
121
202
  if (!force && prior) fail('loopwright: task already active (run lw.mjs done first, or start --force)');
@@ -274,6 +355,207 @@ try {
274
355
  out(state);
275
356
  break;
276
357
  }
358
+ case 'tasks': {
359
+ // Read-only: lists what is open in every worktree. Never creates a .loopwright/ or touches a task.
360
+ const real = (p) => realpathLoose(resolve(p));
361
+ const here = real(gitTopLevel(cwd));
362
+ const trees = listWorktrees();
363
+ const [main] = trees;
364
+ const live = trees.filter((t) => t !== main && existsSync(t.path));
365
+ const result = { inProgress: [], proposed: [], olderLayout: [], worktreeGone: [], unreadable: [] };
366
+ const entry = (wt, branch, task, t) => ({
367
+ worktree: wt,
368
+ branch,
369
+ task,
370
+ title: t.title,
371
+ stage: t.stage,
372
+ goal: t.goal,
373
+ current: real(wt) === here,
374
+ });
375
+ const gone = new Map();
376
+ for (const wt of trees) {
377
+ const root = join(wt.path, '.loopwright');
378
+ let names = [];
379
+ try {
380
+ if (existsSync(join(root, 'tasks')))
381
+ names = readdirSync(join(root, 'tasks')).filter((n) => n.endsWith('.md'));
382
+ else if (!existsSync(wt.path)) throw new Error('folder missing');
383
+ } catch (err) {
384
+ result.unreadable.push({ worktree: wt.path, branch: wt.branch, reason: err.message });
385
+ continue;
386
+ }
387
+ for (const name of names.sort()) {
388
+ const task = `tasks/${name}`;
389
+ let t;
390
+ try {
391
+ t = readTask(root, task);
392
+ } catch {
393
+ continue; // one unreadable file does not hide the rest
394
+ }
395
+ if (['done', 'stopped', 'moved', 'dropped'].includes(t.status)) continue;
396
+ if (t.status === 'proposed') {
397
+ result.proposed.push(entry(wt.path, wt.branch, task, t));
398
+ continue;
399
+ }
400
+ // Task files written before per-worktree layout sit in the main checkout and name their worktree.
401
+ if (wt === main && t.named && real(t.named.path) !== real(main.path)) {
402
+ const owner = live.find((l) => real(l.path) === real(t.named.path));
403
+ if (owner) result.olderLayout.push(entry(owner.path, owner.branch, task, t));
404
+ else gone.set(`${t.named.path}\0${task}`, entry(t.named.path, t.named.branch, task, t));
405
+ continue;
406
+ }
407
+ result.inProgress.push(entry(wt.path, wt.branch, task, t));
408
+ }
409
+ }
410
+ // A state file whose worktree folder is gone, even when its task file is too.
411
+ const stateDir = join(main.path, '.loopwright', 'state');
412
+ for (const name of existsSync(stateDir) ? readdirSync(stateDir).sort() : []) {
413
+ let s;
414
+ try {
415
+ s = JSON.parse(readFileSync(join(stateDir, name), 'utf8'));
416
+ } catch {
417
+ continue;
418
+ }
419
+ if (typeof s?.worktree !== 'string' || typeof s.task !== 'string' || existsSync(s.worktree)) continue;
420
+ const key = `${resolve(s.worktree)}\0${s.task}`;
421
+ let t = { title: null, stage: null, goal: '' };
422
+ try {
423
+ t = readTask(join(main.path, '.loopwright'), s.task);
424
+ } catch {
425
+ // Task file gone too: report the state alone.
426
+ }
427
+ // An adopted or finished task leaves its main-checkout state behind; its header says it is closed.
428
+ if (['done', 'stopped', 'moved', 'dropped'].includes(t.status)) continue;
429
+ gone.set(key, entry(resolve(s.worktree), s.branch ?? null, s.task, { ...t, stage: s.stage ?? t.stage }));
430
+ }
431
+ result.worktreeGone.push(...gone.values());
432
+ out(result);
433
+ break;
434
+ }
435
+ case 'adopt': {
436
+ // Pulls a task written before per-worktree layout (main checkout) into the worktree it names. Copies; never deletes.
437
+ const task = rest[0];
438
+ if (!task) fail('loopwright: usage: adopt <task-rel-path>');
439
+ if (isMainCheckout())
440
+ fail('loopwright: adopt runs in the linked worktree that should own the task, not in the main checkout');
441
+ const mainDir = mainLoopwrightPath(cwd);
442
+ const src = join(mainDir, task);
443
+ if (!existsSync(src)) fail(`loopwright: adopt: ${task} not found in the main checkout's .loopwright/`);
444
+ const named = namedWorktree(readFileSync(src, 'utf8').split(/^## /m)[0]);
445
+ if (named && realpathLoose(named.path) !== realpathLoose(gitTopLevel(cwd)))
446
+ fail(`loopwright: adopt: ${task} belongs to the worktree ${named.path}; run adopt there`);
447
+ const id = worktreeId(cwd);
448
+ const old = readState(mainDir, id);
449
+ const state = old?.task === task ? old : null;
450
+ const own = loopwrightPath(cwd);
451
+ if (existsSync(join(own, task))) fail(`loopwright: adopt: ${task} already exists in this worktree`);
452
+ if (state && readState(own, id)) fail('loopwright: adopt: this worktree already has an active task');
453
+ const { dir } = ctx(true);
454
+ copyFileSync(src, join(dir, task));
455
+ if (state) {
456
+ note(state, 'adopt', task);
457
+ writeState(dir, id, state);
458
+ }
459
+ markMoved(src, join(dir, task));
460
+ out({ task, state: Boolean(state) });
461
+ break;
462
+ }
463
+ case 'worktree': {
464
+ // Creates a sibling worktree on a new branch with a stub to plan from. Does not enter it or start a session there.
465
+ const usage = 'loopwright: usage: worktree "<title>" [--base <ref>] [--stub <file>] [--kind feature|fix]';
466
+ const baseFlag = flag(rest, '--base');
467
+ const stubFlag = flag(rest, '--stub');
468
+ const kind = flag(rest, '--kind') ?? 'feature';
469
+ const title = rest.join(' ').trim();
470
+ if (!title) fail(usage);
471
+ if (kind !== 'feature' && kind !== 'fix') fail(`${usage} (kind must be feature or fix)`);
472
+ // Validate everything before git changes anything.
473
+ let source = null;
474
+ if (stubFlag) {
475
+ source = resolve(loopwrightPath(cwd), stubFlag);
476
+ if (!existsSync(source)) fail(`loopwright: worktree: stub ${stubFlag} not found`);
477
+ if (readTask(dirname(source), basename(source)).status !== 'proposed')
478
+ fail(`loopwright: worktree: ${stubFlag} is not a proposed stub`);
479
+ }
480
+ let goal = '';
481
+ // isatty, not process.stdin.isTTY: touching process.stdin makes a piped fd 0 non-blocking, so a slow writer fails readFileSync with EAGAIN.
482
+ if (!source && !isatty(0)) goal = readFileSync(0, 'utf8').trim();
483
+ let base = baseFlag;
484
+ if (base !== undefined) {
485
+ if (base.startsWith('-') || !refExists(base)) fail(`loopwright: worktree: unknown base '${base}'`);
486
+ } else {
487
+ // The remote's default branch beats a local main that may be ahead or stale-checked-out.
488
+ base = ['origin/HEAD', 'main', 'master'].find(refExists) ?? 'HEAD';
489
+ }
490
+ const main = mainWorktreeRoot(cwd);
491
+ const slug =
492
+ title
493
+ .toLowerCase()
494
+ .replace(/[^\p{L}\p{N}]+/gu, '-')
495
+ .replace(/^-+|-+$/g, '') || 'task';
496
+ let name;
497
+ let folder;
498
+ for (let n = 1; ; n++) {
499
+ name = `${slug}${n === 1 ? '' : `-${n}`}`;
500
+ folder = join(dirname(main), `${basename(main)}-${name}`);
501
+ if (!existsSync(folder) && !refExists(`refs/heads/${name}`)) break;
502
+ }
503
+ gitOut(['worktree', 'add', '--no-track', '-b', name, folder, base]);
504
+ const dir = join(folder, '.loopwright');
505
+ scaffold(dir, false);
506
+ let stub;
507
+ if (source) {
508
+ stub = `tasks/${basename(source)}`;
509
+ copyFileSync(source, join(dir, stub));
510
+ markMoved(source, join(dir, stub));
511
+ } else {
512
+ stub = writeUnique(
513
+ dir,
514
+ stubBase(title),
515
+ stubText([`# ${title}`, '', `kind: ${kind}`, 'status: proposed', 'stage: plan', 'plan: draft'], goal),
516
+ );
517
+ }
518
+ const hook = join('.agents', 'loopwright', 'hooks', 'lw.mjs');
519
+ out({
520
+ worktree: folder,
521
+ branch: name,
522
+ base,
523
+ stub,
524
+ installMissing: existsSync(join(gitTopLevel(cwd), hook)) && !existsSync(join(folder, hook)),
525
+ });
526
+ break;
527
+ }
528
+ case 'carry': {
529
+ // Moves this worktree's proposed stubs to the main checkout so they outlive the worktree. Copies; never deletes.
530
+ if (isMainCheckout())
531
+ fail('loopwright: carry runs in a linked worktree; the main checkout already holds its stubs');
532
+ const own = loopwrightPath(cwd);
533
+ const mainDir = mainLoopwrightPath(cwd);
534
+ scaffold(mainDir, true);
535
+ const carried = [];
536
+ const names = existsSync(join(own, 'tasks')) ? readdirSync(join(own, 'tasks')).sort() : [];
537
+ for (const name of names.filter((n) => n.endsWith('.md'))) {
538
+ const file = join(own, 'tasks', name);
539
+ let status;
540
+ try {
541
+ status = readTask(own, `tasks/${name}`).status;
542
+ } catch {
543
+ continue; // one unreadable file does not block the rest
544
+ }
545
+ if (status !== 'proposed') continue;
546
+ const to = join(mainDir, writeUnique(mainDir, name.slice(0, -3), readFileSync(file, 'utf8')));
547
+ markMoved(file, to);
548
+ carried.push({ from: file, to });
549
+ }
550
+ out({ carried });
551
+ break;
552
+ }
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')));
557
+ break;
558
+ }
277
559
  case 'effort':
278
560
  process.stdout.write(effortFor(rest[0]) + '\n');
279
561
  break;
@@ -290,26 +572,13 @@ try {
290
572
  const active = existing ? (readState(existing, worktreeId(cwd))?.task ?? null) : null;
291
573
  if (blocks && !active) fail('loopwright: park --blocks needs an active task');
292
574
  const { dir } = ctx(true);
293
- const d = new Date();
294
- const p2 = (n) => String(n).padStart(2, '0');
295
- const base = `${d.getFullYear()}-${p2(d.getMonth() + 1)}-${p2(d.getDate())}-${title.replace(/\s+/g, '-').replace(/[\\/:*?"<>|]/g, '-')}`;
296
575
  const foundWhile = active && existsSync(join(dir, active)) ? active : null;
297
576
  if (active && !foundWhile)
298
577
  process.stderr.write(`loopwright: warning: active task file ${active} is missing; follow-up not linked\n`);
299
578
  const header = [`# ${title}`, '', `kind: ${kind}`, 'status: proposed', 'stage: plan', 'plan: draft'];
300
579
  if (foundWhile) header.push(`found while: ${foundWhile}`);
301
580
  if (blocks && foundWhile) header.push(`blocks: ${foundWhile}`);
302
- const text = header.join('\n') + '\n\n## Goal\n\n## Evidence\n';
303
- let stub;
304
- for (let n = 1; ; n++) {
305
- stub = `tasks/${base}${n === 1 ? '' : `-${n}`}.md`;
306
- try {
307
- writeFileSync(join(dir, stub), text, { flag: 'wx' });
308
- break;
309
- } catch (err) {
310
- if (err.code !== 'EEXIST') throw err;
311
- }
312
- }
581
+ const stub = writeUnique(dir, stubBase(title), stubText(header));
313
582
  if (foundWhile) {
314
583
  const line = `- ${title} — ${stub}${blocks ? ' [blocking]' : ''}`;
315
584
  const file = join(dir, foundWhile);
@@ -436,7 +705,7 @@ try {
436
705
  }
437
706
  default:
438
707
  fail(
439
- 'loopwright: usage: lw.mjs <dir|start|stage|reopen|lock|check-locks|fingerprint|verdict|await-user|resume|park|explore|status|effort|done>',
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>',
440
709
  );
441
710
  }
442
711
  } catch (err) {
@@ -18,7 +18,7 @@ Run `node "{{LW_HOME}}/hooks/lw.mjs" check-locks`. It prints `{ok, changed, miss
18
18
  Blind pass (default): work only from
19
19
  - the task file (the caller gives you its absolute path),
20
20
  - the diff against the base commit (`baseCommit` in `status`): `git diff <baseCommit>` plus untracked files from `git status --porcelain`,
21
- - standards: `AGENTS.md` and the `docs/agents/` docs it links,
21
+ - standards: `{{LW_HOME}}/prompts/standards.md`, `AGENTS.md` and the `docs/agents/` docs it links,
22
22
  - existing codebase patterns,
23
23
  - output of the task's check commands, which you run yourself.
24
24
 
@@ -34,12 +34,15 @@ Second pass: only when the caller hands you the implementer's report. Verify eac
34
34
  4. **List candidate blocking issues silently.** Don't report anything yet. Consider:
35
35
  - bugs, regressions, security vulnerabilities;
36
36
  - architecturally bad decisions;
37
- - non-simplified code paths (a much simpler path does the same);
37
+ - non-simplified code paths (a much simpler path does the same; the finding must show the smaller version);
38
+ - duplicated docs: the change states a fact that another doc, comment or contract already states (proof: both locations; the fix is to remove the new copy and link, never to delete the older home);
39
+ - bypassed mechanism: the change branches or hardcodes what an existing mechanism (config, registry, helper) already handles (proof: the mechanism `path:line`);
38
40
  - missing tests for new behavior;
39
41
  - violations of a decision or acceptance criterion; scope creep beyond the task;
40
- - comment rule violations: "Comments explain why, briefly. State each rationale in exactly one place. Never restate what the code does.";
42
+ - violations of the other named rules in `standards.md` (comment rule included);
41
43
  - deviations from the standards docs or established codebase patterns.
42
44
  Exclude lint/format-level nits; mechanical checks own them. Exception: a lint or format check failing on a changed file that is not locked is Blocking; failing on a locked test file is Undecided (the user decides, Build cannot touch it). A failing test assertion stays Blocking.
45
+ A proven violation of a named rule in `standards.md` is high impact (Blocking when confidence is high). Without that proof (smaller version, both locations, mechanism `path:line`, or the hunk) it is dropped. A violation inside a locked test file stays Undecided (the user decides, Build cannot touch it).
43
46
  5. **Investigate each candidate.** Self-verify first: re-read the code, run a repro or a test. Then assign impact (high/mid/low) and confidence (high/mid/low).
44
47
  6. **Report.**
45
48
  - **Blocking** — high impact, high confidence, confirmed by your investigation.
@@ -0,0 +1,18 @@
1
+ # loopwright code standards
2
+
3
+ Shared by the tester, implementer and reviewer. The repo's own docs on architecture and conventions (`AGENTS.md`, `CLAUDE.md`, `ARCHITECTURE.md`, `README.md`, `CONTRIBUTING.md`, `docs/` and similar) win over this file on any conflict.
4
+
5
+ ## Rules
6
+
7
+ - **Existing mechanism first.** Use what the repo already has (config layering, per-environment settings, feature toggles, DI wiring, error types, validation) before adding anything, even when the new setting is the first of its kind. Differences between environments, deployments or tenants go in config; never branch on the environment name in code. Why: each new `if` on an environment is a second place to change when one is added.
8
+ - **Fewest clear lines.** Write the smallest version that is still readable. Why: every line is read, tested and maintained.
9
+ - **Respect the layers.** Keep code in the layer the repo docs (`AGENTS.md`, `ARCHITECTURE.md`, `docs/`) assign it; do not reach across them. Why: crossed layers make later changes spread.
10
+ - **No trivial wrappers or one-off helpers.** Call the underlying function. A helper with one call site exists only if it names a step the reader would otherwise have to decode. Why: an indirection that adds nothing hides where the work happens.
11
+ - **Delete what you replace.** Remove the code, tests and docs your change makes dead: no old path kept "just in case", no unused parameters, no unrequested compatibility shims. Why: dead code reads as live behavior.
12
+ - **Validate at the boundaries.** Check input where it enters (user, network, files), not again in every inner function; trust types inside. No guards for impossible states, no catch blocks that swallow errors, no fallbacks that hide bugs. Why: repeated checks disagree and bury the real one.
13
+ - **No speculative generality.** Build for the cases the task states, not ones that might come: no interface with one implementation, no option or parameter nobody asked for, no generic version of a one-off. A requested per-environment flag is not speculative. Why: unused options are code to maintain with no proof they fit.
14
+ - **One home per fact.** State each fact in one place and link to it elsewhere or say nothing. API behavior for callers goes in the contract (OpenAPI description, public API doc, docs page); why the code is shaped this way in a short comment at the one surprising spot; expected behavior in the test name; cross-task rules in `AGENTS.md`, never feature details. Why: copies drift apart.
15
+ - **Comments.** Comments explain why, briefly. State each rationale in exactly one place. Never restate what the code does. Why: a comment that repeats the code or another comment goes stale first.
16
+ - **No change-log comments.** Do not write "added", "changed from" or "now uses"; history lives in git. Why: the comment is wrong once the next change lands.
17
+ - **Leave existing docs alone.** Edit docs and comments you did not need to change only when your change makes them false. Why: unrelated rewrites bury the real diff.
18
+ - **The test name carries the behavior.** Name a test for what it checks and skip doc blocks or comments that restate the name or the criterion. Why: a restated criterion is a second copy to keep in sync.
@@ -9,14 +9,14 @@ 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 `<lw>/config.json` (default `docs/agents`).
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
13
  3. `node "{{LW_HOME}}/hooks/lw.mjs" status` → `task`, `verdict`. 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
15
  4. `node "{{LW_HOME}}/hooks/lw.mjs" stage done`, and set `stage: done` in the task file header.
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.
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.
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.
@@ -29,6 +29,8 @@ If `CLAUDE.md` exists and has no line `@AGENTS.md`, propose adding that import l
29
29
 
30
30
  `grep -l "^found while: <this task path>" <lw>/tasks/*.md` lists the stubs parked while this task ran (`status: proposed` ones are still open). For each, draft issue text (title, what and why, `path:line` evidence from its `## Evidence`) and show it to the user. It is shown only: never file it, and write no task paths or ids into it. A stub with `blocks: <this task path>` that is still `proposed` → ask one question: clear the flag (the stub no longer blocks) or note it in the PR.
31
31
 
32
+ In a linked worktree, its `status: proposed` stubs are deleted along with the worktree. List them and offer one question: move them to the main checkout with `node "{{LW_HOME}}/hooks/lw.mjs" carry` (it copies each into the main checkout's `tasks/` and marks the source `status: moved`; it fails in the main checkout, where the stubs already are). Run it only on yes; a stub the user keeps here is lost when the worktree is removed, so say so.
33
+
32
34
  ## 3. Commit message and PR description
33
35
 
34
36
  Never write task ids (AC, D, S shorthands) into tests, code, comments, commit messages or PR drafts. Describe decisions in words.
@@ -10,9 +10,26 @@ Entry for bug fixes. It reuses Plan, Test, Build, Review and Done with `kind: fi
10
10
 
11
11
  1. Run every loopwright command from the worktree root: `cd "$(git rev-parse --show-toplevel)"`.
12
12
  2. `node "{{LW_HOME}}/hooks/lw.mjs" dir` prints the `.loopwright` directory (`<lw>` below). `null` inside a git repo → no task has started here yet; `lw.mjs start` creates `.loopwright/`, so continue with a new 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`. It prints a task → the task is in progress; tell the user to continue it with `/loopwright-flow` and do not start a second. "no active task" → continue.
13
+ 3. `node "{{LW_HOME}}/hooks/lw.mjs" status`. "no active task" → this worktree is free; the bug is a new goal, so run "Goal intake" below before Steps (a related task in another worktree is not started again here). It prints a task → this worktree is occupied; follow "Goal intake" below instead of starting a second task here.
14
14
  4. Hooks check: `grep -l "loopwright/hooks/" .claude/settings.json .codex/config.toml .junie/config.json ~/.claude/settings.json ~/.codex/config.toml ~/.junie/config.json 2>/dev/null`. No match → warn the user once: "loopwright hooks are not installed, so locked tests, the stop gate and context restore are not enforced; run `npx loopwright init` to install them." Continue unless the user objects.
15
15
 
16
+ ## Goal intake
17
+
18
+ A new goal, while open tasks may exist: `node "{{LW_HOME}}/hooks/lw.mjs" tasks` lists every worktree's open tasks (`inProgress`, each with its `goal` and `current`) and the parked stubs. Whether a task is related to the goal is your judgment; ask the user when unsure.
19
+
20
+ First step, before any question or message: if `node "{{LW_HOME}}/hooks/lw.mjs" status` shows this worktree's task in `build` or `review`, run `node "{{LW_HOME}}/hooks/lw.mjs" await-user "handing a new goal to a new worktree"` once, so the stop gate does not push this session into that task or spend its stop-block cap on any turn of this intake. Never run `resume` in goal intake: the wait clears when that task's own work resumes (its stage skill's `stage` call, `reopen` or `verdict`), also when the user switches to continuing it.
21
+ - A related task in this worktree → ask whether to continue it with `/loopwright-flow`. A related task in another worktree → do not start here; tell the user to continue it there and print the start command.
22
+ - Only unrelated tasks, and this worktree is free (`status` prints "no active task") → start the goal here.
23
+ - This worktree is occupied (`status` prints a task; the Plan stage counts) → say which task occupies it, suggest a new worktree, and never offer to close or shelve an unrelated task. On yes, pass the goal on stdin through a quoted heredoc, so backticks and `$` in it stay text (pick a delimiter that does not appear alone on a line in the goal), then print the start command.
24
+ ```bash
25
+ node "{{LW_HOME}}/hooks/lw.mjs" worktree "<title>" --kind fix <<'LW_GOAL'
26
+ <goal, exactly as the user wrote it>
27
+ LW_GOAL
28
+ ```
29
+ It prints `{worktree, branch, base, stub, installMissing}`. Planning happens in the new session, from the stub, not here.
30
+ - `installMissing` true → the new worktree lacks the repo-mode install: say so and print `npx loopwright update` (run in that folder) before the start command.
31
+ - Start command, by tool: Claude `cd <path> && claude "/loopwright-flow"`; Codex `cd <path> && codex '$loopwright-flow'`; Junie `cd <path>`, then start Junie and run `/loopwright-flow`. This session does not change directory; the user starts the new session.
32
+
16
33
  ## Steps
17
34
 
18
35
  1. Input: a bug description, issue text, or a path to a log or report. None given → ask the user for one.
@@ -16,12 +16,30 @@ Runs the stage skills in order for the confirmed tier and resumes where a task l
16
16
  ## Resume
17
17
 
18
18
  `node "{{LW_HOME}}/hooks/lw.mjs" status`:
19
- - Prints a task → read `<lw>/<task>` and continue at its `stage` (plan: run `loopwright-plan`, which resumes the open plan; review: count rounds from the review log).
19
+ - Prints a task, and the user gave a new goal → the worktree is occupied: follow "Goal intake" below, never continue the task unasked. Prints a task, and no goal or the goal is that task → read `<lw>/<task>` and continue at its `stage` (plan: run `loopwright-plan`, which resumes the open plan; review: count rounds from the review log).
20
20
  - "no active task" → `grep -l "^status: active" <lw>/tasks/*.md`.
21
21
  - One or more files → ask the user which one (or a new task). For the chosen file, offer to rebuild state from it: `node "{{LW_HOME}}/hooks/lw.mjs" start tasks/<file>.md --base <base commit from its header>`, then `node "{{LW_HOME}}/hooks/lw.mjs" stage <stage from its header>`. Locked-test hashes are lost with the state: if the task already has acceptance tests and is past Test, tell the user; re-lock the test files named in its AC lines (`stage test`, `lock <files>`, then `stage <stage>`) only if the user confirms they are unchanged.
22
22
  - None, or the user wants a new task → continue below.
23
- - Also list stubs parked by `/loopwright-park`: `grep -l "^status: proposed" <lw>/tasks/*.md`. Offer each as start, drop, or a new task instead. Start → run `loopwright-plan` on it as in that skill ("Parked stubs"). Drop → set `status: dropped` in the stub; never delete it.
24
- - No stubs and no task, or the user wants a new task → start at Plan with the user's goal or spec path.
23
+ - Also list stubs parked by `/loopwright-park` (`status: proposed` in `lw.mjs tasks`, from any worktree; `grep -l "^status: proposed" <lw>/tasks/*.md` lists this worktree's). Offer each as start, drop, or a new task instead. Start → run `loopwright-plan` on it as in that skill ("Parked stubs"); a stub that sits in another worktree starts in a new worktree instead (`lw.mjs worktree "<title>" --stub <absolute path>`, then print the start command). Drop → set `status: dropped` in the stub; never delete it.
24
+ - An `olderLayout` entry listed under this worktree is a task from before tasks were kept per worktree: offer `node "{{LW_HOME}}/hooks/lw.mjs" adopt <task>` to copy it and its state (with locks) in. Nothing moves or is deleted unasked.
25
+ - No stubs and no task, or the user wants a new task → run "Goal intake" below for the user's goal, then start at Plan with the goal or spec path.
26
+
27
+ ## Goal intake
28
+
29
+ A new goal, while open tasks may exist: `node "{{LW_HOME}}/hooks/lw.mjs" tasks` lists every worktree's open tasks (`inProgress`, each with its `goal` and `current`) and the parked stubs (`proposed`). Whether a task is related to the goal is your judgment; ask the user when unsure.
30
+
31
+ First step, before any question or message: if `node "{{LW_HOME}}/hooks/lw.mjs" status` shows this worktree's task in `build` or `review`, run `node "{{LW_HOME}}/hooks/lw.mjs" await-user "handing a new goal to a new worktree"` once, so the stop gate does not push this session into that task or spend its stop-block cap on any turn of this intake. Never run `resume` in goal intake: the wait clears when that task's own work resumes (its stage skill's `stage` call, `reopen` or `verdict`), also when the user switches to continuing it.
32
+ - A related task in this worktree → ask whether to continue it. A related task in another worktree → do not start here; tell the user to continue it there and print the start command.
33
+ - Only unrelated tasks, and this worktree is free (`status` prints "no active task") → start the goal here.
34
+ - This worktree is occupied (`status` prints a task; the Plan stage counts) → say which task occupies it, suggest a new worktree, and never offer to close or shelve an unrelated task. On yes, pass the goal on stdin through a quoted heredoc, so backticks and `$` in it stay text (pick a delimiter that does not appear alone on a line in the goal), then print the start command.
35
+ ```bash
36
+ node "{{LW_HOME}}/hooks/lw.mjs" worktree "<title>" <<'LW_GOAL'
37
+ <goal, exactly as the user wrote it>
38
+ LW_GOAL
39
+ ```
40
+ It prints `{worktree, branch, base, stub, installMissing}`. Planning happens in the new session, from the stub, not here.
41
+ - `installMissing` true → the new worktree lacks the repo-mode install: say so and print `npx loopwright update` (run in that folder) before the start command.
42
+ - Start command, by tool: Claude `cd <path> && claude "/loopwright-flow"`; Codex `cd <path> && codex '$loopwright-flow'`; Junie `cd <path>`, then start Junie and run `/loopwright-flow`. This session does not change directory; the user starts the new session.
25
43
 
26
44
  ## Run
27
45
 
@@ -18,8 +18,8 @@ Captures work found mid-task (call it B) as a stub, so the current task (A) keep
18
18
  2. Ask one question, "Does this block the current task?", recommendation "no" (Claude: `AskUserQuestion`; Codex: numbered text). It needs an active task; with none, skip it.
19
19
  3. Run `node "{{LW_HOME}}/hooks/lw.mjs" park "<title>"`, adding `--blocks` when the answer is yes and `--kind fix` when B is a bug. It prints `{stub, foundWhile, blocks}`.
20
20
  4. Write the agreed goal under `## Goal` and the evidence under `## Evidence` of `<lw>/<stub>`.
21
- 5. Blocking → suggest running B first in another worktree (the stub is shared by all worktrees), and leave A as it is.
22
- 6. Tell the user the stub path and that it is listed under A's `## Follow-ups`. Resume A where it was.
21
+ 5. Blocking → suggest running B first in a new worktree (`node "{{LW_HOME}}/hooks/lw.mjs" worktree "<title>" --stub <stub>` moves the stub there; print the start command as `loopwright-flow` describes under "Goal intake"), and leave A as it is.
22
+ 6. Tell the user the stub path (it lives in this worktree's `.loopwright/`) and that it is listed under A's `## Follow-ups`. Resume A where it was.
23
23
 
24
24
  ## Rules
25
25
 
@@ -10,14 +10,32 @@ Plan runs in this main thread. You state assumptions; the user decides. Do not e
10
10
 
11
11
  1. Run every loopwright command from the worktree root: `cd "$(git rev-parse --show-toplevel)"`.
12
12
  2. `node "{{LW_HOME}}/hooks/lw.mjs" dir` prints the `.loopwright` directory (`<lw>` below). `null` inside a git repo → no task has started here yet; `lw.mjs start` (section 3) creates `.loopwright/`, so continue with a new 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`. "no active task" → continue with a new task. If it prints a task, read `<lw>/<task>`:
13
+ 3. `node "{{LW_HOME}}/hooks/lw.mjs" status`. "no active task" → this worktree is free; a new goal still goes through "Goal intake" below first (a related task in another worktree is not started again here), then continue with a new task. If it prints a task, read `<lw>/<task>`:
14
14
  - `stage: plan` and reopened (`status` `history` has a `reopen` event after the last `stage build` event; that event's `reason` says why) → this is the same task returning to Plan for added scope, not a second task: keep its decisions, ACs and tests, run sections 2–6 only for what the reason adds or changes (a new slice starts `[todo]`), then section 7. Do not ask whether the plan is abandoned.
15
+ - `stage: plan`, and the user gave a new goal unrelated to this plan → the worktree is occupied: follow "Goal intake" below, do not resume.
15
16
  - `stage: plan` → resume this plan: the first `— pending` item under `## Open questions`, else the proposal (step 6), else the confirmation (step 7). If the user says this plan is abandoned, offer to start the new one with `start tasks/<new file>.md --force` (the old task file stays).
16
- - past `plan` → the task is in progress; tell the user to continue it with `/loopwright-flow`. Do not start a second.
17
- 4. Read `<lw>/config.json` for `maxFixRounds` (missing file or key → 3).
17
+ - past `plan` → the task is in progress; tell the user to continue it with `/loopwright-flow`. Do not start a second here; a new goal follows "Goal intake".
18
+ 4. `node "{{LW_HOME}}/hooks/lw.mjs" config` prints the main checkout's config; read `maxFixRounds` from it (missing key → 3).
18
19
  5. `git status --porcelain` not empty → uncommitted changes will be part of the reviewed diff. Ask the user whether to commit/stash them first or include them; record the answer as a decision once the task file exists.
19
20
  6. Upstream check: `GIT_TERMINAL_PROMPT=0 git fetch --quiet` (never prompts for credentials; it fails offline or without auth → skip this check). Then list `git log --oneline HEAD..@{u}`; with no upstream, use `HEAD..origin/HEAD`; with neither, skip. Repeat in any sibling repo the goal touches (e.g. a separate frontend repo). New upstream commits → tell the user and ask whether to pull first. A commit or branch that already touches the goal's feature → ask whether someone has already done this work. Record the answers as decisions once the task file exists.
20
21
 
22
+ ## Goal intake
23
+
24
+ A new goal, while open tasks may exist: `node "{{LW_HOME}}/hooks/lw.mjs" tasks` lists every worktree's open tasks (`inProgress`, each with its `goal` and `current`) and the parked stubs. Whether a task is related to the goal is your judgment; ask the user when unsure.
25
+
26
+ First step, before any question or message: if `node "{{LW_HOME}}/hooks/lw.mjs" status` shows this worktree's task in `build` or `review`, run `node "{{LW_HOME}}/hooks/lw.mjs" await-user "handing a new goal to a new worktree"` once, so the stop gate does not push this session into that task or spend its stop-block cap on any turn of this intake. Never run `resume` in goal intake: the wait clears when that task's own work resumes (its stage skill's `stage` call, `reopen` or `verdict`), also when the user switches to continuing it.
27
+ - A related task in this worktree → ask whether to continue it with `/loopwright-flow`. A related task in another worktree → do not start here; tell the user to continue it there and print the start command.
28
+ - Only unrelated tasks, and this worktree is free (`status` prints "no active task") → start the goal here.
29
+ - This worktree is occupied (`status` prints a task; the Plan stage counts) → say which task occupies it, suggest a new worktree, and never offer to close or shelve an unrelated task. On yes, pass the goal on stdin through a quoted heredoc, so backticks and `$` in it stay text (pick a delimiter that does not appear alone on a line in the goal), then print the start command.
30
+ ```bash
31
+ node "{{LW_HOME}}/hooks/lw.mjs" worktree "<title>" <<'LW_GOAL'
32
+ <goal, exactly as the user wrote it>
33
+ LW_GOAL
34
+ ```
35
+ Add `--kind fix` for a fix. It prints `{worktree, branch, base, stub, installMissing}`. Planning happens in the new session, from the stub, not here.
36
+ - `installMissing` true → the new worktree lacks the repo-mode install: say so and print `npx loopwright update` (run in that folder) before the start command.
37
+ - Start command, by tool: Claude `cd <path> && claude "/loopwright-flow"`; Codex `cd <path> && codex '$loopwright-flow'`; Junie `cd <path>`, then start Junie and run `/loopwright-flow`. This session does not change directory; the user starts the new session.
38
+
21
39
  ## Parked stubs
22
40
 
23
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.
@@ -39,7 +57,7 @@ Never ask the user a question the repo can answer. If the scout report leaves a
39
57
  List every assumption you would otherwise make silently, one line each: `A<n> [high|low] <assumption> — <evidence: scout path:line, or "none">`.
40
58
  - **high-impact**: a wrong guess changes public behavior, an interface or name others use, a data/file format, scope, architecture, the test runner, or forces more than a small rework. When unsure, tag high.
41
59
  - **low-impact**: everything else (internal naming, file placement following an existing pattern, minor edge-case choices).
42
- - 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.
60
+ - 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.
43
61
 
44
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.
45
63
 
@@ -11,7 +11,7 @@ Reviewers judge in their own context. This thread dispatches them, merges their
11
11
  1. Run every loopwright command from the worktree root: `cd "$(git rev-parse --show-toplevel)"`.
12
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
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 `<lw>/config.json` (`crossAgentReview`, `models.crossAgentReviewer`; missing → `off`).
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`).
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
17
 
@@ -25,6 +25,7 @@ The tester writes acceptance tests from the confirmed ACs and locks them. This t
25
25
  3. Verify the report:
26
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
27
  - 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
+ - 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.
28
29
  - 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.
29
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`.
30
31
  - (a) Provide the missing evidence: add it to `## Bug report`, dispatch the tester again.
@@ -38,5 +39,5 @@ The tester writes acceptance tests from the confirmed ACs and locks them. This t
38
39
  ## Rules
39
40
 
40
41
  - Never write task ids (AC, D, S shorthands) into tests, code, comments, commit messages or PR drafts.
41
- - 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. Outside a reopen, if one is wrong, tell the user and let them decide.
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.
42
43
  - Do not read the implementation to judge the tests; the ACs are the contract.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "loopwright",
3
3
  "author": "Xuan Son Trinh",
4
- "version": "0.1.5",
4
+ "version": "0.1.6",
5
5
  "description": "Agent workflow installer for Claude Code, Codex and Junie",
6
6
  "type": "module",
7
7
  "bin": {