@iceinvein/agent-skills 0.25.0 → 0.26.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.
Files changed (33) hide show
  1. package/README.md +2 -2
  2. package/dist/cli/index.js +775 -236
  3. package/package.json +2 -1
  4. package/skills/index.json +2 -2
  5. package/skills/magpie/SKILL.md +35 -18
  6. package/skills/magpie/bin/magpie.ts +28 -0
  7. package/skills/magpie/package.json +1 -1
  8. package/skills/magpie/references/critic.md +2 -2
  9. package/skills/magpie/references/peer-review.md +7 -7
  10. package/skills/magpie/references/proof.md +2 -2
  11. package/skills/magpie/scripts/__tests__/peer-run.test.ts +231 -0
  12. package/skills/magpie/scripts/__tests__/preflight.test.ts +22 -1
  13. package/skills/magpie/scripts/__tests__/setup-cmd.test.ts +14 -0
  14. package/skills/magpie/scripts/__tests__/skill-lint.test.ts +45 -4
  15. package/skills/magpie/scripts/peer-run.ts +146 -0
  16. package/skills/magpie/scripts/preflight.ts +20 -20
  17. package/skills/magpie/scripts/setup-cmd.ts +7 -1
  18. package/skills/magpie/skill.json +1 -1
  19. package/skills/sluice/SKILL.md +21 -6
  20. package/skills/sluice/references/deep-channel.md +35 -25
  21. package/skills/sluice/references/finish.md +2 -2
  22. package/skills/sluice/references/intent.md +1 -1
  23. package/skills/sluice/references/status.md +10 -4
  24. package/skills/sluice/references/test-first.md +12 -0
  25. package/skills/sluice/scripts/board-index.sh +59 -37
  26. package/skills/sluice/scripts/board.sh +72 -40
  27. package/skills/sluice/scripts/host.sh +60 -0
  28. package/skills/sluice/scripts/run-stats.sh +41 -3
  29. package/skills/sluice/scripts/session-start.sh +75 -17
  30. package/skills/sluice/scripts/status.sh +9 -5
  31. package/skills/sluice/scripts/stop-guard.sh +101 -37
  32. package/skills/sluice/scripts/transcript.sh +221 -0
  33. package/skills/sluice/skill.json +1 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@iceinvein/agent-skills",
3
- "version": "0.25.0",
3
+ "version": "0.26.0",
4
4
  "description": "Install agent skills into AI coding tools",
5
5
  "author": "iceinvein",
6
6
  "license": "MIT",
@@ -26,6 +26,7 @@
26
26
  "skill:audit": "bun run scripts/audit-skills.ts",
27
27
  "eval:fresh": "bun run scripts/eval-freshness.ts",
28
28
  "eval:plugins": "bun run scripts/eval-plugins.ts",
29
+ "eval:host": "bun run scripts/eval-host.ts",
29
30
  "release": "bash scripts/release.sh"
30
31
  },
31
32
  "keywords": [
package/skills/index.json CHANGED
@@ -227,7 +227,7 @@
227
227
  "name": "magpie",
228
228
  "description": "Interactive PR review pipeline. Runs five parallel specialist subagents (security, bugs, performance, code-smells, architecture) plus a once-per-PR checks pass that finds tests and controls able to pass without proving their purpose, drops findings whose quoted evidence is not in the code, dedupes, runs critic subagents that re-check each finding against the worktree and set its risk label, peer-reviews via codex exec (falling back to a Claude second opinion when codex is unavailable), and serves an interactive HTML report for selecting or dismissing findings to post via gh, recording the outcome per finding as labels. Bundles a Bun CLI put on PATH by the skill's postinstall step under a bunx install, or by the plugin's bin/ under a Claude Code plugin install. Use when the user asks to review a GitHub pull request. Local mode (setup --local) runs the same pipeline on the current branch's diff from its merge base, uncommitted and untracked work included, against the caller's live tree, with no server or posting, and hands the ranked findings back in the terminal for an implementing or orchestrating agent to address. Splits oversized diffs into budgeted shards and rebuilds the diff from the local clone when gh pr diff refuses it.",
229
229
  "type": "prompt",
230
- "version": "0.17.0"
230
+ "version": "0.18.0"
231
231
  },
232
232
  {
233
233
  "name": "migrate",
@@ -295,7 +295,7 @@
295
295
  "name": "sluice",
296
296
  "description": "Routes work by change shape into four channels (bypass, fast, main, deep) and applies only the rules each channel needs, so a one-line fix does not pay the cost of a multi-subsystem build. Carries nine rules as one-liners in the router and the full treatment in references read only on friction. Deep runs read the repo before designing, map the spec's intent to its decisions, and check spec against intent and plan against spec with a fresh reader, with plan.sh validate enforcing that every decision is covered. Checks the finished plan with plan.sh validate rather than trusting it to memory, seeds the run state from it, keeps a deep run's task breakdown in .sluice/run.json so a statusline segment, one status command and a SessionStart hook can answer where the run is (the hook prints a live run at every session start, compaction included), lists every live deep run and routed fast or main session on the machine in one board.sh view (drawn once, watched, or as JSON), and closes each run with a ledger read out of the session transcript: elapsed, tools, tokens, and what each dispatched agent cost where the transcript recorded it. Two Stop hooks hold a handback: one refuses a tree that moved since its last recorded check, the other refuses a changed existing test not proven to fail on the session's starting code (or recorded with a reason). Claude Code only; stands down where the superpowers pipeline governs the repo.",
297
297
  "type": "prompt",
298
- "version": "0.29.0"
298
+ "version": "0.30.0"
299
299
  },
