loopwright 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,215 @@
1
+ #!/usr/bin/env node
2
+ // Loopwright state tool. Usage: node lw.mjs <cmd> [args]
3
+ import { copyFileSync, existsSync, mkdirSync, unlinkSync, writeFileSync } from 'node:fs';
4
+ import { homedir } from 'node:os';
5
+ import { isAbsolute, join, resolve } from 'node:path';
6
+ import { execFileSync } from 'node:child_process';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { fingerprint, gitTopLevel, loopwrightDir, loopwrightPath, readState, repoRelative, sha256File, statePath, worktreeId, writeState } from './lib.mjs';
9
+
10
+ const STAGES = ['plan', 'test', 'build', 'review', 'done'];
11
+ const cwd = process.cwd();
12
+
13
+ function fail(msg) {
14
+ process.stderr.write(msg + '\n');
15
+ process.exit(1);
16
+ }
17
+ const note = (state, event, detail) => {
18
+ (state.history ??= []).push({ event, detail, at: new Date().toISOString() });
19
+ };
20
+ const out = (v) => process.stdout.write(JSON.stringify(v, null, 2) + '\n');
21
+
22
+ function flag(args, name) {
23
+ const i = args.indexOf(name);
24
+ if (i === -1) return undefined;
25
+ const v = args[i + 1];
26
+ if (v === undefined) fail(`loopwright: ${name} requires a value`);
27
+ args.splice(i, 2);
28
+ return v;
29
+ }
30
+
31
+ /** Create <main worktree>/.loopwright/ (global installs, fresh clones). Config seeds from ~/.config/loopwright/config.json, else the default. */
32
+ function scaffold(dir) {
33
+ mkdirSync(join(dir, 'tasks'), { recursive: true });
34
+ mkdirSync(join(dir, 'state'), { recursive: true });
35
+ const ignore = join(dir, '.gitignore');
36
+ if (!existsSync(ignore)) writeFileSync(ignore, '*\n');
37
+ const cfg = join(dir, 'config.json');
38
+ if (existsSync(cfg)) return;
39
+ const user = join(homedir(), '.config', 'loopwright', 'config.json');
40
+ copyFileSync(existsSync(user) ? user : fileURLToPath(new URL('./default-config.json', import.meta.url)), cfg);
41
+ }
42
+
43
+ function ctx(create = false) {
44
+ let dir = loopwrightDir(cwd);
45
+ if (!dir) {
46
+ const path = loopwrightPath(cwd);
47
+ if (!path) fail('loopwright: no .loopwright directory found (not inside a git repository)');
48
+ if (!create) fail('loopwright: no active task (no .loopwright directory yet; lw.mjs start creates it)');
49
+ scaffold(path);
50
+ dir = path;
51
+ }
52
+ return { dir, id: worktreeId(cwd) };
53
+ }
54
+
55
+ function requireState() {
56
+ const { dir, id } = ctx();
57
+ const state = readState(dir, id);
58
+ if (!state) fail('loopwright: no active task (run lw.mjs start <task-file>)');
59
+ return { dir, id, state };
60
+ }
61
+
62
+ const gitOut = (args) => execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
63
+
64
+ const [cmd, ...rest] = process.argv.slice(2);
65
+ try {
66
+ switch (cmd) {
67
+ case 'dir':
68
+ process.stdout.write((loopwrightDir(cwd) ?? 'null') + '\n');
69
+ break;
70
+ case 'start': {
71
+ const base = flag(rest, '--base') ?? 'HEAD';
72
+ const force = rest.includes('--force');
73
+ if (force) rest.splice(rest.indexOf('--force'), 1);
74
+ const task = rest[0];
75
+ if (!task) fail('loopwright: usage: start <task-rel-path> [--base <sha>] [--force]');
76
+ const { dir, id } = ctx(true);
77
+ const prior = readState(dir, id);
78
+ if (!force && prior) fail('loopwright: task already active (run lw.mjs done first, or start --force)');
79
+ const state = {
80
+ version: 1,
81
+ task,
82
+ stage: 'plan',
83
+ baseCommit: gitOut(['rev-parse', base]),
84
+ worktree: gitTopLevel(cwd),
85
+ branch: gitOut(['rev-parse', '--abbrev-ref', 'HEAD']),
86
+ // A forced restart keeps the audit trail and the lock records, so a locked test edited
87
+ // during Build cannot be re-baselined unnoticed.
88
+ lockedTests: Array.isArray(prior?.lockedTests) ? prior.lockedTests : [],
89
+ verdict: null,
90
+ stopBlocks: 0,
91
+ history: Array.isArray(prior?.history) ? prior.history : [],
92
+ };
93
+ if (force) note(state, 'start', '--force');
94
+ else note(state, 'start', task);
95
+ writeState(dir, id, state);
96
+ out(state);
97
+ break;
98
+ }
99
+ case 'stage': {
100
+ const name = rest[0];
101
+ if (!STAGES.includes(name)) fail(`loopwright: invalid stage '${name ?? ''}' (one of ${STAGES.join(', ')})`);
102
+ const { dir, id, state } = requireState();
103
+ state.stage = name;
104
+ state.stopBlocks = 0;
105
+ delete state.awaitingUser;
106
+ note(state, 'stage', name);
107
+ writeState(dir, id, state);
108
+ out(state);
109
+ break;
110
+ }
111
+ case 'lock': {
112
+ if (rest.length === 0) fail('loopwright: usage: lock <paths...>');
113
+ const { dir, id, state } = requireState();
114
+ if (state.stage !== 'test') fail('loopwright: tests can only be locked in stage test');
115
+ for (const p of rest) {
116
+ const abs = isAbsolute(p) ? p : resolve(cwd, p);
117
+ if (!existsSync(abs)) fail(`loopwright: cannot lock missing file ${p}`);
118
+ const rel = repoRelative(cwd, p);
119
+ if (rel.startsWith('..')) fail(`loopwright: path outside worktree: ${p}`);
120
+ const entry = { path: rel, sha256: sha256File(abs) };
121
+ const i = state.lockedTests.findIndex((l) => l.path === rel);
122
+ if (i === -1) state.lockedTests.push(entry);
123
+ else state.lockedTests[i] = entry;
124
+ note(state, 'lock', rel);
125
+ }
126
+ writeState(dir, id, state);
127
+ out(state.lockedTests);
128
+ break;
129
+ }
130
+ case 'check-locks': {
131
+ const { state } = requireState();
132
+ const top = gitTopLevel(cwd);
133
+ const changed = [];
134
+ const missing = [];
135
+ for (const l of state.lockedTests) {
136
+ const abs = resolve(top, l.path);
137
+ if (!existsSync(abs)) missing.push(l.path);
138
+ else if (sha256File(abs) !== l.sha256) changed.push(l.path);
139
+ }
140
+ const ok = changed.length === 0 && missing.length === 0;
141
+ // Re-locking an existing lock after a build could launder an implementer's edit; first-time locks in later slices are legitimate.
142
+ const lockedAfterBuild = [];
143
+ const seen = new Map();
144
+ for (const e of state.history ?? []) {
145
+ if (e.event === 'stage' && e.detail === 'build') for (const p of seen.keys()) seen.set(p, true);
146
+ if (e.event !== 'lock') continue;
147
+ if (seen.get(e.detail) === true && !lockedAfterBuild.includes(e.detail)) lockedAfterBuild.push(e.detail);
148
+ seen.set(e.detail, false);
149
+ }
150
+ let built = false;
151
+ let forcedRestartAfterBuild = false;
152
+ for (const e of state.history ?? []) {
153
+ if (e.event === 'stage' && e.detail === 'build') built = true;
154
+ if (built && e.event === 'start' && e.detail === '--force') forcedRestartAfterBuild = true;
155
+ }
156
+ out({ ok, changed, missing, lockedAfterBuild, forcedRestartAfterBuild });
157
+ process.exit(ok ? 0 : 1);
158
+ break;
159
+ }
160
+ case 'fingerprint': {
161
+ const { state } = requireState();
162
+ out({ fingerprint: fingerprint(cwd, state.baseCommit) });
163
+ break;
164
+ }
165
+ case 'verdict': {
166
+ const result = rest.shift();
167
+ if (result !== 'pass' && result !== 'fail') fail('loopwright: usage: verdict <pass|fail> --round <n>');
168
+ const roundRaw = flag(rest, '--round');
169
+ const round = Number(roundRaw);
170
+ if (roundRaw === undefined || !Number.isInteger(round) || round < 0) fail('loopwright: verdict requires --round <n>');
171
+ const { dir, id, state } = requireState();
172
+ state.verdict = { pass: result === 'pass', fingerprint: fingerprint(cwd, state.baseCommit), round };
173
+ delete state.awaitingUser;
174
+ note(state, 'verdict', `${result} round ${round}`);
175
+ writeState(dir, id, state);
176
+ out(state.verdict);
177
+ break;
178
+ }
179
+ case 'await-user': {
180
+ const reason = rest.join(' ').trim();
181
+ if (!reason) fail('loopwright: usage: await-user <reason>');
182
+ const { dir, id, state } = requireState();
183
+ state.awaitingUser = reason;
184
+ note(state, 'await-user', reason);
185
+ writeState(dir, id, state);
186
+ out(state);
187
+ break;
188
+ }
189
+ case 'resume': {
190
+ const { dir, id, state } = requireState();
191
+ note(state, 'resume', state.awaitingUser ?? '');
192
+ delete state.awaitingUser;
193
+ writeState(dir, id, state);
194
+ out(state);
195
+ break;
196
+ }
197
+ case 'status': {
198
+ out(requireState().state);
199
+ break;
200
+ }
201
+ case 'done': {
202
+ const { dir, id, state } = requireState();
203
+ state.stage = 'done';
204
+ note(state, 'done', state.task);
205
+ writeState(dir, id, state);
206
+ unlinkSync(statePath(dir, id));
207
+ out(state);
208
+ break;
209
+ }
210
+ default:
211
+ fail('loopwright: usage: lw.mjs <dir|start|stage|lock|check-locks|fingerprint|verdict|await-user|resume|status|done>');
212
+ }
213
+ } catch (err) {
214
+ fail(`loopwright: ${err instanceof Error ? err.message : String(err)}`);
215
+ }
@@ -0,0 +1,66 @@
1
+ #!/usr/bin/env node
2
+ // SessionStart(compact) hook: re-inject the active task summary after context compaction.
3
+ import { existsSync, readFileSync } from 'node:fs';
4
+ import { join } from 'node:path';
5
+ import { allow, exitIfHooksOff, failOpen, loopwrightDir, readState, readStdinJson, worktreeId } from './lib.mjs';
6
+
7
+ const NEXT = {
8
+ plan: 'Continue /loopwright-plan: finish the assumption ledger and confirm the tier.',
9
+ test: 'Continue /loopwright-test.',
10
+ build: 'Continue /loopwright-build; locked tests must not be edited.',
11
+ review: 'Continue /loopwright-review.',
12
+ done: 'Run /loopwright-done.',
13
+ };
14
+
15
+ function goalParagraph(text) {
16
+ const lines = text.split('\n');
17
+ const i = lines.findIndex((l) => /^#{1,6}\s*goal\b/i.test(l.trim()));
18
+ if (i === -1) return [];
19
+ const out = [];
20
+ for (const l of lines.slice(i + 1)) {
21
+ if (/^#{1,6}\s/.test(l)) break;
22
+ if (l.trim() === '') {
23
+ if (out.length) break;
24
+ continue;
25
+ }
26
+ out.push(l);
27
+ }
28
+ return out;
29
+ }
30
+
31
+ exitIfHooksOff();
32
+
33
+ try {
34
+ const tool = process.argv.includes('--tool') ? process.argv[process.argv.indexOf('--tool') + 1] : 'claude';
35
+ const input = await readStdinJson();
36
+ const cwd = input.cwd || process.cwd();
37
+ const dir = loopwrightDir(cwd);
38
+ if (!dir) allow();
39
+ const state = readState(dir, worktreeId(cwd));
40
+ if (!state) allow();
41
+
42
+ const lines = [`loopwright: active task ${state.task}`];
43
+ const file = join(dir, String(state.task));
44
+ if (existsSync(file)) {
45
+ const text = readFileSync(file, 'utf8');
46
+ lines.push(...goalParagraph(text));
47
+ lines.push(`Stage: ${state.stage}`);
48
+ lines.push(...text.split('\n').filter((l) => l.startsWith('- D')));
49
+ } else {
50
+ lines.push(`Stage: ${state.stage}`);
51
+ }
52
+ if (state.awaitingUser) lines.push(`Waiting on the user: ${state.awaitingUser} — do not proceed until they answer; then run lw.mjs resume.`);
53
+ else lines.push(NEXT[state.stage] ?? NEXT.plan);
54
+ const body = lines.slice(0, 40);
55
+ if (lines.length > 40) body[39] = lines[lines.length - 1];
56
+ const out = body.join('\n');
57
+
58
+ if (tool === 'codex') {
59
+ process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: 'SessionStart', additionalContext: out } }) + '\n');
60
+ } else {
61
+ process.stdout.write(out + '\n');
62
+ }
63
+ allow();
64
+ } catch (err) {
65
+ failOpen(err);
66
+ }
@@ -0,0 +1,37 @@
1
+ #!/usr/bin/env node
2
+ // Stop hook: block stopping in build/review without a passing review for the current code.
3
+ import { allow, exitIfHooksOff, deny, failOpen, fingerprint, loopwrightDir, readState, readStdinJson, worktreeId, writeState } from './lib.mjs';
4
+
5
+ const CAP = 3;
6
+
7
+ exitIfHooksOff();
8
+
9
+ try {
10
+ const input = await readStdinJson();
11
+ const cwd = input.cwd || process.cwd();
12
+ const dir = loopwrightDir(cwd);
13
+ if (!dir) allow();
14
+ const id = worktreeId(cwd);
15
+ const state = readState(dir, id);
16
+ if (!state || (state.stage !== 'build' && state.stage !== 'review')) allow();
17
+ // The agent is ending its turn to let the user decide; blocking would push it past the human gate.
18
+ if (state.awaitingUser) allow();
19
+ // A backgrounded subagent (e.g. the reviewer) is still working: the turn ends to wait for it, not to quit.
20
+ // Claude re-invokes the agent when it finishes, and that Stop carries no running tasks, so the gate applies then.
21
+ if (Array.isArray(input.background_tasks) && input.background_tasks.some((t) => t && t.status === 'running')) allow();
22
+
23
+ const v = state.verdict;
24
+ if (v && v.pass === true && v.fingerprint === fingerprint(cwd, state.baseCommit)) allow();
25
+
26
+ const blocks = Number(state.stopBlocks) || 0;
27
+ if (blocks >= CAP) {
28
+ process.stderr.write('loopwright: stop-gate limit reached; review gate NOT satisfied.\n');
29
+ allow();
30
+ }
31
+ state.stopBlocks = blocks + 1;
32
+ (state.history ??= []).push({ event: 'stop-blocked', detail: String(state.stopBlocks), at: new Date().toISOString() });
33
+ writeState(dir, id, state);
34
+ deny('', '', 'loopwright: no passing review for the current code. Run /loopwright-review (or finish the fix loop) before stopping.');
35
+ } catch (err) {
36
+ failOpen(err);
37
+ }
@@ -0,0 +1,66 @@
1
+ # loopwright review procedure
2
+
3
+ You review one change against its task file. You judge; you do not fix. Do not modify any file: no edits, no formatting, no `git add`/`commit`/`stash`/`checkout`. Running read-only commands, tests and check commands is allowed; never with flags that rewrite files (snapshot updates, `--fix`, `--write`).
4
+
5
+ State tool: `node "{{LW_HOME}}/hooks/lw.mjs" <cmd>`, run from the task's worktree. Use only `status`, `check-locks`, `fingerprint`, invoked exactly as written here (a headless reviewer's allowlist matches that text).
6
+
7
+ ## 0. Locked tests (always first)
8
+
9
+ Run `node "{{LW_HOME}}/hooks/lw.mjs" check-locks`. It prints `{ok, changed, missing, lockedAfterBuild, forcedRestartAfterBuild}` and exits 1 when `ok` is false.
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).
12
+ - `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
+ - The command errors (e.g. no active task) → one Blocking finding with the error text as proof.
14
+
15
+ ## Inputs
16
+
17
+ Blind pass (default): work only from
18
+ - the task file (the caller gives you its absolute path),
19
+ - the diff against the base commit (`baseCommit` in `status`): `git diff <baseCommit>` plus untracked files from `git status --porcelain`,
20
+ - standards: `AGENTS.md` and the `docs/agents/` docs it links,
21
+ - existing codebase patterns,
22
+ - output of the task's check commands, which you run yourself.
23
+
24
+ Never read or ask for an implementer report in the blind pass.
25
+
26
+ Second pass: only when the caller hands you the implementer's report. Verify each claim in it (tests run, behavior, deviations) against the code and command output. A false or unverifiable claim with high impact is a finding. Same reporting rules as below.
27
+
28
+ ## Procedure
29
+
30
+ 1. **Scope** — the diff vs the base commit, the locked tests, the task file. Nothing outside the diff is in scope unless the diff breaks it.
31
+ 2. **Intent** — read the goal, decisions (`D…`) and acceptance criteria (`AC…`). These, not your preferences, define correct.
32
+ 3. **Inspect** the changed files and nearby code until you understand the call paths the change touches. Run the check commands.
33
+ 4. **List candidate blocking issues silently.** Don't report anything yet. Consider:
34
+ - bugs, regressions, security vulnerabilities;
35
+ - architecturally bad decisions;
36
+ - non-simplified code paths (a much simpler path does the same);
37
+ - missing tests for new behavior;
38
+ - violations of a decision or acceptance criterion; scope creep beyond the task;
39
+ - comment rule violations: "Comments explain why, briefly. State each rationale in exactly one place. Never restate what the code does.";
40
+ - deviations from the standards docs or established codebase patterns.
41
+ Exclude lint/format-level nits; mechanical checks own them.
42
+ 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).
43
+ 6. **Report.**
44
+ - **Blocking** — high impact, high confidence, confirmed by your investigation.
45
+ - **Undecided** — high impact, not confirmed, but backed by proof. The user decides fix or dismiss.
46
+ - Everything else (no proof, or impact below high) is dropped. Count it in `droppedCount`; do not describe it. `droppedCount` is a non-negative integer.
47
+ 7. **Verdict rule.** `pass` is true only when `blocking` and `undecided` are both empty. Undecided findings go to the user; only they can resolve them.
48
+
49
+ ## Findings
50
+
51
+ Every reported finding has:
52
+ - `location` — `path:line` (or `path` when file-level, or the command run);
53
+ - `expectation` — the violated expectation, citing its source (`D3`, `AC2`, `AGENTS.md`, the comment rule, an existing pattern at `path:line`);
54
+ - `proof` — concrete evidence: `file:line` with what it shows, failing command and its output excerpt, a reputable SDK source or official doc link, or a decision/AC id. "Looks wrong" is not proof;
55
+ - `impact` — always `"high"` (lower impact is dropped);
56
+ - `confidence` — how sure you are the issue is real; Blocking requires `"high"`.
57
+
58
+ If a high-impact candidate hinges on intent the task file does not settle, make it Undecided with your proof rather than guessing.
59
+
60
+ ## Output
61
+
62
+ Output exactly one JSON object matching `{{LW_HOME}}/schemas/verdict.json`, with nothing before or after it: no prose, no code fence. Shape:
63
+
64
+ ```
65
+ {"pass": false, "blocking": [{"location": "src/a.ts:42", "expectation": "AC2 empty input returns []", "proof": "npm test: a.test.ts 'empty input' expected [] got undefined", "impact": "high", "confidence": "high"}], "undecided": [], "droppedCount": 3}
66
+ ```
@@ -0,0 +1,26 @@
1
+ {
2
+ "title": "loopwright review verdict",
3
+ "type": "object",
4
+ "required": ["pass", "blocking", "undecided", "droppedCount"],
5
+ "additionalProperties": false,
6
+ "properties": {
7
+ "pass": { "type": "boolean", "description": "True only when blocking and undecided are both empty." },
8
+ "blocking": { "type": "array", "items": { "$ref": "#/$defs/Finding" } },
9
+ "undecided": { "type": "array", "items": { "$ref": "#/$defs/Finding" } },
10
+ "droppedCount": { "type": "integer" }
11
+ },
12
+ "$defs": {
13
+ "Finding": {
14
+ "type": "object",
15
+ "required": ["location", "expectation", "proof", "impact", "confidence"],
16
+ "additionalProperties": false,
17
+ "properties": {
18
+ "location": { "type": "string" },
19
+ "expectation": { "type": "string" },
20
+ "proof": { "type": "string" },
21
+ "impact": { "type": "string", "enum": ["high"] },
22
+ "confidence": { "type": "string", "enum": ["high", "mid", "low"] }
23
+ }
24
+ }
25
+ }
26
+ }
@@ -0,0 +1,35 @@
1
+ ---
2
+ name: loopwright-build
3
+ description: Use when a loopwright task is ready to implement, after Plan (small tier) or Test (standard and large), or when Review sends blocking findings back for a fix round.
4
+ ---
5
+ # loopwright build
6
+
7
+ The implementer subagent writes the code. This thread dispatches it and hands the result to Review; do not edit code here.
8
+
9
+ ## Setup
10
+
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.
14
+ 4. Read the task file header (`tier`, `checks`).
15
+ - Header not `plan: confirmed` → stop; the plan is not confirmed yet, point the user to `/loopwright-plan`.
16
+ - `standard` or `large` with no `lockedTests` (or, large, the current slice is still `[todo]`) → run `/loopwright-test` first.
17
+ - `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.
18
+
19
+ ## Steps
20
+
21
+ 1. `node "{{LW_HOME}}/hooks/lw.mjs" stage build`, and set `stage: build` in the task file header.
22
+ 2. Now spawn the `loopwright-implementer` subagent and wait for its result. The prompt contains only:
23
+ - the absolute task file path (`<lw>/<task>`);
24
+ - large tier: "Implement slice S<n> only.";
25
+ - small tier (no locked tests): "This task has no locked acceptance tests. Write tests covering each acceptance criterion (AC…) as part of your change.";
26
+ - fix round: the findings to fix, verbatim from Review (location, expectation, proof).
27
+ Never paste chat history, your own summary of the decisions, or design ideas; the task file is the source.
28
+ 3. Keep the implementer report verbatim in this conversation; a two-pass review needs it.
29
+ 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) or wants it fixed (spawn the `loopwright-implementer` subagent and wait for its result again, with the deviation as the finding).
30
+ 5. Go straight to `/loopwright-review`. The stop gate blocks ending the turn in Build without a passing review.
31
+
32
+ ## Rules
33
+
34
+ - Never edit locked tests or ask the implementer to. A locked test that looks wrong goes to the user.
35
+ - Do not run `lw.mjs verdict` here; only Review records verdicts.
@@ -0,0 +1,40 @@
1
+ ---
2
+ name: loopwright-done
3
+ description: Use after a loopwright task passes review, to propose AGENTS.md knowledge updates, draft the commit message and PR description, and close the task without committing.
4
+ ---
5
+ # loopwright done
6
+
7
+ Done runs in this main thread; do not spawn the subagents here. You propose; the user approves each change. You do not commit.
8
+
9
+ ## Setup
10
+
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`).
13
+ 3. `node "{{LW_HOME}}/hooks/lw.mjs" status` → `task`, `verdict`. Then `node "{{LW_HOME}}/hooks/lw.mjs" fingerprint`.
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.
16
+
17
+ ## 1. Knowledge (AGENTS.md)
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.
20
+ - Write concepts, not file paths; one line per entry.
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
+ - Prune: AGENTS.md or docs entries this task showed to be stale or wrong → propose an edit or removal.
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.
25
+
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
+
28
+ ## 2. Commit message and PR description
29
+
30
+ Draft both and show them to the user:
31
+ - Commit: imperative subject ≤ 72 chars; body says why, the key decisions, and the rejected options with the reason.
32
+ - PR: summary of intent; decisions and rejected options (`D…`); 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.
33
+
34
+ ## 3. Close
35
+
36
+ 1. Set `status: done` in the task file header.
37
+ 2. `node "{{LW_HOME}}/hooks/lw.mjs" done` (removes this worktree's machine state; the task file stays).
38
+ 3. Tell the user the work is ready to commit, including any approved AGENTS.md/docs changes.
39
+
40
+ Do not commit, push, or create the PR. Never delete the task file.
@@ -0,0 +1,40 @@
1
+ ---
2
+ name: loopwright-flow
3
+ description: Use to run or resume the whole loopwright loop (Plan, Test, Build, Review, Done) for a task, stopping at every point where the user must decide.
4
+ ---
5
+ # loopwright flow
6
+
7
+ Runs the stage skills in order for the confirmed tier and resumes where a task left off. Each stage's own SKILL.md is the authority for that stage.
8
+
9
+ ## Setup
10
+
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. Not a git repo → tell the user loopwright must run inside a git repo, stop.
13
+ 3. Hooks check: `grep -l "loopwright/hooks/" .claude/settings.json .codex/config.toml ~/.claude/settings.json ~/.codex/config.toml 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. In Codex, hooks also need approval via `/hooks`.
14
+
15
+ ## Resume
16
+
17
+ `node "{{LW_HOME}}/hooks/lw.mjs" status`:
18
+ - 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
+ - "no active task" → `grep -l "^status: active" <lw>/tasks/*.md`.
20
+ - 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.
21
+ - None, or the user wants a new task → start at Plan with the user's goal or spec path.
22
+
23
+ ## Run
24
+
25
+ Follow each stage skill in turn (Claude Code `/loopwright-<stage>`, Codex `$loopwright-<stage>`):
26
+ - small: `loopwright-plan` → `loopwright-build` → `loopwright-review` → `loopwright-done`
27
+ - standard: `loopwright-plan` → `loopwright-test` → `loopwright-build` → `loopwright-review` → `loopwright-done`
28
+ - large: `loopwright-plan` → for each slice in order: `loopwright-test` → `loopwright-build` → `loopwright-review` → then one whole-branch `loopwright-review` → `loopwright-done`
29
+ - A failed review returns to `loopwright-build` and then `loopwright-review`, up to the task's fix-round cap.
30
+
31
+ When a stage says to spawn the `loopwright-<role>` subagent, spawn the subagent and wait for its result; never do its work in this thread. After each stage, tell the user one line: what finished and what runs next.
32
+
33
+ ## Gates: stop and wait for the user
34
+
35
+ - each high-impact question, the low-impact batch, the tier/settings proposal, and the final plan confirmation;
36
+ - tester `Uncovered`/`Needs` items and implementer `Deviations`;
37
+ - each undecided review finding, and the fix-round cap being reached;
38
+ - each AGENTS.md / docs change, and the commit message and PR draft.
39
+
40
+ In Build and Review, run `node "{{LW_HOME}}/hooks/lw.mjs" await-user "<reason>"` before asking and `resume` after the answer, as those skills say; otherwise the stop gate pushes you past the gate. Never answer a gate yourself or treat silence as approval. Do not commit at any point.
@@ -0,0 +1,106 @@
1
+ ---
2
+ name: loopwright-plan
3
+ description: Use to start a loopwright task from a goal or an imported spec. Scouts the repo, builds an assumption ledger, asks the user about high-impact assumptions one at a time, confirms tier and checks, then writes the task file. Nothing is built in this stage.
4
+ ---
5
+ # loopwright plan
6
+
7
+ Plan runs in this main thread. You state assumptions; the user decides. Do not edit code in this stage, and nothing is built until the user confirms the plan.
8
+
9
+ ## Setup
10
+
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` 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>`:
14
+ - `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).
15
+ - past `plan` → the task is in progress; tell the user to continue it with `/loopwright-flow`. Do not start a second.
16
+ 4. Read `<lw>/config.json` for `maxFixRounds` (missing file or key → 3).
17
+ 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.
18
+
19
+ ## 1. Input
20
+
21
+ - A goal in the user's words, or a path to an imported spec/plan (e.g. from superpowers).
22
+ - 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.
23
+
24
+ ## 2. Scout
25
+
26
+ Before writing any assumption, spawn the `loopwright-scout` subagent and wait for its result. Give it only the goal text or the spec path.
27
+ 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.
28
+
29
+ ## 3. Assumption ledger
30
+
31
+ List every assumption you would otherwise make silently, one line each: `A<n> [high|low] <assumption> — <evidence: scout path:line, or "none">`.
32
+ - **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.
33
+ - **low-impact**: everything else (internal naming, file placement following an existing pattern, minor edge-case choices).
34
+ - 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.
35
+
36
+ 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.
37
+
38
+ ## 4. High-impact questions, one at a time
39
+
40
+ For each high-impact item, most impactful first: ask ONE question, wait for the answer, write it to the task file immediately, then ask the next.
41
+ - Claude Code: use `AskUserQuestion` with 2–4 options, your recommendation first and marked "(recommended)".
42
+ - Codex: numbered plain-text options, recommendation first. The first time, add: "Tip: `/plan` mode offers structured prompts."
43
+ Record the answer as `D<n> [asked] <decision> — rejected: <option, why>`. An answer that raises a new high-impact question goes into the ledger and is asked the same way.
44
+
45
+ ## 5. Low-impact batch
46
+
47
+ Send all low-impact items in ONE numbered message: "Reply ok, or override by number." Do not ask them one by one.
48
+ Write the result immediately: accepted → `[batch-confirmed]`, changed by the user → `[overridden]` with the user's version. Choices about what to build go under Decisions; facts about the repo or environment go under Assumptions.
49
+
50
+ ## 6. Proposal
51
+
52
+ In one message, propose and explain each in one line:
53
+ - **tier**: `small` (one area, few files, low risk; no acceptance-test stage, the implementer writes tests for every AC), `standard` (default; tests first, then build), `large` (several separable parts; split into ordered slices, each run Test → Build → Review, then one whole-branch review).
54
+ - **two-pass** review on/off: on when the implementer's claims matter beyond what tests show (performance, migrations, concurrency, external APIs); otherwise off.
55
+ - **fix-round cap**: default `maxFixRounds` from config; may be lower for small tasks.
56
+ - **check commands**: exact lint / typecheck / test commands from the scout report.
57
+ - **acceptance criteria** `AC<n>`: observable behavior, each with the module path and export the test will use (the tester stops without one), and the planned test file. Large tier: slices `S<n>` with their ACs.
58
+ The user confirms or edits each item; write the outcome to the header and sections immediately.
59
+
60
+ ## 7. Confirm
61
+
62
+ 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.
63
+ On explicit confirmation, set the header line to `plan: confirmed` (Test and Build refuse to run without it). Then, 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) or `/loopwright-build` (small); under `/loopwright-flow`, return to the flow.
64
+
65
+ ## Task file
66
+
67
+ Path: `<lw>/tasks/<YYYY-MM-DD>-<readable-title>.md` — today's date and a short title from the goal. Keep meaningful casing (`2026-11-08-add-CLAUDE-to-project.md`); spaces become `-`; replace only filesystem-unsafe characters (`/ \ : * ? " < > |`). If the name exists, append `-2`, `-3`, … before `.md`.
68
+ One line per entry; target ≤ ~150 lines. Template:
69
+
70
+ ```markdown
71
+ # <title>
72
+
73
+ status: active
74
+ stage: plan
75
+ plan: draft
76
+ tier: <small|standard|large>
77
+ two-pass: <on|off>
78
+ fix-round cap: <n>
79
+ checks: `<lint>` · `<typecheck>` · `<test>`
80
+ worktree: <path> (branch <branch>)
81
+ base commit: <sha>
82
+
83
+ ## Goal
84
+ <one paragraph: what and why>
85
+
86
+ ## Decisions
87
+ - D1 [asked] <decision> — rejected: <option, why>
88
+ - D2 [batch-confirmed] <decision>
89
+ - D3 [overridden] <user's version> (was: <your assumption>)
90
+
91
+ ## Assumptions
92
+ - A1 [confirmed] <fact about repo or environment> — <evidence>
93
+
94
+ ## Acceptance criteria
95
+ - AC1 <observable behavior> — interface: <module path, export> — test: <file>
96
+
97
+ ## Slices
98
+ - S1 [todo] <slice> — AC1, AC2
99
+
100
+ ## Review log
101
+
102
+ ## Open questions
103
+ - <question> — <who answers, when>
104
+ ```
105
+
106
+ Omit `## Slices` unless the tier is large. Keep `## Goal` and the `- D<n>` line shape: the context-reinjection hook reads them.