@iceinvein/agent-skills 0.25.0 → 0.27.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 (44) hide show
  1. package/README.md +14 -5
  2. package/dist/cli/index.js +913 -239
  3. package/package.json +2 -1
  4. package/skills/index.json +4 -4
  5. package/skills/magpie/README.md +24 -6
  6. package/skills/magpie/SKILL.md +35 -18
  7. package/skills/magpie/bin/magpie.ts +28 -0
  8. package/skills/magpie/package.json +1 -1
  9. package/skills/magpie/references/critic.md +2 -2
  10. package/skills/magpie/references/peer-review.md +7 -7
  11. package/skills/magpie/references/proof.md +2 -2
  12. package/skills/magpie/scripts/__tests__/peer-run.test.ts +231 -0
  13. package/skills/magpie/scripts/__tests__/preflight.test.ts +22 -1
  14. package/skills/magpie/scripts/__tests__/setup-cmd.test.ts +14 -0
  15. package/skills/magpie/scripts/__tests__/skill-lint.test.ts +45 -4
  16. package/skills/magpie/scripts/peer-run.ts +146 -0
  17. package/skills/magpie/scripts/preflight.ts +20 -20
  18. package/skills/magpie/scripts/setup-cmd.ts +7 -1
  19. package/skills/magpie/skill.json +21 -3
  20. package/skills/sluice/SKILL.md +24 -7
  21. package/skills/sluice/evals/README.md +4 -3
  22. package/skills/sluice/evals/deep-run-mirrors-the-task-list/case.yaml +4 -0
  23. package/skills/sluice/evals/deep-run-mirrors-the-task-list/fixture.sh +304 -0
  24. package/skills/sluice/evals/deep-run-mirrors-the-task-list/graders/every-task-done.md +7 -0
  25. package/skills/sluice/evals/deep-run-mirrors-the-task-list/graders/sluice-fired.md +5 -0
  26. package/skills/sluice/evals/deep-run-mirrors-the-task-list/graders/task-list-completed.md +7 -0
  27. package/skills/sluice/evals/deep-run-mirrors-the-task-list/graders/task-list-created.md +8 -0
  28. package/skills/sluice/evals/deep-run-mirrors-the-task-list/prompt.md +13 -0
  29. package/skills/sluice/evals/rules.json +9 -0
  30. package/skills/sluice/references/deep-channel.md +52 -25
  31. package/skills/sluice/references/finish.md +2 -2
  32. package/skills/sluice/references/intent.md +1 -1
  33. package/skills/sluice/references/status.md +18 -7
  34. package/skills/sluice/references/test-first.md +12 -0
  35. package/skills/sluice/scripts/board-index.sh +59 -37
  36. package/skills/sluice/scripts/board.sh +72 -40
  37. package/skills/sluice/scripts/host.sh +60 -0
  38. package/skills/sluice/scripts/postinstall.sh +3 -3
  39. package/skills/sluice/scripts/run-stats.sh +41 -3
  40. package/skills/sluice/scripts/session-start.sh +75 -17
  41. package/skills/sluice/scripts/status.sh +9 -5
  42. package/skills/sluice/scripts/stop-guard.sh +101 -37
  43. package/skills/sluice/scripts/transcript.sh +221 -0
  44. package/skills/sluice/skill.json +28 -4
@@ -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
+ })
@@ -143,7 +143,7 @@ test('references/critic.md asks for the verdict shape critic-apply accepts', asy
143
143
  expect(block).toMatch(/"keep".*"drop".*"merge"/)
144
144
  expect(block).toMatch(/"impact"[\s\S]*"likelihood"[\s\S]*"confidence"[\s\S]*"action"/)
145
145
  // The subagent writes the file itself; the old in-conversation fenced reply is gone.
146
- expect(block).toMatch(/Write tool/)
146
+ expect(block).toMatch(/[Ww]rite the file/)
147
147
  expect(block).toContain('critic: <kept> kept, <dropped> dropped, <merged> merged')
148
148
  expect(block).not.toContain('review-critic')
149
149
  })
@@ -190,10 +190,10 @@ test('references/critic.md keeps confirmed defects actionable and names what is
190
190
  expect(drop).toMatch(/what the test checks/)
191
191
  })
192
192
 
