loopwright 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,176 +1,110 @@
1
1
  # loopwright
2
2
 
3
- A Plan → Test → Build → Review → Done workflow for AI coding agents, installed into your repo as skills, subagents and hooks.
3
+ Make your AI coding agent plan, test, build and review like a careful team: a **Plan → Test → Build → Review → Done** workflow (Test is skipped for small tasks, and Review loops back to Build until it passes), installed into your repo as skills, subagents and hooks.
4
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).
5
+ ## Why
6
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
7
+ Left alone, coding agents:
55
8
 
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.
9
+ - bake silent assumptions into the plan,
10
+ - write tests that fit their own code,
11
+ - grade their own work,
12
+ - forget agreed decisions after context compaction.
61
13
 
62
- Tiers:
14
+ loopwright counters each of these:
63
15
 
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.
16
+ - **Assumption ledger**: every assumption is stated; high-impact ones are asked one at a time.
17
+ - **Isolated contexts**: the tester never sees the implementation; the reviewer starts blind.
18
+ - **Enforced gates**: hooks block edits to locked tests and block finishing without a passing review.
19
+ - **No document sprawl**: one short task file per task, kept locally. Durable lessons go to your `AGENTS.md` only with your approval.
67
20
 
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.
21
+ ## Quick start
69
22
 
70
- ## Commands
23
+ You need Node >= 22.14 and a git repository.
71
24
 
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
- }
25
+ ```bash
26
+ cd your-repo
27
+ npx loopwright init
100
28
  ```
101
29
 
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:
30
+ Then open Claude Code in the repo and run:
111
31
 
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.
32
+ ```text
33
+ /loopwright-flow add rate limiting to the login endpoint
34
+ ```
123
35
 
124
- ### Codex trust step (WIP)
36
+ The agent scouts your repo, asks you about its high-impact assumptions, and then walks the task through Test, Build, Review and Done, stopping wherever you need to decide. Nothing is committed for you.
125
37
 
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.
38
+ `init` writes skills, subagents, hooks and a local `.loopwright/` folder. Commit the result to share it with your team, or use `npx loopwright init --global` to install into your home directory instead. See [Installation](docs/installation.md) for flags and the exact files written.
127
39
 
128
- ## Worktrees
40
+ ## How it works
129
41
 
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.
42
+ The stages run in order, but the path depends on the task's size (its *tier*) and a failed review loops back to Build.
131
43
 
132
- ## Update and uninstall
44
+ ```mermaid
45
+ flowchart TD
46
+ goal(["Your goal or spec"]) --> plan["Plan<br/>scout the repo, assumption ledger,<br/>you confirm tier, checks and criteria"]
47
+ plan --> tier{"Tier"}
48
+ tier -- "small" --> build
49
+ tier -- "standard" --> test["Test<br/>tester writes and locks acceptance tests"]
50
+ tier -- "large" --> slices["Split into slices<br/>each runs Test, Build, Review,<br/>then one whole-branch review"]
51
+ test --> build["Build<br/>implementer makes the tests pass"]
52
+ build --> review{"Review<br/>separate reviewer: passes?"}
53
+ review -- "blocking findings, rounds left" --> build
54
+ review -- "fix-round cap reached" --> you{{"You decide"}}
55
+ review -- "pass" --> done["Done<br/>AGENTS.md proposals, commit and PR draft"]
56
+ slices -.-> done
57
+ done --> commit(["You commit"])
58
+ ```
133
59
 
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).
60
+ - **Plan** runs in your session. A read-only scout maps the repo, then you answer the high-impact questions one at a time and confirm the plan. Nothing is built before that.
61
+ - **Test** (standard and large): a tester subagent, which never sees the implementation, writes acceptance tests from your confirmed criteria and locks them.
62
+ - **Build**: an implementer subagent makes the locked tests pass. Small tasks skip Test, so the implementer writes the tests.
63
+ - **Review**: a reviewer that starts blind runs your checks, confirms the locked tests are untouched, and reports only proven, high-impact findings. Blocking findings send the task back to Build, up to 3 rounds by default; findings it cannot confirm come to you to fix or dismiss.
64
+ - **Done**: proposes `AGENTS.md` updates and drafts the commit and PR message. You approve each change; loopwright never commits.
137
65
 
