@iceinvein/agent-skills 0.23.14 → 0.25.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 (76) hide show
  1. package/README.md +4 -2
  2. package/package.json +1 -1
  3. package/skills/index.json +7 -1
  4. package/skills/magpie/README.md +14 -0
  5. package/skills/magpie/SKILL.md +7 -5
  6. package/skills/magpie/bin/magpie.ts +63 -3
  7. package/skills/magpie/evals/README.md +1 -1
  8. package/skills/magpie/evals/post-folds-selection-events/fixture.sh +35 -0
  9. package/skills/magpie/evals/post-folds-selection-events/graders/selection-read-from-magpie-view.md +6 -0
  10. package/skills/magpie/evals/post-folds-selection-events/prompt.md +2 -2
  11. package/skills/magpie/evals/rules.json +2 -2
  12. package/skills/magpie/package.json +1 -1
  13. package/skills/magpie/scripts/__tests__/helper.test.ts +300 -0
  14. package/skills/magpie/scripts/__tests__/labels.test.ts +46 -1
  15. package/skills/magpie/scripts/__tests__/mark-cmd.test.ts +129 -0
  16. package/skills/magpie/scripts/__tests__/post-cmd.test.ts +298 -1
  17. package/skills/magpie/scripts/__tests__/render-cmd.test.ts +15 -1
  18. package/skills/magpie/scripts/__tests__/render-findings.test.ts +13 -0
  19. package/skills/magpie/scripts/__tests__/server.test.ts +96 -1
  20. package/skills/magpie/scripts/__tests__/skill-lint.test.ts +23 -0
  21. package/skills/magpie/scripts/__tests__/view-cmd.test.ts +219 -0
  22. package/skills/magpie/scripts/helper.js +44 -4
  23. package/skills/magpie/scripts/labels.ts +11 -0
  24. package/skills/magpie/scripts/mark-cmd.ts +56 -0
  25. package/skills/magpie/scripts/post-cmd.ts +75 -5
  26. package/skills/magpie/scripts/render-cmd.ts +3 -1
  27. package/skills/magpie/scripts/render-findings.ts +3 -1
  28. package/skills/magpie/scripts/server.ts +31 -2
  29. package/skills/magpie/scripts/view-cmd.ts +143 -0
  30. package/skills/magpie/skill.json +1 -1
  31. package/skills/test-redundancy-auditor/SKILL.md +117 -0
  32. package/skills/test-redundancy-auditor/evals/README.md +35 -0
  33. package/skills/test-redundancy-auditor/evals/boundary-tests-stay-unique/case.yaml +4 -0
  34. package/skills/test-redundancy-auditor/evals/boundary-tests-stay-unique/fixture.sh +76 -0
  35. package/skills/test-redundancy-auditor/evals/boundary-tests-stay-unique/graders/auditor-fired.md +5 -0
  36. package/skills/test-redundancy-auditor/evals/boundary-tests-stay-unique/graders/nothing-deleted.md +26 -0
  37. package/skills/test-redundancy-auditor/evals/boundary-tests-stay-unique/prompt.md +11 -0
  38. package/skills/test-redundancy-auditor/evals/callers-tree-unchanged/case.yaml +4 -0
  39. package/skills/test-redundancy-auditor/evals/callers-tree-unchanged/fixture.sh +60 -0
  40. package/skills/test-redundancy-auditor/evals/callers-tree-unchanged/graders/auditor-fired.md +5 -0
  41. package/skills/test-redundancy-auditor/evals/callers-tree-unchanged/graders/output-ignores-itself.md +11 -0
  42. package/skills/test-redundancy-auditor/evals/callers-tree-unchanged/graders/source-unchanged.md +10 -0
  43. package/skills/test-redundancy-auditor/evals/callers-tree-unchanged/graders/tests-unchanged.md +10 -0
  44. package/skills/test-redundancy-auditor/evals/callers-tree-unchanged/graders/tree-unchanged.md +13 -0
  45. package/skills/test-redundancy-auditor/evals/callers-tree-unchanged/prompt.md +11 -0
  46. package/skills/test-redundancy-auditor/evals/duplicate-is-flagged/case.yaml +4 -0
  47. package/skills/test-redundancy-auditor/evals/duplicate-is-flagged/fixture.sh +60 -0
  48. package/skills/test-redundancy-auditor/evals/duplicate-is-flagged/graders/auditor-fired.md +5 -0
  49. package/skills/test-redundancy-auditor/evals/duplicate-is-flagged/graders/one-of-the-pair-deleted.md +34 -0
  50. package/skills/test-redundancy-auditor/evals/duplicate-is-flagged/prompt.md +11 -0
  51. package/skills/test-redundancy-auditor/evals/guard-test-is-kept/case.yaml +4 -0
  52. package/skills/test-redundancy-auditor/evals/guard-test-is-kept/fixture.sh +58 -0
  53. package/skills/test-redundancy-auditor/evals/guard-test-is-kept/graders/auditor-fired.md +5 -0
  54. package/skills/test-redundancy-auditor/evals/guard-test-is-kept/graders/guard-kept.md +32 -0
  55. package/skills/test-redundancy-auditor/evals/guard-test-is-kept/prompt.md +11 -0
  56. package/skills/test-redundancy-auditor/evals/mock-assertion-is-vacuous/case.yaml +4 -0
  57. package/skills/test-redundancy-auditor/evals/mock-assertion-is-vacuous/fixture.sh +73 -0
  58. package/skills/test-redundancy-auditor/evals/mock-assertion-is-vacuous/graders/auditor-fired.md +5 -0
  59. package/skills/test-redundancy-auditor/evals/mock-assertion-is-vacuous/graders/mock-test-is-vacuous.md +33 -0
  60. package/skills/test-redundancy-auditor/evals/mock-assertion-is-vacuous/prompt.md +11 -0
  61. package/skills/test-redundancy-auditor/evals/mutate-without-tool-stops/case.yaml +4 -0
  62. package/skills/test-redundancy-auditor/evals/mutate-without-tool-stops/fixture.sh +60 -0
  63. package/skills/test-redundancy-auditor/evals/mutate-without-tool-stops/graders/auditor-fired.md +5 -0
  64. package/skills/test-redundancy-auditor/evals/mutate-without-tool-stops/graders/labelled-rubric-only.md +26 -0
  65. package/skills/test-redundancy-auditor/evals/mutate-without-tool-stops/graders/nothing-installed.md +12 -0
  66. package/skills/test-redundancy-auditor/evals/mutate-without-tool-stops/prompt.md +11 -0
  67. package/skills/test-redundancy-auditor/evals/rules.json +193 -0
  68. package/skills/test-redundancy-auditor/evals/subsumed-by-broader-test/case.yaml +4 -0
  69. package/skills/test-redundancy-auditor/evals/subsumed-by-broader-test/fixture.sh +62 -0
  70. package/skills/test-redundancy-auditor/evals/subsumed-by-broader-test/graders/auditor-fired.md +5 -0
  71. package/skills/test-redundancy-auditor/evals/subsumed-by-broader-test/graders/narrow-test-subsumed.md +35 -0
  72. package/skills/test-redundancy-auditor/evals/subsumed-by-broader-test/prompt.md +11 -0
  73. package/skills/test-redundancy-auditor/references/findings-format.md +71 -0
  74. package/skills/test-redundancy-auditor/references/mutation-mode.md +100 -0
  75. package/skills/test-redundancy-auditor/references/rubric.md +144 -0
  76. package/skills/test-redundancy-auditor/skill.json +24 -0
