@attalabs/vinaya 0.42.1 → 0.43.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 (88) hide show
  1. package/dist/checks/bin/check-evidence-fresh.js +177 -152
  2. package/dist/checks/bin/check-registry-gates.js +10 -3
  3. package/dist/index.js +300 -173
  4. package/dist/lib/pre-push-cache-test-run.js +145 -144
  5. package/dist/lib/pre-push-changed-files.js +10 -3
  6. package/dist/lib/pre-push-progress-dir.js +169 -147
  7. package/dist/lib/pre-push-select-tests.js +16 -4
  8. package/dist/lib/push-progress-observer.js +169 -147
  9. package/dist/programs/archive.js +172 -148
  10. package/dist/programs/audit.js +169 -147
  11. package/dist/programs/check.js +172 -148
  12. package/dist/programs/commit-msg.js +172 -148
  13. package/dist/programs/dev-review-loop.js +300 -176
  14. package/dist/programs/dispatch.js +1905 -1877
  15. package/dist/programs/log-emit.js +172 -148
  16. package/dist/programs/log-selftest.js +172 -148
  17. package/dist/programs/log-send.js +172 -148
  18. package/dist/programs/pr-report.js +177 -152
  19. package/dist/programs/pr-snapshot.js +172 -148
  20. package/dist/programs/pr-verify-evidence.js +177 -152
  21. package/dist/programs/pr.js +172 -148
  22. package/dist/programs/review-post.js +172 -148
  23. package/dist/programs/review-status.js +180 -148
  24. package/dist/programs/run-engine.js +110594 -0
  25. package/dist/programs/supervised-command.js +67 -0
  26. package/dist/programs/sync.js +63 -39
  27. package/dist/programs/task-brief.js +174 -150
  28. package/dist/programs/task-sweep.js +244 -151
  29. package/dist/programs/task-tools-serve.js +260 -163
  30. package/dist/programs/tokens.js +172 -148
  31. package/dist/programs/waiver.js +172 -148
  32. package/dist/vinaya-strict/checks/registry.ts +1085 -0
  33. package/dist/vinaya-strict/executing/code-reviewer/README.md +3 -0
  34. package/dist/vinaya-strict/executing/code-reviewer/doctrine.md +185 -0
  35. package/dist/vinaya-strict/executing/code-reviewer/evals/README.md +1 -0
  36. package/dist/vinaya-strict/executing/code-reviewer/evals/code-reviewer-cases.json +280 -0
  37. package/dist/vinaya-strict/executing/code-reviewer/grants.yaml +22 -0
  38. package/dist/vinaya-strict/executing/code-reviewer/output.schema.json +93 -0
  39. package/dist/vinaya-strict/executing/code-reviewer/review-result.ts +347 -0
  40. package/dist/vinaya-strict/executing/dev-review.flow.yaml +103 -0
  41. package/dist/vinaya-strict/executing/developer/README.md +3 -0
  42. package/dist/vinaya-strict/executing/developer/developer-doctrine-shape.test.ts +69 -0
  43. package/dist/vinaya-strict/executing/developer/developer-turn-result.ts +286 -0
  44. package/dist/vinaya-strict/executing/developer/doctrine.md +111 -0
  45. package/dist/vinaya-strict/executing/developer/evals/README.md +1 -0
  46. package/dist/vinaya-strict/executing/developer/evals/developer-capability-cases.json +6275 -0
  47. package/dist/vinaya-strict/executing/developer/evals/developer-capability-held-out.json +11526 -0
  48. package/dist/vinaya-strict/executing/developer/evals/developer-capability-suite.test.ts +498 -0
  49. package/dist/vinaya-strict/executing/developer/evals/developer-capability-suite.ts +1407 -0
  50. package/dist/vinaya-strict/executing/developer/grants.yaml +25 -0
  51. package/dist/vinaya-strict/executing/developer/output.schema.json +148 -0
  52. package/dist/vinaya-strict/executing/developer/reference.md +376 -0
  53. package/dist/vinaya-strict/executing/operator/doctrine.md +209 -0
  54. package/dist/vinaya-strict/executing/security-reviewer/README.md +3 -0
  55. package/dist/vinaya-strict/executing/security-reviewer/doctrine.md +171 -0
  56. package/dist/vinaya-strict/executing/security-reviewer/evals/README.md +1 -0
  57. package/dist/vinaya-strict/executing/security-reviewer/evals/security-reviewer-cases.json +141 -0
  58. package/dist/vinaya-strict/executing/security-reviewer/grants.yaml +22 -0
  59. package/dist/vinaya-strict/executing/security-reviewer/output.schema.json +93 -0
  60. package/dist/vinaya-strict/integration/config/vinaya-config-section.ts +1278 -0
  61. package/dist/vinaya-strict/integration/policies/vinaya-policies.ts +52 -0
  62. package/dist/vinaya-strict/integration/process/process-integration.ts +57 -0
  63. package/dist/vinaya-strict/loops/dev-review/v2/dev-review-v2.flow.yaml +136 -0
  64. package/dist/vinaya-strict/process.yaml +43 -0
  65. package/dist/vinaya-strict/retrospecting/archivist/doctrine.md +174 -0
  66. package/dist/vinaya-strict/retrospecting/tranche-archivist/doctrine.md +270 -0
  67. package/dist/vinaya-strict/thinking/architect/doctrine.md +110 -0
  68. package/dist/vinaya-strict/thinking/planner/doctrine.md +105 -0
  69. package/dist/vinaya-strict/thinking/planner/tools/amend-rationale-deps.test.ts +128 -0
  70. package/dist/vinaya-strict/thinking/planner/tools/amend-rationale-deps.ts +169 -0
  71. package/dist/vinaya-strict/thinking/planner/tools/open-issue.test.ts +701 -0
  72. package/dist/vinaya-strict/thinking/planner/tools/open-issue.ts +1035 -0
  73. package/dist/vinaya-strict/thinking/planner/tools/planner-operations.test.ts +359 -0
  74. package/dist/vinaya-strict/thinking/planner/tools/planner-operations.ts +815 -0
  75. package/dist/vinaya-strict/thinking/planner/tools/planner-tools.test.ts +200 -0
  76. package/dist/vinaya-strict/thinking/planner/tools/planner-tools.ts +458 -0
  77. package/package.json +4 -2
  78. package/studio-standalone/apps/vinaya-studio/.next/BUILD_ID +1 -1
  79. package/studio-standalone/apps/vinaya-studio/.next/build-manifest.json +2 -2
  80. package/studio-standalone/apps/vinaya-studio/.next/server/app/_global-error.html +1 -1
  81. package/studio-standalone/apps/vinaya-studio/.next/server/app/_global-error.rsc +1 -1
  82. package/studio-standalone/apps/vinaya-studio/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  83. package/studio-standalone/apps/vinaya-studio/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  84. package/studio-standalone/apps/vinaya-studio/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  85. package/studio-standalone/apps/vinaya-studio/.next/server/middleware-build-manifest.js +1 -1
  86. package/studio-standalone/apps/vinaya-studio/.next/server/pages/500.html +1 -1
  87. /package/studio-standalone/apps/vinaya-studio/.next/static/{yFfoujElgbwPk-7KNS-kw → x2q88XfwsihlevulRhIvs}/_buildManifest.js +0 -0
  88. /package/studio-standalone/apps/vinaya-studio/.next/static/{yFfoujElgbwPk-7KNS-kw → x2q88XfwsihlevulRhIvs}/_ssgManifest.js +0 -0