138
- ## What loopwright never touches
66
+ Each task's goal, decisions, criteria and review log live in `.loopwright/tasks/<date>-<title>.md`. For the large-tier slice loop, step-by-step Plan and Review charts, and every point where loopwright waits for you, see [Workflow in detail](docs/workflow.md).
139
67
 
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.
68
+ ### Commands
144
69
 
145
- ## Releasing (maintainers)
70
+ Run a single stage, or the whole loop with `flow`. In Codex, use `$` instead of `/`.
146
71
 
147
- `main` only accepts pull requests, so **a release is a merged PR that bumps the `version` in `package.json`**. Releases use npm **staged publishing**: CI can stage a version but cannot make it installable, so every release needs your 2FA approval.
72
+ | Command | Does |
73
+ |---|---|
74
+ | `/loopwright-flow` | Run or resume the whole loop, stopping wherever you must decide |
75
+ | `/loopwright-plan` | Plan stage |
76
+ | `/loopwright-test` | Test stage |
77
+ | `/loopwright-build` | Build stage |
78
+ | `/loopwright-review` | Review stage |
79
+ | `/loopwright-done` | Done stage |
148
80
 
149
- When CI (`ci.yml`) passes for a push to `main`, `.github/workflows/publish.yml` runs for that exact commit. If its version has no GitHub release yet, it:
81
+ ## Support
150
82
 
151
- 1. Builds and runs `npm stage publish` with trusted publishing (OIDC; no npm token in the repo). A version already live on npm is not staged again.
152
- 2. Creates the `vX.Y.Z` tag on that commit and a GitHub release with generated notes.
83
+ | Feature | Claude Code | Codex | Junie CLI |
84
+ |---|---|---|---|
85
+ | Skills install | Supported, tested | WIP: installed, not tested end-to-end | WIP: reads `.agents/skills` |
86
+ | Subagents (scout, tester, implementer, reviewer) | Supported, tested | WIP: installed, not tested end-to-end | WIP: `.junie/agents` |
87
+ | Hook enforcement (locked-test guard, stop gate, context reinjection) | Supported, tested | WIP: installed, not tested end-to-end | Experimental (`--experimental junie-hooks`, Early Access) |
88
+ | Structured questions | `AskUserQuestion` | Plain-text fallback (numbered options) | Plain-text fallback |
89
+ | Cross-agent review (as the reviewer) | Supported, tested | WIP: untested | Not supported |
90
+ | Global install | Supported, tested | WIP: installed, not tested end-to-end | WIP: `~/.junie/agents` |
153
91
 
154
- CI failures, 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`, which first checks that CI passed for `main`'s head).
92
+ Codex and Junie CLI support is work in progress.
155
93
 
156
- **To release a new version:**
94
+ - **Codex**: behavior was derived from Codex source and CLI help; no real Codex session has been run against loopwright yet. Expect rough edges.
95
+ - **Junie CLI**: its hooks are Early Access. Subagents are installed with per-role models from `models.junie` (default: scout `opus`, tester and implementer `sonnet`, reviewer `gpt`, so the review comes from a different vendor than the code). If your Junie plan cannot use a model, the stage skills retry the subagent without a model (Junie's default).
157
96
 
158
- ```bash
159
- git switch main && git pull
160
- git switch -c release-x.y.z
161
- npm version patch --no-git-tag-version # or minor / major; edits package.json + package-lock.json only
162
- git commit -am "release x.y.z"
163
- git push -u origin HEAD
164
- gh pr create --fill # merge it once CI is green
165
- ```
97
+ ## Learn more
166
98
 
167
- Then **approve the staged version**: on npmjs.com → `loopwright` → **Staged Packages** → **Approve** (or `npm stage list loopwright` and `npm stage approve <id>`, npm ≥ 11.15). It becomes installable and `latest` only after approval. Check with `npm view loopwright versions dist-tags`.
99
+ - [Installation](docs/installation.md): flags, files written, update, uninstall, worktrees.
100
+ - [Configuration](docs/configuration.md): models, fix rounds, cross-agent review, effort profiles (`lean`, `balanced`, `thorough`, `deep`; set with `--profile`), experimental features.
101
+ - [Workflow in detail](docs/workflow.md): the full flow with charts: slices, the Plan and Review steps, and where it waits for you.
102
+ - [Enforcement and its limits](docs/enforcement.md): what the hooks block, and what they cannot.
103
+ - [Dogfood checklist](docs/dogfood-checklist.md): a manual end-to-end test run.
168
104
 
169
- **One-time setup:**
105
+ ## Contributing
170
106
 
171
- 1. Trusted publishing can only be configured for a package that already exists, so the first version (0.1.0) is published by hand (`npm publish --access public`; `prepublishOnly` builds `dist/`).
172
- 2. On npmjs.com → `loopwright` → Settings → Trusted publishing → GitHub Actions: repository `xuansontrinh/loopwright`, workflow `publish.yml`, with **Allow `npm publish`** and **Allow `npm dist-tag`** left unchecked (stage-only).
173
- 3. Publishing access: "Require two-factor authentication and disallow tokens".
107
+ See [CLAUDE.md](CLAUDE.md) for the project layout and conventions, [writing documentation guidelines](docs/writing-documentation-guidelines.md) before editing docs, and [Releasing](docs/releasing.md) for maintainers.
174
108
 
175
109
  ## License
176
110
 
@@ -14,6 +14,7 @@ The main thread gives you the task file path, and on a fix round the reviewer's
14
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
15
  - Stay in scope: implement what the decisions and ACs require. No unrelated refactors, renames or cleanups.
16
16
  - Do not commit, push, or change git state other than the working tree.
17
+ - 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.
17
18
  - 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
 
19
20
  ## Standards
@@ -14,11 +14,12 @@ The main thread gives you the task file path. Read its acceptance criteria (`AC
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
  - Write only test files (and fixtures they need). Do not create or edit implementation code, not even stubs.