300
300
  {
301
301
  "name": "temporal-coupling-detector",
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: magpie
3
- description: Use when the user asks to review a GitHub pull request (a PR number, PR URL, or "review this PR"), or to self-review the current branch diff before a PR exists, typically requested by an implementing or orchestrating agent, with findings handed back in the terminal. Interactive PR review pipeline; five parallel specialist subagents, dedupe, critic, codex/Claude peer review, and an interactive HTML report for posting selected findings via gh. Follow the stage walkthrough in this skill; the description is not the procedure.
3
+ description: Use when the user asks to review a GitHub pull request (a PR number, PR URL, or "review this PR"), or to self-review the current branch diff before a PR exists, typically requested by an implementing or orchestrating agent, with findings handed back in the terminal. Interactive PR review pipeline; five parallel specialist subagents, dedupe, critic, peer review by a configured second model, and an interactive HTML report for posting selected findings via gh. Follow the stage walkthrough in this skill; the description is not the procedure.
4
4
  argument-hint: "[<pr#>|<pr-url>|local (default)] [--base <ref>] [--intent-file <path>]"
5
5
  ---
6
6
 
@@ -8,11 +8,19 @@ argument-hint: "[<pr#>|<pr-url>|local (default)] [--base <ref>] [--intent-file <
8
8
 
9
9
  ## Prerequisites
10
10
 
11
- The skill pre-flights `bun`, `gh`, `git` (required) and `codex` (optional). A missing required binary aborts the run with a single install hint line. Without `codex` the run continues and peer review falls back to a Claude second-opinion subagent (setup prints a one-line notice and logs `{stage: preflight, status: done, missingOptional: ["codex"]}`).
11
+ The skill pre-flights `bun`, `gh`, `git` (required) and the peer provider (optional): `MAGPIE_PEER` is `codex` (default), `claude` or `agy`, `MAGPIE_PEER_MODEL` its model, `MAGPIE_PEER_TIMEOUT` its limit in seconds (default 600). A missing required binary or bad peer setting fails setup: show setup's stderr verbatim. A missing peer only moves peer review to a subagent (setup logs `{stage: preflight, status: done, missingOptional: ["<provider>"]}`). The host's sandbox must allow network for `gh` and writes to `~/.magpie` and the repo's `.git`.
12
+
13
+ ## Hosts
14
+
15
+ "Dispatch a subagent" means, per host:
16
+
17
+ - Claude Code: the Agent tool, `general-purpose` type. Host family `claude`.
18
+ - Codex: spawn a subagent. Host family `codex`.
19
+ - Antigravity: `invoke_subagent`. Host family `antigravity`.
12
20
 
13
21
  ## Stage walkthrough
14
22
 
15
- Stop reading and follow these steps in order. Do not skip stages. Use the exact Bash invocations below.
23
+ Stop reading and follow these steps in order. Do not skip stages. Use the exact shell invocations below.
16
24
 
17
25
  ### 0. Identify the PR
18
26
 
@@ -63,12 +71,14 @@ Setup also runs a deterministic test-coverage check: when the diff contains zero
63
71
 
64
72
  ### 2. Serve
65
73
 
66
- Start the HTML server in the background using the Bash tool with `run_in_background: true`:
74
+ Start the HTML server as a background process (on Claude Code, the Bash tool with `run_in_background: true`):
67
75
 
68
76
  ```
69
77
  magpie serve "$RUN_DIR"
70
78
  ```
71
79
 
80
+ A host without background processes tells the user to run `magpie serve "$RUN_DIR"` and carries on.
81
+
72
82
  Read `$RUN_DIR/state/server-info` for the URL (written within ~1s; re-read if missing). Print to the user: "Open <url> in your browser to follow along."
73
83
 
74
84
  The server stops after 30 idle minutes (an open report tab keeps it up); nothing depends on it, so re-run `magpie serve "$RUN_DIR"` to bring the report back.
@@ -85,7 +95,7 @@ Append `{stage: context, status: running}` to `$RUN_DIR/log.jsonl` and re-render
85
95
 
86
96
  Set `WORKTREE=$(magpie target "$RUN_DIR")`, the directory findings are anchored against (the run's own `worktree/` checkout on a PR run), and `TARGET` to `PR #$PR_NUMBER`. Every prompt from here on takes both.
87
97
 
88
- Read `references/scout.md` and `references/checks.md`, then dispatch two subagents (Agent tool, `general-purpose`) in one message: the scout, carrying the `magpie-scout` block with `<<RUN_DIR>>`, `<<WORKTREE>>` and `<<TARGET>>` substituted, which writes `$RUN_DIR/brief.json`; and the checks pass, built as `references/checks.md` says, which writes `$RUN_DIR/findings/checks.json` once for the run.
98
+ Read `references/scout.md` and `references/checks.md`, then, in one message, dispatch a subagent for each of two jobs: the scout, carrying the `magpie-scout` block with `<<RUN_DIR>>`, `<<WORKTREE>>` and `<<TARGET>>` substituted, which writes `$RUN_DIR/brief.json`; and the checks pass, built as `references/checks.md` says, which writes `$RUN_DIR/findings/checks.json` once for the run.
89
99
 
90
100
  Append `{stage: context, status: done}` and re-render progress. If the scout wrote no `brief.json`, append `{stage: context, status: skipped}` instead and continue: the brief is optional everywhere it is read. If the checks pass wrote no `checks.json`, append `{stage: checks, status: skipped}`; nothing downstream needs it.
91
101
 
@@ -101,9 +111,8 @@ Run `magpie history "$RUN_DIR"` once; any output is part 6 of every specialist p
101
111
 
102
112
  **One shard, zero shards, or no manifest** (a diff filtered down to nothing, e.g. a
103
113
  lockfile-only PR, yields `shards: []` in an otherwise normal manifest; a run predating
104
- this feature has no manifest at all): dispatch the five specialists in a single message,
105
- five parallel Agent calls, one per focus in (security, bugs, performance, code-smells,
106
- architecture), each carrying the prompt `references/specialists.md` describes with the
114
+ this feature has no manifest at all): dispatch a subagent per focus (security, bugs, performance, code-smells,
115
+ architecture), all five in one message, each carrying the prompt `references/specialists.md` describes with the
107
116
  unsharded run header. The shard gate and the wave dispatch below do not apply; the
108
117
  logging and the file check at the end of this stage still do.
109
118
 
@@ -163,7 +172,7 @@ The critic runs as subagents that read `$WORKTREE`. The CLI fills its prompt fro
163
172
  magpie critic-prompt "$RUN_DIR"
164
173
  ```
165
174
 
166
- It prints `<prompt path>\t<output path>` per batch of about 30 candidates (a merge group always stays in one batch). Dispatch one subagent (Agent tool, `general-purpose`) per line, all in one message, each one's entire task the verbatim contents of its prompt file. Each writes its output path and returns one summary line. No lines printed means no candidates: go straight to `critic-apply`.
175
+ It prints `<prompt path>\t<output path>` per batch of about 30 candidates (a merge group always stays in one batch). Then dispatch a subagent per line, all in one message, each one's entire task the verbatim contents of its prompt file. Each writes its output path and returns one summary line. No lines printed means no candidates: go straight to `critic-apply`.
167
176
 
168
177
  Confirm every output path exists; re-dispatch any batch whose file is missing. On a resume, dispatch only the batches whose output file is missing. Apply the verdicts:
169
178
 
@@ -175,9 +184,15 @@ It writes `findings.kept.json` and `critic-dropped.json` and logs the critic `do
175
184
 
176
185
  ### 7. Peer review
177
186
 
178
- Append `{stage: peer-review, status: running}` to `$RUN_DIR/log.jsonl` and re-render progress. This stage always runs. `codex` is preferred because it is a different model from the Claude agents that produced the findings; without it, a Claude second-opinion subagent stands in.
187
+ Append `{stage: peer-review, status: running}` to `$RUN_DIR/log.jsonl` and re-render progress. This stage always runs. Read the preset first:
179
188
 
180
- Build the peer-review prompt first: read `references/peer-review.md`, take the `magpie-peer-review` block from it, and substitute the placeholders listed in that file's `## Substitute before use` preamble.
189
+ ```
190
+ echo "${MAGPIE_PEER:-codex}"
191
+ ```
192
+
193
+ `<<PRIMARY_PROVIDER>>` is the host family (Hosts). When the preset is the host's own family (`agy` is `antigravity`), say so once in the terminal.
194
+
195
+ Build the peer-review prompt: read `references/peer-review.md`, take the `magpie-peer-review` block from it, and substitute the placeholders listed in that file's `## Substitute before use` preamble.
181
196
 
182
197
  One batch carries up to 40 findings; above that, split them 30 at a time.
183
198
  Write each batch's prompt, its `<<KEPT_FINDINGS_COMPACT>>` narrowed to that batch, to
@@ -187,23 +202,25 @@ Write each batch's prompt, its `<<KEPT_FINDINGS_COMPACT>>` narrowed to that batc
187
202
  finding in `findings.final.json` must have a unique one or the report and post stages
188
203
  crash.
189
204
 
190
- **Codex path (preferred).** If `codex` is available (setup did not log `missingOptional: ["codex"]` and `command -v codex` succeeds), set `<<PEER_PROVIDER>>` to `codex` and run codex once per batch, that batch's prompt piped on stdin:
205
+ **Peer path.** When preflight's `missingOptional` omits the preset, set `<<PEER_PROVIDER>>` to the preset and run each batch (omit `--batch` for a single batch):
191
206
 
192
207
  ```
193
- codex exec < "$RUN_DIR/peer-prompt-<k>.md" > "$RUN_DIR/peer-<k>.out"
208
+ magpie peer-run "$RUN_DIR" [--batch <k>]
194
209
  ```
195
210
 
196
- Each `peer-<k>.out` is codex's full transcript; extract the fenced JSON block tagged `review-peer-review` from each. Write the concatenated verdict arrays to `$RUN_DIR/peer.json` once, after the last batch: writing `peer.json` per batch keeps only the last batch's verdicts and silently discards the rest. Then append `{stage: peer-review, status: done, provider: codex}` and apply the verdicts as described below.
211
+ Extract the fenced `review-peer-review` JSON block from each `peer-<k>.out`. Write the concatenated verdict arrays to `$RUN_DIR/peer.json` once, after the last batch: per batch keeps only the last batch's verdicts.
212
+
213
+ On a non-zero exit, log `{stage: peer-review, provider: <preset>, status: fallback, batch: <k>, error: "<first stderr line>"}` and take the fallback for that batch. Never log `status: error` for a peer failure: `magpie status` would report the run poisoned.
197
214
 
198
- If codex returns non-zero on a batch, do not abort: record `{stage: peer-review, provider: codex, status: fallback, batch: <k>, error: "<first line of stderr>"}` and take the Claude path for that batch. (Never log `status: error` for a recoverable codex failure: `magpie status` stops at the first `error` entry and would report the run as poisoned even after the Claude fallback succeeds.)
215
+ **Fallback.** When the preset is missing or failed, prepend the `magpie-peer-review-same-family-preamble` block from `references/peer-review.md` to that batch's `peer-prompt[-<k>].md`, set `<<PEER_PROVIDER>>` to the host family, and dispatch a subagent per batch whose entire task is that file, returning only the fenced `review-peer-review` JSON block. Write its reply to `peer-<k>.out` and merge as above. A preset in `missingOptional` first logs that `status: fallback` line per batch, `error: "<preset> not on PATH"`.
199
216
 
200
- **Claude path (fallback).** When `codex` is unavailable or failed, get the second opinion from a Claude subagent instead, one per batch. Set `<<PEER_PROVIDER>>` to `claude`, then prepend the `magpie-peer-review-claude-preamble` block from `references/peer-review.md` to each batch's substituted prompt (the preamble forces genuine independence, since the reviewer shares a model family with the primary reviewers). Dispatch one subagent (Agent tool, `general-purpose`) per batch whose entire task is that combined prompt, and instruct it to return only the fenced `review-peer-review` JSON block. Write each output to `$RUN_DIR/peer-<k>.out`, extract each `review-peer-review` block, merge into `$RUN_DIR/peer.json` after the last batch as above, and append `{stage: peer-review, status: done, provider: claude}` (`provider: mixed` if codex handled some batches).
217
+ Then append `{stage: peer-review, status: done, provider: <p>}`: the preset, the host family if only the fallback ran, or `mixed`.
201
218
 
202
219
  **Apply the verdicts (both paths).** Parse the merged verdicts and apply the `update` / `add` entries (an empty array means no change). A peer `fields.severity` (or `finding.severity` on an `add`) is ignored: severity is derived from `risk.impact`. Mint each `add`'s `id` as above before merging, since the peer contract does not carry ids. Then write `findings.final.json`. Re-render progress.
203
220
 
204
221
  ### 7b. Proof
205
222
 
206
- Append `{stage: proof, status: running}` and re-render progress. `magpie proof-prompt "$RUN_DIR"` fills `references/proof.md` for up to 8 must-fix or should-fix findings, printing `<prompt path>\t<output path>` each. On a PR run with any printed, first install `$WORKTREE`'s dependencies once with the repo's frozen-lockfile command (`npm ci`, `uv sync --frozen`, ...); on failure log `{stage: proof-deps, status: skipped, error}` and go on. Dispatch the prompts as stage 6 does its batches, then `magpie proof-apply "$RUN_DIR"`: it drops disproved findings to `proof-dropped.json`, marks the rest and logs `done`. On a non-zero exit, delete only the `proof-<id>.json` files or leftovers stderr names, then re-dispatch or re-apply.
223
+ Append `{stage: proof, status: running}` and re-render progress. `magpie proof-prompt "$RUN_DIR"` fills `references/proof.md` for up to 8 must-fix or should-fix findings, printing `<prompt path>\t<output path>` each. On a PR run with any printed, first install `$WORKTREE`'s dependencies once with the repo's frozen-lockfile command (`npm ci`, `uv sync --frozen`, ...); on failure log `{stage: proof-deps, status: skipped, error}` and go on. Then dispatch a subagent per prompt as stage 6 does its batches, then `magpie proof-apply "$RUN_DIR"`: it drops disproved findings to `proof-dropped.json`, marks the rest and logs `done`. On a non-zero exit, delete only the `proof-<id>.json` files or leftovers stderr names, then re-dispatch or re-apply.
207
224
 
208
225
  ### 8. Report
209
226
 
@@ -278,7 +295,7 @@ On a non-zero exit, show stderr verbatim to the caller and stop. The diff runs f
278
295
  - Stage 8: `magpie handoff "$RUN_DIR"`. On exit 4 (`findings.final.json` or `local.json` missing) or 2 (not a local run), show stderr to the caller and stop.
279
296
  - Then `magpie cleanup "$RUN_DIR" --repo "$REPO"` at once. Reply to the caller with the handoff stdout verbatim, then one line `Run archived at <path>`, `<path>` from cleanup's `archived to <path>`. End the turn.
280
297
 
281
- Do not edit the tree mid-run: anchors and evidence are read from it live. Without the Agent tool, stop and say so rather than reviewing single-handed. The local ladder ends at handoff, then cleanup; there is no server to restart.
298
+ Do not edit the tree mid-run: anchors and evidence are read from it live. A host that cannot dispatch subagents stops and says so rather than reviewing single-handed. The local ladder ends at handoff, then cleanup; there is no server to restart.
282
299
 
283
300
  ## Resuming a crashed run
284
301
 
@@ -25,6 +25,9 @@ Subcommands:
25
25
  dedupe <run-dir> Merge specialist findings into deduped set
26
26
  critic-prompt <run-dir> [--batch-size N]
27
27
  Write one critic prompt per batch, print prompt and output paths
28
+ peer-run <run-dir> [--batch K]
29
+ Run the peer reviewer ($MAGPIE_PEER: codex, claude or agy) on
30
+ peer-prompt[-K].md, write its stdout to peer[-K].out
28
31
  critic-apply <run-dir> [--design-cap N]
29
32
  Apply critic verdicts, write findings.kept.json (no cap on
30
33
  code-smells + architecture keeps unless --design-cap is given)
@@ -252,6 +255,31 @@ const HANDLERS: Record<string, Handler> = {
252
255
  const { runDedupe } = await import('../scripts/dedupe-cmd.ts')
253
256
  return runDedupe(runDir, threshold !== undefined ? { threshold } : {})
254
257
  },
258
+ 'peer-run': async (args) => {
259
+ const runDir = args[0]
260
+ if (!runDir || runDir.startsWith('-')) {
261
+ process.stderr.write('peer-run: missing <run-dir> [--batch <k>]\n')
262
+ return 2
263
+ }
264
+ const flag = args.indexOf('--batch')
265
+ const raw = flag !== -1 ? args[flag + 1] : undefined
266
+ let batch: number | null = null
267
+ if (flag !== -1) {
268
+ const n = Number(raw)
269
+ if (!Number.isInteger(n) || n <= 0) {
270
+ process.stderr.write(`peer-run: invalid --batch ${raw} (want a positive integer)\n`)
271
+ return 2
272
+ }
273
+ batch = n
274
+ }
275
+ const { runPeer } = await import('../scripts/peer-run.ts')
276
+ const result = await runPeer(runDir, batch, process.env)
277
+ if (!result.ok) {
278
+ process.stderr.write(`peer-run: ${result.error}\n`)
279
+ return 1
280
+ }
281
+ return 0
282
+ },
255
283
  'critic-prompt': async (args) => {
256
284
  const runDir = args[0]
257
285
  if (!runDir) {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "magpie",
3
- "version": "0.17.0",
3
+ "version": "0.18.0",
4
4
  "private": true,
5
5
  "type": "module",
6
6
  "scripts": {
@@ -17,7 +17,7 @@ from the run directory, and writes one prompt file per batch of candidates:
17
17
  - `<<WORKTREE>>`, `<<DIFF_PATH>>`: the run's worktree and `diff.patch`.
18
18
  - `<<OUTPUT_PATH>>`: where this batch's verdicts go, `critic.json` or `critic-<k>.json`.
19
19
 
20
- Each prompt file is the entire task of one `general-purpose` subagent. `magpie
20
+ Each prompt file is the entire task of one subagent. `magpie
21
21
  critic-apply "$RUN_DIR"` then reads every output file, rejects the set if any verdict
22
22
  is malformed, and writes `findings.kept.json` and `critic-dropped.json`. The output
23
23
  contract in the block is exactly what critic-apply accepts; change one only with the
@@ -163,7 +163,7 @@ followed by no reason from that list means "should-fix".
163
163
 
164
164
  ## Output contract
165
165
 
166
- Write a JSON array to <<OUTPUT_PATH>> with the Write tool, one entry per candidate
166
+ Write a JSON array to <<OUTPUT_PATH>> (write the file), one entry per candidate
167
167
  below, every candidate exactly once. Copy each `id` verbatim and invent none. Each
168
168
  entry is:
169
169
 
@@ -1,6 +1,6 @@
1
1
  # Peer-review prompt
2
2
 
3
- The agent substitutes the placeholders below and writes the result to `<run-dir>/peer-prompt.md`. Stage 7 then feeds that prompt to the peer reviewer: `codex exec < <run-dir>/peer-prompt.md > <run-dir>/peer.out` when codex is available, or a Claude `general-purpose` subagent (with the `magpie-peer-review-claude-preamble` prepended) writing to `<run-dir>/peer.out` when it is not.
3
+ The agent substitutes the placeholders below and writes the result to `<run-dir>/peer-prompt.md`. Stage 7 then feeds that prompt to the peer reviewer: `magpie peer-run <run-dir>` runs the configured peer (`MAGPIE_PEER`, default `codex`) on it and writes `<run-dir>/peer.out`, or, when that peer is missing or fails, a subagent (with the `magpie-peer-review-same-family-preamble` prepended) writes `<run-dir>/peer.out`.
4
4
 
5
5
  Either way, extract the fenced `review-peer-review` block from `peer.out` and save it to `<run-dir>/peer.json`.
6
6
 
@@ -13,14 +13,14 @@ last batch. Everything below is per batch and otherwise unchanged.
13
13
 
14
14
  Replace each `<<NAME>>` placeholder in the block below:
15
15
 
16
- - `<<PRIMARY_PROVIDER>>` — the agent that produced the findings (e.g. `claude`).
17
- - `<<PEER_PROVIDER>>` — the agent auditing the review (e.g. `codex`).
16
+ - `<<PRIMARY_PROVIDER>>` — the host family that produced the findings: `claude`, `codex` or `antigravity`.
17
+ - `<<PEER_PROVIDER>>` — the agent auditing the review: the `MAGPIE_PEER` preset (e.g. `codex`), or the host family when the subagent fallback runs.
18
18
  - `<<PR_TITLE>>` — `jq -r .title < $RUN_DIR/pr.json`
19
19
  - `<<PR_AUTHOR>>` — `jq -r .author.login < $RUN_DIR/pr.json`
20
20
  - `<<PR_HEAD_BRANCH>>` — `jq -r .headRefName < $RUN_DIR/pr.json`
21
21
  - `<<PR_BASE_BRANCH>>` — `jq -r .baseRefName < $RUN_DIR/pr.json`
22
22
  - `<<PR_FILES_CHANGED>>` — `grep -c '^diff --git' $RUN_DIR/diff.patch`
23
- - `<<KEPT_FINDINGS_COMPACT>>` — pretty-printed JSON array of kept findings with the fields codex needs:
23
+ - `<<KEPT_FINDINGS_COMPACT>>` — pretty-printed JSON array of kept findings with the fields the peer needs:
24
24
  ```
25
25
  jq '[.[] | {id, file, line, risk, domain, title, description}]' "$RUN_DIR/findings.kept.json"
26
26
  ```
@@ -83,11 +83,11 @@ Rules:
83
83
  ```
84
84
  ````
85
85
 
86
- ## Claude peer-review preamble
86
+ ## Same-family peer-review preamble
87
87
 
88
- Used only by the Claude fallback path in stage 7. Prepend this block verbatim (no substitutions) to the substituted `magpie-peer-review` prompt before dispatching the subagent. Its job is to buy back the independence you lose by using the same model family that produced the findings: the reviewer must re-derive each verdict from the diff rather than trusting the finding text, and must actively resist rubber-stamping.
88
+ Used only by the subagent fallback in stage 7. Prepend this block verbatim (no substitutions) to the substituted `magpie-peer-review` prompt before dispatching the subagent. Its job is to buy back the independence you lose by using the same model family that produced the findings: the reviewer must re-derive each verdict from the diff rather than trusting the finding text, and must actively resist rubber-stamping.
89
89
 
90
- ````magpie-peer-review-claude-preamble
90
+ ````magpie-peer-review-same-family-preamble
91
91
  You are a fresh, independent second-opinion reviewer. You have no memory of, and no stake in, how the findings below were produced. They were generated by other agents that share your model family, so they may carry the same blind spots you would: do not defer to them, and do not assume they are correct because they sound confident.
92
92
 
93
93
  Ground every verdict in the diff hunks provided, not in the prose of the finding. For each finding, independently re-derive whether the described problem is actually present on the cited line before you accept it. If a finding's reasoning does not hold against the hunk, or the anchor is wrong, or the risk is off, say so with "update"; if you can see a clearly actionable adjacent issue in the same hunks that was missed, add it. When the existing finding survives your own check unchanged, leave it alone.
@@ -12,7 +12,7 @@ one prompt file per finding:
12
12
  the worktree is the caller's own repo.
13
13
  - `<<OUTPUT_PATH>>`: where this finding's result goes, `proof-<id>.json`.
14
14
 
15
- Each prompt file is the entire task of one `general-purpose` subagent. `magpie
15
+ Each prompt file is the entire task of one subagent. `magpie
16
16
  proof-apply "$RUN_DIR"` then reads every result, rejects the set if any is missing or
17
17
  malformed, drops the disproved findings to `proof-dropped.json`, and marks the rest in
18
18
  `findings.final.json`. The output contract in the block is exactly what proof-apply
@@ -82,7 +82,7 @@ Diff: <<DIFF_PATH>>
82
82
 
83
83
  ## Output contract
84
84
 
85
- Write one JSON object to <<OUTPUT_PATH>> with the Write tool:
85
+ Write one JSON object to <<OUTPUT_PATH>> (write the file):
86
86
 
87
87
  ```
88
88
  {
@@ -0,0 +1,231 @@
1
+ import { expect, test } from 'bun:test'
2
+ import { existsSync } from 'node:fs'
3
+ import { chmod, mkdtemp, readFile, writeFile } from 'node:fs/promises'
4
+ import { tmpdir } from 'node:os'
5
+ import { join } from 'node:path'
6
+ import { killProviderGroup, peerArgv, peerConfigFromEnv, runPeer } from '../peer-run.ts'
7
+
8
+ const CLI = new URL('../../bin/magpie.ts', import.meta.url).pathname
9
+ const P = 'review these findings'
10
+
11
+ async function fakeProvider(body: string): Promise<string> {
12
+ const dir = await mkdtemp(join(tmpdir(), 'magpie-peer-bin-'))
13
+ const bin = join(dir, 'fake-codex')
14
+ await writeFile(bin, `#!/bin/sh\n${body}\n`)
15
+ await chmod(bin, 0o755)
16
+ return bin
17
+ }
18
+
19
+ // A killed grandchild is reparented and reaped asynchronously, so for a moment it
20
+ // can linger as exiting (E) or a zombie (Z); both count as stopped, since it runs nothing.
21
+ function isRunning(pid: number): boolean {
22
+ const stat = Bun.spawnSync(['ps', '-o', 'stat=', '-p', String(pid)]).stdout.toString().trim()
23
+ return stat !== '' && !stat.startsWith('Z') && !stat.startsWith('E')
24
+ }
25
+
26
+ async function runDirWith(files: Record<string, string>): Promise<string> {
27
+ const runDir = await mkdtemp(join(tmpdir(), 'magpie-peer-run-'))
28
+ for (const [name, text] of Object.entries(files)) await writeFile(join(runDir, name), text)
29
+ return runDir
30
+ }
31
+
32
+ test('codex preset runs exec with the model and reads the prompt from stdin', () => {
33
+ expect(peerArgv('codex', 'codex', 'm1', P)).toEqual({
34
+ argv: ['codex', 'exec', '-m', 'm1', '-'],
35
+ stdin: P,
36
+ })
37
+ })
38
+
39
+ test('codex preset without a model leaves out the -m pair', () => {
40
+ expect(peerArgv('codex', 'codex', null, P)).toEqual({ argv: ['codex', 'exec', '-'], stdin: P })
41
+ })
42
+
43
+ test('claude preset runs print mode with the model and reads the prompt from stdin', () => {
44
+ expect(peerArgv('claude', 'claude', 'm2', P)).toEqual({
45
+ argv: ['claude', '-p', '--model', 'm2'],
46
+ stdin: P,
47
+ })
48
+ })
49
+
50
+ test('agy preset passes the prompt as an argument and nothing on stdin', () => {
51
+ expect(peerArgv('agy', 'agy', 'm3', P)).toEqual({
52
+ argv: ['agy', '-p', P, '--model', 'm3'],
53
+ stdin: null,
54
+ })
55
+ })
56
+
57
+ test('an empty environment configures codex with no model, 600s and the codex binary', () => {
58
+ expect(peerConfigFromEnv({})).toEqual({ provider: 'codex', model: null, timeoutSec: 600, bin: 'codex' })
59
+ })
60
+
61
+ test('MAGPIE_PEER, MAGPIE_PEER_MODEL and the provider bin variable pick the peer', () => {
62
+ expect(
63
+ peerConfigFromEnv({
64
+ MAGPIE_PEER: 'agy',
65
+ MAGPIE_PEER_MODEL: 'm9',
66
+ MAGPIE_PEER_TIMEOUT: '30',
67
+ MAGPIE_AGY_BIN: '/opt/agy',
68
+ MAGPIE_CODEX_BIN: '/opt/codex',
69
+ }),
70
+ ).toEqual({ provider: 'agy', model: 'm9', timeoutSec: 30, bin: '/opt/agy' })
71
+ })
72
+
73
+ test('an unknown MAGPIE_PEER throws naming the known providers', () => {
74
+ expect(() => peerConfigFromEnv({ MAGPIE_PEER: 'gpt' })).toThrow('codex, claude, agy')
75
+ })
76
+
77
+ test('a non-positive MAGPIE_PEER_TIMEOUT throws', () => {
78
+ expect(() => peerConfigFromEnv({ MAGPIE_PEER_TIMEOUT: '0' })).toThrow('MAGPIE_PEER_TIMEOUT')
79
+ })
80
+
81
+ test('a non-numeric MAGPIE_PEER_TIMEOUT throws', () => {
82
+ expect(() => peerConfigFromEnv({ MAGPIE_PEER_TIMEOUT: 'soon' })).toThrow('MAGPIE_PEER_TIMEOUT')
83
+ })
84
+
85
+ test('runPeer writes the provider stdout to peer.out', async () => {
86
+ const bin = await fakeProvider('cat')
87
+ const runDir = await runDirWith({ 'peer-prompt.md': 'single batch prompt' })
88
+ const result = await runPeer(runDir, null, { MAGPIE_CODEX_BIN: bin })
89
+ expect(result).toEqual({ ok: true, outPath: join(runDir, 'peer.out') })
90
+ expect(await readFile(join(runDir, 'peer.out'), 'utf8')).toBe('single batch prompt')
91
+ })
92
+
93
+ test('peer-run --batch 2 reads peer-prompt-2.md and writes peer-2.out', async () => {
94
+ const bin = await fakeProvider('cat')
95
+ const runDir = await runDirWith({ 'peer-prompt.md': 'wrong', 'peer-prompt-2.md': 'second batch' })
96
+ const proc = Bun.spawn(['bun', CLI, 'peer-run', runDir, '--batch', '2'], {
97
+ env: { ...process.env, MAGPIE_PEER: 'codex', MAGPIE_CODEX_BIN: bin },
98
+ stdout: 'pipe',
99
+ stderr: 'pipe',
100
+ })
101
+ expect(await proc.exited).toBe(0)
102
+ expect(await readFile(join(runDir, 'peer-2.out'), 'utf8')).toBe('second batch')
103
+ })
104
+
105
+ test('a provider exiting non-zero yields its first stderr line as the error', async () => {
106
+ const bin = await fakeProvider('echo boom >&2\necho later >&2\nexit 3')
107
+ const runDir = await runDirWith({ 'peer-prompt.md': 'p' })
108
+ const result = await runPeer(runDir, null, { MAGPIE_CODEX_BIN: bin })
109
+ expect(result.ok).toBe(false)
110
+ expect(!result.ok && result.error).toContain('boom')
111
+ expect(!result.ok && result.error).not.toContain('later')
112
+ })
113
+
114
+ test('peer-run exits 1 printing the provider stderr line', async () => {
115
+ const bin = await fakeProvider('echo boom >&2\nexit 3')
116
+ const runDir = await runDirWith({ 'peer-prompt.md': 'p' })
117
+ const proc = Bun.spawn(['bun', CLI, 'peer-run', runDir], {
118
+ env: { ...process.env, MAGPIE_PEER: 'codex', MAGPIE_CODEX_BIN: bin },
119
+ stdout: 'pipe',
120
+ stderr: 'pipe',
121
+ })
122
+ expect(await proc.exited).toBe(1)
123
+ expect(await new Response(proc.stderr).text()).toContain('boom')
124
+ })
125
+
126
+ test('a timed-out provider is killed along with the processes it started', async () => {
127
+ const pidFile = join(await mkdtemp(join(tmpdir(), 'magpie-peer-pid-')), 'child.pid')
128
+ const bin = await fakeProvider(`sleep 30 &\necho $! > ${pidFile}\nwait`)
129
+ const runDir = await runDirWith({ 'peer-prompt.md': 'p' })
130
+ await runPeer(runDir, null, { MAGPIE_CODEX_BIN: bin, MAGPIE_PEER_TIMEOUT: '1' })
131
+ const childPid = Number(await readFile(pidFile, 'utf8'))
132
+ expect(isRunning(childPid)).toBe(false)
133
+ })
134
+
135
+ test('a provider running past MAGPIE_PEER_TIMEOUT is reported as timed out', async () => {
136
+ const bin = await fakeProvider('sleep 5')
137
+ const runDir = await runDirWith({ 'peer-prompt.md': 'p' })
138
+ const result = await runPeer(runDir, null, { MAGPIE_CODEX_BIN: bin, MAGPIE_PEER_TIMEOUT: '1' })
139
+ expect(result.ok).toBe(false)
140
+ expect(!result.ok && result.error).toContain('timed out after 1s')
141
+ })
142
+
143
+ test('SIGTERM to peer-run kills the provider group and exits 143', async () => {
144
+ const pidFile = join(await mkdtemp(join(tmpdir(), 'magpie-peer-pid-')), 'child.pid')
145
+ const bin = await fakeProvider(`sleep 30 &\necho $! > ${pidFile}\nwait`)
146
+ const runDir = await runDirWith({ 'peer-prompt.md': 'p' })
147
+ const proc = Bun.spawn(['bun', CLI, 'peer-run', runDir], {
148
+ env: { ...process.env, MAGPIE_PEER: 'codex', MAGPIE_CODEX_BIN: bin },
149
+ stdout: 'pipe',
150
+ stderr: 'pipe',
151
+ })
152
+ const deadline = Date.now() + 5000
153
+ while (!existsSync(pidFile) || (await readFile(pidFile, 'utf8')).trim() === '') {
154
+ if (Date.now() > deadline) throw new Error('fake provider never wrote its child pid')
155
+ await Bun.sleep(20)
156
+ }
157
+ const childPid = Number(await readFile(pidFile, 'utf8'))
158
+ proc.kill('SIGTERM')
159
+ expect(await proc.exited).toBe(143)
160
+ expect(isRunning(childPid)).toBe(false)
161
+ })
162
+
163
+ test('SIGHUP to peer-run kills the provider group and exits 129', async () => {
164
+ const pidFile = join(await mkdtemp(join(tmpdir(), 'magpie-peer-pid-')), 'child.pid')
165
+ const bin = await fakeProvider(`sleep 30 &\necho $! > ${pidFile}\nwait`)
166
+ const runDir = await runDirWith({ 'peer-prompt.md': 'p' })
167
+ const proc = Bun.spawn(['bun', CLI, 'peer-run', runDir], {
168
+ env: { ...process.env, MAGPIE_PEER: 'codex', MAGPIE_CODEX_BIN: bin },
169
+ stdout: 'pipe',
170
+ stderr: 'pipe',
171
+ })
172
+ const deadline = Date.now() + 5000
173
+ while (!existsSync(pidFile) || (await readFile(pidFile, 'utf8')).trim() === '') {
174
+ if (Date.now() > deadline) throw new Error('fake provider never wrote its child pid')
175
+ await Bun.sleep(20)
176
+ }
177
+ const childPid = Number(await readFile(pidFile, 'utf8'))
178
+ proc.kill('SIGHUP')
179
+ expect(await proc.exited).toBe(129)
180
+ expect(isRunning(childPid)).toBe(false)
181
+ })
182
+
183
+ test('killing a provider group that has already exited does not throw', async () => {
184
+ const gone = Bun.spawn(['true'], { detached: true })
185
+ await gone.exited
186
+ expect(() => killProviderGroup(gone.pid)).not.toThrow()
187
+ })
188
+
189
+ test('a provider that exits 0 but leaves a child holding its output returns its output within the time limit', async () => {
190
+ const bin = await fakeProvider('sleep 20 &\necho OUT\nexit 0')
191
+ const runDir = await runDirWith({ 'peer-prompt.md': 'p' })
192
+ const started = Date.now()
193
+ const result = await runPeer(runDir, null, { MAGPIE_CODEX_BIN: bin, MAGPIE_PEER_TIMEOUT: '2' })
194
+ expect(Date.now() - started).toBeLessThan(3000)
195
+ expect(result).toEqual({ ok: true, outPath: join(runDir, 'peer.out') })
196
+ expect(await readFile(join(runDir, 'peer.out'), 'utf8')).toBe('OUT\n')
197
+ }, 30000)
198
+
199
+ test('a provider that exits 0 does not leave the child it started running', async () => {
200
+ const pidFile = join(await mkdtemp(join(tmpdir(), 'magpie-peer-pid-')), 'child.pid')
201
+ const bin = await fakeProvider(`sleep 20 >/dev/null 2>&1 &\necho $! > ${pidFile}\nexit 0`)
202
+ const runDir = await runDirWith({ 'peer-prompt.md': 'p' })
203
+ await runPeer(runDir, null, { MAGPIE_CODEX_BIN: bin, MAGPIE_PEER_TIMEOUT: '2' })
204
+ const childPid = Number(await readFile(pidFile, 'utf8'))
205
+ expect(isRunning(childPid)).toBe(false)
206
+ }, 30000)
207
+
208
+ test('a provider that exits non-zero but leaves a child holding its stderr fails within the time limit', async () => {
209
+ const bin = await fakeProvider('sleep 20 &\necho boom >&2\nexit 4')
210
+ const runDir = await runDirWith({ 'peer-prompt.md': 'p' })
211
+ const started = Date.now()
212
+ const result = await runPeer(runDir, null, { MAGPIE_CODEX_BIN: bin, MAGPIE_PEER_TIMEOUT: '2' })
213
+ expect(Date.now() - started).toBeLessThan(3000)
214
+ expect(result).toEqual({ ok: false, error: 'boom' })
215
+ }, 30000)
216
+
217
+ test('a child that leaves the provider group and holds its output still ends the run at the time limit', async () => {
218
+ const pidFile = join(await mkdtemp(join(tmpdir(), 'magpie-peer-pid-')), 'child.pid')
219
+ const bin = await fakeProvider(
220
+ // The provider waits for the pid file so the child has left the group before the provider exits.
221
+ `perl -e 'setpgrp(0, 0); open(my $f, ">", $ARGV[0]); print $f $$; close $f; exec "sleep", "20"' ${pidFile} &\nwhile [ ! -s ${pidFile} ]; do sleep 0.05; done\necho OUT\nexit 0`,
222
+ )
223
+ const runDir = await runDirWith({ 'peer-prompt.md': 'p' })
224
+ const started = Date.now()
225
+ const result = await runPeer(runDir, null, { MAGPIE_CODEX_BIN: bin, MAGPIE_PEER_TIMEOUT: '2' })
226
+ const elapsed = Date.now() - started
227
+ // setpgrp made the child its own group leader, so its pid names its group.
228
+ killProviderGroup(Number(await readFile(pidFile, 'utf8')))
229
+ expect(elapsed).toBeLessThan(3000)
230
+ expect(result).toEqual({ ok: false, error: 'timed out after 2s' })
231
+ }, 30000)
@@ -1,5 +1,5 @@
1
1
  import { expect, test } from 'bun:test'
2
- import { preflight } from '../preflight.ts'
2
+ import { defaultDeps, preflight, renderInstallHint } from '../preflight.ts'
3
3
 
4
4
  test('returns ok when all binaries resolve', async () => {
5
5
  const result = await preflight({
@@ -43,3 +43,24 @@ test('renderInstallHint produces a single-line message per missing tool', () =>
43
43
  expect(out).toContain('codex:')
44
44
  expect(out.split('\n').length).toBeGreaterThanOrEqual(2)
45
45
  })
46
+
47
+ test('the configured peer provider is the optional dependency', async () => {
48
+ const result = await preflight(
49
+ defaultDeps({ MAGPIE_PEER: 'claude', MAGPIE_CLAUDE_BIN: 'no-such-claude-bin-789' }),
50
+ )
51
+ expect(result.ok).toBe(true)
52
+ expect(result.missing).toEqual([])
53
+ expect(result.missingOptional).toEqual(['claude'])
54
+ })
55
+
56
+ test('renderInstallHint gives agy an install line rather than the not-on-PATH fallback', () => {
57
+ const hint = renderInstallHint(['agy'])
58
+ expect(hint).toStartWith('agy: install')
59
+ expect(hint).not.toContain('not found on PATH')
60
+ })
61
+
62
+ test('with no MAGPIE_PEER the codex binary is the optional dependency', async () => {
63
+ const result = await preflight(defaultDeps({ MAGPIE_CODEX_BIN: 'no-such-codex-bin' }))
64
+ expect(result.ok).toBe(true)
65
+ expect(result.missingOptional).toEqual(['codex'])
66
+ })
@@ -959,3 +959,17 @@ test('a re-review lists the files changed since the last review when the new hea
959
959
  await rm(magpieHome, { recursive: true, force: true })
960
960
  }
961
961
  })
962
+
963
+ test('setup with an unknown MAGPIE_PEER exits 2 naming the providers, without a stack trace', async () => {
964
+ const cli = new URL('../../bin/magpie.ts', import.meta.url).pathname
965
+ const proc = Bun.spawn(['bun', cli, 'setup', runDir, '--pr', '1', '--repo', repo], {
966
+ env: { ...process.env, MAGPIE_PEER: 'gpt' },
967
+ stdout: 'pipe',
968
+ stderr: 'pipe',
969
+ })
970
+ const exit = await proc.exited
971
+ const stderr = await new Response(proc.stderr).text()
972
+ expect(exit).toBe(2)
973
+ expect(stderr).toContain('codex, claude, agy')
974
+ expect(stderr).not.toContain(' at ')
975
+ })