193
- test('references/peer-review.md holds the prompt and the Claude preamble', async () => {
193
+ test('references/peer-review.md holds the prompt and the same-family preamble', async () => {
194
194
  const text = await readFile(ref('peer-review.md'), 'utf8')
195
195
  expect(text).toContain('```magpie-peer-review')
196
- expect(text).toContain('```magpie-peer-review-claude-preamble')
196
+ expect(text).toContain('```magpie-peer-review-same-family-preamble')
197
197
  expect(text).toContain('review-peer-review')
198
198
  for (const ph of ['<<PRIMARY_PROVIDER>>', '<<PEER_PROVIDER>>', '<<KEPT_FINDINGS_COMPACT>>']) {
199
199
  expect(text).toContain(ph)
@@ -528,7 +528,7 @@ test('stage 6 runs the critic through critic-prompt and critic-apply subagents',
528
528
  const section = await skillSection('### 6. Critic')
529
529
  expect(section).toContain('magpie critic-prompt "$RUN_DIR"')
530
530
  expect(section).toContain('magpie critic-apply "$RUN_DIR"')
531
- expect(section).toContain('general-purpose')
531
+ expect(section).toContain('dispatch a subagent')
532
532
  // critic-apply logs its own done entry; a second one from the agent double-counts.
533
533
  expect(section).not.toMatch(/\{stage: critic, status: done\}/)
534
534
  // The in-conversation rubric and its batching paragraph are gone.
@@ -571,3 +571,44 @@ test('stage 9 takes the selection from magpie view rather than folding state/eve
571
571
  expect(section).not.toMatch(/LAST event/i)
572
572
  expect(section).not.toContain('state/events')
573
573
  })
574
+
575
+ const hostsSection = (text: string) => {
576
+ const start = text.indexOf('\n## Hosts\n')
577
+ expect(start).toBeGreaterThan(-1)
578
+ const next = text.indexOf('\n## ', start + 1)
579
+ return text.slice(start, next === -1 ? undefined : next)
580
+ }
581
+
582
+ test('SKILL.md maps subagent dispatch onto each host in a Hosts section', async () => {
583
+ const hosts = hostsSection(await readFile(SKILL, 'utf8'))
584
+ expect(hosts).toContain('Agent tool')
585
+ expect(hosts).toContain('invoke_subagent')
586
+ expect(hosts).toContain('Codex')
587
+ })
588
+
589
+ test('stage 7 runs the peer through magpie peer-run rather than codex exec', async () => {
590
+ const text = await readFile(SKILL, 'utf8')
591
+ expect(text).toContain('magpie peer-run')
592
+ expect(text).not.toContain('codex exec <')
593
+ })
594
+
595
+ test('references/peer-review.md opens its same-family preamble as a fresh independent reviewer', async () => {
596
+ const text = await readFile(ref('peer-review.md'), 'utf8')
597
+ const block =
598
+ text.match(/^(`{3,4})magpie-peer-review-same-family-preamble\n([\s\S]*?)\n\1[ \t]*$/m)?.[2] ?? ''
599
+ expect(block).toContain('fresh, independent second-opinion reviewer')
600
+ })
601
+
602
+ test('only the Hosts section names a host-specific subagent type', async () => {
603
+ const text = await readFile(SKILL, 'utf8')
604
+ expect(text.replace(hostsSection(text), '')).not.toContain('general-purpose')
605
+ const dir = new URL('../../references/', import.meta.url).pathname
606
+ for (const name of await readdir(dir)) {
607
+ expect(await readFile(ref(name), 'utf8')).not.toContain('general-purpose')
608
+ }
609
+ })
610
+
611
+ test('stage 7 fallback prepends the same-family preamble to the batch prompt file', async () => {
612
+ const section = await skillSection('### 7. Peer review')
613
+ expect(section).toMatch(/prepend the `magpie-peer-review-same-family-preamble`[^\n]*peer-prompt/)
614
+ })
@@ -0,0 +1,146 @@
1
+ import { readFile, writeFile } from 'node:fs/promises'
2
+ import { join } from 'node:path'
3
+
4
+ export type PeerProvider = 'codex' | 'claude' | 'agy'
5
+
6
+ const PROVIDERS: readonly PeerProvider[] = ['codex', 'claude', 'agy']
7
+
8
+ const BIN_VARS: Record<PeerProvider, string> = {
9
+ codex: 'MAGPIE_CODEX_BIN',
10
+ claude: 'MAGPIE_CLAUDE_BIN',
11
+ agy: 'MAGPIE_AGY_BIN',
12
+ }
13
+
14
+ const DEFAULT_TIMEOUT_SEC = 600
15
+
16
+ export type PeerConfig = { provider: PeerProvider; model: string | null; timeoutSec: number; bin: string }
17
+
18
+ export function peerConfigFromEnv(env: Record<string, string | undefined>): PeerConfig {
19
+ const name = env.MAGPIE_PEER || 'codex'
20
+ const provider = PROVIDERS.find((p) => p === name)
21
+ if (!provider) {
22
+ throw new Error(`unknown MAGPIE_PEER ${name} (want one of ${PROVIDERS.join(', ')})`)
23
+ }
24
+ let timeoutSec = DEFAULT_TIMEOUT_SEC
25
+ const rawTimeout = env.MAGPIE_PEER_TIMEOUT
26
+ if (rawTimeout !== undefined && rawTimeout !== '') {
27
+ timeoutSec = Number(rawTimeout)
28
+ if (!Number.isFinite(timeoutSec) || timeoutSec <= 0) {
29
+ throw new Error(`invalid MAGPIE_PEER_TIMEOUT ${rawTimeout} (want a positive number of seconds)`)
30
+ }
31
+ }
32
+ return {
33
+ provider,
34
+ model: env.MAGPIE_PEER_MODEL || null,
35
+ timeoutSec,
36
+ bin: env[BIN_VARS[provider]] || provider,
37
+ }
38
+ }
39
+
40
+ export function peerArgv(
41
+ provider: PeerProvider,
42
+ bin: string,
43
+ model: string | null,
44
+ prompt: string,
45
+ ): { argv: string[]; stdin: string | null } {
46
+ if (provider === 'codex') {
47
+ return { argv: [bin, 'exec', ...(model ? ['-m', model] : []), '-'], stdin: prompt }
48
+ }
49
+ if (provider === 'claude') {
50
+ return { argv: [bin, '-p', ...(model ? ['--model', model] : [])], stdin: prompt }
51
+ }
52
+ // agy reads no prompt from stdin, so it goes in as the -p argument.
53
+ return { argv: [bin, '-p', prompt, ...(model ? ['--model', model] : [])], stdin: null }
54
+ }
55
+
56
+ export function killProviderGroup(pid: number): void {
57
+ try {
58
+ process.kill(-pid, 'SIGKILL')
59
+ } catch (err) {
60
+ // The group exiting on its own between the check and the kill is the goal reached.
61
+ if ((err as NodeJS.ErrnoException).code !== 'ESRCH') throw err
62
+ }
63
+ }
64
+
65
+ export async function runPeer(
66
+ runDir: string,
67
+ batch: number | null,
68
+ env: Record<string, string | undefined>,
69
+ ): Promise<{ ok: true; outPath: string } | { ok: false; error: string }> {
70
+ let config: PeerConfig
71
+ try {
72
+ config = peerConfigFromEnv(env)
73
+ } catch (err) {
74
+ return { ok: false, error: err instanceof Error ? err.message : String(err) }
75
+ }
76
+ const suffix = batch === null ? '' : `-${batch}`
77
+ const promptPath = join(runDir, `peer-prompt${suffix}.md`)
78
+ const outPath = join(runDir, `peer${suffix}.out`)
79
+ let prompt: string
80
+ try {
81
+ prompt = await readFile(promptPath, 'utf8')
82
+ } catch (err) {
83
+ return { ok: false, error: `cannot read ${promptPath}: ${err instanceof Error ? err.message : String(err)}` }
84
+ }
85
+ const { argv, stdin } = peerArgv(config.provider, config.bin, config.model, prompt)
86
+ let proc: ReturnType<typeof Bun.spawn>
87
+ try {
88
+ // Its own process group, so a timeout can kill whatever the provider started:
89
+ // npm-installed codex and claude are node wrappers around the real process.
90
+ proc = Bun.spawn(argv, {
91
+ detached: true,
92
+ stdin: stdin === null ? 'ignore' : new Blob([stdin]),
93
+ stdout: 'pipe',
94
+ stderr: 'pipe',
95
+ })
96
+ } catch (err) {
97
+ return { ok: false, error: `cannot run ${config.bin}: ${err instanceof Error ? err.message : String(err)}` }
98
+ }
99
+ const stdoutText = new Response(proc.stdout as ReadableStream).text()
100
+ const stderrText = new Response(proc.stderr as ReadableStream).text()
101
+ let timer: ReturnType<typeof setTimeout> | undefined
102
+ const timedOut = new Promise<'timeout'>((resolve) => {
103
+ timer = setTimeout(() => resolve('timeout'), config.timeoutSec * 1000)
104
+ })
105
+ // The detached group no longer receives the terminal's Ctrl-C or hangup, so an
106
+ // interrupt has to stop the provider by hand or it keeps running and spending tokens.
107
+ const pid = proc.pid
108
+ const stopOnInterrupt = (code: number) => () => {
109
+ killProviderGroup(pid)
110
+ process.exit(code)
111
+ }
112
+ const onSigint = stopOnInterrupt(130)
113
+ const onSigterm = stopOnInterrupt(143)
114
+ const onSighup = stopOnInterrupt(129)
115
+ process.on('SIGINT', onSigint)
116
+ process.on('SIGTERM', onSigterm)
117
+ process.on('SIGHUP', onSighup)
118
+ try {
119
+ const outcome = await Promise.race([proc.exited, timedOut])
120
+ // A background child the provider left behind would hold the pipes open and
121
+ // outlive peer-run, so the group goes as soon as the provider is done.
122
+ if (outcome !== 'timeout') killProviderGroup(pid)
123
+ // A child that left the group escapes that kill and can still hold the pipes,
124
+ // so the time limit bounds the drain too.
125
+ const output = outcome === 'timeout' ? 'timeout' : await Promise.race([Promise.all([stdoutText, stderrText]), timedOut])
126
+ if (output === 'timeout') {
127
+ // A grandchild can hold the pipes open until it is reaped, so the pending
128
+ // reads are abandoned rather than awaited.
129
+ killProviderGroup(pid)
130
+ await proc.exited
131
+ return { ok: false, error: `timed out after ${config.timeoutSec}s` }
132
+ }
133
+ const [stdout, stderr] = output
134
+ if (outcome !== 0) {
135
+ const firstLine = stderr.split('\n').find((line) => line.trim() !== '')
136
+ return { ok: false, error: firstLine ?? `${config.bin} exited with code ${outcome}` }
137
+ }
138
+ await writeFile(outPath, stdout)
139
+ return { ok: true, outPath }
140
+ } finally {
141
+ clearTimeout(timer)
142
+ process.off('SIGINT', onSigint)
143
+ process.off('SIGTERM', onSigterm)
144
+ process.off('SIGHUP', onSighup)
145
+ }
146
+ }
@@ -1,9 +1,6 @@
1
- export type Deps = {
2
- bun: string
3
- gh: string
4
- codex: string
5
- git: string
6
- }
1
+ import { type PeerProvider, peerConfigFromEnv } from './peer-run.ts'
2
+
3
+ export type Deps = { bun: string; gh: string; git: string } & Partial<Record<PeerProvider, string>>
7
4
 
8
5
  export type PreflightResult = {
9
6
  ok: boolean
@@ -11,19 +8,19 @@ export type PreflightResult = {
11
8
  missing: string[]
12
9
  /** Optional binaries that did not resolve; these only degrade features, they never abort. */
13
10
  missingOptional: string[]
14
- resolved: Record<keyof Deps, string | null>
11
+ resolved: Partial<Record<keyof Deps, string | null>>
15
12
  }
16
13
 
17
- // codex only powers the optional peer-review stage; a missing codex degrades that
18
- // stage to skipped rather than blocking the whole run.
19
- const OPTIONAL_DEPS: ReadonlySet<keyof Deps> = new Set<keyof Deps>(['codex'])
14
+ // The peer provider only powers the optional peer-review stage; a missing one
15
+ // degrades that stage to a subagent of the host's own model family rather than
16
+ // blocking the run.
17
+ const OPTIONAL_DEPS: ReadonlySet<keyof Deps> = new Set<keyof Deps>(['codex', 'claude', 'agy'])
20
18
 
21
19
  export async function preflight(deps: Deps): Promise<PreflightResult> {
22
- const resolved: Record<keyof Deps, string | null> = {
23
- bun: Bun.which(deps.bun),
24
- gh: Bun.which(deps.gh),
25
- codex: Bun.which(deps.codex),
26
- git: Bun.which(deps.git),
20
+ const resolved: Partial<Record<keyof Deps, string | null>> = {}
21
+ for (const key of Object.keys(deps) as Array<keyof Deps>) {
22
+ const bin = deps[key]
23
+ if (bin !== undefined) resolved[key] = Bun.which(bin)
27
24
  }
28
25
  const unresolved = (Object.keys(resolved) as Array<keyof Deps>).filter(
29
26
  (k) => resolved[k] === null,
@@ -37,6 +34,8 @@ const HINTS: Record<string, string> = {
37
34
  bun: 'bun: install from https://bun.sh',
38
35
  gh: 'gh: install from https://cli.github.com (run `gh auth login` after)',
39
36
  codex: 'codex: install the Codex CLI per Codex docs (run `codex auth login` after)',
37
+ claude: 'claude: install Claude Code per its docs (run `claude` once to log in)',
38
+ agy: 'agy: install the Antigravity CLI per its docs and log in',
40
39
  git: 'git: install via your package manager',
41
40
  }
42
41
 
@@ -44,11 +43,12 @@ export function renderInstallHint(missing: string[]): string {
44
43
  return missing.map((m) => HINTS[m] ?? `${m}: not found on PATH`).join('\n')
45
44
  }
46
45
 
47
- export function defaultDeps(): Deps {
46
+ export function defaultDeps(env: Record<string, string | undefined> = process.env): Deps {
47
+ const peer = peerConfigFromEnv(env)
48
48
  return {
49
- bun: process.env.MAGPIE_BUN_BIN || 'bun',
50
- gh: process.env.MAGPIE_GH_BIN || 'gh',
51
- codex: process.env.MAGPIE_CODEX_BIN || 'codex',
52
- git: process.env.MAGPIE_GIT_BIN || 'git',
49
+ bun: env.MAGPIE_BUN_BIN || 'bun',
50
+ gh: env.MAGPIE_GH_BIN || 'gh',
51
+ git: env.MAGPIE_GIT_BIN || 'git',
52
+ [peer.provider]: peer.bin,
53
53
  }
54
54
  }
@@ -24,7 +24,13 @@ async function logLine(runDir: string, entry: Record<string, unknown>): Promise<
24
24
  }
25
25
 
26
26
  export async function runSetup(input: RunSetupInput): Promise<number> {
27
- const deps = input.deps ?? defaultDeps()
27
+ let deps: Deps
28
+ try {
29
+ deps = input.deps ?? defaultDeps()
30
+ } catch (err) {
31
+ process.stderr.write(`magpie: ${err instanceof Error ? err.message : String(err)}\n`)
32
+ return 2
33
+ }
28
34
  // Absolute so target.json and every git call agree on the repo whatever the cwd.
29
35
  const repoPath = resolve(input.repoPath)
30
36
  // Resolved once so the inside-repo guard checks the same path mkdir creates:
@@ -1,11 +1,13 @@
1
1
  {
2
2
  "name": "magpie",
3
- "version": "0.17.0",
4
- "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.",
3
+ "version": "0.19.0",
4
+ "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 through a configured provider (codex, claude or agy) with a subagent fallback when the provider 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.",
5
5
  "author": "iceinvein",
6
6
  "type": "prompt",
7
7
  "tools": [
8
- "claude"
8
+ "claude",
9
+ "codex",
10
+ "antigravity"
9
11
  ],
10
12
  "files": {
11
13
  "prompt": "SKILL.md"
@@ -34,6 +36,22 @@
34
36
  "bundleRoot": ".claude/skills/magpie",
35
37
  "postinstall": "install.sh",
36
38
  "postremove": "uninstall.sh"
39
+ },
40
+ "codex": {
41
+ "prompt": ".agents/skills/magpie/SKILL.md",
42
+ "bundleRoot": ".agents/skills/magpie",
43
+ "postinstall": "install.sh",
44
+ "postremove": "uninstall.sh"
45
+ },
46
+ "antigravity": {
47
+ "prompt": ".agents/skills/magpie/SKILL.md",
48
+ "bundleRoot": ".agents/skills/magpie",
49
+ "postinstall": "install.sh",
50
+ "postremove": "uninstall.sh",
51
+ "global": {
52
+ "prompt": ".gemini/config/skills/magpie/SKILL.md",
53
+ "bundleRoot": ".gemini/config/skills/magpie"
54
+ }
37
55
  }
38
56
  }
39
57
  }