@@ -0,0 +1,219 @@
1
+ import { afterEach, beforeEach, expect, test } from 'bun:test'
2
+ import { cp, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
3
+ import { tmpdir } from 'node:os'
4
+ import { join } from 'node:path'
5
+ import { runView } from '../view-cmd.ts'
6
+
7
+ const FIXTURE = new URL('../../fixtures/example-pr', import.meta.url).pathname
8
+ const CLI = new URL('../../bin/magpie.ts', import.meta.url).pathname
9
+
10
+ type ViewFinding = {
11
+ id: string
12
+ hunk: string | null
13
+ fileDiff: string | null
14
+ postStatus: 'posted' | 'failed' | null
15
+ postMessage: string | null
16
+ dismissed: string | null
17
+ selected: boolean
18
+ recommended: boolean
19
+ }
20
+ type View = { pr: { number: number; title: string; url: string }; findings: ViewFinding[] }
21
+
22
+ let runDir: string
23
+
24
+ beforeEach(async () => {
25
+ runDir = await mkdtemp(join(tmpdir(), 'magpie-view-'))
26
+ await cp(FIXTURE, runDir, { recursive: true })
27
+ await writeFile(join(runDir, 'target.json'), JSON.stringify({ mode: 'pr', root: '/wt' }))
28
+ })
29
+
30
+ afterEach(async () => {
31
+ await rm(runDir, { recursive: true, force: true })
32
+ })
33
+
34
+ async function view(
35
+ args: string[] = [],
36
+ ): Promise<{ exit: number; stdout: string; stderr: string }> {
37
+ const proc = Bun.spawn(['bun', CLI, 'view', runDir, ...args], { stdout: 'pipe', stderr: 'pipe' })
38
+ const exit = await proc.exited
39
+ const stdout = await new Response(proc.stdout).text()
40
+ const stderr = await new Response(proc.stderr).text()
41
+ return { exit, stdout, stderr }
42
+ }
43
+
44
+ async function viewOk(args: string[] = []): Promise<View> {
45
+ const result = await view(args)
46
+ expect(result.stderr).toBe('')
47
+ expect(result.exit).toBe(0)
48
+ return JSON.parse(result.stdout) as View
49
+ }
50
+
51
+ function finding(v: View, id: string): ViewFinding {
52
+ const f = v.findings.find((x) => x.id === id)
53
+ if (!f) throw new Error(`no finding ${id} in view`)
54
+ return f
55
+ }
56
+
57
+ async function writeEvents(lines: string[]): Promise<void> {
58
+ await mkdir(join(runDir, 'state'), { recursive: true })
59
+ await writeFile(join(runDir, 'state', 'events'), `${lines.join('\n')}\n`)
60
+ }
61
+
62
+ test('view prints the PR number, title and url from pr.json', async () => {
63
+ const v = await viewOk()
64
+ expect(v.pr).toEqual({
65
+ number: 1337,
66
+ title: 'Migrate session store to Redis and introduce TextOnlyPrompt abstraction',
67
+ url: 'https://github.com/example/repo/pull/1337',
68
+ })
69
+ })
70
+
71
+ test('view lists findings in findings.final.json order', async () => {
72
+ const v = await viewOk()
73
+ expect(v.findings.map((f) => f.id)).toEqual([
74
+ 'security-1',
75
+ 'bugs-1',
76
+ 'perf-1',
77
+ 'code-smells-1',
78
+ 'arch-1',
79
+ 'bugs-2',
80
+ 'code-smells-2',
81
+ 'perf-2',
82
+ ])
83
+ })
84
+
85
+ test('the hunk of a finding is the diff.patch hunk whose new side holds its line', async () => {
86
+ const hunk = finding(await viewOk(), 'security-1').hunk
87
+ expect(
88
+ hunk?.startsWith('@@ -80,20 +80,35 @@ function validateToken(token: string): boolean {\n'),
89
+ ).toBe(true)
90
+ expect(hunk).toContain("+ await redis.set(key, token, 'EX', SESSION_TTL_SECONDS)")
91
+ expect(hunk).not.toContain('diff --git')
92
+ })
93
+
94
+ test('the fileDiff of a finding is the whole diff --git section of its file', async () => {
95
+ const fileDiff = finding(await viewOk(), 'security-1').fileDiff
96
+ expect(fileDiff?.startsWith('diff --git a/src/api/session.ts b/src/api/session.ts\n')).toBe(true)
97
+ expect(fileDiff).not.toContain('src/cache/invalidation.ts')
98
+ })
99
+
100
+ test('a finding in a file diff.patch does not cover has a null hunk and fileDiff', async () => {
101
+ const f = finding(await viewOk(), 'code-smells-1')
102
+ expect(f.hunk).toBeNull()
103
+ expect(f.fileDiff).toBeNull()
104
+ })
105
+
106
+ test('without diff.patch every hunk and fileDiff is null', async () => {
107
+ await rm(join(runDir, 'diff.patch'))
108
+ const v = await viewOk()
109
+ expect(v.findings.every((f) => f.hunk === null && f.fileDiff === null)).toBe(true)
110
+ })
111
+
112
+ test('a finding stored as posted has postStatus posted and no message', async () => {
113
+ const f = finding(await viewOk(), 'security-1')
114
+ expect(f.postStatus).toBe('posted')
115
+ expect(f.postMessage).toBeNull()
116
+ })
117
+
118
+ test('a finding stored as failed has postStatus failed with the stored message', async () => {
119
+ const f = finding(await viewOk(), 'perf-1')
120
+ expect(f.postStatus).toBe('failed')
121
+ expect(f.postMessage).toBe('HTTP 422: pull_request_review_thread: line out of diff')
122
+ })
123
+
124
+ test('a finding with no post record has postStatus null', async () => {
125
+ expect(finding(await viewOk(), 'bugs-1').postStatus).toBeNull()
126
+ })
127
+
128
+ test('with no events file nothing is selected', async () => {
129
+ const v = await viewOk()
130
+ expect(v.findings.filter((f) => f.selected)).toEqual([])
131
+ })
132
+
133
+ test('a select event for a finding makes it selected', async () => {
134
+ await writeEvents([JSON.stringify({ type: 'select', findingId: 'bugs-1', timestamp: 1 })])
135
+ const v = await viewOk()
136
+ expect(v.findings.filter((f) => f.selected).map((f) => f.id)).toEqual(['bugs-1'])
137
+ })
138
+
139
+ test('a dismiss event sets the finding dismissed with its reason', async () => {
140
+ await writeEvents([
141
+ JSON.stringify({ type: 'dismiss', findingId: 'bugs-2', reason: 'not-worth-it', timestamp: 1 }),
142
+ ])
143
+ const v = await viewOk()
144
+ expect(v.findings.filter((f) => f.dismissed !== null).map((f) => [f.id, f.dismissed])).toEqual([
145
+ ['bugs-2', 'not-worth-it'],
146
+ ])
147
+ })
148
+
149
+ // Risk scores from the fixture: security-1 10 (posted), bugs-1 8.8, arch-1 7.2 (posted),
150
+ // perf-1 6.4, code-smells-1 6.2, bugs-2 4.4; code-smells-2 and perf-2 are suggestions.
151
+ test('--top 2 recommends the two highest-ranked actionable findings', async () => {
152
+ const v = await viewOk(['--top', '2'])
153
+ expect(v.findings.filter((f) => f.recommended).map((f) => f.id)).toEqual(['security-1', 'bugs-1'])
154
+ })
155
+
156
+ test('a dismissed finding drops out of the recommended set', async () => {
157
+ await writeEvents([
158
+ JSON.stringify({ type: 'dismiss', findingId: 'bugs-1', reason: 'wrong', timestamp: 1 }),
159
+ ])
160
+ const v = await viewOk(['--top', '2'])
161
+ expect(v.findings.filter((f) => f.recommended).map((f) => f.id)).toEqual(['security-1', 'arch-1'])
162
+ })
163
+
164
+ test('a malformed events line exits 2 naming the line', async () => {
165
+ await writeEvents([
166
+ JSON.stringify({ type: 'select', findingId: 'bugs-1', timestamp: 1 }),
167
+ '{nope',
168
+ ])
169
+ const result = await view()
170
+ expect(result.exit).toBe(2)
171
+ expect(result.stderr).toContain(`${join(runDir, 'state', 'events')}:2 is not valid JSON`)
172
+ })
173
+
174
+ test('a malformed post-status.json exits 2 with one stderr line naming it', async () => {
175
+ await writeFile(join(runDir, 'post-status.json'), '{ not json')
176
+ const result = await view()
177
+ expect(result.exit).toBe(2)
178
+ expect(result.stderr).toStartWith(`view: ${join(runDir, 'post-status.json')}`)
179
+ expect(result.stderr.trimEnd().split('\n')).toHaveLength(1)
180
+ })
181
+
182
+ test('a run without pr.json exits 2', async () => {
183
+ await rm(join(runDir, 'pr.json'))
184
+ const result = await view()
185
+ expect(result.exit).toBe(2)
186
+ expect(result.stderr).toContain('pr.json')
187
+ })
188
+
189
+ test('a pr.json without a url exits 2', async () => {
190
+ await writeFile(join(runDir, 'pr.json'), JSON.stringify({ number: 1337, title: 'x' }))
191
+ const result = await view()
192
+ expect(result.exit).toBe(2)
193
+ expect(result.stderr).toContain('url')
194
+ })
195
+
196
+ test('--top 0 exits 2', async () => {
197
+ expect((await view(['--top', '0'])).exit).toBe(2)
198
+ })
199
+
200
+ test('--top x exits 2', async () => {
201
+ expect((await view(['--top', 'x'])).exit).toBe(2)
202
+ })
203
+
204
+ test('a local run exits 2', async () => {
205
+ await writeFile(join(runDir, 'target.json'), JSON.stringify({ mode: 'local', root: '/repo' }))
206
+ const result = await view()
207
+ expect(result.exit).toBe(2)
208
+ expect(result.stderr).toContain('local')
209
+ })
210
+
211
+ test('a run without findings.final.json exits 4', async () => {
212
+ await rm(join(runDir, 'findings.final.json'))
213
+ expect((await view()).exit).toBe(4)
214
+ })
215
+
216
+ test('runView returns 4 when findings.final.json is missing', async () => {
217
+ await rm(join(runDir, 'findings.final.json'))
218
+ expect(await runView(runDir, 10)).toBe(4)
219
+ })
@@ -218,6 +218,39 @@
218
218
  if (postSel) postSel.disabled = ids.size === 0
219
219
  }
