@iceinvein/agent-skills 0.24.0 → 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 (30) hide show
  1. package/README.md +2 -1
  2. package/package.json +1 -1
  3. package/skills/index.json +1 -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
@@ -0,0 +1,129 @@
1
+ import { afterEach, beforeEach, expect, test } from 'bun:test'
2
+ import { existsSync } from 'node:fs'
3
+ import { cp, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
4
+ import { tmpdir } from 'node:os'
5
+ import { join } from 'node:path'
6
+ import { readDismissed } from '../labels.ts'
7
+
8
+ const FIXTURE = new URL('../../fixtures/example-pr', import.meta.url).pathname
9
+ const CLI = new URL('../../bin/magpie.ts', import.meta.url).pathname
10
+
11
+ let runDir: string
12
+ let eventsPath: string
13
+
14
+ beforeEach(async () => {
15
+ runDir = await mkdtemp(join(tmpdir(), 'magpie-mark-'))
16
+ await cp(FIXTURE, runDir, { recursive: true })
17
+ eventsPath = join(runDir, 'state', 'events')
18
+ })
19
+
20
+ afterEach(async () => {
21
+ await rm(runDir, { recursive: true, force: true })
22
+ })
23
+
24
+ async function mark(args: string[]): Promise<{ exit: number; stderr: string }> {
25
+ const proc = Bun.spawn(['bun', CLI, 'mark', runDir, ...args], { stdout: 'pipe', stderr: 'pipe' })
26
+ const exit = await proc.exited
27
+ const stderr = await new Response(proc.stderr).text()
28
+ return { exit, stderr }
29
+ }
30
+
31
+ async function eventLines(): Promise<Array<Record<string, unknown>>> {
32
+ const text = await readFile(eventsPath, 'utf8')
33
+ return text
34
+ .split('\n')
35
+ .filter((line) => line !== '')
36
+ .map((line) => JSON.parse(line) as Record<string, unknown>)
37
+ }
38
+
39
+ const EXISTING = '{"type":"select","findingId":"perf-1","timestamp":1}\n'
40
+
41
+ async function seedEvents(): Promise<void> {
42
+ await mkdir(join(runDir, 'state'), { recursive: true })
43
+ await writeFile(eventsPath, EXISTING)
44
+ }
45
+
46
+ test('mark select appends one select line for the finding', async () => {
47
+ const result = await mark(['bugs-1', 'select'])
48
+ expect(result.stderr).toBe('')
49
+ expect(result.exit).toBe(0)
50
+ const lines = await eventLines()
51
+ expect(lines).toHaveLength(1)
52
+ expect(lines[0]?.type).toBe('select')
53
+ expect(lines[0]?.findingId).toBe('bugs-1')
54
+ expect(typeof lines[0]?.timestamp).toBe('number')
55
+ })
56
+
57
+ test('mark appends after the events already in state/events', async () => {
58
+ await seedEvents()
59
+ expect((await mark(['bugs-1', 'deselect'])).exit).toBe(0)
60
+ const lines = await eventLines()
61
+ expect(lines.map((l) => [l.type, l.findingId])).toEqual([
62
+ ['select', 'perf-1'],
63
+ ['deselect', 'bugs-1'],
64
+ ])
65
+ })
66
+
67
+ test('mark dismiss writes the reason on the line', async () => {
68
+ expect((await mark(['bugs-1', 'dismiss', 'style'])).exit).toBe(0)
69
+ const lines = await eventLines()
70
+ expect(lines).toHaveLength(1)
71
+ expect(lines[0]?.type).toBe('dismiss')
72
+ expect(lines[0]?.findingId).toBe('bugs-1')
73
+ expect(lines[0]?.reason).toBe('style')
74
+ })
75
+
76
+ test('a dismissal written by mark is read back by readDismissed with its reason', async () => {
77
+ expect((await mark(['bugs-1', 'dismiss', 'style'])).exit).toBe(0)
78
+ expect(await readDismissed(runDir)).toEqual(new Map([['bugs-1', 'style']]))
79
+ })
80
+
81
+ test('mark undismiss appends an undismiss line', async () => {
82
+ expect((await mark(['bugs-1', 'undismiss'])).exit).toBe(0)
83
+ const lines = await eventLines()
84
+ expect(lines.map((l) => [l.type, l.findingId])).toEqual([['undismiss', 'bugs-1']])
85
+ })
86
+
87
+ test('mark of an id not in findings.final.json exits 2 and leaves state/events unchanged', async () => {
88
+ await seedEvents()
89
+ const result = await mark(['nope-1', 'select'])
90
+ expect(result.exit).toBe(2)
91
+ expect(result.stderr).toContain('nope-1')
92
+ expect(await readFile(eventsPath, 'utf8')).toBe(EXISTING)
93
+ })
94
+
95
+ test('mark with an unknown verb exits 2 and leaves state/events unchanged', async () => {
96
+ await seedEvents()
97
+ const result = await mark(['bugs-1', 'toggle'])
98
+ expect(result.exit).toBe(2)
99
+ expect(result.stderr).toContain('toggle')
100
+ expect(await readFile(eventsPath, 'utf8')).toBe(EXISTING)
101
+ })
102
+
103
+ test('mark dismiss with an unknown reason exits 2 and leaves state/events unchanged', async () => {
104
+ await seedEvents()
105
+ const result = await mark(['bugs-1', 'dismiss', 'meh'])
106
+ expect(result.exit).toBe(2)
107
+ expect(result.stderr).toContain('meh')
108
+ expect(await readFile(eventsPath, 'utf8')).toBe(EXISTING)
109
+ })
110
+
111
+ test('mark dismiss without a reason exits 2 and leaves state/events unchanged', async () => {
112
+ await seedEvents()
113
+ const result = await mark(['bugs-1', 'dismiss'])
114
+ expect(result.exit).toBe(2)
115
+ expect(await readFile(eventsPath, 'utf8')).toBe(EXISTING)
116
+ })
117
+
118
+ test('mark with a reason after a verb other than dismiss exits 2 and leaves state/events unchanged', async () => {
119
+ await seedEvents()
120
+ const result = await mark(['bugs-1', 'select', 'wrong'])
121
+ expect(result.exit).toBe(2)
122
+ expect(result.stderr).toContain('wrong')
123
+ expect(await readFile(eventsPath, 'utf8')).toBe(EXISTING)
124
+ })
125
+
126
+ test('a rejected mark on a run with no state/events creates no file', async () => {
127
+ expect((await mark(['nope-1', 'select'])).exit).toBe(2)
128
+ expect(existsSync(eventsPath)).toBe(false)
129
+ })
@@ -1,5 +1,6 @@
1
1
  import { afterEach, beforeEach, describe, expect, test } from 'bun:test'
2
- import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
2
+ import { existsSync } from 'node:fs'
3
+ import { cp, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
3
4
  import { tmpdir } from 'node:os'
4
5
  import { join } from 'node:path'
5
6
  import {
@@ -11,6 +12,7 @@ import {
11
12
  parseRepoFromUrl,
12
13
  postFindingsAsReview,
13
14
  runPost,
15
+ runPostReview,
14
16
  } from '../post-cmd.ts'
15
17
 
16
18
  let runDir: string
@@ -680,3 +682,298 @@ test('formatInlineBody leaves a not-proven note out of the posted comment', () =
680
682
  } as never)
681
683
  expect(body).not.toContain('needs a live database')
682
684
  })
