@iceinvein/agent-skills 0.1.40 → 0.2.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 (139) hide show
  1. package/README.md +18 -2
  2. package/dist/cli/index.js +105 -28
  3. package/package.json +1 -1
  4. package/skills/index.json +14 -2
  5. package/skills/magpie/SKILL.md +118 -40
  6. package/skills/magpie/bin/magpie.ts +43 -0
  7. package/skills/magpie/fixtures/fake-gh-nodiff.sh +38 -0
  8. package/skills/magpie/package.json +1 -1
  9. package/skills/magpie/references/peer-review.md +7 -2
  10. package/skills/magpie/references/specialists.md +38 -7
  11. package/skills/magpie/scripts/__tests__/cli.test.ts +101 -1
  12. package/skills/magpie/scripts/__tests__/dedupe-cmd.test.ts +187 -0
  13. package/skills/magpie/scripts/__tests__/diff-chunks.test.ts +51 -0
  14. package/skills/magpie/scripts/__tests__/filter-diff-preservation.test.ts +54 -0
  15. package/skills/magpie/scripts/__tests__/findings-files.test.ts +35 -0
  16. package/skills/magpie/scripts/__tests__/gh.test.ts +69 -0
  17. package/skills/magpie/scripts/__tests__/git-diff.test.ts +83 -0
  18. package/skills/magpie/scripts/__tests__/helpers/git-fixture.ts +47 -0
  19. package/skills/magpie/scripts/__tests__/path-filter.test.ts +27 -0
  20. package/skills/magpie/scripts/__tests__/render-cmd.test.ts +95 -0
  21. package/skills/magpie/scripts/__tests__/render-findings.test.ts +33 -0
  22. package/skills/magpie/scripts/__tests__/render-progress.test.ts +42 -0
  23. package/skills/magpie/scripts/__tests__/setup-cmd.test.ts +83 -1
  24. package/skills/magpie/scripts/__tests__/shard.test.ts +165 -0
  25. package/skills/magpie/scripts/__tests__/skill-lint.test.ts +96 -1
  26. package/skills/magpie/scripts/dedupe-cmd.ts +58 -3
  27. package/skills/magpie/scripts/diff-chunks.ts +28 -0
  28. package/skills/magpie/scripts/findings-files.ts +32 -0
  29. package/skills/magpie/scripts/gh.ts +64 -13
  30. package/skills/magpie/scripts/git-diff.ts +111 -0
  31. package/skills/magpie/scripts/path-filter.ts +9 -5
  32. package/skills/magpie/scripts/refresh.ts +8 -0
  33. package/skills/magpie/scripts/render-cmd.ts +28 -9
  34. package/skills/magpie/scripts/render-findings.ts +11 -1
  35. package/skills/magpie/scripts/render-progress.ts +6 -1
  36. package/skills/magpie/scripts/setup-cmd.ts +38 -1
  37. package/skills/magpie/scripts/shard.ts +171 -0
  38. package/skills/magpie/scripts/status-cmd.ts +4 -1
  39. package/skills/magpie/skill.json +2 -2
  40. package/skills/magpie/templates/styles.css +5 -0
  41. package/skills/migrate/README.md +194 -0
  42. package/skills/migrate/SKILL.md +197 -0
  43. package/skills/migrate/bin/migrate +15 -0
  44. package/skills/migrate/bin/migrate.ts +309 -0
  45. package/skills/migrate/biome.json +35 -0
  46. package/skills/migrate/bun.lock +24 -0
  47. package/skills/migrate/docs/architecture.md +294 -0
  48. package/skills/migrate/docs/reference.md +590 -0
  49. package/skills/migrate/fixtures/tiny-express/GROUND-TRUTH.md +39 -0
  50. package/skills/migrate/fixtures/tiny-express/app.js +29 -0
  51. package/skills/migrate/fixtures/tiny-express/cron.js +6 -0
  52. package/skills/migrate/fixtures/tiny-express/reports/daily-users.json +6 -0
  53. package/skills/migrate/fixtures/tiny-express/schema.sql +12 -0
  54. package/skills/migrate/fixtures/tiny-express/settings.json +4 -0
  55. package/skills/migrate/fixtures/tiny-express/views/users.html +9 -0
  56. package/skills/migrate/fixtures/tiny-webforms/Controllers/UsersController.cs +68 -0
  57. package/skills/migrate/fixtures/tiny-webforms/Default.aspx +7 -0
  58. package/skills/migrate/fixtures/tiny-webforms/Default.aspx.cs +14 -0
  59. package/skills/migrate/fixtures/tiny-webforms/GROUND-TRUTH.md +50 -0
  60. package/skills/migrate/fixtures/tiny-webforms/Integrations/BillingClient.cs +16 -0
  61. package/skills/migrate/fixtures/tiny-webforms/Jobs/NightlyDigestJob.cs +33 -0
  62. package/skills/migrate/fixtures/tiny-webforms/Reports/DailyUsers.rdl +11 -0
  63. package/skills/migrate/fixtures/tiny-webforms/Schema.sql +12 -0
  64. package/skills/migrate/fixtures/tiny-webforms/Site.master +16 -0
  65. package/skills/migrate/fixtures/tiny-webforms/Users.aspx +8 -0
  66. package/skills/migrate/fixtures/tiny-webforms/Users.aspx.cs +14 -0
  67. package/skills/migrate/fixtures/tiny-webforms/web.config +10 -0
  68. package/skills/migrate/install.sh +68 -0
  69. package/skills/migrate/package.json +17 -0
  70. package/skills/migrate/references/phases/enumerate.md +291 -0
  71. package/skills/migrate/references/phases/extract.md +652 -0
  72. package/skills/migrate/references/phases/parity.md +275 -0
  73. package/skills/migrate/references/phases/probe.md +135 -0
  74. package/skills/migrate/references/phases/queue.md +242 -0
  75. package/skills/migrate/references/phases/seam.md +416 -0
  76. package/skills/migrate/references/recipes/README.md +116 -0
  77. package/skills/migrate/references/recipes/aspnet.md +287 -0
  78. package/skills/migrate/references/run-ops.md +280 -0
  79. package/skills/migrate/scripts/__tests__/census.test.ts +775 -0
  80. package/skills/migrate/scripts/__tests__/check.test.ts +458 -0
  81. package/skills/migrate/scripts/__tests__/citations.test.ts +156 -0
  82. package/skills/migrate/scripts/__tests__/cli.test.ts +183 -0
  83. package/skills/migrate/scripts/__tests__/concurrency.test.ts +164 -0
  84. package/skills/migrate/scripts/__tests__/config.test.ts +112 -0
  85. package/skills/migrate/scripts/__tests__/e2e-express.test.ts +1093 -0
  86. package/skills/migrate/scripts/__tests__/e2e-webforms.test.ts +1276 -0
  87. package/skills/migrate/scripts/__tests__/e2e.test.ts +320 -0
  88. package/skills/migrate/scripts/__tests__/ids.test.ts +38 -0
  89. package/skills/migrate/scripts/__tests__/import.test.ts +155 -0
  90. package/skills/migrate/scripts/__tests__/init.test.ts +192 -0
  91. package/skills/migrate/scripts/__tests__/leaks.test.ts +176 -0
  92. package/skills/migrate/scripts/__tests__/lock.test.ts +183 -0
  93. package/skills/migrate/scripts/__tests__/paths.test.ts +129 -0
  94. package/skills/migrate/scripts/__tests__/phase-cmd.test.ts +151 -0
  95. package/skills/migrate/scripts/__tests__/phases.test.ts +70 -0
  96. package/skills/migrate/scripts/__tests__/queue.test.ts +475 -0
  97. package/skills/migrate/scripts/__tests__/report.test.ts +150 -0
  98. package/skills/migrate/scripts/__tests__/run-state.test.ts +136 -0
  99. package/skills/migrate/scripts/__tests__/status-reset.test.ts +318 -0
  100. package/skills/migrate/scripts/__tests__/store.test.ts +132 -0
  101. package/skills/migrate/scripts/__tests__/validate.test.ts +54 -0
  102. package/skills/migrate/scripts/census-cmd.ts +109 -0
  103. package/skills/migrate/scripts/census.ts +342 -0
  104. package/skills/migrate/scripts/check-cmd.ts +24 -0
  105. package/skills/migrate/scripts/check.ts +376 -0
  106. package/skills/migrate/scripts/citations.ts +92 -0
  107. package/skills/migrate/scripts/config.ts +237 -0
  108. package/skills/migrate/scripts/ids.ts +31 -0
  109. package/skills/migrate/scripts/import-cmd.ts +141 -0
  110. package/skills/migrate/scripts/init-cmd.ts +118 -0
  111. package/skills/migrate/scripts/leaks.ts +184 -0
  112. package/skills/migrate/scripts/lock.ts +188 -0
  113. package/skills/migrate/scripts/paths.ts +103 -0
  114. package/skills/migrate/scripts/phase-cmd.ts +63 -0
  115. package/skills/migrate/scripts/phases.ts +113 -0
  116. package/skills/migrate/scripts/queue-cmd.ts +98 -0
  117. package/skills/migrate/scripts/queue.ts +258 -0
  118. package/skills/migrate/scripts/report-cmd.ts +47 -0
  119. package/skills/migrate/scripts/report.ts +131 -0
  120. package/skills/migrate/scripts/reset-cmd.ts +120 -0
  121. package/skills/migrate/scripts/status-cmd.ts +52 -0
  122. package/skills/migrate/scripts/store.ts +159 -0
  123. package/skills/migrate/scripts/types.ts +137 -0
  124. package/skills/migrate/scripts/validate.ts +221 -0
  125. package/skills/migrate/skill.json +33 -0
  126. package/skills/migrate/templates/config.toml +27 -0
  127. package/skills/migrate/templates/queue-item.md +17 -0
  128. package/skills/migrate/tsconfig.json +18 -0
  129. package/skills/migrate/uninstall.sh +31 -0
  130. package/skills/sluice/SKILL.md +82 -0
  131. package/skills/sluice/references/deep-channel.md +94 -0
  132. package/skills/sluice/references/finish.md +35 -0
  133. package/skills/sluice/references/intent.md +29 -0
  134. package/skills/sluice/references/review.md +42 -0
  135. package/skills/sluice/references/root-cause.md +38 -0
  136. package/skills/sluice/references/show-or-say.md +36 -0
  137. package/skills/sluice/references/test-first.md +35 -0
  138. package/skills/sluice/references/verify.md +26 -0
  139. package/skills/sluice/skill.json +32 -0