220
220
 
221
+ // Ticks already live in state/events, so applying them must not post events
222
+ // back; posted ids get the checked, disabled state a fresh render gives them.
223
+ function applySelection(selection) {
224
+ const selected = new Set(selection.selected)
225
+ const posted = new Set(selection.posted)
226
+ for (const id of posted) applyResult({ id, status: 'posted' })
227
+ for (const cb of allCheckboxes()) {
228
+ if (cb.disabled) continue
229
+ cb.checked = selected.has(cb.dataset.findingId)
230
+ }
231
+ recountSelected()
232
+ }
233
+
234
+ async function syncSelection() {
235
+ let selection
236
+ try {
237
+ const r = await fetch('/selection')
238
+ selection = await r.json()
239
+ if (!r.ok) {
240
+ showStatus(
241
+ `Could not load selection: ${selection?.error || `HTTP ${r.status}`}`,
242
+ 'warn',
243
+ true,
244
+ )
245
+ return
246
+ }
247
+ } catch (err) {
248
+ showStatus(`Could not load selection: ${err?.message || err}`, 'warn', true)
249
+ return
250
+ }
251
+ applySelection(selection)
252
+ }
253
+
221
254
  function restoreSelection() {
222
255
  const persisted = readPersistedSelection()
223
256
  if (persisted.size === 0) return
@@ -518,7 +551,7 @@
518
551
  function applyReviewResult(result) {
519
552
  if (!result) return
520
553
  for (const c of result.comments || []) {
521
- if (c.status === 'posted') {
554
+ if (c.status === 'posted' || c.status === 'already-posted') {
522
555
  for (const el of findAnnotation(c.id)) {
523
556
  el.setAttribute('data-posted', 'true')
524
557
  const chip = el.querySelector('.status-chip')
@@ -544,12 +577,14 @@
544
577
  }
545
578
  updateSelectedCount()
546
579
  const okCount = (result.comments || []).filter((c) => c.status === 'posted').length
580
+ const alreadyCount = (result.comments || []).filter((c) => c.status === 'already-posted').length
547
581
  const failCount = (result.comments || []).filter((c) => c.status === 'failed').length
548
582
  const reviewBit = result.reviewId ? ` (review ${result.reviewId})` : ''
583
+ const alreadyBit = alreadyCount > 0 ? `, ${alreadyCount} already posted` : ''
549
584
  if (failCount === 0) {
550
- showStatus(`Posted ${okCount}${reviewBit}.`, 'ok')
585
+ showStatus(`Posted ${okCount}${alreadyBit}${reviewBit}.`, 'ok')
551
586
  } else {
552
- showStatus(`Posted ${okCount}, ${failCount} failed${reviewBit}.`, 'warn', true)
587
+ showStatus(`Posted ${okCount}${alreadyBit}, ${failCount} failed${reviewBit}.`, 'warn', true)
553
588
  }
554
589
  }
555
590
 
@@ -791,7 +826,9 @@
791
826
  }
792
827
  })
793
828
 
794
- restoreSelection()
829
+ // While live, state/events holds the ticks (syncSelection); localStorage
830
+ // seeds only a report opened with no server behind it.
831
+ if (!isLive) restoreSelection()
795
832
  recountSelected()
796
833
  }
