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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Xuan Son Trinh
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,174 @@
1
+ # loopwright
2
+
3
+ A Plan → Test → Build → Review → Done workflow for AI coding agents, installed into your repo as skills, subagents and hooks.
4
+
5
+ Agents tend to bake silent assumptions into a plan, write tests to fit their own code, grade their own work, and forget agreed decisions after compaction. loopwright counters this with an **assumption ledger** (every assumption is stated; high-impact ones are asked one at a time), **isolated contexts** (a tester that never sees the implementation, a reviewer that starts blind), **enforced gates** (hooks block edits to locked tests and block finishing without a passing review), and **no document sprawl** (one short task file per task, kept locally; durable lessons go to your existing `AGENTS.md` only with your approval).
6
+
7
+ ## Support
8
+
9
+ | Feature | Claude Code | Codex |
10
+ |---|---|---|
11
+ | Skills install | Supported, tested | WIP: installed, not tested end-to-end |
12
+ | Subagents (scout, tester, implementer, reviewer) | Supported, tested | WIP: installed, not tested end-to-end |
13
+ | Hook enforcement (locked-test guard, stop gate, context reinjection) | Supported, tested | WIP: installed, not tested end-to-end |
14
+ | Structured questions | `AskUserQuestion` | Plain-text fallback (numbered options) |
15
+ | Cross-model review (as the reviewer) | Supported, tested | WIP: untested |
16
+ | Global install | Supported, tested | WIP: installed, not tested end-to-end |
17
+
18
+ **Codex support is work in progress.** Its behavior was derived from Codex source and CLI help; no real Codex session has been run against loopwright yet. Expect rough edges.
19
+
20
+ ## Install
21
+
22
+ ```bash
23
+ npx loopwright init # into the current git repo (commit the result to share it)
24
+ npx loopwright init --global # into your user directories instead
25
+ npx loopwright update # refresh installed files to this version
26
+ npx loopwright uninstall # remove installed files
27
+ ```
28
+
29
+ Requires Node >= 22.14. Repo mode needs a git repository; `--global` does not.
30
+
31
+ | Flag | Effect |
32
+ |---|---|
33
+ | `--global` | Install into your home directory instead of the repo. Shows the planned changes and asks before touching user config. |
34
+ | `--no-hook` | Skip hook wiring. Skills still work but nothing is enforced. |
35
+ | `--no-symlink` | Do not create the `.claude/skills` symlink. |
36
+ | `--dry-run` | Show what would change without writing. |
37
+ | `--force` | Overwrite conflicts and skip confirmation prompts. |
38
+ | `-v`, `--version` / `-h`, `--help` | Print version / help. |
39
+
40
+ ### What gets written
41
+
42
+ Repo install:
43
+
44
+ - `.agents/skills/loopwright-{flow,plan,test,build,review,done}/SKILL.md`, and `.claude/skills` as a symlink to `../.agents/skills` (existing directories or other symlinks are prompted about unless `--force`)
45
+ - `.claude/agents/loopwright-<role>.md` and `.codex/agents/loopwright-<role>.toml` for `scout`, `tester`, `implementer`, `reviewer`
46
+ - `.agents/loopwright/` with `hooks/`, `prompts/reviewer.md`, `schemas/verdict.json`
47
+ - hook wiring (unless `--no-hook`): entries in `.claude/settings.json`, and a `# BEGIN loopwright` ... `# END loopwright` block in `.codex/config.toml`
48
+ - `.loopwright/` (in the main worktree) with its own `.gitignore` (`*`), `config.json`, `manifest.json`, `tasks/`, `state/`
49
+
50
+ In a repo without `.loopwright/` (a global install, or a fresh clone, since `.loopwright/` ignores itself), the first task start creates it: `.gitignore`, `tasks/`, `state/` and a `config.json` seeded from `~/.config/loopwright/config.json` if that exists, else the defaults.
51
+
52
+ Global install writes the equivalents to `~/.agents/skills`, `~/.claude/skills` (copies, not a symlink), `~/.claude/agents`, `~/.codex/agents`, `~/.claude/settings.json`, `~/.codex/config.toml`, and `~/.config/loopwright/` (hooks, prompts, schemas, `manifest.json`). It does not create `~/.config/loopwright/config.json`; that file is optional (see Configuration).
53
+
54
+ ## The loop
55
+
56
+ 1. **Plan** (main thread): a read-only scout investigates the repo; you get an assumption ledger. High-impact assumptions are asked one at a time, low-impact ones in a single batch to skim and override. The agent proposes tier, two-pass review, fix-round cap and check commands (lint/typecheck/test), and you confirm. Each answer is written to the task file immediately. You can import an existing spec or plan as input.
57
+ 2. **Test**: a tester subagent writes acceptance tests from the confirmed criteria, confirms they fail for the right reason, and locks them by file hash. It sees no implementation.
58
+ 3. **Build**: an implementer subagent makes the locked tests pass and adds its own unit tests. Comments explain why, briefly, never what.
59
+ 4. **Review**: a reviewer subagent runs the checks, re-hashes the locked tests (a mismatch fails the review), and does a blind pass over the diff against your decisions, criteria, standards and codebase patterns. Only proven, high-impact findings are reported: confirmed ones block; unconfirmed but evidenced ones go to you as *undecided*; the rest are dropped (count logged). The verdict is bound to a fingerprint of the working tree, so any later change makes it stale. Optional second pass checks the implementer's claims.
60
+ 5. **Done** (main thread): proposes `AGENTS.md` / `docs/agents/` additions and prunes (each approved individually), and drafts a commit/PR message with the decisions and rejected options. It does not commit.
61
+
62
+ Tiers:
63
+
64
+ - **small**: Plan, Build, Review (blind pass only by default).
65
+ - **standard**: Plan, Test, Build, Review.
66
+ - **large**: Plan splits work into slices; each slice runs Test, Build, Review; then one whole-branch review.
67
+
68
+ A failed review returns to Build for up to the fix-round cap (default 3), then stops and hands the open findings to you.
69
+
70
+ ## Commands
71
+
72
+ | Claude Code | Codex | Does |
73
+ |---|---|---|
74
+ | `/loopwright-flow` | `$loopwright-flow` | Run or resume the whole loop, stopping wherever you must decide |
75
+ | `/loopwright-plan` | `$loopwright-plan` | Plan stage |
76
+ | `/loopwright-test` | `$loopwright-test` | Test stage |
77
+ | `/loopwright-build` | `$loopwright-build` | Build stage |
78
+ | `/loopwright-review` | `$loopwright-review` | Review stage |
79
+ | `/loopwright-done` | `$loopwright-done` | Done stage |
80
+
81
+ Task files live in `.loopwright/tasks/<date>-<title>.md`: goal, decisions (tagged asked / batch-confirmed / overridden), assumptions, acceptance criteria, review log, open questions.
82
+
83
+ ## Configuration
84
+
85
+ `.loopwright/config.json` is created with these defaults (by `init`, or by the first task start) and never overwritten. `init`/`update` render the model settings into the generated agent files, so re-run `update` after editing.
86
+
87
+ Global installs read `~/.config/loopwright/config.json` if you create it (it is optional and not written by `init --global`): its model settings go into the global agent files, and it seeds the `config.json` of each repo's new `.loopwright/`.
88
+
89
+ ```json
90
+ {
91
+ "maxFixRounds": 3,
92
+ "crossModelReview": "off",
93
+ "docsDir": "docs/agents",
94
+ "models": {
95
+ "claude": { "scout": "opus", "tester": "sonnet", "implementer": "sonnet", "reviewer": "opus" },
96
+ "codex": { "scout": "inherit", "tester": "inherit", "implementer": "inherit", "reviewer": "inherit" },
97
+ "crossModelReviewer": { "claude": "opus", "codex": "inherit" }
98
+ }
99
+ }
100
+ ```
101
+
102
+ - `maxFixRounds`: default fix-round cap; Plan may propose a lower one per task.
103
+ - `crossModelReview`: `"off"`, `"codex"` or `"claude"`. When set, the review also runs the same reviewer prompt headlessly through the other CLI (`codex exec` or `claude -p`) and both verdicts must pass. A missing or failing CLI is skipped with a note in the review log; it never blocks.
104
+ - `docsDir`: where Done puts longer standards docs linked from `AGENTS.md`.
105
+ - `models`: per tool and role; tool-native aliases or full IDs, or `inherit` (the session model). Codex also accepts `models.codex.effort.<role>`. Editing generated agent files directly counts as a user modification and is kept on update.
106
+ - Plan runs in your main thread, so it uses your session's model. Start the session on the model you want for planning.
107
+
108
+ ## Enforcement and its limits
109
+
110
+ Three hooks (plain Node scripts, no dependencies) are wired by default:
111
+
112
+ - **Locked-test guard** (PreToolUse): during Build, blocks edit tools on locked test files.
113
+ - **Stop gate** (Stop): in Build or Review, blocks finishing unless a passing verdict matches the current working-tree fingerprint. It blocks at most 3 times per stage, then lets the stop through with a warning, so it cannot deadlock a session. It stands down while the agent is waiting for your decision.
114
+ - **Context reinjection** (SessionStart after compaction): re-prints goal, stage, decisions and next step from the task file.
115
+
116
+ Limits, stated plainly:
117
+
118
+ - Shell edits (`sed -i`, redirects) are not intercepted. The review re-hashes locked tests and fails on any mismatch; that is the real backstop.
119
+ - State fields such as `awaitingUser` and the history log are tamper-evident, not tamper-proof. A determined agent can write them; the aim is to catch drift, not adversaries.
120
+ - Hooks fail open: if a hook crashes or state is unreadable it warns and allows, so a loopwright bug never bricks your session. Review checks remain authoritative.
121
+ - With `--no-hook`, none of this is enforced.
122
+ - Setting `LOOPWRIGHT_HOOKS=off` in a session's environment turns every loopwright hook into a silent no-op. The cross-model review sets it on the headless `claude -p` / `codex exec` reviewer so that session is not gated.
123
+
124
+ ### Codex trust step (WIP)
125
+
126
+ Codex requires you to trust the project and approve hooks. After `init`, open Codex in the repo and approve the loopwright hooks via `/hooks`. Until approved, hooks do not run. This path is untested end-to-end.
127
+
128
+ ## Worktrees
129
+
130
+ All worktrees of a repo share one `.loopwright/` in the main worktree (found via `git rev-parse --git-common-dir`); machine state is kept per worktree under `.loopwright/state/`. Task files therefore survive removing a linked worktree. Note that `git worktree remove` refuses to remove a worktree that contains untracked, non-ignored files; `.loopwright/` ignores itself so it does not trigger that, but your own stray files can.
131
+
132
+ ## Update and uninstall
133
+
134
+ - `update` re-applies the current version using the manifest. A file you edited is kept (with a warning), not overwritten. It reuses the `--no-hook`/`--no-symlink` choices recorded at `init` unless you pass them again. Files a newer version no longer ships stay tracked in the manifest (not deleted), so `uninstall` still removes them.
135
+ - `uninstall` removes only manifest files whose content still matches what was installed, plus loopwright's own hook entries and Codex block (from the manifest's records and always from the target's `.claude/settings.json` and `.codex/config.toml`). Modified files are kept. `.claude/settings.json` and `.codex/config.toml` are never deleted, only cleaned of loopwright entries. `.loopwright/tasks/` and config are never touched.
136
+ - Both accept `--global`, `--dry-run` and `--force` (`--force` skips confirmation prompts; for `update` it also overwrites files you edited).
137
+
138
+ ## What loopwright never touches
139
+
140
+ - `AGENTS.md` and `CLAUDE.md`: `init` never edits them. The Done stage may propose edits, applied only with your approval (if `CLAUDE.md` lacks `@AGENTS.md` it proposes the import rather than duplicating content).
141
+ - Your `.gitignore`: `.loopwright/` ignores itself.
142
+ - Your commits: the agent drafts messages but does not commit.
143
+ - Anything under `.loopwright/tasks/` on update or uninstall.
144
+
145
+ ## Releasing (maintainers)
146
+
147
+ `main` only accepts pull requests, so **a release is a merged PR that bumps the `version` in `package.json`**. On every push to `main`, `.github/workflows/publish.yml` checks whether that version is already released; if not, it:
148
+
149
+ 1. Runs `npm ci`, the typecheck, and the tests.
150
+ 2. Publishes to npm with trusted publishing (OIDC; no npm token in the repo). A version already on npm is not re-published.
151
+ 3. Creates the `vX.Y.Z` tag on the merge commit and a GitHub release with generated notes.
152
+
153
+ Pushes that don't change the version (and the `0.0.0` placeholder) release nothing. A failed run leaves no tag; fix the cause, then re-run it from the Actions tab ("Run workflow" on `main`).
154
+
155
+ **To release a new version:**
156
+
157
+ ```bash
158
+ git switch main && git pull
159
+ git switch -c release-x.y.z
160
+ npm version patch --no-git-tag-version # or minor / major; edits package.json + package-lock.json only
161
+ git commit -am "release x.y.z"
162
+ git push -u origin HEAD
163
+ gh pr create --fill # merge it once CI is green
164
+ ```
165
+
166
+ **One-time setup** (needed once, for the first release):
167
+
168
+ 1. Trusted publishing can only be configured for a package that already exists, so the first version is published by hand from the bump branch before merging: `npm login`, then `npm publish --access public` (`prepublishOnly` builds `dist/` first). Merging the PR then sees the version on npm and only creates the tag and release.
169
+ 2. On npmjs.com → `loopwright` → Settings → Trusted publishing, add GitHub Actions with repository `xuansontrinh/loopwright` and workflow `publish.yml`.
170
+ 3. A trusted-publisher config that has not completed a publish expires after 48 hours, so add it when you are about to merge the next version bump. After CI has published once, disallow token-based publishing in the package settings.
171
+
172
+ ## License
173
+
174
+ MIT
File without changes
@@ -0,0 +1,41 @@
1
+ ---
2
+ name: loopwright-implementer
3
+ description: Implements a task by making its locked acceptance tests pass without editing them, adding its own unit tests and following the repo standards.
4
+ tools: Read, Grep, Glob, Edit, Write, MultiEdit, Bash
5
+ ---
6
+ You are the loopwright implementer. You make the smallest change that satisfies the task's decisions and acceptance criteria, in the style of the surrounding code.
7
+
8
+ ## Input
9
+
10
+ The main thread gives you the task file path, and on a fix round the reviewer's Blocking findings. Read the task file fresh every time: goal, decisions (`D…`), acceptance criteria (`AC…`), check commands, locked tests. The task file wins over any summary in your prompt.
11
+
12
+ ## Boundaries
13
+
14
+ - Do not edit, move, delete or reformat locked test files (`node "{{LW_HOME}}/hooks/lw.mjs" status` lists them under `lockedTests`). Do not change test config to skip or weaken them. Review re-hashes them; any change fails the review.
15
+ - Stay in scope: implement what the decisions and ACs require. No unrelated refactors, renames or cleanups.
16
+ - Do not commit, push, or change git state other than the working tree.
17
+ - You cannot ask the user questions. If a decision is contradictory, a locked test looks wrong, or the task cannot be done as decided, stop and report it under "Deviations"; do not work around it silently.
18
+
19
+ ## Standards
20
+
21
+ - Follow `AGENTS.md` and the `docs/agents/` docs it links, and the patterns of nearby code (error handling, naming, layout, test style).
22
+ - Prefer the simplest code path that does the job. Reuse existing helpers before adding new ones.
23
+ - Comments explain why, briefly. State each rationale in exactly one place. Never restate what the code does.
24
+
25
+ ## Steps
26
+
27
+ 1. Read the locked tests and the code they exercise.
28
+ 2. 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.
29
+ 3. 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.
30
+ 4. On a fix round, address each Blocking finding; if you disagree with one, say why with proof instead of changing code.
31
+
32
+ ## Report
33
+
34
+ Return plain text, short:
35
+
36
+ ```
37
+ Changes: path — what and why, one line each
38
+ Tests added: path — what they cover
39
+ Checks run: command — result (pass/fail, counts)
40
+ Deviations: from decisions, ACs or standards, with reason; "none" if none
41
+ ```
@@ -0,0 +1,15 @@
1
+ ---
2
+ name: loopwright-reviewer
3
+ description: Reviews a change against its task file, standards and locked tests, and returns a JSON verdict with only proven high-impact findings. Never edits code.
4
+ tools: Read, Grep, Glob, Bash
5
+ ---
6
+ You are the loopwright reviewer, a context separate from the one that wrote the code.
7
+
8
+ Read `{{LW_HOME}}/prompts/reviewer.md` and follow it exactly. It defines your inputs, the procedure, the findings rules and the output format.
9
+
10
+ Boundaries, which hold even where your tools would allow more:
11
+ - Do not modify any file. Bash is for reading, running tests and check commands, and the read-only `lw.mjs` commands named in the procedure.
12
+ - In the blind pass, do not read or ask for the implementer's report. Run the second pass only when the caller supplies that report.
13
+ - You cannot ask the user questions. Anything you cannot confirm but can back with proof goes in `undecided`.
14
+
15
+ Your final message is the JSON verdict object and nothing else.
@@ -0,0 +1,36 @@
1
+ ---
2
+ name: loopwright-scout
3
+ description: Read-only codebase scout for the Plan stage. Maps the files, conventions, check commands and risks relevant to a goal, before any decision is made.
4
+ tools: Read, Grep, Glob
5
+ ---
6
+ You are the loopwright scout. The main thread gives you a goal (or an imported spec). You investigate the repository and report facts, so the planner can write an assumption ledger from evidence instead of guesses.
7
+
8
+ ## Boundaries
9
+
10
+ - Do not modify any file. Do not run commands that change state.
11
+ - Report facts, not plans. Do not recommend scope, tier, design or task splits; the user decides those in Plan.
12
+ - You cannot ask the user questions. When something cannot be determined from the repo, list it under "Unknowns" instead of guessing.
13
+
14
+ ## Investigate
15
+
16
+ 1. Read `AGENTS.md`, `CLAUDE.md` and any `docs/agents/` docs they link. Note the rules that apply to this goal.
17
+ 2. Find the code the goal touches: entry points, the modules involved, their callers, existing tests for them.
18
+ 3. Find how the repo checks itself: test runner and how a single test file runs, lint, format, typecheck. Take commands from the manifest scripts, CI config or docs; do not invent them.
19
+ 4. Note conventions a change here must follow: error handling, naming, module layout, test style, comment style. Cite one example `path:line` per convention.
20
+ 5. Note risks: shared code with many callers, public API or file formats, migrations, generated files, platform-specific code, missing tests.
21
+
22
+ Stop when you can fill the report. Do not read the whole repo.
23
+
24
+ ## Report
25
+
26
+ Return plain text, at most ~60 lines, one line per item, each with `path` or `path:line`:
27
+
28
+ ```
29
+ Relevant files: path — role in the goal
30
+ Standards: rule — source path
31
+ Conventions: convention — example path:line
32
+ Checks: test (all) / test (one file) / lint / format / typecheck — exact command, or "none found"
33
+ Tests: runner, location and style of existing tests near the goal
34
+ Risks: risk — evidence path:line
35
+ Unknowns: question the repo cannot answer
36
+ ```
@@ -0,0 +1,39 @@
1
+ ---
2
+ name: loopwright-tester
3
+ description: Writes the acceptance tests for a task from its acceptance criteria before any implementation exists, confirms each fails for the right reason, then locks them.
4
+ tools: Read, Grep, Glob, Edit, Write, Bash
5
+ ---
6
+ You are the loopwright tester. You turn the task's acceptance criteria into tests that fail now and will pass only when the behavior exists. A separate implementer will make them pass without being allowed to change them, so the tests are the contract.
7
+
8
+ ## Input
9
+
10
+ The main thread gives you the task file path. Read its acceptance criteria (`AC…`), decisions (`D…`) and check commands. Do not rely on any other summary of them.
11
+
12
+ ## Boundaries
13
+
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
+ - Write only test files (and fixtures they need). Do not create or edit implementation code, not even stubs.
16
+ - Use the repo's existing test runner, file layout and test style. Do not add a test framework or dependency.
17
+ - You cannot ask the user questions. If an AC is ambiguous, untestable, or needs a runner that does not exist, stop and report what you need; do not guess.
18
+
19
+ ## Steps
20
+
21
+ 1. For each AC, write one or more tests named so the AC id is visible (e.g. `AC2: empty input returns []`). Test observable behavior through the public interface, not implementation details.
22
+ 2. Run the new tests with the task's test command, targeting only your files.
23
+ 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.
24
+ 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.
25
+ 4. When every test fails for the right reason, lock them:
26
+ `node "{{LW_HOME}}/hooks/lw.mjs" lock <test-file> [<test-file>…]`
27
+ Lock every acceptance test file and fixture you wrote. Locking only works in stage `test`; if it errors, report the error.
28
+
29
+ ## Report
30
+
31
+ Return plain text, short:
32
+
33
+ ```
34
+ Tests: path — ACs covered
35
+ Locked: output of the lock command (paths)
36
+ Run: command and a failure excerpt per AC (or one per file when the module is absent) showing the expected reason
37
+ Uncovered: AC id — why it has no test
38
+ Needs: anything that blocked you
39
+ ```
@@ -0,0 +1,23 @@
1
+ {
2
+ "maxFixRounds": 3,
3
+ "crossModelReview": "off",
4
+ "docsDir": "docs/agents",
5
+ "models": {
6
+ "claude": {
7
+ "scout": "opus",
8
+ "tester": "sonnet",
9
+ "implementer": "sonnet",
10
+ "reviewer": "opus"
11
+ },
12
+ "codex": {
13
+ "scout": "inherit",
14
+ "tester": "inherit",
15
+ "implementer": "inherit",
16
+ "reviewer": "inherit"
17
+ },
18
+ "crossModelReviewer": {
19
+ "claude": "opus",
20
+ "codex": "inherit"
21
+ }
22
+ }
23
+ }
@@ -0,0 +1,35 @@
1
+ #!/usr/bin/env node
2
+ // PreToolUse guard: block edits to locked acceptance tests during the build stage.
3
+ import { allow, exitIfHooksOff, deny, failOpen, loopwrightDir, readState, readStdinJson, repoRelative, worktreeId } from './lib.mjs';
4
+
5
+ function patchPaths(command) {
6
+ const out = [];
7
+ for (const line of String(command ?? '').split('\n')) {
8
+ for (const prefix of ['*** Add File: ', '*** Update File: ', '*** Delete File: ', '*** Move to: ']) {
9
+ if (line.startsWith(prefix)) out.push(line.slice(prefix.length).trim());
10
+ }
11
+ }
12
+ return out;
13
+ }
14
+
15
+ exitIfHooksOff();
16
+
17
+ try {
18
+ const input = await readStdinJson();
19
+ const cwd = input.cwd || process.cwd();
20
+ const dir = loopwrightDir(cwd);
21
+ if (!dir) allow();
22
+ const state = readState(dir, worktreeId(cwd));
23
+ if (!state || state.stage !== 'build' || !Array.isArray(state.lockedTests) || state.lockedTests.length === 0) allow();
24
+
25
+ const ti = input.tool_input ?? {};
26
+ const raw = input.tool_name === 'apply_patch' ? patchPaths(ti.command) : ti.file_path ? [ti.file_path] : [];
27
+ const locked = new Set(state.lockedTests.map((l) => l.path));
28
+ for (const p of raw) {
29
+ const rel = repoRelative(cwd, p);
30
+ if (locked.has(rel)) deny('', '', `loopwright: ${rel} is a locked acceptance test. Ask the user before changing it.`);
31
+ }
32
+ allow();
33
+ } catch (err) {
34
+ failOpen(err);
35
+ }
@@ -0,0 +1,147 @@
1
+ // Loopwright hook runtime library. Only node:* imports.
2
+ import { execFileSync } from 'node:child_process';
3
+ import { createHash } from 'node:crypto';
4
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readlinkSync, realpathSync, renameSync, writeFileSync } from 'node:fs';
5
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
6
+
7
+ const MAX_BUFFER = 1024 * 1024 * 1024;
8
+
9
+ function git(cwd, args) {
10
+ return execFileSync('git', args, { cwd, stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf8' }).trim();
11
+ }
12
+
13
+ export function gitTopLevel(cwd) {
14
+ return git(cwd, ['rev-parse', '--show-toplevel']);
15
+ }
16
+
17
+ function mainWorktreeRoot(cwd) {
18
+ const common = git(cwd, ['rev-parse', '--path-format=absolute', '--git-common-dir']);
19
+ if (basename(common) === '.git') return dirname(common);
20
+ return gitTopLevel(cwd);
21
+ }
22
+
23
+ /** Main-worktree .loopwright path (whether or not it exists); null outside git. */
24
+ export function loopwrightPath(cwd) {
25
+ try {
26
+ return join(mainWorktreeRoot(cwd), '.loopwright');
27
+ } catch {
28
+ return null;
29
+ }
30
+ }
31
+
32
+ /** Main-worktree .loopwright directory if it exists; null outside git or if absent. */
33
+ export function loopwrightDir(cwd) {
34
+ const dir = loopwrightPath(cwd);
35
+ return dir && existsSync(dir) ? dir : null;
36
+ }
37
+
38
+ export function worktreeId(cwd) {
39
+ return createHash('sha256').update(gitTopLevel(cwd)).digest('hex').slice(0, 12);
40
+ }
41
+
42
+ export function statePath(dir, id) {
43
+ return join(dir, 'state', `${id}.json`);
44
+ }
45
+
46
+ export function readState(dir, id) {
47
+ const path = statePath(dir, id);
48
+ let raw;
49
+ try {
50
+ raw = readFileSync(path, 'utf8');
51
+ } catch {
52
+ return null;
53
+ }
54
+ try {
55
+ return JSON.parse(raw);
56
+ } catch {
57
+ process.stderr.write(`loopwright: ignoring corrupt state file ${path}\n`);
58
+ return null;
59
+ }
60
+ }
61
+
62
+ export function writeState(dir, id, state) {
63
+ const path = statePath(dir, id);
64
+ mkdirSync(dirname(path), { recursive: true });
65
+ const tmp = `${path}.${process.pid}.tmp`;
66
+ writeFileSync(tmp, JSON.stringify(state, null, 2) + '\n');
67
+ renameSync(tmp, path);
68
+ }
69
+
70
+ export function sha256File(path) {
71
+ return createHash('sha256').update(readFileSync(path)).digest('hex');
72
+ }
73
+
74
+ export function fingerprint(cwd, baseCommit) {
75
+ const h = createHash('sha256');
76
+ const top = gitTopLevel(cwd);
77
+ const diffArgs = ['-c', 'core.quotePath=false', 'diff', '--binary', '--no-color', '--no-ext-diff', '--no-textconv', '--no-renames', '--full-index', '--no-relative', '--src-prefix=a/', '--dst-prefix=b/', baseCommit];
78
+ h.update(execFileSync('git', diffArgs, { cwd: top, maxBuffer: MAX_BUFFER, stdio: ['ignore', 'pipe', 'pipe'] }));
79
+ const out = execFileSync('git', ['-c', 'core.quotePath=false', 'ls-files', '--others', '--exclude-standard', '-z'], { cwd: top, maxBuffer: MAX_BUFFER, stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf8' });
80
+ const files = out.split('\0').filter(Boolean).sort();
81
+ for (const f of files) {
82
+ h.update(f + '\0');
83
+ try {
84
+ // Never follow or open anything but a regular file: a FIFO or device would block the hook.
85
+ const p = join(top, f);
86
+ const st = lstatSync(p);
87
+ if (st.isFile()) h.update(readFileSync(p));
88
+ else if (st.isSymbolicLink()) h.update('symlink\0' + readlinkSync(p));
89
+ } catch {
90
+ /* unreadable or vanished: path alone contributes */
91
+ }
92
+ }
93
+ return h.digest('hex');
94
+ }
95
+
96
+ /** Hooks call this first: LOOPWRIGHT_HOOKS=off (e.g. a headless cross-model reviewer) disables them silently. */
97
+ export function exitIfHooksOff() {
98
+ if (process.env.LOOPWRIGHT_HOOKS === 'off') process.exit(0);
99
+ }
100
+
101
+ export async function readStdinJson() {
102
+ const chunks = [];
103
+ for await (const c of process.stdin) chunks.push(c);
104
+ const text = Buffer.concat(chunks).toString('utf8').trim();
105
+ return text ? JSON.parse(text) : {};
106
+ }
107
+
108
+ export function allow() {
109
+ process.exit(0);
110
+ }
111
+
112
+ // Claude and Codex both block via stderr reason + exit 2. The reason must be
113
+ // non-empty: Codex ignores exit 2 with empty stderr.
114
+ export function deny(_tool, _event, reason) {
115
+ const text = String(reason ?? '').trim() || 'loopwright: blocked';
116
+ process.stderr.write(text + '\n');
117
+ process.exit(2);
118
+ }
119
+
120
+ export function failOpen(err) {
121
+ const msg = err instanceof Error ? err.message : String(err);
122
+ process.stderr.write(`loopwright hook error: ${msg}\n`);
123
+ process.exit(0);
124
+ }
125
+
126
+ /** realpath of the nearest existing ancestor, with the not-yet-existing tail re-appended. */
127
+ export function realpathLoose(abs) {
128
+ const tail = [];
129
+ let cur = abs;
130
+ for (;;) {
131
+ try {
132
+ return join(realpathSync(cur), ...tail.reverse());
133
+ } catch {
134
+ const parent = dirname(cur);
135
+ if (parent === cur) return abs;
136
+ tail.push(basename(cur));
137
+ cur = parent;
138
+ }
139
+ }
140
+ }
141
+
142
+ /** Worktree-top-relative POSIX path of p (relative to cwd if not absolute), symlinks resolved. May start with '..' if outside. */
143
+ export function repoRelative(cwd, p) {
144
+ const top = realpathSync(gitTopLevel(cwd));
145
+ const abs = realpathLoose(isAbsolute(p) ? resolve(p) : resolve(cwd, p));
146
+ return relative(top, abs).split(sep).join('/');
147
+ }