@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
@@ -1,5 +1,6 @@
1
1
  import { afterEach, beforeEach, expect, test } from 'bun:test'
2
- import { mkdir, mkdtemp, readFile, rm, utimes, writeFile } from 'node:fs/promises'
2
+ import { existsSync } from 'node:fs'
3
+ import { cp, mkdir, mkdtemp, readFile, rm, utimes, writeFile } from 'node:fs/promises'
3
4
  import { tmpdir } from 'node:os'
4
5
  import { join } from 'node:path'
5
6
  import { type ServerHandle, startServer } from '../server.ts'
@@ -299,3 +300,97 @@ test('POST /post with an unrecognised via still posts and logs no via', async ()
299
300
  expect(entries).toHaveLength(1)
300
301
  expect('via' in (entries[0] ?? {})).toBe(false)
301
302
  })
303
+
304
+ test('POST /api/post-review answers an already-posted id already-posted and sends no gh call for it', async () => {
305
+ const ghDir = await mkdtemp(join(tmpdir(), 'magpie-server-gh-'))
306
+ const ghBin = join(ghDir, 'recording-gh.sh')
307
+ const callsPath = join(ghDir, 'gh-calls')
308
+ await writeFile(ghBin, `#!/usr/bin/env bash\ncat >> '${callsPath}'\necho '{"id": 77}'\n`)
309
+ await Bun.spawn(['chmod', '+x', ghBin]).exited
310
+ const previousGh = process.env.MAGPIE_GH_BIN
311
+ process.env.MAGPIE_GH_BIN = ghBin
312
+ try {
313
+ await seedPostable('findings.json')
314
+ await writeFile(join(runDir, 'post-status.json'), JSON.stringify({ 'sec-1': 'posted' }))
315
+ server = await startServer({ runDir, idleMs: 60_000 })
316
+ const res = await fetch(`${server.url}/api/post-review`, {
317
+ method: 'POST',
318
+ headers: { 'content-type': 'application/json' },
319
+ body: JSON.stringify({ findingIds: ['sec-1'], via: 'selected' }),
320
+ })
321
+ const body = (await res.json()) as { comments: Array<{ id: string; status: string }> }
322
+ expect(body.comments).toEqual([{ id: 'sec-1', status: 'already-posted' }])
323
+ expect(existsSync(callsPath)).toBe(false)
324
+ } finally {
325
+ if (previousGh === undefined) delete process.env.MAGPIE_GH_BIN
326
+ else process.env.MAGPIE_GH_BIN = previousGh
327
+ await rm(ghDir, { recursive: true, force: true })
328
+ }
329
+ })
330
+
331
+ test('GET /selection folds the posted events and lists the posted ids', async () => {
332
+ await cp(new URL('../../fixtures/example-pr', import.meta.url).pathname, runDir, {
333
+ recursive: true,
334
+ })
335
+ server = await startServer({ runDir, idleMs: 60_000 })
336
+ for (const [type, findingId] of [
337
+ ['select', 'bugs-1'],
338
+ ['select', 'code-smells-1'],
339
+ ['deselect', 'bugs-1'],
340
+ ]) {
341
+ await fetch(`${server.url}/events`, {
342
+ method: 'POST',
343
+ headers: { 'Content-Type': 'application/json' },
344
+ body: JSON.stringify({ type, findingId, timestamp: 1 }),
345
+ })
346
+ }
347
+ const res = await fetch(`${server.url}/selection`)
348
+ expect(res.status).toBe(200)
349
+ expect(await res.json()).toEqual({
350
+ selected: ['code-smells-1'],
351
+ posted: ['security-1', 'arch-1'],
352
+ })
353
+ })
354
+
355
+ async function withGh(script: string, run: () => Promise<void>): Promise<void> {
356
+ const ghDir = await mkdtemp(join(tmpdir(), 'magpie-server-gh-'))
357
+ const ghBin = join(ghDir, 'gh.sh')
358
+ await writeFile(ghBin, `#!/usr/bin/env bash\n${script}\n`)
359
+ await Bun.spawn(['chmod', '+x', ghBin]).exited
360
+ const previousGh = process.env.MAGPIE_GH_BIN
361
+ process.env.MAGPIE_GH_BIN = ghBin
362
+ try {
363
+ await run()
364
+ } finally {
365
+ if (previousGh === undefined) delete process.env.MAGPIE_GH_BIN
366
+ else process.env.MAGPIE_GH_BIN = previousGh
367
+ await rm(ghDir, { recursive: true, force: true })
368
+ }
369
+ }
370
+
371
+ test('POST /api/post-review answers 200 when every id was already posted', async () => {
372
+ await withGh('cat > /dev/null\necho \'{"id": 77}\'', async () => {
373
+ await seedPostable('findings.json')
374
+ await writeFile(join(runDir, 'post-status.json'), JSON.stringify({ 'sec-1': 'posted' }))
375
+ server = await startServer({ runDir, idleMs: 60_000 })
376
+ const res = await fetch(`${server.url}/api/post-review`, {
377
+ method: 'POST',
378
+ headers: { 'content-type': 'application/json' },
379
+ body: JSON.stringify({ findingIds: ['sec-1'], via: 'selected' }),
380
+ })
381
+ expect(res.status).toBe(200)
382
+ })
383
+ })
384
+
385
+ test('POST /api/post-review answers 502 when gh creates no review', async () => {
386
+ await withGh('cat > /dev/null\necho "HTTP 422" >&2\nexit 1', async () => {
387
+ await seedPostable('findings.json')
388
+ server = await startServer({ runDir, idleMs: 60_000 })
389
+ const res = await fetch(`${server.url}/api/post-review`, {
390
+ method: 'POST',
391
+ headers: { 'content-type': 'application/json' },
392
+ body: JSON.stringify({ findingIds: ['sec-1'], via: 'selected' }),
393
+ })
394
+ expect(res.status).toBe(502)
395
+ })
396
+ })
@@ -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.
@@ -548,3 +548,67 @@ test('stages 8 to 10 name the top-N fold, Dismiss, and labels.json', async () =>
548
548
  expect(post).toMatch(/Post Recommended[^\n]*top/)
549
549
  expect(await skillSection('### 10. Cleanup')).toContain('labels.json')
550
550
  })
551
+
552
+ test('stage 8 opens the magpie panel with the run dir, magpie path and PATH when the mod is installed', async () => {
553
+ const section = await skillSection('### 8. Report')
554
+ expect(section).toContain('mcp__magpie-panel__show_findings')
555
+ // The mod runs magpie without a shell, so it needs the resolved binary and
556
+ // the Bash tool's PATH rather than variable names it cannot expand.
557
+ expect(section).toContain('command -v magpie')
558
+ expect(section).toMatch(/runDir[\s\S]*magpieBin[\s\S]*path/)
559
+ })
560
+
561
+ test("stage 8's closing line names both the report URL and the panel", async () => {
562
+ const section = await skillSection('### 8. Report')
563
+ const closing = section.match(/^Print to the terminal: .*$/gm) ?? []
564
+ expect(closing.some((line) => line.includes('<url>') && /panel/i.test(line))).toBe(true)
565
+ })
566
+
567
+ test('stage 9 takes the selection from magpie view rather than folding state/events by hand', async () => {
568
+ const section = await skillSection('### 9. Post')
569
+ expect(section).toContain('magpie view "$RUN_DIR"')
570
+ expect(section).toContain('`selected`')
571
+ expect(section).not.toMatch(/LAST event/i)
572
+ expect(section).not.toContain('state/events')
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,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
+ }