@iceinvein/agent-skills 0.24.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 (55) hide show
  1. package/README.md +4 -3
  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/README.md +14 -0
  6. package/skills/magpie/SKILL.md +42 -23
  7. package/skills/magpie/bin/magpie.ts +91 -3
  8. package/skills/magpie/evals/README.md +1 -1
  9. package/skills/magpie/evals/post-folds-selection-events/fixture.sh +35 -0
  10. package/skills/magpie/evals/post-folds-selection-events/graders/selection-read-from-magpie-view.md +6 -0
  11. package/skills/magpie/evals/post-folds-selection-events/prompt.md +2 -2
  12. package/skills/magpie/evals/rules.json +2 -2
  13. package/skills/magpie/package.json +1 -1
  14. package/skills/magpie/references/critic.md +2 -2
  15. package/skills/magpie/references/peer-review.md +7 -7
  16. package/skills/magpie/references/proof.md +2 -2
  17. package/skills/magpie/scripts/__tests__/helper.test.ts +300 -0
  18. package/skills/magpie/scripts/__tests__/labels.test.ts +46 -1
  19. package/skills/magpie/scripts/__tests__/mark-cmd.test.ts +129 -0
  20. package/skills/magpie/scripts/__tests__/peer-run.test.ts +231 -0
  21. package/skills/magpie/scripts/__tests__/post-cmd.test.ts +298 -1
  22. package/skills/magpie/scripts/__tests__/preflight.test.ts +22 -1
  23. package/skills/magpie/scripts/__tests__/render-cmd.test.ts +15 -1
  24. package/skills/magpie/scripts/__tests__/render-findings.test.ts +13 -0
  25. package/skills/magpie/scripts/__tests__/server.test.ts +96 -1
  26. package/skills/magpie/scripts/__tests__/setup-cmd.test.ts +14 -0
  27. package/skills/magpie/scripts/__tests__/skill-lint.test.ts +68 -4
  28. package/skills/magpie/scripts/__tests__/view-cmd.test.ts +219 -0
  29. package/skills/magpie/scripts/helper.js +44 -4
  30. package/skills/magpie/scripts/labels.ts +11 -0
  31. package/skills/magpie/scripts/mark-cmd.ts +56 -0
  32. package/skills/magpie/scripts/peer-run.ts +146 -0
  33. package/skills/magpie/scripts/post-cmd.ts +75 -5
  34. package/skills/magpie/scripts/preflight.ts +20 -20
  35. package/skills/magpie/scripts/render-cmd.ts +3 -1
  36. package/skills/magpie/scripts/render-findings.ts +3 -1
  37. package/skills/magpie/scripts/server.ts +31 -2
  38. package/skills/magpie/scripts/setup-cmd.ts +7 -1
  39. package/skills/magpie/scripts/view-cmd.ts +143 -0
  40. package/skills/magpie/skill.json +1 -1
  41. package/skills/sluice/SKILL.md +21 -6
  42. package/skills/sluice/references/deep-channel.md +35 -25
  43. package/skills/sluice/references/finish.md +2 -2
  44. package/skills/sluice/references/intent.md +1 -1
  45. package/skills/sluice/references/status.md +10 -4
  46. package/skills/sluice/references/test-first.md +12 -0
  47. package/skills/sluice/scripts/board-index.sh +59 -37
  48. package/skills/sluice/scripts/board.sh +72 -40
  49. package/skills/sluice/scripts/host.sh +60 -0
  50. package/skills/sluice/scripts/run-stats.sh +41 -3
  51. package/skills/sluice/scripts/session-start.sh +75 -17
  52. package/skills/sluice/scripts/status.sh +9 -5
  53. package/skills/sluice/scripts/stop-guard.sh +101 -37
  54. package/skills/sluice/scripts/transcript.sh +221 -0
  55. package/skills/sluice/skill.json +1 -1
@@ -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
+ }
@@ -504,7 +504,7 @@ export type PostReviewInput = {
504
504
 
505
505
  export type PostReviewCommentResult = {
506
506
  id: string
507
- status: 'posted' | 'failed'
507
+ status: 'posted' | 'failed' | 'already-posted' | 'unknown-id'
508
508
  message?: string
509
509
  }
510
510
 
@@ -584,13 +584,24 @@ export async function postFindingsAsReview(input: PostReviewInput): Promise<Post
584
584
  validRightLines = null
585
585
  }
586
586
 