@@ -0,0 +1,165 @@
1
+ import { afterEach, beforeEach, expect, test } from 'bun:test'
2
+ import { existsSync } from 'node:fs'
3
+ import { mkdir, mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises'
4
+ import { tmpdir } from 'node:os'
5
+ import { join } from 'node:path'
6
+ import { DEFAULT_SHARD_BUDGET, groupKey, planShards, shardDiff } from '../shard.ts'
7
+
8
+ let runDir: string
9
+
10
+ beforeEach(async () => {
11
+ runDir = await mkdtemp(join(tmpdir(), 'magpie-shard-'))
12
+ })
13
+
14
+ afterEach(async () => {
15
+ await rm(runDir, { recursive: true, force: true })
16
+ })
17
+
18
+ /** A file chunk with `bodyLines` added lines, shaped like a real patch. */
19
+ function chunk(path: string, bodyLines: number): string {
20
+ const body = Array.from({ length: bodyLines }, (_, i) => `+line ${i}`).join('\n')
21
+ return [
22
+ `diff --git a/${path} b/${path}`,
23
+ 'index 0000000..1111111 100644',
24
+ `--- a/${path}`,
25
+ `+++ b/${path}`,
26
+ `@@ -0,0 +1,${bodyLines} @@`,
27
+ body,
28
+ '',
29
+ ].join('\n')
30
+ }
31
+
32
+ test('groupKey caps the grouping directory at two segments', () => {
33
+ expect(groupKey('src/cli/commands/install.ts')).toBe('src/cli')
34
+ expect(groupKey('src/a.ts')).toBe('src')
35
+ expect(groupKey('README.md')).toBe('.')
36
+ })
37
+
38
+ test('planShards keeps a directory group together when it fits', () => {
39
+ const chunks = [
40
+ { path: 'src/cli/a.ts', text: '', lines: 100 },
41
+ { path: 'src/web/b.ts', text: '', lines: 100 },
42
+ { path: 'src/cli/c.ts', text: '', lines: 100 },
43
+ ]
44
+ const shards = planShards(chunks, 1000, 80)
45
+ expect(shards).toHaveLength(1)
46
+ // Grouping reorders: both src/cli files are adjacent.
47
+ expect(shards[0]?.map((c) => c.path)).toEqual(['src/cli/a.ts', 'src/cli/c.ts', 'src/web/b.ts'])
48
+ })
49
+
50
+ test('planShards splits when the line budget is exceeded', () => {
51
+ const chunks = [
52
+ { path: 'src/a/1.ts', text: '', lines: 600 },
53
+ { path: 'src/b/2.ts', text: '', lines: 600 },
54
+ { path: 'src/c/3.ts', text: '', lines: 600 },
55
+ ]
56
+ const shards = planShards(chunks, 1000, 80)
57
+ expect(shards).toHaveLength(3)
58
+ })
59
+
60
+ test('planShards splits when max-files is reached before the budget', () => {
61
+ const chunks = Array.from({ length: 5 }, (_, i) => ({
62
+ path: `src/g${i}/f.ts`,
63
+ text: '',
64
+ lines: 1,
65
+ }))
66
+ const shards = planShards(chunks, 10_000, 2)
67
+ expect(shards).toHaveLength(3)
68
+ expect(shards[0]).toHaveLength(2)
69
+ expect(shards[2]).toHaveLength(1)
70
+ })
71
+
72
+ test('planShards gives an over-budget file a shard to itself', () => {
73
+ const chunks = [
74
+ { path: 'src/a/small.ts', text: '', lines: 10 },
75
+ { path: 'src/b/huge.ts', text: '', lines: 9000 },
76
+ { path: 'src/c/other.ts', text: '', lines: 10 },
77
+ ]
78
+ const shards = planShards(chunks, 1000, 80)
79
+ expect(shards).toHaveLength(3)
80
+ expect(shards[1]?.map((c) => c.path)).toEqual(['src/b/huge.ts'])
81
+ })
82
+
83
+ test('shardDiff writes a single-shard manifest pointing at diff.patch', async () => {
84
+ await writeFile(join(runDir, 'diff.patch'), chunk('src/a.ts', 3))
85
+ const manifest = await shardDiff(runDir)
86
+ expect(manifest.shards).toHaveLength(1)
87
+ expect(manifest.shards[0]?.path).toBe('diff.patch')
88
+ expect(manifest.totalFiles).toBe(1)
89
+ expect(manifest.budget).toBe(DEFAULT_SHARD_BUDGET)
90
+ expect(existsSync(join(runDir, 'shards', 'shard-1.patch'))).toBe(false)
91
+ const onDisk = JSON.parse(await readFile(join(runDir, 'shards', 'manifest.json'), 'utf8'))
92
+ expect(onDisk.shards[0].files).toEqual(['src/a.ts'])
93
+ })
94
+
95
+ test('shardDiff writes one patch per shard when the budget forces a split', async () => {
96
+ const diff = chunk('src/a/one.ts', 200) + chunk('src/b/two.ts', 200)
97
+ await writeFile(join(runDir, 'diff.patch'), diff)
98
+ const manifest = await shardDiff(runDir, { budget: 150 })
99
+ expect(manifest.shards).toHaveLength(2)
100
+ expect(manifest.shards[0]?.path).toBe('shards/shard-1.patch')
101
+ const first = await readFile(join(runDir, 'shards', 'shard-1.patch'), 'utf8')
102
+ expect(first).toContain('diff --git a/src/a/one.ts')
103
+ expect(first).not.toContain('src/b/two.ts')
104
+ // diff.patch is a view source, never replaced.
105
+ const whole = await readFile(join(runDir, 'diff.patch'), 'utf8')
106
+ expect(whole).toContain('src/a/one.ts')
107
+ expect(whole).toContain('src/b/two.ts')
108
+ })
109
+
110
+ test('a re-split into fewer shards leaves no orphaned shard patches behind', async () => {
111
+ const diff =
112
+ chunk('src/a/one.ts', 200) + chunk('src/b/two.ts', 200) + chunk('src/c/three.ts', 200)
113
+ await writeFile(join(runDir, 'diff.patch'), diff)
114
+ const first = await shardDiff(runDir, { budget: 150 })
115
+ expect(first.shards).toHaveLength(3)
116
+ expect(existsSync(join(runDir, 'shards', 'shard-3.patch'))).toBe(true)
117
+
118
+ // Re-split with room for two shards. shard-3.patch describes a file set no
119
+ // shard id owns any more, so it must not survive the new split.
120
+ const second = await shardDiff(runDir, { budget: 450 })
121
+ expect(second.shards).toHaveLength(2)
122
+ const patches = (await readdir(join(runDir, 'shards'))).filter((n) => n.endsWith('.patch')).sort()
123
+ expect(patches).toEqual(['shard-1.patch', 'shard-2.patch'])
124
+ expect(existsSync(join(runDir, 'shards', 'manifest.json'))).toBe(true)
125
+ })
126
+
127
+ test('a re-split down to one shard clears every shard patch and keeps the manifest', async () => {
128
+ const diff = chunk('src/a/one.ts', 200) + chunk('src/b/two.ts', 200)
129
+ await writeFile(join(runDir, 'diff.patch'), diff)
130
+ expect((await shardDiff(runDir, { budget: 150 })).shards).toHaveLength(2)
131
+ const manifest = await shardDiff(runDir, { budget: 10_000 })
132
+ expect(manifest.shards).toHaveLength(1)
133
+ expect(manifest.shards[0]?.path).toBe('diff.patch')
134
+ // Only the manifest is left: the single-shard entry points at diff.patch, and
135
+ // diff.patch itself lives outside shards/ and is never touched.
136
+ expect(await readdir(join(runDir, 'shards'))).toEqual(['manifest.json'])
137
+ expect(existsSync(join(runDir, 'diff.patch'))).toBe(true)
138
+ })
139
+
140
+ test('shardDiff handles an empty diff without writing shard files', async () => {
141
+ await writeFile(join(runDir, 'diff.patch'), '')
142
+ const manifest = await shardDiff(runDir)
143
+ expect(manifest.shards).toEqual([])
144
+ expect(manifest.totalFiles).toBe(0)
145
+ })
146
+
147
+ test('shardDiff propagates a non-ENOENT read failure instead of treating it as an empty diff', async () => {
148
+ // Make diff.patch a directory: reading it as text is a real, portable I/O
149
+ // failure (EISDIR) that is not "file absent" and must not be swallowed.
150
+ await mkdir(join(runDir, 'diff.patch'))
151
+ await expect(shardDiff(runDir)).rejects.toThrow()
152
+ })
153
+
154
+ test('shardDiff treats a diff.patch that does not exist yet as an empty diff', async () => {
155
+ // No writeFile at all here: diff.patch is genuinely absent, the one case
156
+ // the ENOENT branch exists to tolerate. Task 4 wires shardDiff into
157
+ // runSetup and Task 6 reads the manifest unconditionally, so "no diff yet"
158
+ // must still leave a readable manifest rather than a missing file.
159
+ expect(existsSync(join(runDir, 'diff.patch'))).toBe(false)
160
+ const manifest = await shardDiff(runDir)
161
+ expect(manifest.shards).toEqual([])
162
+ expect(manifest.totalFiles).toBe(0)
163
+ expect(manifest.totalLines).toBe(0)
164
+ expect(existsSync(join(runDir, 'shards', 'manifest.json'))).toBe(true)
165
+ })
@@ -117,7 +117,9 @@ test('SKILL.md no longer inlines the prompt bodies it moved out', async () => {
117
117
  expect(text).not.toContain(`\`\`\`${tag}`)
118
118
  }
119
119
  // The walkthrough is the always-read part; keep it small enough to be cheap.
120
- expect(text.split(/\s+/).length).toBeLessThan(2600)
120
+ // Raised from 2600 when the sharded-dispatch and fallback-diff prose was added:
121
+ // that's real, load-bearing procedure, not bloat.
122
+ expect(text.split(/\s+/).length).toBeLessThan(3000)
121
123
  })