16
16
  - Use the repo's existing test runner, file layout and test style. Do not add a test framework or dependency.
17
+ - 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.
17
18
  - 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
 
19
20
  ## Steps
20
21
 
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
+ 1. For each AC, write one or more tests. Name each test by the behavior it checks (e.g. `empty input returns []`), not by an id. Test observable behavior through the public interface, not implementation details.
22
23
  2. Run the new tests with the task's test command, targeting only your files.
23
24
  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
25
  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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "maxFixRounds": 3,
3
- "crossModelReview": "off",
3
+ "crossAgentReview": "off",
4
4
  "docsDir": "docs/agents",
5
5
  "models": {
6
6
  "claude": {
@@ -15,7 +15,13 @@
15
15
  "implementer": "inherit",
16
16
  "reviewer": "inherit"
17
17
  },
18
- "crossModelReviewer": {
18
+ "junie": {
19
+ "scout": "opus",
20
+ "tester": "sonnet",
21
+ "implementer": "sonnet",
22
+ "reviewer": "gpt"
23
+ },
24
+ "crossAgentReviewer": {
19
25
  "claude": "opus",
20
26
  "codex": "inherit"
21
27
  }
@@ -1,6 +1,16 @@
1
1
  #!/usr/bin/env node
2
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';
3
+ import {
4
+ allow,
5
+ exitIfHooksOff,
6
+ deny,
7
+ failOpen,
8
+ loopwrightDir,
9
+ readState,
10
+ readStdinJson,
11
+ repoRelative,
12
+ worktreeId,
13
+ } from './lib.mjs';
4
14
 
5
15
  function patchPaths(command) {
6
16
  const out = [];
@@ -16,18 +26,25 @@ exitIfHooksOff();
16
26
 
17
27
  try {
18
28
  const input = await readStdinJson();
19
- const cwd = input.cwd || process.cwd();
29
+ // Junie runs hooks from ~/.junie and reports the repo as project_path.
30
+ const cwd = input.project_path || input.cwd || process.cwd();
20
31
  const dir = loopwrightDir(cwd);
21
32
  if (!dir) allow();
22
33
  const state = readState(dir, worktreeId(cwd));
23
34
  if (!state || state.stage !== 'build' || !Array.isArray(state.lockedTests) || state.lockedTests.length === 0) allow();
24
35
 
25
36
  const ti = input.tool_input ?? {};
26
- const raw = input.tool_name === 'apply_patch' ? patchPaths(ti.command) : ti.file_path ? [ti.file_path] : [];
37
+ const raw =
38
+ input.tool_name === 'apply_patch'
39
+ ? patchPaths(ti.patch ?? ti.command)
40
+ : ti.file_path && input.tool_name !== 'Read' // Junie fires PreToolUse for reads too; only edits are guarded
41
+ ? [ti.file_path]
42
+ : [];
27
43
  const locked = new Set(state.lockedTests.map((l) => l.path));
28
44
  for (const p of raw) {
29
45
  const rel = repoRelative(cwd, p);
30
- if (locked.has(rel)) deny('', '', `loopwright: ${rel} is a locked acceptance test. Ask the user before changing it.`);
46
+ if (locked.has(rel))
47
+ deny('', '', `loopwright: ${rel} is a locked acceptance test. Ask the user before changing it.`);
31
48
  }
32
49
  allow();
33
50
  } catch (err) {
@@ -1,9 +1,26 @@
1
1
  // Loopwright hook runtime library. Only node:* imports.
2
2
  import { execFileSync } from 'node:child_process';
3
3
  import { createHash } from 'node:crypto';
4
- import { existsSync, lstatSync, mkdirSync, readFileSync, readlinkSync, realpathSync, renameSync, writeFileSync } from 'node:fs';
4
+ import {
5
+ existsSync,
6
+ lstatSync,
7
+ mkdirSync,
8
+ readFileSync,
9
+ readlinkSync,
10
+ realpathSync,
11
+ renameSync,
12
+ writeFileSync,
13
+ } from 'node:fs';
5
14
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
6
15
 
16
+ /** Mirror of PROFILES in src/core/profiles.ts (a test pins them equal). */
17
+ export const PROFILES = {
18
+ lean: { scout: 'low', tester: 'low', implementer: 'low', reviewer: 'medium' },
19
+ balanced: { scout: 'medium', tester: 'medium', implementer: 'medium', reviewer: 'high' },
20
+ thorough: { scout: 'high', tester: 'high', implementer: 'high', reviewer: 'xhigh' },
21
+ deep: { scout: 'xhigh', tester: 'xhigh', implementer: 'xhigh', reviewer: 'xhigh' },
22
+ };
23
+
7
24
  const MAX_BUFFER = 1024 * 1024 * 1024;
8
25
 
9
26
  function git(cwd, args) {
@@ -11,12 +28,13 @@ function git(cwd, args) {
11
28
  }
12
29
 
13
30
  export function gitTopLevel(cwd) {
14
- return git(cwd, ['rev-parse', '--show-toplevel']);
31
+ // Git prints forward slashes on Windows; resolve() gives the platform form.
32
+ return resolve(git(cwd, ['rev-parse', '--show-toplevel']));
15
33
  }
16
34
 
17
- function mainWorktreeRoot(cwd) {
35
+ export function mainWorktreeRoot(cwd) {
18
36
  const common = git(cwd, ['rev-parse', '--path-format=absolute', '--git-common-dir']);
19
- if (basename(common) === '.git') return dirname(common);
37
+ if (basename(common) === '.git') return resolve(dirname(common));
20
38
  return gitTopLevel(cwd);
21
39
  }
22
40
 
@@ -64,7 +82,16 @@ export function writeState(dir, id, state) {
64
82
  mkdirSync(dirname(path), { recursive: true });
65
83
  const tmp = `${path}.${process.pid}.tmp`;
66
84
  writeFileSync(tmp, JSON.stringify(state, null, 2) + '\n');
67
- renameSync(tmp, path);
85
+ // Windows: rename fails with EPERM/EBUSY/EACCES while another process briefly holds the target.
86
+ for (let attempt = 0; ; attempt++) {
87
+ try {
88
+ renameSync(tmp, path);
89
+ return;
90
+ } catch (err) {
91
+ if (attempt >= 5 || !['EPERM', 'EBUSY', 'EACCES'].includes(err?.code)) throw err;
92
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20 * (attempt + 1));
93
+ }
94
+ }
68
95
  }
69
96
 
70
97
  export function sha256File(path) {
@@ -74,9 +101,28 @@ export function sha256File(path) {
74
101
  export function fingerprint(cwd, baseCommit) {
75
102
  const h = createHash('sha256');
76
103
  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];
104
+ const diffArgs = [
105
+ '-c',
106
+ 'core.quotePath=false',
107
+ 'diff',
108
+ '--binary',
109
+ '--no-color',
110
+ '--no-ext-diff',
111
+ '--no-textconv',
112
+ '--no-renames',
113
+ '--full-index',
114
+ '--no-relative',
115
+ '--src-prefix=a/',
116
+ '--dst-prefix=b/',
117
+ baseCommit,
118
+ ];
78
119
  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' });
120
+ const out = execFileSync('git', ['-c', 'core.quotePath=false', 'ls-files', '--others', '--exclude-standard', '-z'], {
121
+ cwd: top,
122
+ maxBuffer: MAX_BUFFER,
123
+ stdio: ['ignore', 'pipe', 'pipe'],
124
+ encoding: 'utf8',
125
+ });
80
126
  const files = out.split('\0').filter(Boolean).sort();
81
127
  for (const f of files) {
82
128
  h.update(f + '\0');
@@ -93,7 +139,7 @@ export function fingerprint(cwd, baseCommit) {
93
139
  return h.digest('hex');
94
140
  }
95
141
 
96
- /** Hooks call this first: LOOPWRIGHT_HOOKS=off (e.g. a headless cross-model reviewer) disables them silently. */
142
+ /** Hooks call this first: LOOPWRIGHT_HOOKS=off (e.g. a headless cross-agent reviewer) disables them silently. */
97
143
  export function exitIfHooksOff() {
98
144
  if (process.env.LOOPWRIGHT_HOOKS === 'off') process.exit(0);
99
145
  }
@@ -123,13 +169,22 @@ export function failOpen(err) {
123
169
  process.exit(0);
124
170
  }
125
171
 
172
+ /** Native realpath expands Windows 8.3 short names (RUNNER~1) the way git reports them; JS realpath keeps them. Falls back so a native throw cannot fail the guard open. */
173
+ export function realpathResolve(path, impl = realpathSync.native) {
174
+ try {
175
+ return impl(path);
176
+ } catch {
177
+ return realpathSync(path);
178
+ }
179
+ }
180
+
126
181
  /** realpath of the nearest existing ancestor, with the not-yet-existing tail re-appended. */
127
182
  export function realpathLoose(abs) {
128
183
  const tail = [];
129
184
  let cur = abs;
130
185
  for (;;) {
131
186
  try {
132
- return join(realpathSync(cur), ...tail.reverse());
187
+ return join(realpathResolve(cur), ...tail.reverse());
133
188
  } catch {
134
189
  const parent = dirname(cur);
135
190
  if (parent === cur) return abs;
@@ -140,8 +195,10 @@ export function realpathLoose(abs) {
140
195
  }
141
196
 
142
197
  /** 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));
198
+ export function repoRelative(cwd, p, platform = process.platform) {
199
+ const top = realpathResolve(gitTopLevel(cwd));
145
200
  const abs = realpathLoose(isAbsolute(p) ? resolve(p) : resolve(cwd, p));
146
- return relative(top, abs).split(sep).join('/');
201
+ const rel = relative(top, abs).split(sep).join('/');
202
+ // Windows paths are case-insensitive: fold so Test/T.test.ts matches a locked test/t.test.ts.
203
+ return platform === 'win32' ? rel.toLowerCase() : rel;
147
204
  }
@@ -1,11 +1,23 @@
1
1
  #!/usr/bin/env node
2
2
  // Loopwright state tool. Usage: node lw.mjs <cmd> [args]
3
- import { copyFileSync, existsSync, mkdirSync, unlinkSync, writeFileSync } from 'node:fs';
3
+ import { copyFileSync, existsSync, readFileSync, mkdirSync, unlinkSync, writeFileSync } from 'node:fs';
4
4
  import { homedir } from 'node:os';
5
5
  import { isAbsolute, join, resolve } from 'node:path';
6
6
  import { execFileSync } from 'node:child_process';
7
7
  import { fileURLToPath } from 'node:url';
8
- import { fingerprint, gitTopLevel, loopwrightDir, loopwrightPath, readState, repoRelative, sha256File, statePath, worktreeId, writeState } from './lib.mjs';
8
+ import {
9
+ PROFILES,
10
+ fingerprint,
11
+ gitTopLevel,
12
+ loopwrightDir,
13
+ loopwrightPath,
14
+ readState,
15
+ repoRelative,
16
+ sha256File,
17
+ statePath,
18
+ worktreeId,
19
+ writeState,
20
+ } from './lib.mjs';
9
21
 
10
22
  const STAGES = ['plan', 'test', 'build', 'review', 'done'];
11
23
  const cwd = process.cwd();
@@ -48,7 +60,7 @@ function ctx(create = false) {
48
60
  if (!create) fail('loopwright: no active task (no .loopwright directory yet; lw.mjs start creates it)');
49
61
  scaffold(path);
50
62
  dir = path;
51
- }
63
+ } else if (create) scaffold(dir); // idempotent: seeds a config.json missing from an existing .loopwright/
52
64
  return { dir, id: worktreeId(cwd) };
53
65
  }
54
66
 
@@ -59,6 +71,37 @@ function requireState() {
59
71
  return { dir, id, state };
60
72
  }
61
73
 
74
+ /** Effort for a role: the task header's `profile:`, else the manifest's recorded profile, else balanced. */
75
+ function effortFor(role) {
76
+ if (!Object.hasOwn(PROFILES.balanced, role))
77
+ fail(`loopwright: usage: effort <${Object.keys(PROFILES.balanced).join('|')}>`);
78
+ // Works before `start` (Plan's scout spawn): no task or repo state just means no header.
79
+ let name;
80
+ let dir = null;
81
+ try {
82
+ dir = loopwrightDir(cwd);
83
+ const state = dir && readState(dir, worktreeId(cwd));
84
+ if (state?.task && existsSync(join(dir, state.task))) {
85
+ name = /^profile:\s*(\S+)\s*$/m.exec(readFileSync(join(dir, state.task), 'utf8').split(/^## /m)[0])?.[1];
86
+ }
87
+ } catch {
88
+ // Unreadable task or state: fall through to the manifest profile.
89
+ }
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')]) {
92
+ if (name || !m || !existsSync(m)) continue;
93
+ try {
94
+ name = JSON.parse(readFileSync(m, 'utf8')).options?.profile;
95
+ } catch {
96
+ // Unreadable manifest: try the next one.
97
+ }
98
+ }
99
+ name ??= 'balanced';
100
+ if (!Object.hasOwn(PROFILES, name))
101
+ fail(`loopwright: unknown profile '${name}' (allowed: ${Object.keys(PROFILES).join(', ')})`);
102
+ return PROFILES[name][role];
103
+ }
104
+
62
105
  const gitOut = (args) => execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
63
106
 
64
107
  const [cmd, ...rest] = process.argv.slice(2);
@@ -167,7 +210,8 @@ try {
167
210
  if (result !== 'pass' && result !== 'fail') fail('loopwright: usage: verdict <pass|fail> --round <n>');
168
211
  const roundRaw = flag(rest, '--round');
169
212
  const round = Number(roundRaw);
170
- if (roundRaw === undefined || !Number.isInteger(round) || round < 0) fail('loopwright: verdict requires --round <n>');
213
+ if (roundRaw === undefined || !Number.isInteger(round) || round < 0)
214
+ fail('loopwright: verdict requires --round <n>');
171
215
  const { dir, id, state } = requireState();
172
216
  state.verdict = { pass: result === 'pass', fingerprint: fingerprint(cwd, state.baseCommit), round };
173
217
  delete state.awaitingUser;
@@ -194,6 +238,9 @@ try {
194
238
  out(state);
195
239
  break;
196
240
  }
241
+ case 'effort':
242
+ process.stdout.write(effortFor(rest[0]) + '\n');
243
+ break;
197
244
  case 'status': {
198
245
  out(requireState().state);
199
246
  break;
@@ -208,7 +255,9 @@ try {
208
255
  break;
209
256
  }
210
257
  default:
211
- fail('loopwright: usage: lw.mjs <dir|start|stage|lock|check-locks|fingerprint|verdict|await-user|resume|status|done>');
258
+ fail(
259
+ 'loopwright: usage: lw.mjs <dir|start|stage|lock|check-locks|fingerprint|verdict|await-user|resume|status|effort|done>',
260
+ );
212
261
  }
213
262
  } catch (err) {
214
263
  fail(`loopwright: ${err instanceof Error ? err.message : String(err)}`);