685
+
686
+ // ---------------------------------------------------------------------------
687
+ // post --review on the example-pr fixture
688
+ // ---------------------------------------------------------------------------
689
+
690
+ const FIXTURE = new URL('../../fixtures/example-pr', import.meta.url).pathname
691
+ const CLI = new URL('../../bin/magpie.ts', import.meta.url).pathname
692
+
693
+ async function fixtureRunDir(): Promise<string> {
694
+ const dir = await mkdtemp(join(tmpdir(), 'magpie-post-fixture-'))
695
+ await cp(FIXTURE, dir, { recursive: true })
696
+ return dir
697
+ }
698
+
699
+ /** A gh that records each review payload it is sent, one per line, and answers review 501. */
700
+ async function recordingGh(dir: string): Promise<{ bin: string; calls: () => Promise<string[]> }> {
701
+ const bin = join(dir, 'recording-gh.sh')
702
+ const callsPath = join(dir, 'gh-calls')
703
+ await writeFile(
704
+ bin,
705
+ `#!/usr/bin/env bash\ncat >> '${callsPath}'\necho >> '${callsPath}'\necho '{"id": 501}'\n`,
706
+ )
707
+ await Bun.spawn(['chmod', '+x', bin]).exited
708
+ return {
709
+ bin,
710
+ calls: async () => {
711
+ if (!existsSync(callsPath)) return []
712
+ return (await readFile(callsPath, 'utf8')).split('\n').filter(Boolean)
713
+ },
714
+ }
715
+ }
716
+
717
+ async function failingGh(dir: string): Promise<string> {
718
+ const bin = join(dir, 'failing-gh.sh')
719
+ await writeFile(
720
+ bin,
721
+ '#!/usr/bin/env bash\ncat >/dev/null\necho "HTTP 502: bad gateway" >&2\nexit 1\n',
722
+ )
723
+ await Bun.spawn(['chmod', '+x', bin]).exited
724
+ return bin
725
+ }
726
+
727
+ async function runCli(
728
+ args: string[],
729
+ ghBin: string,
730
+ ): Promise<{ exit: number; stdout: string; stderr: string }> {
731
+ const proc = Bun.spawn(['bun', CLI, 'post', ...args], {
732
+ stdout: 'pipe',
733
+ stderr: 'pipe',
734
+ env: { ...process.env, MAGPIE_GH_BIN: ghBin },
735
+ })
736
+ const [stdout, stderr, exit] = await Promise.all([
737
+ new Response(proc.stdout).text(),
738
+ new Response(proc.stderr).text(),
739
+ proc.exited,
740
+ ])
741
+ return { exit, stdout, stderr }
742
+ }
743
+
744
+ describe('postFindingsAsReview with ids already posted', () => {
745
+ let dir: string
746
+ beforeEach(async () => {
747
+ dir = await fixtureRunDir()
748
+ })
749
+ afterEach(async () => {
750
+ await rm(dir, { recursive: true, force: true })
751
+ })
752
+
753
+ test('sends a review holding only the ids not yet posted', async () => {
754
+ const gh = await recordingGh(dir)
755
+ await postFindingsAsReview({
756
+ runDir: dir,
757
+ findingIds: ['security-1', 'bugs-1'],
758
+ prNumber: 1337,
759
+ headSha: '9f3a8c0211dbb5fe7a82a2c1b08e0a45c2d1ee01',
760
+ repo: 'example/repo',
761
+ ghBin: gh.bin,
762
+ })
763
+ const calls = await gh.calls()
764
+ expect(calls).toHaveLength(1)
765
+ const payload = JSON.parse(calls[0] as string) as {
766
+ body: string
767
+ comments: Array<{ path: string; line: number }>
768
+ }
769
+ expect(payload.comments.map((c) => ({ path: c.path, line: c.line }))).toEqual([
770
+ { path: 'src/cache/invalidation.ts', line: 142 },
771
+ ])
772
+ expect(payload.body).not.toContain('Session token written to Redis')
773
+ })
774
+
775
+ test('reports an id already posted as already-posted', async () => {
776
+ const gh = await recordingGh(dir)
777
+ const r = await postFindingsAsReview({
778
+ runDir: dir,
779
+ findingIds: ['security-1', 'bugs-1'],
780
+ prNumber: 1337,
781
+ headSha: '9f3a8c0211dbb5fe7a82a2c1b08e0a45c2d1ee01',
782
+ repo: 'example/repo',
783
+ ghBin: gh.bin,
784
+ })
785
+ expect(r.comments).toEqual([
786
+ { id: 'security-1', status: 'already-posted' },
787
+ { id: 'bugs-1', status: 'posted' },
788
+ ])
789
+ })
790
+
791
+ test('posting the same id twice invokes gh once', async () => {
792
+ const gh = await recordingGh(dir)
793
+ const input = {
794
+ runDir: dir,
795
+ findingIds: ['bugs-1'],
796
+ prNumber: 1337,
797
+ headSha: '9f3a8c0211dbb5fe7a82a2c1b08e0a45c2d1ee01',
798
+ repo: 'example/repo',
799
+ ghBin: gh.bin,
800
+ }
801
+ await postFindingsAsReview(input)
802
+ const second = await postFindingsAsReview(input)
803
+ expect(await gh.calls()).toHaveLength(1)
804
+ expect(second.reviewId).toBeNull()
805
+ expect(second.comments).toEqual([{ id: 'bugs-1', status: 'already-posted' }])
806
+ })
807
+ })
808
+
809
+ describe('runPostReview', () => {
810
+ let dir: string
811
+ beforeEach(async () => {
812
+ dir = await fixtureRunDir()
813
+ })
814
+ afterEach(async () => {
815
+ await rm(dir, { recursive: true, force: true })
816
+ })
817
+
818
+ test('posts the review to the PR named in pr.json and returns its id', async () => {
819
+ const gh = await recordingGh(dir)
820
+ const r = await runPostReview({ runDir: dir, findingIds: ['bugs-1'], ghBin: gh.bin })
821
+ expect(r).toEqual({
822
+ ok: true,
823
+ reviewId: '501',
824
+ results: [{ id: 'bugs-1', status: 'posted' }],
825
+ })
826
+ })
827
+
828
+ test('fails with an error when pr.json has no head SHA', async () => {
829
+ const prJson = JSON.parse(await readFile(join(dir, 'pr.json'), 'utf8'))
830
+ delete prJson.headRefOid
831
+ await writeFile(join(dir, 'pr.json'), JSON.stringify(prJson))
832
+ const gh = await recordingGh(dir)
833
+ const r = await runPostReview({ runDir: dir, findingIds: ['bugs-1'], ghBin: gh.bin })
834
+ expect(r.ok).toBe(false)
835
+ expect(r.reviewId).toBeNull()
836
+ expect(r.error).toContain('headSha')
837
+ expect(await gh.calls()).toHaveLength(0)
838
+ })
839
+
840
+ test('is not ok when gh fails to create the review', async () => {
841
+ const r = await runPostReview({
842
+ runDir: dir,
843
+ findingIds: ['bugs-1'],
844
+ ghBin: await failingGh(dir),
845
+ })
846
+ expect(r.ok).toBe(false)
847
+ expect(r.reviewId).toBeNull()
848
+ expect(r.results).toEqual([
849
+ { id: 'bugs-1', status: 'failed', message: 'HTTP 502: bad gateway' },
850
+ ])
851
+ })
852
+
853
+ test('reports an id that is no finding as unknown-id and sends no review', async () => {
854
+ const gh = await recordingGh(dir)
855
+ const r = await runPostReview({ runDir: dir, findingIds: ['no-such-finding'], ghBin: gh.bin })
856
+ expect(r).toEqual({
857
+ ok: true,
858
+ reviewId: null,
859
+ results: [{ id: 'no-such-finding', status: 'unknown-id' }],
860
+ })
861
+ expect(await gh.calls()).toHaveLength(0)
862
+ })
863
+
864
+ test('never records an id that is no finding in post-status.json', async () => {
865
+ const gh = await recordingGh(dir)
866
+ await runPostReview({ runDir: dir, findingIds: ['no-such-finding', 'bugs-1'], ghBin: gh.bin })
867
+ const status = JSON.parse(await readFile(join(dir, 'post-status.json'), 'utf8'))
868
+ expect(status['no-such-finding']).toBeUndefined()
869
+ expect(status['bugs-1']).toBe('posted')
870
+ })
871
+
872
+ test('posts an id given twice as one inline comment and reports it once', async () => {
873
+ const gh = await recordingGh(dir)
874
+ const r = await runPostReview({ runDir: dir, findingIds: ['bugs-1', 'bugs-1'], ghBin: gh.bin })
875
+ const calls = await gh.calls()
876
+ const payload = JSON.parse(calls[0] as string) as { comments: unknown[] }
877
+ expect(calls).toHaveLength(1)
878
+ expect(payload.comments).toHaveLength(1)
879
+ expect(r.results).toEqual([{ id: 'bugs-1', status: 'posted' }])
880
+ })
881
+
882
+ test('is ok with no review when every id was already posted', async () => {
883
+ const gh = await recordingGh(dir)
884
+ const r = await runPostReview({
885
+ runDir: dir,
886
+ findingIds: ['security-1', 'arch-1'],
887
+ ghBin: gh.bin,
888
+ })
889
+ expect(r).toEqual({
890
+ ok: true,
891
+ reviewId: null,
892
+ results: [
893
+ { id: 'security-1', status: 'already-posted' },
894
+ { id: 'arch-1', status: 'already-posted' },
895
+ ],
896
+ })
897
+ expect(await gh.calls()).toHaveLength(0)
898
+ })
899
+ })
900
+
901
+ describe('magpie post CLI', () => {
902
+ let dir: string
903
+ beforeEach(async () => {
904
+ dir = await fixtureRunDir()
905
+ })
906
+ afterEach(async () => {
907
+ await rm(dir, { recursive: true, force: true })
908
+ })
909
+
910
+ test('post --review prints the review id and per-id results as JSON', async () => {
911
+ const gh = await recordingGh(dir)
912
+ const r = await runCli([dir, '--ids', 'security-1,bugs-1', '--review'], gh.bin)
913
+ expect(r.exit).toBe(0)
914
+ expect(JSON.parse(r.stdout)).toEqual({
915
+ ok: true,
916
+ reviewId: '501',
917
+ results: [
918
+ { id: 'security-1', status: 'already-posted' },
919
+ { id: 'bugs-1', status: 'posted' },
920
+ ],
921
+ })
922
+ })
923
+
924
+ test('post --review exits 2 when pr.json has no PR number', async () => {
925
+ const prJson = JSON.parse(await readFile(join(dir, 'pr.json'), 'utf8'))
926
+ delete prJson.number
927
+ await writeFile(join(dir, 'pr.json'), JSON.stringify(prJson))
928
+ const gh = await recordingGh(dir)
929
+ const r = await runCli([dir, '--ids', 'bugs-1', '--review'], gh.bin)
930
+ expect(r.exit).toBe(2)
931
+ expect(r.stderr).toStartWith('post: ')
932
+ })
933
+
934
+ test('post --review exits 1 when gh fails to create the review', async () => {
935
+ const r = await runCli([dir, '--ids', 'bugs-1', '--review'], await failingGh(dir))
936
+ expect(r.exit).toBe(1)
937
+ expect(JSON.parse(r.stdout).ok).toBe(false)
938
+ })
939
+
940
+ test('post --review exits 0 when every id was already posted', async () => {
941
+ const gh = await recordingGh(dir)
942
+ const r = await runCli([dir, '--ids', 'security-1', '--review'], gh.bin)
943
+ expect(r.exit).toBe(0)
944
+ expect(JSON.parse(r.stdout)).toEqual({
945
+ ok: true,
946
+ reviewId: null,
947
+ results: [{ id: 'security-1', status: 'already-posted' }],
948
+ })
949
+ })
950
+
951
+ test('post --review --via one records via one on the post log entries', async () => {
952
+ const gh = await recordingGh(dir)
953
+ await runCli([dir, '--ids', 'bugs-1', '--review', '--via', 'one'], gh.bin)
954
+ const ok = (await logEntries(dir)).filter((e) => e.stage === 'post' && e.status === 'ok')
955
+ expect(ok.map((e) => ({ id: e.id, via: e.via }))).toEqual([{ id: 'bugs-1', via: 'one' }])
956
+ })
957
+
958
+ test('post --via selected records via selected on the comment route', async () => {
959
+ const gh = await recordingGh(dir)
960
+ await runCli([dir, '--ids', 'bugs-1', '--via', 'selected'], gh.bin)
961
+ const ok = (await logEntries(dir)).filter((e) => e.status === 'ok' && e.id === 'bugs-1')
962
+ expect(ok.map((e) => e.via)).toEqual(['selected'])
963
+ })
964
+
965
+ test('post without --via records via cli on the comment route', async () => {
966
+ const gh = await recordingGh(dir)
967
+ await runCli([dir, '--ids', 'bugs-1'], gh.bin)
968
+ const ok = (await logEntries(dir)).filter((e) => e.status === 'ok' && e.id === 'bugs-1')
969
+ expect(ok.map((e) => e.via)).toEqual(['cli'])
970
+ })
971
+
972
+ test('post with an unknown --via exits 2 and posts nothing', async () => {
973
+ const gh = await recordingGh(dir)
974
+ const r = await runCli([dir, '--ids', 'bugs-1', '--review', '--via', 'bogus'], gh.bin)
975
+ expect(r.exit).toBe(2)
976
+ expect(r.stderr).toBe('post: invalid --via bogus (want recommended|selected|one|cli)\n')
977
+ expect(await gh.calls()).toHaveLength(0)
978
+ })
979
+ })
@@ -1,5 +1,5 @@
1
1
  import { afterEach, beforeEach, expect, test } from 'bun:test'