122
124
 
123
125
  test('SKILL.md never instructs the agent to approve indexing', async () => {
@@ -327,3 +329,96 @@ test('the output contract tells specialists to look before they hedge', async ()
327
329
  expect(contract).toContain('Needs verification:')
328
330
  expect(contract).toMatch(/look before .*hedg/i)
329
331
  })
332
+
333
+ test('the output contract documents both findings filenames', async () => {
334
+ const text = await readFile(ref('specialists.md'), 'utf8')
335
+ const contract = text.slice(0, text.indexOf('```magpie-specialist-'))
336
+ // The pre-existing assertion must keep holding.
337
+ expect(contract).toMatch(/findings\/<focus>\.json/)
338
+ expect(contract).toMatch(/findings\/<focus>\.shard-<n>\.json/)
339
+ })
340
+
341
+ test('the run header documents the shard lines', async () => {
342
+ const text = await readFile(ref('specialists.md'), 'utf8')
343
+ expect(text).toContain('Shard: <n> of <N>')
344
+ expect(text).toContain('shards/shard-<n>.patch')
345
+ })
346
+
347
+ test('specialists are told excluded files are still reachable', async () => {
348
+ const text = await readFile(ref('specialists.md'), 'utf8')
349
+ expect(text).toContain('diff.full.patch')
350
+ expect(text).toContain('excluded-files.json')
351
+ })
352
+
353
+ test('stage 4 pins the shard field on the specialist log entry', async () => {
354
+ const text = await readFile(SKILL, 'utf8')
355
+ const start = text.indexOf('### 4. Specialists')
356
+ expect(start).toBeGreaterThan(-1)
357
+ const section = text.slice(start, text.indexOf('\n### 5.', start))
358
+ // render-cmd sums per-focus findings counts keyed on this field. Drop it from a
359
+ // sharded run and every shard of a focus lands in one 'all' bucket,
360
+ // last-write-wins, so the progress page under-reports by up to the shard count
361
+ // with no error anywhere. This prose is the only thing that produces the field.
362
+ expect(section).toMatch(/\{stage: specialist,[^}]*\bshard: <n>/)
363
+ // ... and the unsharded path must still omit it, or 'all' would never be used.
364
+ expect(section).toMatch(/omit `shard`/i)
365
+ })
366
+
367
+ test('stage 4 reconciles the expected findings files before dedupe', async () => {
368
+ const text = await readFile(SKILL, 'utf8')
369
+ const start = text.indexOf('### 4. Specialists')
370
+ const section = text.slice(start, text.indexOf('\n### 5.', start))
371
+ // Stage 4 fails only when every specialist fails, so losing 1 of 30 agents
372
+ // otherwise renders a report indistinguishable from a complete one.
373
+ expect(section).toMatch(/findings\/<focus>\.shard-<n>\.json/)
374
+ expect(section).toMatch(/5 × <shard count>/)
375
+ })
376
+
377
+ test('the stage-4 gate offers only options the pipeline can carry out', async () => {
378
+ const text = await readFile(SKILL, 'utf8')
379
+ const start = text.indexOf('**More than four shards')
380
+ expect(start).toBeGreaterThan(-1)
381
+ const gate = text.slice(start, text.indexOf('\n\n', start))
382
+ // Option 2: --max-files is what binds on a PR of many small files, so naming
383
+ // only --budget sends the user back to an unchanged shard count.
384
+ expect(gate).toContain('--budget')
385
+ expect(gate).toContain('--max-files')
386
+ // Option 3 must name a mechanism that exists. There is no unreviewed marker in
387
+ // the report, so the record is a diagnostic log entry, on a stage outside
388
+ // status-cmd's ORDER ladder and never `status: error`.
389
+ const { ORDER } = await import('../status-cmd.ts')
390
+ const stage = gate.match(/\{stage: ([a-z-]+), status: ([a-z-]+)/)
391
+ expect(stage?.[1]).toBeDefined()
392
+ expect(ORDER as readonly string[]).not.toContain(stage?.[1])
393
+ expect(stage?.[2]).not.toBe('error')
394
+ expect(gate).toMatch(/skipped/)
395
+ })
396
+
397
+ test('the excluded-files note is part of the specialist prompt, not commentary', async () => {
398
+ const spec = await readFile(ref('specialists.md'), 'utf8')
399
+ // Every other specialist-directed line lives in a fenced block; this one used to
400
+ // sit unfenced between two numbered assembly parts, where an assembling agent
401
+ // reads it as a note to itself and the specialist never sees it.
402
+ const fences = [...spec.matchAll(/^```[a-z-]*\n([\s\S]*?)^```/gm)].map((m) => m[1] ?? '')
403
+ const inFence = fences.some((body) => body.includes('diff.full.patch'))
404
+ expect(inFence).toBe(true)
405
+ // And it must be a numbered part of the assembly list, not floating text.
406
+ expect(spec).toMatch(/^\d+\. The excluded-files block below/m)
407
+ })
408
+
409
+ test('the specialist assembly list is numbered contiguously from 1', async () => {
410
+ const spec = await readFile(ref('specialists.md'), 'utf8')
411
+ // Anchor on the heading, not on item 3's inline `## Output Contract` reference.
412
+ const preamble = spec.slice(0, spec.indexOf('\n## Output Contract'))
413
+ const numbers = [...preamble.matchAll(/^(\d+)\. /gm)].map((m) => Number(m[1]))
414
+ expect(numbers.length).toBeGreaterThan(4)
415
+ expect(numbers).toEqual(numbers.map((_, i) => i + 1))
416
+ })
417
+
418
+ test('SKILL.md documents the shard manifest and the fan-out gate', async () => {
419
+ const text = await readFile(SKILL, 'utf8')
420
+ expect(text).toContain('shards/manifest.json')
421
+ expect(text).toContain('diff.patch')
422
+ // The confirmation gate above four shards is the design's only interactive stop.
423
+ expect(text).toMatch(/more than four shards/i)
424
+ })
@@ -3,6 +3,7 @@ import { join } from 'node:path'
3
3
  import { annotateChangedLines } from './changed-lines.ts'
4
4
  import { deduplicateFindings } from './dedupe.ts'
5
5
  import { verifyEvidence } from './evidence-filter.ts'
6
+ import { namespaceId, parseFindingsFilename } from './findings-files.ts'
6
7
  import { DEFAULT_THRESHOLD, scoreRisk } from './score.ts'
7
8
  import { FOCUS_IDS, parseFinding, type ReviewFinding } from './types.ts'
8
9
 
@@ -16,6 +17,49 @@ export type RunDedupeOptions = {
16
17
  threshold?: number
17
18
  }
18
19
 
20
+ /**
21
+ * The five focuses a specialist subagent writes. `tests` is a `FOCUS_IDS` entry
22
+ * too, but setup writes `findings/tests.json` once for the whole run with no
23
+ * subagent, so it is never expected per shard.
24
+ */
25
+ const SPECIALIST_FOCUS_IDS = FOCUS_IDS.filter((id) => id !== 'tests')
26
+
27
+ type Coverage = { expected: number; missing: string[] }
28
+
29
+ /**
30
+ * Reconcile the findings files on disk against the `(focus, shard)` pairs the
31
+ * shard manifest implies. Stage 4 fails the run only when *every* specialist
32
+ * fails, so a sharded run that lost one agent out of thirty still logs
33
+ * `specialists: done` and renders a report indistinguishable from a complete
34
+ * one. Returns null when there is nothing to reconcile against (no manifest, an
35
+ * unreadable one, or a manifest with no shards, which is what an empty or
36
+ * fully-filtered diff produces), leaving pre-sharder runs behaving exactly as
37
+ * they did before.
38
+ */
39
+ async function reconcileCoverage(runDir: string, present: Set<string>): Promise<Coverage | null> {
40
+ let shards: Array<Record<string, unknown>>
41
+ try {
42
+ const manifest = (await Bun.file(join(runDir, 'shards', 'manifest.json')).json()) as {
43
+ shards?: unknown
44
+ }
45
+ if (!Array.isArray(manifest.shards) || manifest.shards.length === 0) return null
46
+ shards = manifest.shards as Array<Record<string, unknown>>
47
+ } catch {
48
+ return null
49
+ }
50
+ // A single-shard manifest means stage 4 took the unsharded path, so its
51
+ // specialists write `<focus>.json` with no shard suffix.
52
+ const sharded = shards.length > 1
53
+ const expected: string[] = []
54
+ for (const [i, shard] of shards.entries()) {
55
+ const id = typeof shard?.id === 'number' ? shard.id : i + 1
56
+ for (const focus of SPECIALIST_FOCUS_IDS) {
57
+ expected.push(sharded ? `${focus}.shard-${id}.json` : `${focus}.json`)
58
+ }
59
+ }
60
+ return { expected: expected.length, missing: expected.filter((name) => !present.has(name)) }
61
+ }
62
+
19
63
  export async function runDedupe(runDir: string, options: RunDedupeOptions = {}): Promise<number> {
20
64
  const threshold = options.threshold ?? DEFAULT_THRESHOLD
21
65
  const findingsDir = join(runDir, 'findings')
@@ -29,8 +73,8 @@ export async function runDedupe(runDir: string, options: RunDedupeOptions = {}):
29
73
 
30
74
  for (const name of files) {
31
75
  if (!name.endsWith('.json')) continue
32
- const focus = name.slice(0, -'.json'.length)
33
- if (!FOCUS_IDS.includes(focus as (typeof FOCUS_IDS)[number])) {
76
+ const parsed = parseFindingsFilename(name)
77
+ if (!parsed || !FOCUS_IDS.includes(parsed.focus as (typeof FOCUS_IDS)[number])) {
34
78
  await logLine(runDir, {
35
79
  stage: 'dedupe',
36
80
  status: 'skip',
@@ -39,6 +83,7 @@ export async function runDedupe(runDir: string, options: RunDedupeOptions = {}):
39
83
  })
40
84
  continue
41
85
  }
86
+ const { focus, shard } = parsed
42
87
  const path = join(findingsDir, name)
43
88
  let raw: unknown
44
89
  try {
@@ -63,7 +108,8 @@ export async function runDedupe(runDir: string, options: RunDedupeOptions = {}):
63
108
  }
64
109
  for (const item of raw) {
65
110
  try {
66
- collected.push(parseFinding(item))
111
+ const finding = parseFinding(item)
112
+ collected.push({ ...finding, id: namespaceId(finding.id, focus, shard) })
67
113
  } catch (err) {
68
114
  await logLine(runDir, {
69
115
  stage: 'dedupe',
@@ -107,6 +153,14 @@ export async function runDedupe(runDir: string, options: RunDedupeOptions = {}):
107
153
  )}\n`,
108
154
  )
109
155
  }
156
+ const coverage = await reconcileCoverage(runDir, new Set(files))
157
+ if (coverage) {
158
+ process.stdout.write(
159
+ coverage.missing.length === 0
160
+ ? `dedupe: all ${coverage.expected} expected findings files present\n`
161
+ : `dedupe: ${coverage.missing.length} of ${coverage.expected} expected findings files missing (re-dispatch those specialists): ${coverage.missing.join(', ')}\n`,
162
+ )
163
+ }
110
164
  await logLine(runDir, {
111
165
  stage: 'dedupe',
112
166
  status: 'done',
@@ -118,6 +172,7 @@ export async function runDedupe(runDir: string, options: RunDedupeOptions = {}):
118
172
  skipped: evidence.skipped,
119
173
  dropped: evidence.dropped.length,
120
174
  },
175
+ ...(coverage ? { coverage } : {}),
121
176
  })
122
177
  return 0
123
178
  }
@@ -0,0 +1,28 @@
1
+ export type FileChunk = { path: string; text: string; lines: number }
2
+
3
+ export const FILE_HEADER = /^diff --git a\/(.+?) b\/(.+?)$/m
4
+
5
+ /** Split a unified diff on file boundaries. The first element may be a preamble
6
+ * that is not a file chunk; callers decide what to do with it. */
7
+ export function splitRawChunks(diff: string): string[] {
8
+ return diff.split(/^(?=diff --git )/m)
9
+ }
10
+
11
+ /** The b-side path of a file chunk, falling back to the a-side for deletions. */
12
+ export function chunkPath(chunk: string): string | null {
13
+ const m = chunk.match(FILE_HEADER)
14
+ return m?.[2] ?? m?.[1] ?? null
15
+ }
16
+
17
+ /** File chunks only, with their paths and patch-line counts resolved. */
18
+ export function splitFileChunks(diff: string): FileChunk[] {
19
+ if (!diff.trim()) return []
20
+ const out: FileChunk[] = []
21
+ for (const chunk of splitRawChunks(diff)) {
22
+ if (!chunk.startsWith('diff --git ')) continue
23
+ const path = chunkPath(chunk)
24
+ if (!path) continue
25
+ out.push({ path, text: chunk, lines: chunk.split('\n').length })
26
+ }
27
+ return out
28
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * A specialist writes `findings/<focus>.json`, or `findings/<focus>.shard-<n>.json`
3
+ * when stage 4 fanned the focus out across shards. Returns null for anything
4
+ * else, which the caller logs and skips.
5
+ */
6
+ export function parseFindingsFilename(
7
+ name: string,
8
+ ): { focus: string; shard: number | null } | null {
9
+ if (!name.endsWith('.json')) return null
10
+ const stem = name.slice(0, -'.json'.length)
11
+ const parts = stem.split('.')
12
+ const focus = parts[0]
13
+ if (!focus) return null
14
+ if (parts.length === 1) return { focus, shard: null }
15
+ if (parts.length > 2) return null
16
+ const m = /^shard-(\d+)$/.exec(parts[1] ?? '')
17
+ if (!m) return null
18
+ return { focus, shard: Number(m[1]) }
19
+ }
20
+
21
+ /**
22
+ * Every shard's security specialist mints `security-1` for its first finding,
23
+ * so a five-shard run yields five findings sharing one id, and the report and
24
+ * post stages key on id. Rewriting deterministically here beats asking five
25
+ * prompts to encode the shard themselves.
26
+ */
27
+ export function namespaceId(id: string, focus: string, shard: number | null): string {
28
+ if (shard === null) return id
29
+ const tag = `s${shard}`
30
+ const prefix = `${focus}-`
31
+ return id.startsWith(prefix) ? `${prefix}${tag}-${id.slice(prefix.length)}` : `${tag}-${id}`
32
+ }
@@ -1,16 +1,21 @@
1
1
  import { writeFile } from 'node:fs/promises'
2
2
  import { join } from 'node:path'
3
+ import { localPrDiff } from './git-diff.ts'
3
4
 
4
5
  export type FetchPrInput = {
5
6
  ghBin: string
6
7
  prNumber: number
7
8
  runDir: string
8
- /** Working directory for the gh invocation. Defaults to process.cwd(). */
9
+ /** Working directory for the gh and git invocations. Defaults to process.cwd(). */
9
10
  cwd?: string
11
+ /** git binary for the local-diff fallback. Defaults to `git` on PATH. */
12
+ gitBin?: string
13
+ /** Extra environment for the gh invocation. Test seam for the fake gh fixtures. */
14
+ env?: Record<string, string>
10
15
  }
11
16
 
12
17
  export type FetchPrResult =
13
- | { ok: true; prJsonPath: string; diffPath: string }
18
+ | { ok: true; prJsonPath: string; diffPath: string; source: 'gh' | 'git'; mergeBase?: string }
14
19
  | { ok: false; error: string }
15
20
 
16
21
  export const PR_VIEW_FIELDS = [
@@ -31,9 +36,23 @@ export const PR_VIEW_FIELDS = [
31
36
  'closingIssuesReferences',
32
37
  ].join(',')
33
38
 
39
+ function prFileCount(viewStdout: string): number {
40
+ try {
41
+ const parsed = JSON.parse(viewStdout) as { files?: unknown }
42
+ return Array.isArray(parsed.files) ? parsed.files.length : 0
43
+ } catch {
44
+ return 0
45
+ }
46
+ }
47
+
34
48
  export async function fetchPr(input: FetchPrInput): Promise<FetchPrResult> {
35
49
  const { ghBin, prNumber, runDir, cwd } = input
36
- const spawnOpts = { stdout: 'pipe' as const, stderr: 'pipe' as const, ...(cwd ? { cwd } : {}) }
50
+ const spawnOpts = {
51
+ stdout: 'pipe' as const,
52
+ stderr: 'pipe' as const,
53
+ ...(cwd ? { cwd } : {}),
54
+ ...(input.env ? { env: { ...process.env, ...input.env } } : {}),
55
+ }
37
56
  const view = Bun.spawn(
38
57
  [ghBin, 'pr', 'view', String(prNumber), '--json', PR_VIEW_FIELDS],
39
58
  spawnOpts,
@@ -48,20 +67,52 @@ export async function fetchPr(input: FetchPrInput): Promise<FetchPrResult> {
48
67
  }
49
68
  }
50
69
 
70
+ const prJsonPath = join(runDir, 'pr.json')
71
+ const diffPath = join(runDir, 'diff.patch')
72
+ await writeFile(prJsonPath, viewStdout)
73
+
51
74
  const diff = Bun.spawn([ghBin, 'pr', 'diff', String(prNumber)], spawnOpts)
52
75
  const diffStdout = await new Response(diff.stdout).text()
53
76
  const diffStderr = await new Response(diff.stderr).text()
54
77
  const diffExit = await diff.exited
55
- if (diffExit !== 0) {
56
- return {
57
- ok: false,
58
- error: `gh pr diff exit ${diffExit}: ${diffStderr.trim()}`,
59
- }
78
+
79
+ // GitHub refuses the `.diff` media type above roughly 300 files (HTTP 406),
80
+ // and a truncating proxy can answer 200 with nothing at all. Reviewing an
81
+ // empty diff as though it were the PR is the worse failure of the two, so
82
+ // both conditions fall through to the local clone.
83
+ const emptyForNonEmptyPr = diffStdout.trim() === '' && prFileCount(viewStdout) > 0
84
+ if (diffExit === 0 && !emptyForNonEmptyPr) {
85
+ await writeFile(diffPath, diffStdout)
86
+ return { ok: true, prJsonPath, diffPath, source: 'gh' }
60
87
  }
61
88
 
62
- const prJsonPath = join(runDir, 'pr.json')
63
- const diffPath = join(runDir, 'diff.patch')
64
- await writeFile(prJsonPath, viewStdout)
65
- await writeFile(diffPath, diffStdout)
66
- return { ok: true, prJsonPath, diffPath }
89
+ const ghError =
90
+ diffExit !== 0
91
+ ? `gh pr diff exit ${diffExit}: ${diffStderr.trim()}`
92
+ : 'gh pr diff returned an empty diff for a PR with changed files'
93
+
94
+ let pr: { baseRefName?: unknown; headRefOid?: unknown }
95
+ try {
96
+ pr = JSON.parse(viewStdout) as { baseRefName?: unknown; headRefOid?: unknown }
97
+ } catch (err) {
98
+ return { ok: false, error: `${ghError}; pr.json is unparseable: ${String(err)}` }
99
+ }
100
+ const baseRefName = typeof pr.baseRefName === 'string' ? pr.baseRefName : ''
101
+ const headRefOid = typeof pr.headRefOid === 'string' ? pr.headRefOid : ''
102
+ if (!baseRefName || !headRefOid) {
103
+ return { ok: false, error: `${ghError}; pr.json has no baseRefName/headRefOid to diff from` }
104
+ }
105
+
106
+ const local = await localPrDiff({
107
+ gitBin: input.gitBin ?? 'git',
108
+ repoPath: cwd ?? process.cwd(),
109
+ prNumber,
110
+ baseRefName,
111
+ headRefOid,
112
+ })
113
+ if (!local.ok) {
114
+ return { ok: false, error: `${ghError}; local fallback failed: ${local.error}` }
115
+ }
116
+ await writeFile(diffPath, local.diff)
117
+ return { ok: true, prJsonPath, diffPath, source: 'git', mergeBase: local.mergeBase }
67
118
  }
@@ -0,0 +1,111 @@
1
+ export type LocalDiffInput = {
2
+ gitBin: string
3
+ repoPath: string
4
+ prNumber: number
5
+ baseRefName: string
6
+ headRefOid: string
7
+ }
8
+
9
+ export type LocalDiffResult =
10
+ | { ok: true; diff: string; mergeBase: string }
11
+ | { ok: false; error: string }
12
+
13
+ async function git(
14
+ gitBin: string,
15
+ cwd: string,
16
+ args: string[],
17
+ ): Promise<{ exit: number; stdout: string; stderr: string }> {
18
+ const proc = Bun.spawn([gitBin, ...args], { cwd, stdout: 'pipe', stderr: 'pipe' })
19
+ const stdout = await new Response(proc.stdout).text()
20
+ const stderr = await new Response(proc.stderr).text()
21
+ const exit = await proc.exited
22
+ return { exit, stdout, stderr }
23
+ }
24
+
25
+ async function resolveCommit(gitBin: string, cwd: string, ref: string): Promise<string | null> {
26
+ const r = await git(gitBin, cwd, ['rev-parse', '--verify', '--quiet', `${ref}^{commit}`])
27
+ const sha = r.stdout.trim()
28
+ return r.exit === 0 && sha.length > 0 ? sha : null
29
+ }
30
+
31
+ /**
32
+ * Render a fetch's outcome for an error message, so a genuine failure (wrong
33
+ * remote, auth failure, rate limiting) can be told apart from a benign one
34
+ * (no origin, offline, non-GitHub remote) when resolution ends up failing.
35
+ * Empty when the fetch succeeded, since a successful fetch explains nothing.
36
+ */
37
+ function fetchDiagnostic(result: { exit: number; stderr: string }): string {
38
+ if (result.exit === 0) return ''
39
+ const stderr = result.stderr.trim()
40
+ return stderr ? `; git fetch: ${stderr}` : `; git fetch exited ${result.exit}`
41
+ }
42
+
43
+ /**
44
+ * Reproduce `gh pr diff` from the local clone. GitHub refuses the `.diff` media
45
+ * type above roughly 300 files, and a review that cannot get a diff is worth
46
+ * less than one built from local objects.
47
+ *
48
+ * Diffs from the merge base rather than the base tip so the output matches
49
+ * `gh pr diff`'s three-dot semantics: the PR's own changes, not every commit
50
+ * the base branch gained since the branch point.
51
+ */
52
+ export async function localPrDiff(input: LocalDiffInput): Promise<LocalDiffResult> {
53
+ const { gitBin, repoPath, prNumber, baseRefName, headRefOid } = input
54
+ const prRef = `refs/magpie/pr-${prNumber}`
55
+
56
+ // Best effort. `pull/<n>/head` is a GitHub convention and resolves fork PRs
57
+ // that `headRefName` cannot, but a repo with no `origin`, an offline run, or
58
+ // a non-GitHub remote must still work when the commits are already local.
59
+ // Each fetch's own result is kept (not discarded) so, if resolution below
60
+ // still fails, the error can say why the fetch didn't help.
61
+ const headFetch = await git(gitBin, repoPath, [
62
+ 'fetch',
63
+ 'origin',
64
+ `pull/${prNumber}/head:${prRef}`,
65
+ ])
66
+ const baseFetch = await git(gitBin, repoPath, ['fetch', 'origin', baseRefName])
67
+
68
+ let head: string | null = null
69
+ for (const ref of [prRef, headRefOid]) {
70
+ head = await resolveCommit(gitBin, repoPath, ref)
71
+ if (head) break
72
+ }
73
+ if (!head) {
74
+ return {
75
+ ok: false,
76
+ error: `cannot resolve PR head ${headRefOid} locally (tried ${prRef} and the SHA); fetch the PR branch and retry${fetchDiagnostic(headFetch)}`,
77
+ }
78
+ }
79
+ // Reviewing a stale local ref and reporting it as a review of the PR is worse
80
+ // than failing, so a mismatch is fatal rather than a warning.
81
+ if (head !== headRefOid) {
82
+ return {
83
+ ok: false,
84
+ error: `local PR head ${head} does not match the PR head ${headRefOid}; the local ref is stale`,
85
+ }
86
+ }
87
+
88
+ let base: string | null = null
89
+ for (const ref of [`origin/${baseRefName}`, baseRefName]) {
90
+ base = await resolveCommit(gitBin, repoPath, ref)
91
+ if (base) break
92
+ }
93
+ if (!base) {
94
+ return {
95
+ ok: false,
96
+ error: `cannot resolve base branch ${baseRefName} locally (tried origin/${baseRefName} and ${baseRefName})${fetchDiagnostic(baseFetch)}`,
97
+ }
98
+ }
99
+
100
+ const mb = await git(gitBin, repoPath, ['merge-base', base, head])
101
+ if (mb.exit !== 0) {
102
+ return { ok: false, error: `git merge-base exit ${mb.exit}: ${mb.stderr.trim()}` }
103
+ }
104
+ const mergeBase = mb.stdout.trim()
105
+
106
+ const d = await git(gitBin, repoPath, ['diff', '--no-color', '--find-renames', mergeBase, head])
107
+ if (d.exit !== 0) {
108
+ return { ok: false, error: `git diff exit ${d.exit}: ${d.stderr.trim()}` }
109
+ }
110
+ return { ok: true, diff: d.stdout, mergeBase }
111
+ }