@@ -0,0 +1,701 @@
1
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, unlinkSync, writeFileSync } from 'node:fs'
2
+ import { tmpdir } from 'node:os'
3
+ import { join } from 'node:path'
4
+ import { describe, expect, it, vi } from 'vitest'
5
+ import {
6
+ type AmendDepsDeps,
7
+ type AmendDepsFlags,
8
+ appliesTaskIssueGate,
9
+ blastRadiusErrorsForWrite,
10
+ edgesEqual,
11
+ formatLeftoverPrint,
12
+ type LeftoverFacts,
13
+ locateBody,
14
+ parseAmendArgs,
15
+ parseEdgeFlag,
16
+ printLeftoverStatus,
17
+ readSharedPackages,
18
+ resolveMilestoneToAttach,
19
+ resolveShippableArgs,
20
+ resolveTitleForLeftoverCheck,
21
+ runAmendDeps,
22
+ taskIdFromTitle,
23
+ validateAmendFlags
24
+ } from './open-issue'
25
+ import { BRIEF_SECTIONS_SINCE_ISSUE } from '../../../tools/task-contract/issue-validation'
26
+
27
+ describe('appliesTaskIssueGate (task-run-v1 21, #541, round 2 review SECURITY HIGH)', () => {
28
+ it('applies on a vinaya/tranche:* label alone, even with a body carrying no task-shaped content', () => {
29
+ expect(appliesTaskIssueGate(['vinaya/tranche:fixture'], 'just an ordinary body')).toBe(true)
30
+ })
31
+
32
+ it('applies on a labelless body that carries an ## Objectives heading — a backlog Issue, not a bypass', () => {
33
+ const body = ['## Objectives', '', 'O1. Do the thing.', ''].join('\n')
34
+ expect(appliesTaskIssueGate([], body)).toBe(true)
35
+ })
36
+
37
+ it('applies on a labelless body carrying a Planner rationale field, no Objectives heading needed', () => {
38
+ const body = '**Boundary** — some rationale text naming the scope.'
39
+ expect(appliesTaskIssueGate([], body)).toBe(true)
40
+ })
41
+
42
+ it('does NOT apply to a labelless, non-task-shaped body — an ordinary Issue passes through unvalidated, unchanged from before this task', () => {
43
+ expect(appliesTaskIssueGate([], 'just an ordinary bug report')).toBe(false)
44
+ })
45
+
46
+ it('does NOT apply when body is null and no label is present (create with no body yet)', () => {
47
+ expect(appliesTaskIssueGate([], null)).toBe(false)
48
+ })
49
+ })
50
+
51
+ describe('locateBody', () => {
52
+ it('reads --body-file <path> and records the file source with its arg index', () => {
53
+ const dir = mkdtempSync(join(tmpdir(), 'open-issue-test-'))
54
+ const p = join(dir, 'body.md')
55
+ writeFileSync(p, 'hello from file', 'utf8')
56
+ const result = locateBody(['--title', 't', '--body-file', p])
57
+ expect(result).toEqual({
58
+ body: 'hello from file',
59
+ source: { kind: 'file', argIndex: 3, inlineForm: false }
60
+ })
61
+ rmSync(dir, { recursive: true, force: true })
62
+ })
63
+
64
+ it('reads -F <path> the same as --body-file', () => {
65
+ const dir = mkdtempSync(join(tmpdir(), 'open-issue-test-'))
66
+ const p = join(dir, 'body.md')
67
+ writeFileSync(p, 'short flag', 'utf8')
68
+ const result = locateBody(['-F', p])
69
+ expect(result?.body).toBe('short flag')
70
+ expect(result?.source).toEqual({ kind: 'file', argIndex: 1, inlineForm: false })
71
+ rmSync(dir, { recursive: true, force: true })
72
+ })
73
+
74
+ it('reads --body-file=<path> inline-equals form', () => {
75
+ const dir = mkdtempSync(join(tmpdir(), 'open-issue-test-'))
76
+ const p = join(dir, 'body.md')
77
+ writeFileSync(p, 'equals form', 'utf8')
78
+ const result = locateBody([`--body-file=${p}`])
79
+ expect(result?.body).toBe('equals form')
80
+ expect(result?.source).toEqual({ kind: 'file', argIndex: 0, inlineForm: true })
81
+ rmSync(dir, { recursive: true, force: true })
82
+ })
83
+
84
+ it('reads --body/-b as an inline value, not a file source', () => {
85
+ const result = locateBody(['--body', 'literal body text'])
86
+ expect(result).toEqual({ body: 'literal body text', source: { kind: 'inline' } })
87
+ })
88
+
89
+ it('reads --body=<value> inline-equals form', () => {
90
+ const result = locateBody(['--body=literal equals'])
91
+ expect(result).toEqual({ body: 'literal equals', source: { kind: 'inline' } })
92
+ })
93
+
94
+ it('returns null when no body argument is present', () => {
95
+ expect(locateBody(['--title', 'no body here'])).toBeNull()
96
+ })
97
+ })
98
+
99
+ describe('resolveShippableArgs', () => {
100
+ it('materializes a file-sourced body to a fresh temp file with identical bytes, and cleans it up', () => {
101
+ const bodyResult = {
102
+ body: 'validated content',
103
+ source: { kind: 'file' as const, argIndex: 1, inlineForm: false }
104
+ }
105
+ const { finalArgs, cleanup } = resolveShippableArgs(['--body-file', '/some/original/path'], bodyResult)
106
+ const shipPath = finalArgs[1] as string
107
+ expect(shipPath).not.toBe('/some/original/path')
108
+ expect(readFileSync(shipPath, 'utf8')).toBe('validated content')
109
+ cleanup()
110
+ expect(existsSync(shipPath)).toBe(false)
111
+ })
112
+
113
+ it('rewrites the --body-file=<path> inline-equals form to point at the temp file', () => {
114
+ const bodyResult = {
115
+ body: 'inline-equals content',
116
+ source: { kind: 'file' as const, argIndex: 0, inlineForm: true }
117
+ }
118
+ const { finalArgs, cleanup } = resolveShippableArgs(['--body-file=/original/path'], bodyResult)
119
+ expect(finalArgs[0]).toMatch(/^--body-file=/)
120
+ const shipPath = (finalArgs[0] as string).slice('--body-file='.length)
121
+ expect(shipPath).not.toBe('/original/path')
122
+ expect(readFileSync(shipPath, 'utf8')).toBe('inline-equals content')
123
+ cleanup()
124
+ expect(existsSync(shipPath)).toBe(false)
125
+ })
126
+
127
+ it('leaves args untouched for an inline --body value — no temp file created', () => {
128
+ const bodyResult = { body: 'inline body', source: { kind: 'inline' as const } }
129
+ const original = ['--body', 'inline body']
130
+ const { finalArgs, cleanup } = resolveShippableArgs(original, bodyResult)
131
+ expect(finalArgs).toEqual(original)
132
+ expect(finalArgs).toBe(original)
133
+ expect(() => cleanup()).not.toThrow()
134
+ })
135
+
136
+ it('leaves args untouched when there is no body at all', () => {
137
+ const original = ['--title', 'x']
138
+ const { finalArgs, cleanup } = resolveShippableArgs(original, null)
139
+ expect(finalArgs).toEqual(original)
140
+ expect(() => cleanup()).not.toThrow()
141
+ })
142
+ })
143
+
144
+ describe('stream body-file input (the live-fire bug: Issues #329/#330/#331, PRs #325/#332)', () => {
145
+ it('ships the same bytes gh will re-read, even though the original source is gone by the time gh would re-read it', () => {
146
+ // A real /dev/stdin subprocess reproduction is not portable across OSes
147
+ // (confirmed: it throws ENXIO on Linux CI while working fine on macOS —
148
+ // a platform difference in how a piped child stdin resolves that path,
149
+ // not a Bun/Node difference this fix controls). Deleting the source file
150
+ // immediately after the one validation read is a deterministic,
151
+ // OS-independent stand-in for "this path is unreadable a second time" —
152
+ // exactly the property a stream has (drained/EOF) that a regular file
153
+ // does not. It proves the same invariant the bug report cares about:
154
+ // the SHIPPED path must not depend on the original path still being
155
+ // readable later, because for a stream it never is.
156
+ const dir = mkdtempSync(join(tmpdir(), 'open-issue-stream-sim-'))
157
+ const p = join(dir, 'body.md')
158
+ const streamContent = 'this body came from a one-shot source, not a regular file\n'
159
+ writeFileSync(p, streamContent, 'utf8')
160
+
161
+ const bodyResult = locateBody(['--body-file', p])
162
+ expect(bodyResult?.body).toBe(streamContent)
163
+
164
+ const { finalArgs, cleanup } = resolveShippableArgs(['--body-file', p], bodyResult)
165
+ const shipPath = finalArgs[1] as string
166
+
167
+ // Simulate the stream being drained/gone: delete the original source
168
+ // right after the one read that captured it, before gh would ever get
169
+ // to re-read it.
170
+ unlinkSync(p)
171
+
172
+ // gh's own read of the SHIPPED path gets the full content, and
173
+ // re-reading it again (idempotency check) still returns the same
174
+ // content — it's a real, independent file now, not tied to the
175
+ // original one-shot source.
176
+ expect(readFileSync(shipPath, 'utf8')).toBe(streamContent)
177
+ expect(readFileSync(shipPath, 'utf8')).toBe(streamContent)
178
+ // The original path is genuinely gone — proving the fix does not
179
+ // depend on it being re-readable (which is exactly what breaks for a
180
+ // real stream, just via a different underlying mechanism: EOF instead
181
+ // of ENOENT).
182
+ expect(() => readFileSync(p, 'utf8')).toThrow()
183
+
184
+ cleanup()
185
+ rmSync(dir, { recursive: true, force: true })
186
+ })
187
+ })
188
+
189
+ describe('regular-file body-file input is unaffected by the fix', () => {
190
+ it('ships identical content to what was validated, same as before the fix', () => {
191
+ const dir = mkdtempSync(join(tmpdir(), 'open-issue-regular-file-'))
192
+ const p = join(dir, 'body.md')
193
+ const content = 'a perfectly ordinary regular-file PR/Issue body\n'
194
+ writeFileSync(p, content, 'utf8')
195
+
196
+ const bodyResult = locateBody(['--body-file', p])
197
+ expect(bodyResult?.body).toBe(content)
198
+
199
+ const { finalArgs, cleanup } = resolveShippableArgs(['--body-file', p], bodyResult)
200
+ const shipPath = finalArgs[1] as string
201
+ // The shipped path is a NEW temp file, not the original — but its
202
+ // content matches exactly, and the original file is untouched/unaffected.
203
+ expect(shipPath).not.toBe(p)
204
+ expect(readFileSync(shipPath, 'utf8')).toBe(content)
205
+ expect(readFileSync(p, 'utf8')).toBe(content)
206
+
207
+ cleanup()
208
+ rmSync(dir, { recursive: true, force: true })
209
+ })
210
+ })
211
+
212
+ describe('resolveMilestoneToAttach (sample-tranche-v1 task 1 follow-up)', () => {
213
+ const activeLookup = vi.fn((slug: string) =>
214
+ slug === 'sample-tranche-v1' ? { number: 9, title: 'sample-tranche-v1' } : null
215
+ )
216
+
217
+ it('attaches the legacy Milestone TITLE when the label is present, an open Milestone matches, and no explicit --milestone was given', () => {
218
+ const lookup = vi.fn().mockReturnValue({ number: 9, title: 'sample-tranche-v1' })
219
+ const result = resolveMilestoneToAttach(
220
+ ['vinaya/tranche:sample-tranche-v1', 'vinaya/tier:1'],
221
+ ['--title', 't'],
222
+ false,
223
+ lookup
224
+ )
225
+ expect(result).toBe('sample-tranche-v1')
226
+ expect(lookup).toHaveBeenCalledWith('sample-tranche-v1')
227
+ })
228
+
229
+ it('attaches an intent-declared Milestone by its OWN title, not the slug — gh resolves --milestone by title only', () => {
230
+ const lookup = vi.fn().mockReturnValue({ number: 64, title: 'Engine' })
231
+ const result = resolveMilestoneToAttach(['vinaya/tranche:engine-agent-spawn-v1'], ['--title', 't'], false, lookup)
232
+ expect(result).toBe('Engine')
233
+ })
234
+
235
+ it('returns null on edit — creation-time behavior only, never force-attaches retroactively', () => {
236
+ const lookup = vi.fn().mockReturnValue({ number: 9, title: 'sample-tranche-v1' })
237
+ const result = resolveMilestoneToAttach(['vinaya/tranche:sample-tranche-v1'], ['--title', 't'], true, lookup)
238
+ expect(result).toBeNull()
239
+ expect(lookup).not.toHaveBeenCalled()
240
+ })
241
+
242
+ it('returns null when no tranche label is present — not a task Issue', () => {
243
+ const lookup = vi.fn()
244
+ const result = resolveMilestoneToAttach(['vinaya/tier:1'], ['--title', 't'], false, lookup)
245
+ expect(result).toBeNull()
246
+ expect(lookup).not.toHaveBeenCalled()
247
+ })
248
+
249
+ it('returns null when the caller already passed an explicit --milestone flag', () => {
250
+ const lookup = vi.fn()
251
+ const result = resolveMilestoneToAttach(
252
+ ['vinaya/tranche:sample-tranche-v1'],
253
+ ['--milestone', 'something-else'],
254
+ false,
255
+ lookup
256
+ )
257
+ expect(result).toBeNull()
258
+ expect(lookup).not.toHaveBeenCalled()
259
+ })
260
+
261
+ it('returns null when the caller passed --milestone=<value> inline-equals form', () => {
262
+ const lookup = vi.fn()
263
+ const result = resolveMilestoneToAttach(['vinaya/tranche:sample-tranche-v1'], ['--milestone=x'], false, lookup)
264
+ expect(result).toBeNull()
265
+ expect(lookup).not.toHaveBeenCalled()
266
+ })
267
+
268
+ it('returns null when no Milestone exists yet for the slug (not a hard failure)', () => {
269
+ const lookup = vi.fn().mockReturnValue(null)
270
+ const result = resolveMilestoneToAttach(['vinaya/tranche:brand-new-tranche'], ['--title', 't'], false, lookup)
271
+ expect(result).toBeNull()
272
+ })
273
+
274
+ it('returns null when the lookup finds no attach target (e.g. the only match is a closed legacy Milestone)', () => {
275
+ const lookup = vi.fn().mockReturnValue(null)
276
+ const result = resolveMilestoneToAttach(['vinaya/tranche:other-tranche-v1'], ['--title', 't'], false, lookup)
277
+ expect(result).toBeNull()
278
+ })
279
+
280
+ it('uses the first vinaya/tranche:<slug> label when multiple are somehow present', () => {
281
+ const result = resolveMilestoneToAttach(
282
+ ['vinaya/tranche:sample-tranche-v1', 'vinaya/tranche:other-tranche'],
283
+ ['--title', 't'],
284
+ false,
285
+ activeLookup
286
+ )
287
+ expect(result).toBe('sample-tranche-v1')
288
+ })
289
+ })
290
+
291
+ // ---------- taskIdFromTitle (leftover-detection print, #309) -----------------
292
+
293
+ describe('taskIdFromTitle', () => {
294
+ it('extracts the task id from a well-formed task title', () => {
295
+ expect(taskIdFromTitle('[vinaya-ui-pages-v1] 3 — Build /compare page')).toBe('3')
296
+ })
297
+ it('accepts a non-numeric task id (the grammar is \\S+, not digits-only)', () => {
298
+ expect(taskIdFromTitle('[vinaya-ui-pages-v1] 3a — Split follow-up')).toBe('3a')
299
+ })
300
+ it('returns null for a non-task (commitlint-style) title', () => {
301
+ expect(taskIdFromTitle('Fix(cli): open-issue prints leftover-detection')).toBeNull()
302
+ })
303
+ it('returns null when the em dash is missing', () => {
304
+ expect(taskIdFromTitle('[vinaya-ui-pages-v1] 3 no dash here')).toBeNull()
305
+ })
306
+ })
307
+
308
+ // ---------- formatLeftoverPrint / printLeftoverStatus (edit-time leftover-detection, #309/#311) -----
309
+
310
+ describe('formatLeftoverPrint', () => {
311
+ it('reports clean when no branch and no PR exist', () => {
312
+ const facts: LeftoverFacts = { branchExistsRemote: false, commitsAheadOfMain: 0, openPrNumber: null }
313
+ const msg = formatLeftoverPrint('vinaya-ui-pages-v1', '3', facts)
314
+ expect(msg).toContain('task 3 (vinaya-ui-pages-v1) — clean')
315
+ })
316
+
317
+ it('reports stop and names the open PR when real work already exists (the #919 shape)', () => {
318
+ const facts: LeftoverFacts = { branchExistsRemote: true, commitsAheadOfMain: 2, openPrNumber: 1025 }
319
+ const msg = formatLeftoverPrint('vinaya-ui-pages-v1', '3', facts)
320
+ expect(msg).toContain('— stop.')
321
+ expect(msg).toContain('PR #1025 is already open for this task.')
322
+ })
323
+
324
+ it('reports resume when the branch exists but carries no commits yet', () => {
325
+ const facts: LeftoverFacts = { branchExistsRemote: true, commitsAheadOfMain: 0, openPrNumber: null }
326
+ const msg = formatLeftoverPrint('some-tranche', '7', facts)
327
+ expect(msg).toContain('— resume.')
328
+ })
329
+
330
+ it('reports "could not check" without throwing when facts are null (git/gh unreachable)', () => {
331
+ const msg = formatLeftoverPrint('some-tranche', '7', null)
332
+ expect(msg).toContain('could not check task 7 (some-tranche) — git/gh unreachable, skipping.')
333
+ })
334
+ })
335
+
336
+ describe('printLeftoverStatus', () => {
337
+ it('calls the injected fetcher with the derived task branch and logs its formatted result', () => {
338
+ const log = vi.spyOn(console, 'log').mockImplementation(() => undefined)
339
+ const fetchFacts = vi.fn((branch: string): LeftoverFacts | null =>
340
+ branch === 'task/vinaya-ui-pages-v1/3'
341
+ ? { branchExistsRemote: true, commitsAheadOfMain: 2, openPrNumber: 1025 }
342
+ : null
343
+ )
344
+ printLeftoverStatus('vinaya-ui-pages-v1', '3', fetchFacts)
345
+ expect(fetchFacts).toHaveBeenCalledWith('task/vinaya-ui-pages-v1/3')
346
+ expect(log).toHaveBeenCalledWith(expect.stringContaining('PR #1025 is already open'))
347
+ log.mockRestore()
348
+ })
349
+
350
+ it('never throws when the injected fetcher returns null', () => {
351
+ const log = vi.spyOn(console, 'log').mockImplementation(() => undefined)
352
+ expect(() => printLeftoverStatus('some-tranche', '7', () => null)).not.toThrow()
353
+ expect(log).toHaveBeenCalledWith(expect.stringContaining('could not check'))
354
+ log.mockRestore()
355
+ })
356
+ })
357
+
358
+ describe('resolveTitleForLeftoverCheck (the create-path coverage restored on review, #311 round 2)', () => {
359
+ it('uses the argv title on create — never touches the injected fetcher', () => {
360
+ const fetchTitle = vi.fn(() => 'should not be called')
361
+ const title = resolveTitleForLeftoverCheck(
362
+ ['--title', '[vinaya-ui-pages-v1] 3 — Build /compare'],
363
+ false,
364
+ null,
365
+ fetchTitle
366
+ )
367
+ expect(title).toBe('[vinaya-ui-pages-v1] 3 — Build /compare')
368
+ expect(fetchTitle).not.toHaveBeenCalled()
369
+ })
370
+
371
+ it('uses the argv title on edit when one is given — never touches the injected fetcher', () => {
372
+ const fetchTitle = vi.fn(() => 'should not be called')
373
+ const title = resolveTitleForLeftoverCheck(
374
+ ['--title', '[vinaya-ui-pages-v1] 3 — Retitled'],
375
+ true,
376
+ '919',
377
+ fetchTitle
378
+ )
379
+ expect(title).toBe('[vinaya-ui-pages-v1] 3 — Retitled')
380
+ expect(fetchTitle).not.toHaveBeenCalled()
381
+ })
382
+
383
+ it('falls back to the injected fetcher on edit with no argv title — the common body-only re-plan', () => {
384
+ const fetchTitle = vi.fn((issueRef: string) => (issueRef === '919' ? '[vinaya-ui-pages-v1] 3 — From forge' : null))
385
+ const title = resolveTitleForLeftoverCheck(['--body-file', '/tmp/body.md'], true, '919', fetchTitle)
386
+ expect(title).toBe('[vinaya-ui-pages-v1] 3 — From forge')
387
+ expect(fetchTitle).toHaveBeenCalledWith('919')
388
+ })
389
+
390
+ it('returns null on create with no argv title, without ever calling the fetcher — create always requires --title to open the Issue at all, but this function must not assume that and reach for the forge', () => {
391
+ const fetchTitle = vi.fn(() => 'should not be called')
392
+ const title = resolveTitleForLeftoverCheck(['--body-file', '/tmp/body.md'], false, null, fetchTitle)
393
+ expect(title).toBeNull()
394
+ expect(fetchTitle).not.toHaveBeenCalled()
395
+ })
396
+ })
397
+
398
+ // ---------- amend-deps subcommand (Issue #481, drift class #1) ----------------
399
+
400
+ const BODY_429 = readFileSync(join(__dirname, '../../../tools/task-contract/forge/fixtures/issue-429-body.md'), 'utf8')
401
+
402
+ describe('parseEdgeFlag', () => {
403
+ it('splits a comma-joined value into trimmed ids', () => {
404
+ expect(parseEdgeFlag('1, 2, sample-x #3')).toEqual(['1', '2', 'sample-x #3'])
405
+ })
406
+ it('treats every empty marker as no edges', () => {
407
+ for (const marker of ['—', '–', '-', '', ' ']) expect(parseEdgeFlag(marker)).toEqual([])
408
+ })
409
+ })
410
+
411
+ describe('edgesEqual', () => {
412
+ it('is order-sensitive and length-sensitive', () => {
413
+ expect(edgesEqual(['1', '2'], ['1', '2'])).toBe(true)
414
+ expect(edgesEqual(['1', '2'], ['2', '1'])).toBe(false)
415
+ expect(edgesEqual(['1'], ['1', '2'])).toBe(false)
416
+ expect(edgesEqual([], [])).toBe(true)
417
+ })
418
+ })
419
+
420
+ describe('parseAmendArgs', () => {
421
+ it('parses the issue, both edge flags, note, actor, and dry-run', () => {
422
+ const flags = parseAmendArgs([
423
+ '481',
424
+ '--depends-on',
425
+ '1, 2',
426
+ '--conflicts-with',
427
+ '—',
428
+ '--note',
429
+ 'why',
430
+ '--actor',
431
+ 'Alice',
432
+ '--dry-run'
433
+ ])
434
+ expect(flags).toEqual({
435
+ issue: '481',
436
+ dependsOn: ['1', '2'],
437
+ conflictsWith: [],
438
+ note: 'why',
439
+ actor: 'Alice',
440
+ dryRun: true
441
+ })
442
+ })
443
+ it('leaves an unpassed edge field undefined (untouched)', () => {
444
+ const flags = parseAmendArgs(['481', '--conflicts-with', '3', '--note', 'x'])
445
+ expect(flags.dependsOn).toBeUndefined()
446
+ expect(flags.conflictsWith).toEqual(['3'])
447
+ })
448
+ it('supports the --flag=value form', () => {
449
+ const flags = parseAmendArgs(['481', '--depends-on=4,5', '--note=y'])
450
+ expect(flags.dependsOn).toEqual(['4', '5'])
451
+ expect(flags.note).toBe('y')
452
+ })
453
+ })
454
+
455
+ describe('validateAmendFlags', () => {
456
+ const base: AmendDepsFlags = { issue: '481', note: 'why', actor: 'Planner', dryRun: false }
457
+ it('refuses when neither edge flag is present', () => {
458
+ expect(validateAmendFlags(base)).toMatch(/at least one of/)
459
+ })
460
+ it('refuses an empty note', () => {
461
+ expect(validateAmendFlags({ ...base, dependsOn: ['1'], note: ' ' })).toMatch(/non-empty `--note`/)
462
+ })
463
+ it('refuses a missing issue', () => {
464
+ expect(validateAmendFlags({ ...base, issue: null, dependsOn: ['1'] })).toMatch(/target Issue number/)
465
+ })
466
+ it('accepts a well-formed flag set', () => {
467
+ expect(validateAmendFlags({ ...base, dependsOn: ['1'] })).toBeNull()
468
+ })
469
+ })
470
+
471
+ function makeDeps(overrides: Partial<AmendDepsDeps> = {}): {
472
+ deps: AmendDepsDeps
473
+ edited: Array<{ issue: string; body: string }>
474
+ logs: string[]
475
+ } {
476
+ const edited: Array<{ issue: string; body: string }> = []
477
+ const logs: string[] = []
478
+ const deps: AmendDepsDeps = {
479
+ fetchLabels: () => ['vinaya/tranche:other-tranche-v1', 'vinaya/tier:1'],
480
+ fetchBody: () => BODY_429,
481
+ editBody: (issue, body) => edited.push({ issue, body }),
482
+ today: () => '2026-07-13',
483
+ log: (m) => logs.push(m),
484
+ fail: (m) => {
485
+ throw new Error(m)
486
+ },
487
+ ...overrides
488
+ }
489
+ return { deps, edited, logs }
490
+ }
491
+
492
+ describe('runAmendDeps', () => {
493
+ it('refuses when the target is not a task Issue (no vinaya/tranche:* label)', () => {
494
+ const { deps, edited } = makeDeps({ fetchLabels: () => ['vinaya/tier:1'] })
495
+ expect(() => runAmendDeps(parseAmendArgs(['429', '--depends-on', '2', '--note', 'x']), deps)).toThrow(
496
+ /targets task Issues only/
497
+ )
498
+ expect(edited).toHaveLength(0)
499
+ })
500
+
501
+ it('refuses a missing --note (flag validation) with no forge write', () => {
502
+ const { deps, edited } = makeDeps()
503
+ expect(() => runAmendDeps(parseAmendArgs(['429', '--depends-on', '2']), deps)).toThrow(/non-empty `--note`/)
504
+ expect(edited).toHaveLength(0)
505
+ })
506
+
507
+ it('refuses on a round-trip mismatch and writes nothing (the gate, on real data)', () => {
508
+ // `sample-tranche-v1 #368, 5` — the bare `5` inherits the qualifier
509
+ // on parse (→ `sample-tranche-v1 5`), so the read-back != requested.
510
+ const { deps, edited } = makeDeps()
511
+ expect(() =>
512
+ runAmendDeps(parseAmendArgs(['429', '--depends-on', 'sample-tranche-v1 #368, 5', '--note', 'x']), deps)
513
+ ).toThrow(/round-trip FAILED for Depends-on/)
514
+ expect(edited).toHaveLength(0)
515
+ })
516
+
517
+ it('dry-run prints the body + round-trip PASS and performs NO forge write', () => {
518
+ const { deps, edited, logs } = makeDeps()
519
+ runAmendDeps(parseAmendArgs(['429', '--depends-on', '2, 3', '--note', 'Task 3 dropped.', '--dry-run']), deps)
520
+ expect(edited).toHaveLength(0)
521
+ expect(logs).toContain('round-trip PASS')
522
+ expect(logs.some((l) => l.includes('`Depends-on: 2, 3`'))).toBe(true)
523
+ })
524
+
525
+ it('a real run ships the amended body once and logs the edge change', () => {
526
+ const { deps, edited, logs } = makeDeps()
527
+ runAmendDeps(parseAmendArgs(['429', '--depends-on', '2, 3', '--note', 'Task 3 dropped.']), deps)
528
+ expect(edited).toHaveLength(1)
529
+ expect(edited[0]?.issue).toBe('429')
530
+ expect(edited[0]?.body).toContain('**Amendment (2026-07-13, Planner)')
531
+ // The before-set is what the reader declares for fixture #429: since #347
532
+ // that is its labeled span alone, not the bare `3a`/`3b` continuations.
533
+ expect(logs.some((l) => l.includes('Depends-on: [1] → [2, 3]'))).toBe(true)
534
+ })
535
+ })
536
+
537
+ describe('readSharedPackages', () => {
538
+ function makeFixtureRepo(): string {
539
+ return mkdtempSync(join(tmpdir(), 'open-issue-blast-radius-'))
540
+ }
541
+
542
+ it('runs live against this repo — derived packages/* + present built-in defaults, zero-file, no error', () => {
543
+ // This repo's `vinaya.config.json` carries no `blastRadius` field — this
544
+ // is the "brand-new adopter" shape Part 3 exists to make work. The
545
+ // default REPO_ROOT is this checkout.
546
+ const result = readSharedPackages()
547
+ expect(result).toContain('packages/typescript-config')
548
+ expect(result).toContain('packages/typescript-config')
549
+ expect(result).toContain('bun.lock')
550
+ expect(result).toContain('turbo.json')
551
+ expect(result).toContain('.github/workflows')
552
+ // This repo has no `.husky` directory (hooks are tracked elsewhere) — the
553
+ // presence-check must not fabricate a domain for a path that isn't there.
554
+ expect(result).not.toContain('.husky')
555
+ })
556
+
557
+ it('derives + defaults from a fixture repo with zero vinaya.config.json', () => {
558
+ const dir = makeFixtureRepo()
559
+ try {
560
+ writeFileSync(join(dir, 'package.json'), JSON.stringify({ workspaces: ['packages/*'] }), 'utf8')
561
+ mkdirSync(join(dir, 'packages/foo'), { recursive: true })
562
+ mkdirSync(join(dir, 'packages/bar'), { recursive: true })
563
+ writeFileSync(join(dir, 'bun.lock'), '', 'utf8')
564
+ writeFileSync(join(dir, 'turbo.json'), '{}', 'utf8')
565
+
566
+ const result = readSharedPackages(dir)
567
+ expect(result.sort()).toEqual(['bun.lock', 'packages/bar', 'packages/foo', 'turbo.json'].sort())
568
+ } finally {
569
+ rmSync(dir, { recursive: true, force: true })
570
+ }
571
+ })
572
+
573
+ it('an empty directory (no package.json, no defaults present) derives nothing — check A stays dormant', () => {
574
+ const dir = makeFixtureRepo()
575
+ try {
576
+ expect(readSharedPackages(dir)).toEqual([])
577
+ } finally {
578
+ rmSync(dir, { recursive: true, force: true })
579
+ }
580
+ })
581
+
582
+ it('a pnpm adopter (pnpm-workspace.yaml, no `workspaces` key in package.json) still derives packages/* domains', () => {
583
+ // pnpm does not read a `workspaces` key from package.json at all — its
584
+ // real workspace glob lives only in pnpm-workspace.yaml. Review finding
585
+ // on this PR: reading only package.json silently zeroed this out for
586
+ // every pnpm adopter.
587
+ const dir = makeFixtureRepo()
588
+ try {
589
+ writeFileSync(join(dir, 'package.json'), JSON.stringify({ name: 'root' }), 'utf8')
590
+ writeFileSync(join(dir, 'pnpm-workspace.yaml'), "packages:\n - 'packages/*'\n", 'utf8')
591
+ mkdirSync(join(dir, 'packages/foo'), { recursive: true })
592
+ writeFileSync(join(dir, 'pnpm-lock.yaml'), '', 'utf8')
593
+
594
+ const result = readSharedPackages(dir)
595
+ expect(result).toContain('packages/foo')
596
+ expect(result).toContain('pnpm-lock.yaml')
597
+ } finally {
598
+ rmSync(dir, { recursive: true, force: true })
599
+ }
600
+ })
601
+
602
+ it('package.json workspaces AND pnpm-workspace.yaml packages both contribute when both are present', () => {
603
+ const dir = makeFixtureRepo()
604
+ try {
605
+ writeFileSync(join(dir, 'package.json'), JSON.stringify({ workspaces: ['packages/*'] }), 'utf8')
606
+ writeFileSync(join(dir, 'pnpm-workspace.yaml'), "packages:\n - 'apps/*'\n", 'utf8')
607
+ mkdirSync(join(dir, 'packages/foo'), { recursive: true })
608
+ mkdirSync(join(dir, 'apps/bar'), { recursive: true })
609
+
610
+ const result = readSharedPackages(dir)
611
+ expect(result).toContain('packages/foo')
612
+ // apps/* has no packages/ prefix — never derived as a domain, same as
613
+ // any other apps/*-only workspace entry.
614
+ expect(result).not.toContain('apps/bar')
615
+ } finally {
616
+ rmSync(dir, { recursive: true, force: true })
617
+ }
618
+ })
619
+
620
+ it('a workspace negation entry excludes exactly what it names, end to end through readSharedPackages', () => {
621
+ const dir = makeFixtureRepo()
622
+ try {
623
+ writeFileSync(
624
+ join(dir, 'package.json'),
625
+ JSON.stringify({ workspaces: ['packages/*', '!packages/legacy'] }),
626
+ 'utf8'
627
+ )
628
+ mkdirSync(join(dir, 'packages/foo'), { recursive: true })
629
+ mkdirSync(join(dir, 'packages/legacy'), { recursive: true })
630
+
631
+ const result = readSharedPackages(dir)
632
+ expect(result).toContain('packages/foo')
633
+ expect(result).not.toContain('packages/legacy')
634
+ } finally {
635
+ rmSync(dir, { recursive: true, force: true })
636
+ }
637
+ })
638
+
639
+ it("vinaya.config.json's blastRadius.extraDomains ADDS to the derived + default set", () => {
640
+ const dir = makeFixtureRepo()
641
+ try {
642
+ writeFileSync(join(dir, 'package.json'), JSON.stringify({ workspaces: ['packages/*'] }), 'utf8')
643
+ mkdirSync(join(dir, 'packages/foo'), { recursive: true })
644
+ writeFileSync(
645
+ join(dir, 'vinaya.config.json'),
646
+ JSON.stringify({ blastRadius: { extraDomains: ['migrations/codegen'] } }),
647
+ 'utf8'
648
+ )
649
+
650
+ const result = readSharedPackages(dir)
651
+ expect(result).toContain('packages/foo')
652
+ expect(result).toContain('migrations/codegen')
653
+ } finally {
654
+ rmSync(dir, { recursive: true, force: true })
655
+ }
656
+ })
657
+
658
+ it('derived domains AND vinaya.config.json extraDomains apply together, deduplicated', () => {
659
+ const dir = makeFixtureRepo()
660
+ try {
661
+ writeFileSync(join(dir, 'package.json'), JSON.stringify({ workspaces: ['packages/*'] }), 'utf8')
662
+ mkdirSync(join(dir, 'packages/foo'), { recursive: true })
663
+ writeFileSync(
664
+ join(dir, 'vinaya.config.json'),
665
+ // 'packages/foo' is already derived — declaring it again in
666
+ // extraDomains must not produce a duplicate entry.
667
+ JSON.stringify({ blastRadius: { extraDomains: ['packages/foo', 'codegen/out'] } }),
668
+ 'utf8'
669
+ )
670
+
671
+ const result = readSharedPackages(dir)
672
+ expect(result.sort()).toEqual(['codegen/out', 'packages/foo'])
673
+ } finally {
674
+ rmSync(dir, { recursive: true, force: true })
675
+ }
676
+ })
677
+ })
678
+
679
+ describe('blastRadiusErrorsForWrite', () => {
680
+ const shared = ['packages/ui']
681
+ const registry = [{ name: 'vinaya', path: 'apps/vinaya' }]
682
+ const surfaceBody = '## Surface\n\nin: packages/ui/**\nout: —\n\n**Project:** vinaya\n'
683
+
684
+ it('judges a create (no Issue ref) from `## Surface`', () => {
685
+ const errors = blastRadiusErrorsForWrite(surfaceBody, [], shared, registry, null)
686
+ expect(errors).toHaveLength(1)
687
+ expect(errors[0]).toMatch(/packages\/ui/)
688
+ })
689
+
690
+ it('judges an edit above the cutover from `## Surface`, the same as a create', () => {
691
+ const ref = String(BRIEF_SECTIONS_SINCE_ISSUE + 1)
692
+ expect(blastRadiusErrorsForWrite(surfaceBody, [], shared, registry, ref)).toEqual(
693
+ blastRadiusErrorsForWrite(surfaceBody, [], shared, registry, null)
694
+ )
695
+ })
696
+
697
+ it('keeps an edit of an Issue numbered below the cutover on the prose scan', () => {
698
+ const ref = `https://github.com/o/r/issues/${BRIEF_SECTIONS_SINCE_ISSUE - 1}`
699
+ expect(blastRadiusErrorsForWrite(surfaceBody, [], shared, registry, ref)).toEqual([])
700
+ })
701
+ })