587
+ // The report and the panel can both be open on one run, and a page rendered
588
+ // before the other posted still offers those ids, so the guard lives here
589
+ // rather than in either caller.
590
+ const priorStatus = await readPostStatus(input.runDir)
591
+ const findingIds = [...new Set(input.findingIds)]
592
+ const unknownIds = new Set(findingIds.filter((id) => !byId.has(id) && !strictById.has(id)))
593
+ const alreadyPosted = new Set(
594
+ findingIds.filter((id) => !unknownIds.has(id) && priorStatus[id] === 'posted'),
595
+ )
596
+ const toPost = findingIds.filter((id) => !unknownIds.has(id) && !alreadyPosted.has(id))
597
+
587
598
  // Partition into inline (has file + line in diff) and unplaced (everything else).
588
599
  type InlineComment = { path: string; line: number; side: 'RIGHT'; body: string }
589
600
  const inlineComments: InlineComment[] = []
590
601
  const unplacedBodies: string[] = []
591
602
  const demotedIds: string[] = []
592
603
 
593
- for (const id of input.findingIds) {
604
+ for (const id of toPost) {
594
605
  const strict = strictById.get(id)
595
606
  const f =
596
607
  byId.get(id) ??
@@ -661,7 +672,9 @@ export async function postFindingsAsReview(input: PostReviewInput): Promise<Post
661
672
 
662
673
  const demoted = new Set(demotedIds)
663
674
  const buildCommentResults = (status: 'posted' | 'failed', message?: string) =>
664
- input.findingIds.map((id) => {
675
+ findingIds.map((id): PostReviewCommentResult => {
676
+ if (unknownIds.has(id)) return { id, status: 'unknown-id' }
677
+ if (alreadyPosted.has(id)) return { id, status: 'already-posted' }
665
678
  const base: PostReviewCommentResult = { id, status }
666
679
  const m =
667
680
  message ?? (demoted.has(id) ? 'anchor not in PR diff, posted in review body' : undefined)
@@ -670,11 +683,15 @@ export async function postFindingsAsReview(input: PostReviewInput): Promise<Post
670
683
 
671
684
  const viaField = input.via ? { via: input.via } : {}
672
685
  const logEach = async (entry: Record<string, unknown>) => {
673
- for (const id of input.findingIds) {
686
+ for (const id of toPost) {
674
687
  await logEvent(input.runDir, { stage: 'post', id, ...entry, ...viaField })
675
688
  }
676
689
  }
677
690
 
691
+ if (toPost.length === 0) {
692
+ return { reviewId: null, comments: buildCommentResults('posted') }
693
+ }
694
+
678
695
  if (input.dryRun) {
679
696
  await logEach({ status: 'dry-run' })
680
697
  return {
@@ -726,7 +743,7 @@ export async function postFindingsAsReview(input: PostReviewInput): Promise<Post
726
743
 
727
744
  // Persist to post-status.json.
728
745
  const existing = await readPostStatus(input.runDir)
729
- for (const id of input.findingIds) {
746
+ for (const id of toPost) {
730
747
  existing[id] = 'posted'
731
748
  }
732
749
  existing.__lastReviewId = reviewId
@@ -1024,3 +1041,56 @@ export async function runPost(input: PostInput): Promise<PostOutcome> {
1024
1041
  await writePostStatus(input.runDir, status)
1025
1042
  return { ok: true, results, target: { repo, number: prNumber } }
1026
1043
  }
1044
+
1045
+ export type PostReviewOutcome = {
1046
+ ok: boolean
1047
+ reviewId: string | null
1048
+ results: PostReviewCommentResult[]
1049
+ error?: string
1050
+ }
1051
+
1052
+ export async function runPostReview(input: {
1053
+ runDir: string
1054
+ findingIds: string[]
1055
+ via?: PostVia
1056
+ dryRun?: boolean
1057
+ ghBin?: string
1058
+ }): Promise<PostReviewOutcome> {
1059
+ let prJson: Record<string, unknown>
1060
+ try {
1061
+ prJson = JSON.parse(await readFile(join(input.runDir, 'pr.json'), 'utf8'))
1062
+ } catch (err) {
1063
+ return {
1064
+ ok: false,
1065
+ reviewId: null,
1066
+ results: [],
1067
+ error: `Cannot read pr.json: ${(err as Error).message}`,
1068
+ }
1069
+ }
1070
+ const prNumber = Number(prJson.number)
1071
+ const headSha = typeof prJson.headRefOid === 'string' ? prJson.headRefOid : ''
1072
+ const repo = typeof prJson.url === 'string' ? parseRepoFromUrl(prJson.url) : null
1073
+ if (!Number.isFinite(prNumber) || !headSha || !repo) {
1074
+ return {
1075
+ ok: false,
1076
+ reviewId: null,
1077
+ results: [],
1078
+ error: `Missing PR target (number=${prNumber}, headSha=${!!headSha}, repo=${repo ?? 'unknown'}). Re-run setup to refresh pr.json.`,
1079
+ }
1080
+ }
1081
+
1082
+ const result = await postFindingsAsReview({
1083
+ runDir: input.runDir,
1084
+ findingIds: input.findingIds,
1085
+ prNumber,
1086
+ headSha,
1087
+ repo,
1088
+ ...(input.ghBin ? { ghBin: input.ghBin } : {}),
1089
+ ...(input.dryRun ? { dryRun: true } : {}),
1090
+ ...(input.via ? { via: input.via } : {}),
1091
+ })
1092
+ // Only a gh call that created no review marks its ids failed; ids already
1093
+ // posted and dry runs send nothing and so cannot fail.
1094
+ const ok = !result.comments.some((c) => c.status === 'failed')
1095
+ return { ok, reviewId: result.reviewId, results: result.comments }
1096
+ }
@@ -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
  }
@@ -1,7 +1,7 @@
1
1
  import { readdir, readFile } from 'node:fs/promises'
2
2
  import { basename, join } from 'node:path'
3
3
  import { readHistory } from './history.ts'
4
- import { readDismissed } from './labels.ts'
4
+ import { foldSelection, readDismissed, readJsonLines } from './labels.ts'
5
5
  import { describePreviousPosted } from './previous-findings.ts'
6
6
  import { readProofDropped } from './proof-cmd.ts'
7
7
  import { type PostStatusMap, parseClosingIssues, renderFindingsToDisk } from './render-findings.ts'
@@ -155,6 +155,7 @@ export async function runRender(
155
155
  null,
156
156
  )) ?? undefined
157
157
  const dismissed = await readDismissed(runDir)
158
+ const selectedIds = foldSelection(await readJsonLines(join(runDir, 'state', 'events')))
158
159
  const { previous } = await readHistory(runDir)
159
160
  const previousRun = previous ? (describePreviousPosted(previous) ?? undefined) : undefined
160
161
  const unreviewed = await readShardCoverage(runDir)
@@ -175,6 +176,7 @@ export async function runRender(
175
176
  ...(unreviewed ? { unreviewed } : {}),
176
177
  disproved,
177
178
  dismissed,
179
+ selectedIds,
178
180
  topN: opts.topN ?? DEFAULT_TOP_N,
179
181
  },
180
182
  outPath,
@@ -63,6 +63,8 @@ export type RenderFindingsInput = {
63
63
  highlighter: Highlighter
64
64
  /** Finding id to dismiss reason, folded from state/events. */
65
65
  dismissed: Map<string, string>
66
+ /** Finding ids ticked in state/events. Absent where no run's events are read, so nothing is ticked. */
67
+ selectedIds?: Set<string>
66
68
  /** How many findings the issues view recommends before folding the rest. */
67
69
  topN: number
68
70
  /** Where diff.patch came from. Absent means gh, which needs no note. */
@@ -270,7 +272,7 @@ export function renderFindingsHtml(input: RenderFindingsInput): string {
270
272
  const files = input.files ?? []
271
273
  const diff = input.diff ?? ''
272
274
  const splitDiffs = splitDiffByFile(diff)
273
- const selectedIds = new Set<string>()
275
+ const selectedIds = input.selectedIds ?? new Set<string>()
274
276
  const { dismissed, topN } = input
275
277
  const briefHtml = briefBlock(input.brief, input.issues ?? [])
276
278
 
@@ -1,6 +1,6 @@
1
1
  import { appendFile, readdir, readFile, stat, unlink, writeFile } from 'node:fs/promises'
2
2
  import { join } from 'node:path'
3
- import { parseVia } from './labels.ts'
3
+ import { foldSelection, parseVia, readJsonLines } from './labels.ts'
4
4
  import { parseRepoFromUrl, postFindingsAsReview } from './post-cmd.ts'
5
5
 
6
6
  export type ServerHandle = {
@@ -45,6 +45,18 @@ async function newestScreenPath(runDir: string): Promise<string | null> {
45
45
  return bestPath
46
46
  }
47
47
 
48
+ /** post-status.json is written by the post routes; a run that has posted nothing has none. */
49
+ async function readPostStatus(runDir: string): Promise<Record<string, unknown>> {
50
+ let text: string
51
+ try {
52
+ text = await readFile(join(runDir, 'post-status.json'), 'utf8')
53
+ } catch (err) {
54
+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') return {}
55
+ throw err
56
+ }
57
+ return JSON.parse(text) as Record<string, unknown>
58
+ }
59
+
48
60
  const HELPER_PATH = new URL('./helper.js', import.meta.url).pathname
49
61
 
50
62
  async function readScreenHtml(htmlPath: string): Promise<string> {
@@ -74,6 +86,16 @@ export async function startServer(input: StartServerInput): Promise<ServerHandle
74
86
  await appendFile(events, `${body.trim()}\n`)
75
87
  return new Response('ok')
76
88
  }
89
+ if (req.method === 'GET' && url.pathname === '/selection') {
90
+ try {
91
+ const selected = foldSelection(await readJsonLines(events))
92
+ const postStatus = await readPostStatus(runDir)
93
+ const posted = Object.keys(postStatus).filter((id) => postStatus[id] === 'posted')
94
+ return Response.json({ selected: Array.from(selected), posted })
95
+ } catch (err) {
96
+ return Response.json({ error: (err as Error).message ?? String(err) }, { status: 500 })
97
+ }
98
+ }
77
99
  if (req.method === 'POST' && url.pathname === '/heartbeat') {
78
100
  return new Response('ok')
79
101
  }
@@ -164,8 +186,15 @@ export async function startServer(input: StartServerInput): Promise<ServerHandle
164
186
  dryRun: process.env.MAGPIE_DRY_RUN_POST === '1',
165
187
  ...(via ? { via } : {}),
166
188
  })
189
+ // A null reviewId is a failure only when gh was asked for a review; with
190
+ // every id already posted or no finding, nothing was sent.
191
+ const nothingSent = result.comments.every(
192
+ (c) => c.status === 'already-posted' || c.status === 'unknown-id',
193
+ )
167
194
  const status =
168
- result.reviewId == null && process.env.MAGPIE_DRY_RUN_POST !== '1' ? 502 : 200
195
+ result.reviewId == null && process.env.MAGPIE_DRY_RUN_POST !== '1' && !nothingSent
196
+ ? 502
197
+ : 200
169
198
  return new Response(JSON.stringify(result), {
170
199
  status,
171
200
  headers: { 'content-type': 'application/json' },
@@ -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:
@@ -0,0 +1,143 @@
1
+ import { existsSync } from 'node:fs'
2
+ import { readFile } from 'node:fs/promises'
3
+ import { join } from 'node:path'
4
+ import { filePathMatches, parseUnifiedDiffToHunks, splitDiffByFile } from './diff-utils.ts'
5
+ import { foldSelection, readDismissed, readJsonLines } from './labels.ts'
6
+ import { rankActionable } from './render-issues-list.ts'
7
+ import { readTarget } from './target.ts'
8
+ import { type PostStatusMap, parseFinding, type ReviewFinding } from './types.ts'
9
+
10
+ export type ViewFinding = {
11
+ id: string
12
+ file: string
13
+ line: number | null
14
+ severity: string
15
+ action: string
16
+ title: string
17
+ description: string
18
+ suggestion: { body: string } | null
19
+ proof: unknown | null
20
+ hunk: string | null
21
+ fileDiff: string | null
22
+ postStatus: 'posted' | 'failed' | null
23
+ postMessage: string | null
24
+ dismissed: string | null
25
+ selected: boolean
26
+ recommended: boolean
27
+ }
28
+
29
+ export type View = {
30
+ pr: { number: number; title: string; url: string }
31
+ findings: ViewFinding[]
32
+ }
33
+
34
+ function fail(message: string): number {
35
+ process.stderr.write(`view: ${message}\n`)
36
+ return 2
37
+ }
38
+
39
+ async function readJson(path: string): Promise<unknown> {
40
+ return JSON.parse(await readFile(path, 'utf8'))
41
+ }
42
+
43
+ async function readPr(path: string): Promise<View['pr']> {
44
+ if (!existsSync(path)) throw new Error(`${path} is missing`)
45
+ const raw = await readJson(path)
46
+ if (typeof raw !== 'object' || raw === null) throw new Error(`${path}: expected an object`)
47
+ const { number, title, url } = raw as Record<string, unknown>
48
+ if (typeof number !== 'number') throw new Error(`${path}: number must be a number`)
49
+ if (typeof title !== 'string') throw new Error(`${path}: title must be a string`)
50
+ if (typeof url !== 'string') throw new Error(`${path}: url must be a string`)
51
+ return { number, title, url }
52
+ }
53
+
54
+ /** The hunk, header included, whose new-side range holds `line`. */
55
+ function hunkAt(section: string, line: number): string | null {
56
+ const hunks = parseUnifiedDiffToHunks(section)
57
+ const blocks = section.split(/^(?=@@ )/m).filter((block) => block.startsWith('@@ '))
58
+ const index = hunks.findIndex((h) => line >= h.newStart && line < h.newStart + h.newLines)
59
+ return blocks[index] ?? null
60
+ }
61
+
62
+ function postFields(status: PostStatusMap[string] | undefined): {
63
+ postStatus: ViewFinding['postStatus']
64
+ postMessage: string | null
65
+ } {
66
+ if (status === 'posted') return { postStatus: 'posted', postMessage: null }
67
+ if (status?.status === 'failed') return { postStatus: 'failed', postMessage: status.message }
68
+ return { postStatus: null, postMessage: null }
69
+ }
70
+
71
+ export async function runView(runDir: string, top: number): Promise<number> {
72
+ try {
73
+ const target = await readTarget(runDir)
74
+ if (target.mode === 'local') return fail(`${runDir} is a local run; there is nothing to post`)
75
+ } catch (err) {
76
+ return fail(err instanceof Error ? err.message : String(err))
77
+ }
78
+ const findingsPath = join(runDir, 'findings.final.json')
79
+ if (!existsSync(findingsPath)) {
80
+ process.stderr.write(`view: ${findingsPath} is missing\n`)
81
+ return 4
82
+ }
83
+
84
+ let findings: ReviewFinding[]
85
+ let pr: View['pr']
86
+ let selected: Set<string>
87
+ let dismissed: Map<string, string>
88
+ try {
89
+ const raw = await readJson(findingsPath)
90
+ if (!Array.isArray(raw)) throw new Error(`${findingsPath}: expected an array of findings`)
91
+ findings = raw.map(parseFinding)
92
+ pr = await readPr(join(runDir, 'pr.json'))
93
+ selected = foldSelection(await readJsonLines(join(runDir, 'state', 'events')))
94
+ dismissed = await readDismissed(runDir)
95
+ } catch (err) {
96
+ return fail(err instanceof Error ? err.message : String(err))
97
+ }
98
+
99
+ const statusPath = join(runDir, 'post-status.json')
100
+ let postStatus: PostStatusMap = {}
101
+ if (existsSync(statusPath)) {
102
+ try {
103
+ postStatus = (await readJson(statusPath)) as PostStatusMap
104
+ } catch (err) {
105
+ return fail(
106
+ `${statusPath} is not valid JSON: ${err instanceof Error ? err.message : String(err)}`,
107
+ )
108
+ }
109
+ }
110
+ const diffPath = join(runDir, 'diff.patch')
111
+ const sections = existsSync(diffPath)
112
+ ? splitDiffByFile(await readFile(diffPath, 'utf8'))
113
+ : new Map<string, string>()
114
+ const recommended = new Set(
115
+ rankActionable(findings, postStatus, dismissed, top).recommended.map((f) => f.id),
116
+ )
117
+
118
+ const view: View = {
119
+ pr,
120
+ findings: findings.map((f): ViewFinding => {
121
+ const fileDiff = [...sections].find(([path]) => filePathMatches(path, f.file))?.[1] ?? null
122
+ return {
123
+ id: f.id,
124
+ file: f.file,
125
+ line: f.line,
126
+ severity: f.severity,
127
+ action: f.risk.action,
128
+ title: f.title,
129
+ description: f.description,
130
+ suggestion: f.suggestion ? { body: f.suggestion.body } : null,
131
+ proof: f.proof ?? null,
132
+ hunk: fileDiff !== null && f.line !== null ? hunkAt(fileDiff, f.line) : null,
133
+ fileDiff,
134
+ ...postFields(postStatus[f.id]),
135
+ dismissed: dismissed.get(f.id) ?? null,
136
+ selected: selected.has(f.id),
137
+ recommended: recommended.has(f.id),
138
+ }
139
+ }),
140
+ }
141
+ process.stdout.write(`${JSON.stringify(view)}\n`)
142
+ return 0
143
+ }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "magpie",
3
- "version": "0.16.1",
3
+ "version": "0.18.0",
4
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.",
5
5
  "author": "iceinvein",
6
6
  "type": "prompt",
@@ -31,9 +31,10 @@ Two subsystems is `main`; the third is what makes it `deep`.
31
31
  `deep` stops: once for design sign-off before code, once for the plan and
32
32
  pre-flight together before Task 1. A stop ends your turn.
33
33
 
34
- A choice that is your partner's to make goes to them through `AskUserQuestion`
35
- wherever the harness has it, at a stop or between them: options to pick from,
36
- your recommendation first, not a paragraph or a lettered list to reply to.
34
+ A choice that is your partner's to make goes to them through the question tool
35
+ (`## Hosts` names it per host) wherever the harness has it, at a stop or
36
+ between them: options to pick from, your recommendation first, not a paragraph
37
+ or a lettered list to reply to.
37
38
  Asking is not itself a stop, however many options it carried, because the
38
39
  answer comes back to you and the run never left your hands. So at a stop, ask
39
40
  with the tool, then end the turn once the answers are in.
@@ -73,7 +74,7 @@ One line each. Read the reference only on friction: the moment you notice
73
74
  yourself wanting to skip the rule, or arguing that this one is the exception.
74
75
 
75
76
  - **Agree intent** before building. One question at a time, through
76
- `AskUserQuestion`. Propose approaches with a recommendation, not a survey.
77
+ the question tool. Propose approaches with a recommendation, not a survey.
77
78
  `main` agrees in a message, `deep` writes it down. `references/intent.md`
78
79
  - **Test first.** The test comes before the code; run it while it should
79
80
  still be failing, then write the least code that turns it green. Skip that
@@ -129,7 +130,7 @@ Design to `docs/specs/YYYY-MM-DD-<topic>.md`, plan to
129
130
  `docs/plans/YYYY-MM-DD-<topic>.md`, unless the repo has a convention or
130
131
  your partner states a preference. Get the design signed off before code. When
131
132
  the design's shape turns on a fork only your partner can settle, ask that one
132
- question through `AskUserQuestion`, with your recommendation, before the design
133
+ question through the question tool, with your recommendation, before the design
133
134
  is written. `references/deep-channel.md` has the test for what counts.
134
135
 
135
136
  Read the repo before the walk and before any fork question: prior designs, the
@@ -209,7 +210,7 @@ instead of to the branch at large.
209
210
 
210
211
  Pre-flight rides in that same stop: which flagged tasks get a reviewer, which
211
212
  mechanical ones the plan marked for low effort, and whether the work runs
212
- in a worktree. Ask them through `AskUserQuestion`, one question each with the
213
+ in a worktree. Ask them through the question tool, one question each with the
213
214
  counts in the options, never as a paragraph or a lettered list, then end the
214
215
  turn on the answers. Task 1 opens on their next
215
216
  instruction, and an answer that already carries one is that instruction. A
@@ -255,3 +256,17 @@ The test is whether that pipeline governs the work in front of you, not whether
255
256
  a plugin is installed. A repo whose own instructions mandate the sequence rules
256
257
  this router out exactly as the plugin does, with the plugin disabled or absent.
257
258
  Stand down and say so once, in the same breath you would have named a channel.
259
+
260
+ ## Hosts
261
+
262
+ The rest of this skill and its references name a tool by what it does: the
263
+ question tool, dispatch a subagent, the explorer, the worktree. This table is
264
+ the one place that says what each is called on each host.
265
+
266
+ | | Claude Code | Codex | Antigravity |
267
+ |---|---|---|---|
268
+ | Question tool | `AskUserQuestion` | `request_user_input`: at most three options a question, recommendation first, and at most three questions a call, so a longer set goes out in successive calls | `ask_question` |
269
+ | Dispatch a subagent | the Agent tool | `spawn_agent`, then `wait_agent` | `invoke_subagent` |
270
+ | Explorer | the Explore agent | `spawn_agent` told to read and write nothing (Codex shows no built-in explorer type) | `invoke_subagent` told to read and write nothing |
271
+ | Low effort | `subagent_type: sluice-implementer-low` (`sluice:sluice-implementer-low` under a plugin install) | `spawn_agent` with `reasoning_effort: "low"` and `fork_turns: "none"`: Codex takes an effort override only with `fork_turns: "none"`, and only when skill instructions ask, which this row is | not available: the task runs at the session's effort, and pre-flight says so |
272
+ | Worktree | the harness's worktree tool; cut by hand under `.claude/worktrees/` | `git worktree add` under `.sluice/worktrees/` | `Workspace: branch` for implementers, `git worktree add` under `.sluice/worktrees/` for the controller |