797
834
 
@@ -807,6 +844,9 @@
807
844
  if (!isLive) document.documentElement.dataset.mode = 'archived'
808
845
  bind()
809
846
  if (isLive) {
847
+ // Switching back from the terminal is when panel ticks may have changed.
848
+ void syncSelection()
849
+ window.addEventListener('focus', () => void syncSelection())
810
850
  setInterval(() => {
811
851
  fetch('/heartbeat', { method: 'POST' }).catch(() => {})
812
852
  }, 30_000)
@@ -76,6 +76,17 @@ export function foldLabels(input: {
76
76
  })
77
77
  }
78
78
 
79
+ /** Last select, deselect or dismiss per id wins; a dismissed finding is not one to post. */
80
+ export function foldSelection(events: Array<Record<string, unknown>>): Set<string> {
81
+ const selected = new Set<string>()
82
+ for (const event of events) {
83
+ if (typeof event.findingId !== 'string') continue
84
+ if (event.type === 'select') selected.add(event.findingId)
85
+ else if (event.type === 'deselect' || event.type === 'dismiss') selected.delete(event.findingId)
86
+ }
87
+ return selected
88
+ }
89
+
79
90
  export async function readJsonLines(path: string): Promise<Array<Record<string, unknown>>> {
80
91
  let text: string
81
92
  try {
@@ -0,0 +1,56 @@
1
+ import { existsSync } from 'node:fs'
2
+ import { appendFile, mkdir, readFile } from 'node:fs/promises'
3
+ import { join } from 'node:path'
4
+ import { DISMISS_REASONS } from './labels.ts'
5
+ import { parseFinding } from './types.ts'
6
+
7
+ export const MARK_VERBS = ['select', 'deselect', 'dismiss', 'undismiss'] as const
8
+
9
+ function fail(message: string): number {
10
+ process.stderr.write(`mark: ${message}\n`)
11
+ return 2
12
+ }
13
+
14
+ /** Appends one event in the shape the HTML report's POST /events writes. */
15
+ export async function runMark(input: {
16
+ runDir: string
17
+ id: string
18
+ verb: string
19
+ reason?: string
20
+ }): Promise<number> {
21
+ const verb = MARK_VERBS.find((v) => v === input.verb)
22
+ if (!verb) return fail(`unknown action ${input.verb} (want ${MARK_VERBS.join('|')})`)
23
+ // readDismissed throws on a dismiss line with an unknown reason, so one must never be written.
24
+ const reason = DISMISS_REASONS.find((r) => r === input.reason)
25
+ if (verb === 'dismiss' && !reason) {
26
+ return fail(`invalid dismiss reason ${input.reason} (want ${DISMISS_REASONS.join('|')})`)
27
+ }
28
+ if (verb !== 'dismiss' && input.reason !== undefined) {
29
+ return fail(
30
+ `unexpected ${input.reason} after ${verb} (usage: mark <run-dir> <id> select|deselect|undismiss | dismiss <reason>)`,
31
+ )
32
+ }
33
+
34
+ const findingsPath = join(input.runDir, 'findings.final.json')
35
+ if (!existsSync(findingsPath)) return fail(`${findingsPath} is missing`)
36
+ let ids: string[]
37
+ try {
38
+ const raw: unknown = JSON.parse(await readFile(findingsPath, 'utf8'))
39
+ if (!Array.isArray(raw)) throw new Error(`${findingsPath}: expected an array of findings`)
40
+ ids = raw.map((f) => parseFinding(f).id)
41
+ } catch (err) {
42
+ return fail(err instanceof Error ? err.message : String(err))
43
+ }
44
+ if (!ids.includes(input.id)) return fail(`no finding ${input.id} in ${findingsPath}`)
45
+
46
+ const event = {
47
+ type: verb,
48
+ findingId: input.id,
49
+ ...(verb === 'dismiss' ? { reason } : {}),
50
+ timestamp: Date.now(),
51
+ }
52
+ const stateDir = join(input.runDir, 'state')
53
+ await mkdir(stateDir, { recursive: true })
54
+ await appendFile(join(stateDir, 'events'), `${JSON.stringify(event)}\n`)
55
+ return 0
56
+ }
@@ -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,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' },