2
- import { mkdir, mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises'
2
+ import { cp, mkdir, mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises'
3
3
  import { tmpdir } from 'node:os'
4
4
  import { join } from 'node:path'
5
5
  import { runRender } from '../render-cmd.ts'
@@ -334,3 +334,17 @@ for (const bad of ['0', '-2', '2.5', 'ten']) {
334
334
  expect(await readdir(join(runDir, 'screen'))).toEqual([])
335
335
  })
336
336
  }
337
+
338
+ test('render findings ticks the findings the run selected in state/events', async () => {
339
+ await cp(new URL('../../fixtures/example-pr', import.meta.url).pathname, runDir, {
340
+ recursive: true,
341
+ })
342
+ await writeFile(
343
+ join(runDir, 'state', 'events'),
344
+ `${JSON.stringify({ type: 'select', findingId: 'bugs-1', timestamp: 1 })}\n`,
345
+ )
346
+ expect(await runRender(runDir, 'findings')).toBe(0)
347
+ const html = await readFile(join(runDir, 'screen', 'findings.html'), 'utf8')
348
+ expect(html).toMatch(/data-finding-id="bugs-1" checked aria-label/)
349
+ expect(html).not.toMatch(/data-finding-id="perf-2" checked/)
350
+ })
@@ -64,6 +64,19 @@ test('empty findings renders the page shell with an empty-state message', () =>
64
64
  expect(html).toContain('No findings')
65
65
  })
66
66
 
67
+ test('a finding in selectedIds renders its checkbox checked and the others unchecked', () => {
68
+ const html = renderFindingsHtml({
69
+ findings: SAMPLE_FINDINGS,
70
+ postStatus: {},
71
+ selectedIds: new Set(['a']),
72
+ dismissed: new Map(),
73
+ topN: DEFAULT_TOP_N,
74
+ highlighter: hl,
75
+ })
76
+ expect(html).toMatch(/data-finding-id="a" checked aria-label/)
77
+ expect(html).not.toMatch(/data-finding-id="b" checked/)
78
+ })
79
+
67
80
  test('emits the two-tab segmented control with Files and All Issues buttons', () => {
68
81
  const html = renderFindingsHtml({
69
82
  findings: SAMPLE_FINDINGS,
@@ -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
+ })
@@ -548,3 +548,26 @@ 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
+ })