@attalabs/vinaya 0.42.2 → 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 (82) hide show
  1. package/dist/checks/bin/check-evidence-fresh.js +8 -5
  2. package/dist/index.js +20 -17
  3. package/dist/lib/pre-push-cache-test-run.js +3 -1
  4. package/dist/programs/archive.js +3 -1
  5. package/dist/programs/check.js +3 -1
  6. package/dist/programs/commit-msg.js +3 -1
  7. package/dist/programs/dev-review-loop.js +9 -6
  8. package/dist/programs/dispatch.js +3 -1
  9. package/dist/programs/log-emit.js +3 -1
  10. package/dist/programs/log-selftest.js +3 -1
  11. package/dist/programs/log-send.js +3 -1
  12. package/dist/programs/pr-report.js +8 -5
  13. package/dist/programs/pr-snapshot.js +3 -1
  14. package/dist/programs/pr-verify-evidence.js +8 -5
  15. package/dist/programs/pr.js +3 -1
  16. package/dist/programs/review-post.js +3 -1
  17. package/dist/programs/review-status.js +3 -1
  18. package/dist/programs/run-engine.js +110594 -0
  19. package/dist/programs/supervised-command.js +67 -0
  20. package/dist/programs/sync.js +3 -1
  21. package/dist/programs/task-brief.js +5 -3
  22. package/dist/programs/task-sweep.js +3 -1
  23. package/dist/programs/task-tools-serve.js +13 -11
  24. package/dist/programs/tokens.js +3 -1
  25. package/dist/programs/waiver.js +3 -1
  26. package/dist/vinaya-strict/checks/registry.ts +1085 -0
  27. package/dist/vinaya-strict/executing/code-reviewer/README.md +3 -0
  28. package/dist/vinaya-strict/executing/code-reviewer/doctrine.md +185 -0
  29. package/dist/vinaya-strict/executing/code-reviewer/evals/README.md +1 -0
  30. package/dist/vinaya-strict/executing/code-reviewer/evals/code-reviewer-cases.json +280 -0
  31. package/dist/vinaya-strict/executing/code-reviewer/grants.yaml +22 -0
  32. package/dist/vinaya-strict/executing/code-reviewer/output.schema.json +93 -0
  33. package/dist/vinaya-strict/executing/code-reviewer/review-result.ts +347 -0
  34. package/dist/vinaya-strict/executing/dev-review.flow.yaml +103 -0
  35. package/dist/vinaya-strict/executing/developer/README.md +3 -0
  36. package/dist/vinaya-strict/executing/developer/developer-doctrine-shape.test.ts +69 -0
  37. package/dist/vinaya-strict/executing/developer/developer-turn-result.ts +286 -0
  38. package/dist/vinaya-strict/executing/developer/doctrine.md +111 -0
  39. package/dist/vinaya-strict/executing/developer/evals/README.md +1 -0
  40. package/dist/vinaya-strict/executing/developer/evals/developer-capability-cases.json +6275 -0
  41. package/dist/vinaya-strict/executing/developer/evals/developer-capability-held-out.json +11526 -0
  42. package/dist/vinaya-strict/executing/developer/evals/developer-capability-suite.test.ts +498 -0
  43. package/dist/vinaya-strict/executing/developer/evals/developer-capability-suite.ts +1407 -0
  44. package/dist/vinaya-strict/executing/developer/grants.yaml +25 -0
  45. package/dist/vinaya-strict/executing/developer/output.schema.json +148 -0
  46. package/dist/vinaya-strict/executing/developer/reference.md +376 -0
  47. package/dist/vinaya-strict/executing/operator/doctrine.md +209 -0
  48. package/dist/vinaya-strict/executing/security-reviewer/README.md +3 -0
  49. package/dist/vinaya-strict/executing/security-reviewer/doctrine.md +171 -0
  50. package/dist/vinaya-strict/executing/security-reviewer/evals/README.md +1 -0
  51. package/dist/vinaya-strict/executing/security-reviewer/evals/security-reviewer-cases.json +141 -0
  52. package/dist/vinaya-strict/executing/security-reviewer/grants.yaml +22 -0
  53. package/dist/vinaya-strict/executing/security-reviewer/output.schema.json +93 -0
  54. package/dist/vinaya-strict/integration/config/vinaya-config-section.ts +1278 -0
  55. package/dist/vinaya-strict/integration/policies/vinaya-policies.ts +52 -0
  56. package/dist/vinaya-strict/integration/process/process-integration.ts +57 -0
  57. package/dist/vinaya-strict/loops/dev-review/v2/dev-review-v2.flow.yaml +136 -0
  58. package/dist/vinaya-strict/process.yaml +43 -0
  59. package/dist/vinaya-strict/retrospecting/archivist/doctrine.md +174 -0
  60. package/dist/vinaya-strict/retrospecting/tranche-archivist/doctrine.md +270 -0
  61. package/dist/vinaya-strict/thinking/architect/doctrine.md +110 -0
  62. package/dist/vinaya-strict/thinking/planner/doctrine.md +105 -0
  63. package/dist/vinaya-strict/thinking/planner/tools/amend-rationale-deps.test.ts +128 -0
  64. package/dist/vinaya-strict/thinking/planner/tools/amend-rationale-deps.ts +169 -0
  65. package/dist/vinaya-strict/thinking/planner/tools/open-issue.test.ts +701 -0
  66. package/dist/vinaya-strict/thinking/planner/tools/open-issue.ts +1035 -0
  67. package/dist/vinaya-strict/thinking/planner/tools/planner-operations.test.ts +359 -0
  68. package/dist/vinaya-strict/thinking/planner/tools/planner-operations.ts +815 -0
  69. package/dist/vinaya-strict/thinking/planner/tools/planner-tools.test.ts +200 -0
  70. package/dist/vinaya-strict/thinking/planner/tools/planner-tools.ts +458 -0
  71. package/package.json +4 -2
  72. package/studio-standalone/apps/vinaya-studio/.next/BUILD_ID +1 -1
  73. package/studio-standalone/apps/vinaya-studio/.next/build-manifest.json +2 -2
  74. package/studio-standalone/apps/vinaya-studio/.next/server/app/_global-error.html +1 -1
  75. package/studio-standalone/apps/vinaya-studio/.next/server/app/_global-error.rsc +1 -1
  76. package/studio-standalone/apps/vinaya-studio/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  77. package/studio-standalone/apps/vinaya-studio/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  78. package/studio-standalone/apps/vinaya-studio/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  79. package/studio-standalone/apps/vinaya-studio/.next/server/middleware-build-manifest.js +1 -1
  80. package/studio-standalone/apps/vinaya-studio/.next/server/pages/500.html +1 -1
  81. /package/studio-standalone/apps/vinaya-studio/.next/static/{Q_xjhiWztjosXWbMSJ0Yp → x2q88XfwsihlevulRhIvs}/_buildManifest.js +0 -0
  82. /package/studio-standalone/apps/vinaya-studio/.next/static/{Q_xjhiWztjosXWbMSJ0Yp → x2q88XfwsihlevulRhIvs}/_ssgManifest.js +0 -0
@@ -0,0 +1,1035 @@
1
+ #!/usr/bin/env bun
2
+
3
+ /**
4
+ * open-issue — the ONLY sanctioned way to create or body-edit an Issue in
5
+ * this repo. No hook intercepts a raw `gh issue create` /
6
+ * `gh issue edit`; ring-1 CI re-validation is the backstop for one.
7
+ *
8
+ * Gate: a task Issue (any `vinaya/tranche:<slug>` label) must carry the full
9
+ * eight-field Planner's rationale in its body (`checkIssueRationale`,
10
+ * planner-brief contract) — refused locally otherwise, before anything
11
+ * reaches the forge. Non-task Issues (no tranche label) pass through
12
+ * unvalidated: the rationale contract does not apply to them.
13
+ *
14
+ * Content gate: past presence, several checks grade what those fields
15
+ * SAY (and what the Issue carries) against the surface the task touches, and
16
+ * refuse — `checkBlastRadiusScope`
17
+ * (a shared collision domain — live-derived `packages/*` workspace members,
18
+ * built-in cross-cutting defaults, plus `vinaya.config.json`
19
+ * `blastRadius.extraDomains`, see `readSharedPackages` below — that no
20
+ * declared project owns, without a second project or a `blast-radius-ack:`
21
+ * line),
22
+ * `checkProjectsRegistered` (every declared `**Project:**` name resolves
23
+ * against `.vinaya/projects.md`),
24
+ * `checkNoBriefContent` (brief-shaped sections belong in the brief, not here),
25
+ * `checkRationaleNamesDocs` (name a doc/skill path, or the `no-doc-surface`
26
+ * sentinel — the only read-obligation signal a forge write leaves, since no
27
+ * other check observes what the Planner read before this forge write),
28
+ * `checkIssueType` (exactly one `vinaya/type:*` label — `labels.ts`'s `type`
29
+ * category, the commit-type vocabulary applied to the Issue instead of the
30
+ * commit). **CREATE-only**, unlike its four siblings above: the label is
31
+ * required going forward from this axis's own merge, never retroactively —
32
+ * running it on `edit` too would refuse an unrelated edit to any
33
+ * pre-existing Issue for lacking a label nothing ever asked it to carry, a
34
+ * forced backfill through the only sanctioned edit path. See the `isEdit`
35
+ * branch below.
36
+ * `checkConflictCompleteness` warns on an undeclared collision-domain overlap
37
+ * and never blocks. The five block-on-fail checks apply to task Issues only,
38
+ * same as the rationale gate; `checkIssueType` additionally applies to
39
+ * `create` only.
40
+ *
41
+ * Label detection is per-path: on `create`, labels come from this command's
42
+ * own argv (`--label` flags are naturally present there). On `edit`, argv is
43
+ * silent — nobody re-passes `--label` when changing a body — so the target
44
+ * Issue's ACTUAL current labels are fetched from the forge
45
+ * (`gh issue view <n> --json labels`) and unioned with any argv labels. A
46
+ * failed forge fetch is a hard refusal, never treated as "no tranche
47
+ * label" (#417).
48
+ *
49
+ * Usage:
50
+ * bun harness/processes/vinaya-strict/thinking/planner/tools/open-issue.ts --title t --body-file <path> --label "vinaya/tranche:x" [gh args...]
51
+ * bun harness/processes/vinaya-strict/thinking/planner/tools/open-issue.ts edit <n> --body-file <path> [gh args...]
52
+ * bun harness/processes/vinaya-strict/thinking/planner/tools/open-issue.ts --validate-only --body-file <path> --label "vinaya/tranche:x"
53
+ */
54
+
55
+ import { execFileSync } from 'node:child_process'
56
+ import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
57
+ import { tmpdir } from 'node:os'
58
+ import { join } from 'node:path'
59
+ import { amendRationaleDeps } from './amend-rationale-deps'
60
+ import {
61
+ findMilestoneAttachTargetForSlug,
62
+ hasExplicitMilestoneFlag,
63
+ type MilestoneAttachTarget
64
+ } from '../../../tools/task-contract/forge/fetch-milestone'
65
+ import { findTrancheSlug, trancheLabel, trancheSlugLengthError } from '../../../tools/task-contract/forge/labels'
66
+ import { parseRationaleDeps } from '../../../tools/task-contract/forge/parse-rationale-deps'
67
+ import {
68
+ deriveBuiltinCrossCuttingDefaults,
69
+ deriveWorkspacePackageDomains,
70
+ parsePnpmWorkspaceYaml
71
+ } from '../../../tools/task-contract/blast-radius-domains'
72
+ import { checkForgeTitle } from '../../../tools/task-contract/brief-validation'
73
+ import {
74
+ checkBlastRadiusScope,
75
+ checkConflictCompleteness,
76
+ checkIssueObjectives,
77
+ checkIssueRationale,
78
+ checkIssueType,
79
+ checkNoBriefContent,
80
+ checkNoForeignTaskOwnership,
81
+ checkProseAllowsBeyondSurfaceEdit,
82
+ checkObjectivesRespectBoundary,
83
+ checkPartsCiteDefinedObjectives,
84
+ checkPartsCoverageAndSequence,
85
+ checkProjectsRegistered,
86
+ checkRationaleNamesDocs,
87
+ checkSurfaceGlobsResolve,
88
+ isTaskIssueBodyShaped,
89
+ isTaskIssueLabelSet,
90
+ type ProjectPath,
91
+ type TaskIssueFacts
92
+ } from '../../../tools/task-contract/issue-validation'
93
+ import { classifyLeftover } from '../../../tools/task-contract/bin/leftover-detection'
94
+ import { readConfigObjectivesSinceIssue } from '../../../tools/task-contract/objectives-cutover-config'
95
+ import { parseRegistry } from '../../../tools/task-contract/parse-registry'
96
+
97
+ const REPO_ROOT = join(import.meta.dirname, '../../../../../..')
98
+
99
+ /** Trailing digits off a bare number or an Issue URL — mirrors `apps/cli/src/lib/forge-write.ts`'s `parseIssueNumberFromRef` (not importable here: `apps/cli` is downstream of this package). */
100
+ function parseIssueNumberFromRef(ref: string): number | null {
101
+ const m = /(\d+)\s*$/.exec(ref.trim())
102
+ return m ? Number.parseInt(m[1] as string, 10) : null
103
+ }
104
+
105
+ /** `git ls-files -- <glob>` non-empty — mirrors `apps/cli/src/lib/brief-assembly.ts`'s `expandGlob`, used the same way (`checkSurfaceGlobsResolve`'s `resolvesToFile` predicate). */
106
+ function globResolvesToFile(glob: string): boolean {
107
+ try {
108
+ return (
109
+ execFileSync('git', ['ls-files', '--', glob], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim()
110
+ .length > 0
111
+ )
112
+ } catch {
113
+ return false
114
+ }
115
+ }
116
+
117
+ function fail(msg: string): never {
118
+ console.error(`\n[open-issue] REFUSED — ${msg}`)
119
+ console.error('[open-issue] Nothing was sent to the forge. Fix the body and retry.')
120
+ process.exit(1)
121
+ }
122
+
123
+ /** Where a validated body's bytes came from — a file/stream path, or an inline arg value. */
124
+ export type BodySource = { kind: 'file'; argIndex: number; inlineForm: boolean } | { kind: 'inline' }
125
+
126
+ export interface BodyResult {
127
+ body: string
128
+ source: BodySource
129
+ }
130
+
131
+ /**
132
+ * Reads the body exactly once and records where it came from. `argIndex` +
133
+ * `inlineForm` let `resolveShippableArgs` find and replace the same slot
134
+ * later — the read here and the value shipped to `gh` must be the same
135
+ * buffered string, not two independent reads of the same path.
136
+ */
137
+ export function locateBody(args: string[]): BodyResult | null {
138
+ for (let i = 0; i < args.length; i++) {
139
+ const a = args[i] as string
140
+ if (a === '--body-file' || a === '-F') {
141
+ const p = args[i + 1]
142
+ if (!p) fail('`--body-file` given with no path.')
143
+ return { body: readFileSync(p, 'utf8'), source: { kind: 'file', argIndex: i + 1, inlineForm: false } }
144
+ }
145
+ if (a.startsWith('--body-file=')) {
146
+ const p = a.slice('--body-file='.length)
147
+ return { body: readFileSync(p, 'utf8'), source: { kind: 'file', argIndex: i, inlineForm: true } }
148
+ }
149
+ if (a === '--body' || a === '-b') {
150
+ const v = args[i + 1]
151
+ if (v === undefined) fail('`--body` given with no value.')
152
+ return { body: v, source: { kind: 'inline' } }
153
+ }
154
+ if (a.startsWith('--body=')) return { body: a.slice('--body='.length), source: { kind: 'inline' } }
155
+ }
156
+ return null
157
+ }
158
+
159
+ /**
160
+ * Materializes an already-buffered body into a fresh temp file and rewrites
161
+ * the `--body-file`/`-F` slot to point at it, so `gh`'s own read sees the
162
+ * SAME bytes this process validated — never a second read of the original
163
+ * path (which is empty for a stream by the time `gh` opens it). Inline
164
+ * `--body`/`-b` args are untouched: no file, no second read, no risk.
165
+ */
166
+ export function resolveShippableArgs(
167
+ args: string[],
168
+ bodyResult: BodyResult | null
169
+ ): { finalArgs: string[]; cleanup: () => void } {
170
+ if (bodyResult?.source.kind !== 'file') {
171
+ return { finalArgs: args, cleanup: () => {} }
172
+ }
173
+ const dir = mkdtempSync(join(tmpdir(), 'vinaya-open-issue-body-'))
174
+ const tempPath = join(dir, 'body.md')
175
+ writeFileSync(tempPath, bodyResult.body, 'utf8')
176
+ const finalArgs = [...args]
177
+ const { argIndex, inlineForm } = bodyResult.source
178
+ finalArgs[argIndex] = inlineForm ? `--body-file=${tempPath}` : tempPath
179
+ return { finalArgs, cleanup: () => rmSync(dir, { recursive: true, force: true }) }
180
+ }
181
+
182
+ /** Extracts --title/-t value from the passthrough args, if present. */
183
+ function extractTitle(args: string[]): string | null {
184
+ for (let i = 0; i < args.length; i++) {
185
+ const a = args[i] as string
186
+ if (a === '--title' || a === '-t') return args[i + 1] ?? null
187
+ if (a.startsWith('--title=')) return a.slice('--title='.length)
188
+ }
189
+ return null
190
+ }
191
+
192
+ function extractLabels(args: string[]): string[] {
193
+ const labels: string[] = []
194
+ for (let i = 0; i < args.length; i++) {
195
+ const a = args[i] as string
196
+ if (a === '--label' || a === '-l') {
197
+ const v = args[i + 1]
198
+ if (v) labels.push(...v.split(',').map((s) => s.trim()))
199
+ }
200
+ if (a.startsWith('--label='))
201
+ labels.push(
202
+ ...a
203
+ .slice('--label='.length)
204
+ .split(',')
205
+ .map((s) => s.trim())
206
+ )
207
+ if (a.startsWith('--add-label='))
208
+ labels.push(
209
+ ...a
210
+ .slice('--add-label='.length)
211
+ .split(',')
212
+ .map((s) => s.trim())
213
+ )
214
+ if (a === '--add-label') {
215
+ const v = args[i + 1]
216
+ if (v) labels.push(...v.split(',').map((s) => s.trim()))
217
+ }
218
+ }
219
+ return labels
220
+ }
221
+
222
+ /**
223
+ * Fetches the target Issue's actual current labels from the forge. Edit
224
+ * invocations don't normally re-pass `--label` flags, so argv says nothing
225
+ * about whether the target is a task Issue — the forge is the only truthful
226
+ * source (#417). Fails loud/closed: a failed fetch is never treated as "no
227
+ * tranche label", which would silently re-open the exact bypass this
228
+ * function exists to close.
229
+ */
230
+ function fetchForgeLabels(issueRef: string): string[] {
231
+ let out: string
232
+ try {
233
+ out = execFileSync('gh', ['issue', 'view', issueRef, '--json', 'labels'], {
234
+ encoding: 'utf8',
235
+ stdio: ['ignore', 'pipe', 'pipe']
236
+ })
237
+ } catch {
238
+ fail(
239
+ `could not fetch Issue ${issueRef}'s labels from the forge (\`gh issue view\`) — the rationale gate cannot decide whether it applies. Check gh auth/network and retry; refusing to pass the edit through unvalidated.`
240
+ )
241
+ }
242
+ try {
243
+ const parsed = JSON.parse(out) as { labels: Array<{ name: string }> }
244
+ return parsed.labels.map((l) => l.name)
245
+ } catch {
246
+ fail(
247
+ `could not parse \`gh issue view ${issueRef} --json labels\` output — refusing to pass the edit through unvalidated.`
248
+ )
249
+ }
250
+ }
251
+
252
+ /** First `vinaya/tranche:<slug>` label's slug, or `null` when the set carries none. */
253
+ function trancheSlugFromLabels(labels: string[]): string | null {
254
+ return findTrancheSlug(labels)
255
+ }
256
+
257
+ /** `<n>` out of a task title `[<slug>] <n> — …` (the same grammar `checkForgeTitle`'s `taskStyle` accepts), or `null`. */
258
+ export function taskIdFromTitle(title: string): string | null {
259
+ const m = title.match(/^\[[a-z0-9._-]+\] (\S+) —/)
260
+ return m ? (m[1] as string) : null
261
+ }
262
+
263
+ /** Soft-fail title fetch — unlike `fetchForgeLabels`/`fetchForgeBody`, this only feeds an informational print, never a blocking gate, so an unreachable forge yields `null` rather than refusing the whole command. Untested directly, by the same established convention as its siblings `fetchForgeLabels`/`fetchForgeBody`/`ghEditBody` — a real `gh` shim, not logic. `resolveTitleForLeftoverCheck` below is what actually carries the decision logic, and that IS tested, via injection. */
264
+ function fetchForgeTitle(issueRef: string): string | null {
265
+ try {
266
+ const out = execFileSync('gh', ['issue', 'view', issueRef, '--json', 'title'], {
267
+ encoding: 'utf8',
268
+ stdio: ['ignore', 'pipe', 'ignore']
269
+ })
270
+ const parsed = JSON.parse(out) as { title: string }
271
+ return parsed.title
272
+ } catch {
273
+ return null
274
+ }
275
+ }
276
+
277
+ /**
278
+ * The title to derive a task id from, for the leftover-detection print.
279
+ * Argv title first — works identically on `create` and `edit`, no forge
280
+ * call needed. Falls back to a forge fetch only on `edit` with no `--title`
281
+ * in argv (the common re-plan-a-body-only case); `create` always carries a
282
+ * title in argv (required to open the Issue at all), so it never reaches
283
+ * the fetch branch — `issueRef` is `null` there and the ternary short-circuits.
284
+ * `fetchTitle` is injected (mirrors `fetchLeftoverFacts`/`printLeftoverStatus`
285
+ * and this file's own `resolveMilestoneToAttach`/`lookupAttachTarget`) so
286
+ * this branching is unit-tested without a real `gh` call.
287
+ */
288
+ export function resolveTitleForLeftoverCheck(
289
+ bodyArgs: string[],
290
+ isEdit: boolean,
291
+ issueRef: string | null,
292
+ fetchTitle: (issueRef: string) => string | null = fetchForgeTitle
293
+ ): string | null {
294
+ return extractTitle(bodyArgs) ?? (isEdit && issueRef ? fetchTitle(issueRef) : null)
295
+ }
296
+
297
+ /** The three raw facts `classifyLeftover` needs, already fetched — the injectable boundary `printLeftoverStatus` tests against. */
298
+ export type LeftoverFacts = {
299
+ branchExistsRemote: boolean
300
+ commitsAheadOfMain: number
301
+ openPrNumber: number | null
302
+ }
303
+
304
+ /** Real git/gh fetch. Soft-fail: `null` on any failure, never throws — the caller treats that as "could not check," not a refusal. */
305
+ function fetchLeftoverFacts(branch: string): LeftoverFacts | null {
306
+ try {
307
+ const branchExistsRemote =
308
+ execFileSync('git', ['ls-remote', '--heads', 'origin', branch], {
309
+ encoding: 'utf8',
310
+ stdio: ['ignore', 'pipe', 'ignore']
311
+ }).trim().length > 0
312
+
313
+ let commitsAheadOfMain = 0
314
+ if (branchExistsRemote) {
315
+ execFileSync('git', ['fetch', 'origin', branch, '--quiet'], { stdio: 'ignore' })
316
+ const count = execFileSync('git', ['rev-list', '--count', `origin/main..origin/${branch}`], {
317
+ encoding: 'utf8',
318
+ stdio: ['ignore', 'pipe', 'ignore']
319
+ }).trim()
320
+ commitsAheadOfMain = count && !Number.isNaN(Number(count)) ? Number(count) : 0
321
+ }
322
+
323
+ const prOut = execFileSync(
324
+ 'gh',
325
+ ['pr', 'list', '--head', branch, '--state', 'open', '--json', 'number', '--limit', '1'],
326
+ { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }
327
+ )
328
+ const prs = JSON.parse(prOut) as Array<{ number: number }>
329
+ return { branchExistsRemote, commitsAheadOfMain, openPrNumber: prs[0]?.number ?? null }
330
+ } catch {
331
+ return null
332
+ }
333
+ }
334
+
335
+ /** Pure message builder — the whole reason `printLeftoverStatus` is testable without mocking `console.log` or shelling out. `facts: null` is the soft-fail case (git/gh unreachable). */
336
+ export function formatLeftoverPrint(slug: string, taskId: string, facts: LeftoverFacts | null): string {
337
+ if (!facts) {
338
+ return `[open-issue] leftover-detection: could not check task ${taskId} (${slug}) — git/gh unreachable, skipping.`
339
+ }
340
+ const result = classifyLeftover({ ...facts, worktreeExistsLocal: false })
341
+ return `[open-issue] leftover-detection: task ${taskId} (${slug}) — ${result.verdict}. ${result.reason}`
342
+ }
343
+
344
+ /**
345
+ * Unconditional leftover print on both `create` and `edit` — this repo's fix
346
+ * for the class of failure `classifyLeftover`/`verify-dispatch.ts` already
347
+ * solves for the Developer's `Step 0`, one stage too late for a
348
+ * *planning/authoring* session that never runs any command until it opens
349
+ * or re-opens this exact task Issue. `open-issue.ts` is the one command
350
+ * every legitimate task-Issue touch already goes through, so printing here
351
+ * — success or in-flight, every invocation, no flag — needs no agent to
352
+ * remember to ask for it.
353
+ *
354
+ * On `create` too, deliberately (review correction on #311 — an earlier
355
+ * revision of this PR restricted this to `edit` on the reasoning that "an
356
+ * Issue must exist before its branch can," which is true of THIS Issue's
357
+ * own future branch but does not establish that no branch sharing the same
358
+ * `task/<slug>/<n>` name exists yet: `n` is parsed from TITLE TEXT
359
+ * (`taskIdFromTitle`), not derived from this Issue's own number or history,
360
+ * so a brand-new `create` whose title happens to name a task id that
361
+ * collides with an already-in-flight or abandoned branch — two Planner
362
+ * sessions independently cutting `[slug] 3 — …` unaware of each other, the
363
+ * same root cause as the incident this whole check exists to catch, one
364
+ * stage earlier — is exactly the scenario this must not miss. `fetchFacts`
365
+ * is injected (mirrors `resolveMilestoneToAttach`'s `lookupAttachTarget`)
366
+ * purely so the real git/gh shim can be swapped for a fixture in tests;
367
+ * `formatLeftoverPrint` above carries the actual, tested logic.
368
+ */
369
+ export function printLeftoverStatus(
370
+ slug: string,
371
+ taskId: string,
372
+ fetchFacts: (branch: string) => LeftoverFacts | null = fetchLeftoverFacts
373
+ ): void {
374
+ console.log(formatLeftoverPrint(slug, taskId, fetchFacts(`task/${slug}/${taskId}`)))
375
+ }
376
+
377
+ /**
378
+ * Milestone auto-attach on Issue CREATE.
379
+ * `deriveTrancheFromForge`/`listActiveTrancheSlugs` (the forge-state modules)
380
+ * never read an Issue's GitHub-native milestone field — only the
381
+ * `vinaya/tranche:<slug>` label — so this drift was never functionally
382
+ * load-pathing; it is pure GitHub-view hygiene (a Milestone showing
383
+ * `open_issues=0` while 3 real open task Issues carry its label). Creation-time
384
+ * only, by design: `edit` never force-attaches retroactively (an unrelated
385
+ * body edit must not silently reassign an Issue's milestone).
386
+ *
387
+ * Returns the Milestone's TITLE — what `--milestone` actually accepts —
388
+ * never the slug. Those coincide only in the legacy 1:1 regime; an
389
+ * intent-declared Milestone (vinaya-milestone-model-v1) is titled something
390
+ * else entirely, and `gh` handed a slug it does not match fails outright.
391
+ * `lookupAttachTarget` (`resolveMilestoneAttachTarget`'s forge-fetching
392
+ * sibling, the forge-state modules) resolves both cases; it is injected
393
+ * here so this stays testable without a real `gh` call.
394
+ *
395
+ * Not a hard failure when no matching open Milestone exists yet — a
396
+ * tranche's Milestone may not exist yet at first-Issue-cut time (task
397
+ * 5/#429 backfilled Milestones after the fact for the first cohort; a
398
+ * brand-new tranche's very first Issue necessarily precedes its own
399
+ * Milestone in some workflows).
400
+ */
401
+ export function resolveMilestoneToAttach(
402
+ labels: string[],
403
+ args: string[],
404
+ isEdit: boolean,
405
+ lookupAttachTarget: (slug: string) => MilestoneAttachTarget | null
406
+ ): string | null {
407
+ if (isEdit) return null
408
+ if (!isTaskIssueLabelSet(labels)) return null
409
+ if (hasExplicitMilestoneFlag(args)) return null
410
+ const slug = trancheSlugFromLabels(labels)
411
+ if (!slug) return null
412
+ const target = lookupAttachTarget(slug)
413
+ return target ? target.title : null
414
+ }
415
+
416
+ // ---------- amend-deps subcommand --------------------------------------------
417
+ //
418
+ // `amend-deps` is the ONLY sanctioned way to change a task Issue's dependency
419
+ // edges (Issue #481, drift class #1). It rewrites the structured
420
+ // `Dependency rationale` field AND appends the matching `**Amendment (...)**`
421
+ // paragraph in ONE atomic write (`amendRationaleDeps`), with a runtime
422
+ // round-trip parse gate — closing the five-incident class this session where
423
+ // the field and a later free-form amendment drifted apart because nothing
424
+ // forced them to change together. Modeled on the rule that "the sanctioned path is
425
+ // the only path": there is no code path here that rewrites one representation
426
+ // without the other.
427
+
428
+ /** Parses one edge-set flag value into ids. The empty markers (`—`/`–`/`-`/``) yield `[]`. */
429
+ export function parseEdgeFlag(value: string): string[] {
430
+ const t = value.trim()
431
+ if (t === '' || t === '—' || t === '–' || t === '-') return []
432
+ return t
433
+ .split(',')
434
+ .map((s) => s.trim())
435
+ .filter((s) => s.length > 0)
436
+ }
437
+
438
+ /** Order-sensitive edge-set equality — the round-trip gate's core predicate. */
439
+ export function edgesEqual(a: string[], b: string[]): boolean {
440
+ return a.length === b.length && a.every((v, i) => v === b[i])
441
+ }
442
+
443
+ export type AmendDepsFlags = {
444
+ issue: string | null
445
+ dependsOn?: string[]
446
+ conflictsWith?: string[]
447
+ note: string
448
+ actor: string
449
+ dryRun: boolean
450
+ }
451
+
452
+ /**
453
+ * Parses the `amend-deps` subcommand's own flags (its body is composed, never
454
+ * accepted, so `locateBody` is deliberately NOT reused here). A field flag that
455
+ * is absent leaves `dependsOn`/`conflictsWith` `undefined` (untouched);
456
+ * present-but-empty yields `[]` (the explicit `—` marker).
457
+ */
458
+ export function parseAmendArgs(args: string[]): AmendDepsFlags {
459
+ const flags: AmendDepsFlags = { issue: null, note: '', actor: 'Planner', dryRun: false }
460
+ for (let i = 0; i < args.length; i++) {
461
+ const a = args[i] as string
462
+ const valueFor = (name: string): string => {
463
+ if (a.startsWith(`${name}=`)) return a.slice(name.length + 1)
464
+ const v = args[i + 1] ?? ''
465
+ i++
466
+ return v
467
+ }
468
+ if (a === '--dry-run') flags.dryRun = true
469
+ else if (a === '--depends-on' || a.startsWith('--depends-on='))
470
+ flags.dependsOn = parseEdgeFlag(valueFor('--depends-on'))
471
+ else if (a === '--conflicts-with' || a.startsWith('--conflicts-with='))
472
+ flags.conflictsWith = parseEdgeFlag(valueFor('--conflicts-with'))
473
+ else if (a === '--note' || a.startsWith('--note=')) flags.note = valueFor('--note')
474
+ else if (a === '--actor' || a.startsWith('--actor=')) flags.actor = valueFor('--actor') || 'Planner'
475
+ else if (!a.startsWith('-') && flags.issue === null) flags.issue = a
476
+ }
477
+ return flags
478
+ }
479
+
480
+ /** Static flag validation. Returns a refusal message, or `null` when the flags are well-formed. */
481
+ export function validateAmendFlags(flags: AmendDepsFlags): string | null {
482
+ if (flags.issue === null) return 'amend-deps requires the target Issue number as the first argument.'
483
+ if (flags.dependsOn === undefined && flags.conflictsWith === undefined) {
484
+ return 'amend-deps requires at least one of `--depends-on` / `--conflicts-with`.'
485
+ }
486
+ if (flags.note.trim() === '') return 'amend-deps requires a non-empty `--note` (the why for the amendment).'
487
+ return null
488
+ }
489
+
490
+ /** IO seams for {@link runAmendDeps}, injected so the orchestrator is testable without a real `gh`. */
491
+ export type AmendDepsDeps = {
492
+ fetchLabels: (issue: string) => string[]
493
+ fetchBody: (issue: string) => string
494
+ editBody: (issue: string, newBody: string) => void
495
+ today: () => string
496
+ log: (msg: string) => void
497
+ fail: (msg: string) => never
498
+ }
499
+
500
+ /**
501
+ * The `amend-deps` orchestrator. Every real invocation is gated on a runtime
502
+ * round-trip parse (`parseRationaleDeps(newBody)` must deep-equal the requested
503
+ * sets) — the rewrite is NEVER trusted by construction. This is the exact
504
+ * "test against real data, not assumptions" trap (Issue #481) enforced on
505
+ * every invocation forever.
506
+ */
507
+ export function runAmendDeps(flags: AmendDepsFlags, deps: AmendDepsDeps): void {
508
+ const err = validateAmendFlags(flags)
509
+ if (err) deps.fail(err)
510
+ const issue = flags.issue as string
511
+
512
+ const labels = deps.fetchLabels(issue)
513
+ if (!isTaskIssueLabelSet(labels)) {
514
+ deps.fail(`amend-deps targets task Issues only — Issue ${issue} carries no \`vinaya/tranche:*\` label.`)
515
+ }
516
+
517
+ const body = deps.fetchBody(issue)
518
+ const before = parseRationaleDeps(body)
519
+
520
+ const input = {
521
+ note: flags.note,
522
+ date: deps.today(),
523
+ actor: flags.actor,
524
+ ...(flags.dependsOn !== undefined ? { dependsOn: flags.dependsOn } : {}),
525
+ ...(flags.conflictsWith !== undefined ? { conflictsWith: flags.conflictsWith } : {})
526
+ }
527
+
528
+ let newBody: string
529
+ try {
530
+ newBody = amendRationaleDeps(body, input)
531
+ } catch (e) {
532
+ deps.fail(`amend-deps could not rewrite Issue ${issue}: ${(e as Error).message}`)
533
+ }
534
+
535
+ // Round-trip gate (hard) — the writer and parser must agree on the grammar.
536
+ const after = parseRationaleDeps(newBody)
537
+ if (flags.dependsOn !== undefined && !edgesEqual(after.dependsOn, flags.dependsOn)) {
538
+ deps.fail(
539
+ `amend-deps round-trip FAILED for Depends-on: requested [${flags.dependsOn.join(', ')}] but parseRationaleDeps read back [${after.dependsOn.join(', ')}]. Nothing written.`
540
+ )
541
+ }
542
+ if (flags.conflictsWith !== undefined && !edgesEqual(after.conflictsWith, flags.conflictsWith)) {
543
+ deps.fail(
544
+ `amend-deps round-trip FAILED for Conflicts-with: requested [${flags.conflictsWith.join(', ')}] but parseRationaleDeps read back [${after.conflictsWith.join(', ')}]. Nothing written.`
545
+ )
546
+ }
547
+
548
+ // Rationale gate — the amended body must still carry the full rationale.
549
+ const rationale = checkIssueRationale(newBody)
550
+ if (rationale.status === 'fail') {
551
+ deps.fail(
552
+ `amend-deps: the amended body no longer passes the rationale gate (${rationale.errors.join(' | ')}). Nothing written.`
553
+ )
554
+ }
555
+
556
+ if (flags.dryRun) {
557
+ deps.log(newBody)
558
+ deps.log('round-trip PASS')
559
+ return
560
+ }
561
+
562
+ deps.editBody(issue, newBody)
563
+ if (flags.dependsOn !== undefined) {
564
+ deps.log(`[open-issue] Depends-on: [${before.dependsOn.join(', ')}] → [${after.dependsOn.join(', ')}]`)
565
+ }
566
+ if (flags.conflictsWith !== undefined) {
567
+ deps.log(`[open-issue] Conflicts-with: [${before.conflictsWith.join(', ')}] → [${after.conflictsWith.join(', ')}]`)
568
+ }
569
+ }
570
+
571
+ // ---------- content gate I/O (A/B/D block, C warns) --------------------------
572
+ //
573
+ // `issue-validation.ts` stays pure; every disk/forge read the content checks
574
+ // need happens here.
575
+
576
+ /**
577
+ * `package.json`'s `workspaces` array PLUS `pnpm-workspace.yaml`'s
578
+ * `packages:` list, concatenated — the combined source
579
+ * `deriveWorkspacePackageDomains` resolves against. Both are read: pnpm does
580
+ * not honor a `workspaces` key in `package.json` at all, so a pnpm adopter's
581
+ * real workspace glob lives only in `pnpm-workspace.yaml` — reading just
582
+ * `package.json` would silently derive zero `packages/*` domains for every
583
+ * such adopter (review finding on this PR). `repoRoot` is injectable for
584
+ * tests; every real caller uses the default.
585
+ */
586
+ function readWorkspaces(repoRoot: string = REPO_ROOT): string[] {
587
+ const fromPackageJson = (): string[] => {
588
+ try {
589
+ const pkg = JSON.parse(readFileSync(join(repoRoot, 'package.json'), 'utf8')) as { workspaces?: unknown }
590
+ return Array.isArray(pkg.workspaces) ? pkg.workspaces.filter((w): w is string => typeof w === 'string') : []
591
+ } catch {
592
+ return []
593
+ }
594
+ }
595
+ const fromPnpmWorkspaceYaml = (): string[] => {
596
+ try {
597
+ return parsePnpmWorkspaceYaml(readFileSync(join(repoRoot, 'pnpm-workspace.yaml'), 'utf8'))
598
+ } catch {
599
+ return []
600
+ }
601
+ }
602
+ return [...fromPackageJson(), ...fromPnpmWorkspaceYaml()]
603
+ }
604
+
605
+ /** Immediate child directory names of `dir` (relative to `repoRoot`) — the glob-resolution half of `deriveWorkspacePackageDomains`. */
606
+ function listWorkspaceChildDirs(dir: string, repoRoot: string = REPO_ROOT): string[] {
607
+ try {
608
+ return readdirSync(join(repoRoot, dir), { withFileTypes: true })
609
+ .filter((e) => e.isDirectory())
610
+ .map((e) => e.name)
611
+ } catch {
612
+ return []
613
+ }
614
+ }
615
+
616
+ /**
617
+ * `vinaya.config.json`'s `blastRadius.extraDomains` — the sanctioned path for
618
+ * an adopter to declare a collision domain beyond live derivation and the
619
+ * built-in defaults (a `migrations/` folder, a codegen output dir). Read as
620
+ * plain JSON, not through `apps/cli`'s zod schema: the process package cannot depend
621
+ * on `apps/cli` (the dependency runs the other way), and this is a single
622
+ * optional field, not full config validation.
623
+ */
624
+ function readConfigExtraDomains(repoRoot: string = REPO_ROOT): string[] {
625
+ try {
626
+ const raw = JSON.parse(readFileSync(join(repoRoot, 'vinaya.config.json'), 'utf8')) as {
627
+ blastRadius?: { extraDomains?: unknown }
628
+ }
629
+ const extra = raw.blastRadius?.extraDomains
630
+ return Array.isArray(extra) ? extra.filter((d): d is string => typeof d === 'string') : []
631
+ } catch {
632
+ return []
633
+ }
634
+ }
635
+
636
+ /**
637
+ * The full collision-domain list checks A/C consume: every `packages/*`
638
+ * workspace member (live-derived from `package.json`, §Part 1), the
639
+ * built-in cross-cutting defaults (lockfile/monorepo-config/CI/git-hooks
640
+ * presence-checks, §Part 2), and `vinaya.config.json`'s
641
+ * `blastRadius.extraDomains` (the sanctioned "one more domain" path). No
642
+ * knowledge of the legacy retired static packages file — retired, zero backward
643
+ * compatibility, same wave as `apps/cli`'s equivalent removal. A fresh
644
+ * adopter with none of the optional inputs still gets a live, non-empty
645
+ * list from derivation + defaults alone. `repoRoot` is injectable for
646
+ * tests; every real caller uses the default (`REPO_ROOT`).
647
+ */
648
+ export function readSharedPackages(repoRoot: string = REPO_ROOT): string[] {
649
+ const derived = deriveWorkspacePackageDomains(readWorkspaces(repoRoot), (dir) =>
650
+ listWorkspaceChildDirs(dir, repoRoot)
651
+ )
652
+ const defaults = deriveBuiltinCrossCuttingDefaults((p) => existsSync(join(repoRoot, p)))
653
+ const configExtra = readConfigExtraDomains(repoRoot)
654
+ return [...new Set([...derived, ...defaults, ...configExtra])]
655
+ }
656
+
657
+ /** Registry rows (`projects.md`) — the authority for which project owns which path. Absent ⇒ nothing is owned. */
658
+ function readProjectPaths(): ProjectPath[] {
659
+ try {
660
+ return parseRegistry(readFileSync(join(REPO_ROOT, '.vinaya/projects.md'), 'utf8'))
661
+ } catch {
662
+ return []
663
+ }
664
+ }
665
+
666
+ /**
667
+ * The tranche's other open task Issues, for check C. Best-effort by design:
668
+ * C is warn-only, so a forge hiccup must degrade to "no warning", never to a
669
+ * refusal — the opposite of `fetchForgeLabels`, which fails closed because a
670
+ * missing label there would silently skip a *blocking* gate.
671
+ */
672
+ function fetchSiblingTaskIssues(slug: string, selfRef: string | null): TaskIssueFacts[] {
673
+ try {
674
+ // Labels are filtered CLIENT-side, deliberately. `gh issue list --label
675
+ // vinaya/tranche:<slug>` returns an empty set against this repo's live labels
676
+ // even though the label exists and Issues carry it (reproduced on
677
+ // `vinaya/tranche:vinaya-pages-v2`: 11 matching open Issues, `--label` yields
678
+ // 0). Server-side filtering would have shipped C permanently silent and
679
+ // indistinguishable from "no overlap" — the exact false-green shape this
680
+ // whole change exists to remove. Listing open Issues and matching here is
681
+ // one request either way.
682
+ const out = execFileSync(
683
+ 'gh',
684
+ ['issue', 'list', '--state', 'open', '--limit', '200', '--json', 'number,body,labels'],
685
+ { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 32 * 1024 * 1024 }
686
+ )
687
+ return (JSON.parse(out) as Array<{ number: number; body: string; labels: Array<{ name: string }> }>)
688
+ .filter((i) => i.labels.some((l) => l.name === trancheLabel(slug)))
689
+ .filter((i) => String(i.number) !== String(selfRef ?? '').replace(/^#/, ''))
690
+ .map((i) => ({
691
+ ref: `#${i.number}`,
692
+ body: i.body ?? '',
693
+ conflictsWith: parseRationaleDeps(i.body ?? '').conflictsWith
694
+ }))
695
+ } catch {
696
+ console.warn('[open-issue] could not list sibling task Issues — skipping the conflict-completeness warning (C).')
697
+ return []
698
+ }
699
+ }
700
+
701
+ /** Fetches an Issue's current body from the forge — hard refusal on fetch/parse failure (#417 pattern). */
702
+ function fetchForgeBody(issueRef: string): string {
703
+ let out: string
704
+ try {
705
+ out = execFileSync('gh', ['issue', 'view', issueRef, '--json', 'body'], {
706
+ encoding: 'utf8',
707
+ stdio: ['ignore', 'pipe', 'pipe']
708
+ })
709
+ } catch {
710
+ fail(
711
+ `could not fetch Issue ${issueRef}'s body from the forge (\`gh issue view\`). Check gh auth/network and retry; refusing to amend blind.`
712
+ )
713
+ }
714
+ try {
715
+ return (JSON.parse(out) as { body: string }).body
716
+ } catch {
717
+ fail(`could not parse \`gh issue view ${issueRef} --json body\` output — refusing to amend blind.`)
718
+ }
719
+ }
720
+
721
+ /** Ships an amended body through the SAME same-bytes edit machinery `edit` uses (`resolveShippableArgs`). */
722
+ function ghEditBody(issueRef: string, newBody: string): void {
723
+ const bodyResult: BodyResult = { body: newBody, source: { kind: 'file', argIndex: 1, inlineForm: false } }
724
+ const { finalArgs, cleanup } = resolveShippableArgs(['--body-file', '__amend_placeholder__'], bodyResult)
725
+ try {
726
+ const out = execFileSync('gh', ['issue', 'edit', issueRef, ...finalArgs], {
727
+ encoding: 'utf8',
728
+ stdio: ['ignore', 'pipe', 'inherit']
729
+ })
730
+ console.log(out.trim())
731
+ } finally {
732
+ cleanup()
733
+ }
734
+ }
735
+
736
+ /**
737
+ * Create-if-absent for the `vinaya/tranche:<slug>` label — the real
738
+ * creation path Issue #54's Origin names as missing: the prefix family is
739
+ * open-ended by design (a slug the Planner cuts at tranche-cut time), so no
740
+ * fixed install-time list can enumerate it, and until now nothing created it
741
+ * either — cutting a tranche's first Issue failed outright at `gh` with
742
+ * `not found`, worked around by hand-running `gh label create`. This is the
743
+ * one place a new tranche's label is ever minted, matching this file's own
744
+ * status as the ONLY sanctioned Issue-creation path (module header). No
745
+ * `-R` flag — `gh` resolves the current repo from cwd (`REPO_ROOT`, chdir'd
746
+ * above), the same no-`-R` convention `ghLabelGateway` uses
747
+ * (harness/kernel/connectors/git/detect.ts). Existing labels are never modified, matching
748
+ * every other create-if-absent label path in this repo.
749
+ */
750
+ const TRANCHE_LABEL_COLOR = '1D76DB'
751
+
752
+ function ensureTrancheLabelExists(slug: string): void {
753
+ const name = trancheLabel(slug)
754
+ let existing: Array<{ name: string }>
755
+ try {
756
+ const out = execFileSync('gh', ['label', 'list', '--json', 'name', '--limit', '200'], {
757
+ encoding: 'utf8',
758
+ stdio: ['ignore', 'pipe', 'pipe']
759
+ })
760
+ existing = JSON.parse(out) as Array<{ name: string }>
761
+ } catch (err) {
762
+ fail(`could not list labels (\`gh label list\`) to check for '${name}': ${(err as Error).message}`)
763
+ }
764
+ if (existing.some((l) => l.name === name)) return
765
+ try {
766
+ execFileSync('gh', ['label', 'create', name, '--color', TRANCHE_LABEL_COLOR, '--description', `Tranche: ${slug}`], {
767
+ encoding: 'utf8',
768
+ stdio: ['ignore', 'pipe', 'pipe']
769
+ })
770
+ console.log(`[open-issue] created missing tranche label '${name}'.`)
771
+ } catch (err) {
772
+ fail(`could not create tranche label '${name}' (\`gh label create\`): ${(err as Error).message}`)
773
+ }
774
+ }
775
+
776
+ /**
777
+ * Whether the task-Issue content gate (rationale, blast-radius, project
778
+ * registry, brief content, docs-read, Parts/Objectives/Surface, task-type)
779
+ * applies at all. True on a `vinaya/tranche:*` label, same as before this
780
+ * task, OR — O2/O3 (task 21, `#541`, round 2 review SECURITY HIGH) — a
781
+ * labelless body that is still task-shaped: a legitimate backlog Issue,
782
+ * never a Planner mistake to wave through unvalidated. Pulled out as its own
783
+ * pure predicate (mirroring `apps/cli/src/lib/forge-write.ts`'s identical
784
+ * `isTaskIssueLabelSet(labels) || (body !== null && isTaskIssueBodyShaped(body))`
785
+ * OR-clause) so this file's own ring-0 `gh issue create/edit` interception
786
+ * gate is unit-testable without a real `gh` call.
787
+ */
788
+ export function appliesTaskIssueGate(labels: string[], body: string | null): boolean {
789
+ return isTaskIssueLabelSet(labels) || (body !== null && isTaskIssueBodyShaped(body))
790
+ }
791
+
792
+ /**
793
+ * The blast-radius rule for one write, given the Issue ref an `edit` names
794
+ * (`null` on `create`). An edit passes the Issue's own number, so an Issue
795
+ * numbered below the brief-sections cutover keeps the prose scan; a create has
796
+ * no number yet and is judged from `## Surface`, exactly as `apps/cli`'s
797
+ * `validateIssueContent` judges it. Pulled out so that number reaching the
798
+ * rule is unit-testable without a real `gh` call.
799
+ */
800
+ export function blastRadiusErrorsForWrite(
801
+ body: string,
802
+ labels: string[],
803
+ sharedPackages: string[],
804
+ projectPaths: ProjectPath[],
805
+ issueRef: string | null
806
+ ): string[] {
807
+ const issueNumber = issueRef === null ? null : parseIssueNumberFromRef(issueRef)
808
+ return checkBlastRadiusScope(body, labels, sharedPackages, projectPaths, issueNumber).errors
809
+ }
810
+
811
+ export function main(): void {
812
+ const argv = process.argv.slice(2)
813
+ const validateOnly = argv.includes('--validate-only')
814
+ const args = argv.filter((a) => a !== '--validate-only')
815
+
816
+ if (args[0] === 'amend-deps') {
817
+ runAmendDeps(parseAmendArgs(args.slice(1)), {
818
+ fetchLabels: fetchForgeLabels,
819
+ fetchBody: fetchForgeBody,
820
+ editBody: ghEditBody,
821
+ today: () => new Date().toISOString().slice(0, 10),
822
+ log: (m) => console.log(m),
823
+ fail
824
+ })
825
+ return
826
+ }
827
+
828
+ const isEdit = args[0] === 'edit'
829
+ const ghArgs = isEdit ? args.slice(1) : args
830
+ const bodyArgs = isEdit ? ghArgs.slice(1) : ghArgs
831
+
832
+ const bodyResult = locateBody(bodyArgs)
833
+ const body = bodyResult?.body ?? null
834
+ let labels = extractLabels(bodyArgs)
835
+ if (isEdit) {
836
+ const issueRef = ghArgs[0]
837
+ if (!issueRef || issueRef.startsWith('-')) {
838
+ fail('edit mode requires the target Issue number/URL as the first argument after `edit`.')
839
+ }
840
+ const forgeLabels = fetchForgeLabels(issueRef)
841
+ console.log(`[open-issue] edit — Issue ${issueRef} carries ${forgeLabels.length} label(s) on the forge.`)
842
+ labels = [...new Set([...forgeLabels, ...labels])]
843
+ }
844
+
845
+ // O2/O3 (task 21, `#541`, round 2 review SECURITY HIGH): a labelless
846
+ // backlog Issue is task-shaped content too — gating this whole content
847
+ // gate on the label alone let a labelless body through with NONE of
848
+ // `checkIssueRationale`/`checkBlastRadiusScope`/`checkProjectsRegistered`/
849
+ // `checkNoBriefContent`/`checkRationaleNamesDocs`/
850
+ // `checkPartsCiteDefinedObjectives`/`checkSurfaceGlobsResolve` ever
851
+ // running against it, via this file's own ring-0 `gh issue create/edit`
852
+ // interception path — a real bypass distinct from (and narrower than) the
853
+ // `apps/cli` command paths, which already carry this same
854
+ // `isTaskIssueLabelSet(labels) || isTaskIssueBodyShaped(body)` OR-clause
855
+ // (`forge-write.ts`, `commands/issue.ts`).
856
+ if (appliesTaskIssueGate(labels, body)) {
857
+ // GitHub caps a label name at 50 characters and `vinaya/tranche:` spends
858
+ // 15 of them, so a slug that reads fine in prose can be one the forge
859
+ // refuses to create. Caught here — the first place a new tranche's label
860
+ // reaches the forge — rather than as an opaque `gh` 422 later.
861
+ const labelSlug = trancheSlugFromLabels(labels)
862
+ if (labelSlug !== null) {
863
+ const lengthError = trancheSlugLengthError(labelSlug)
864
+ if (lengthError) fail(`open-issue label-length: ${lengthError}`)
865
+ }
866
+
867
+ // Unconditional on every create/edit — see printLeftoverStatus's own doc
868
+ // comment for why create must be covered too, not just edit.
869
+ if (labelSlug !== null) {
870
+ const titleForLeftoverCheck = resolveTitleForLeftoverCheck(
871
+ bodyArgs,
872
+ isEdit,
873
+ isEdit ? (ghArgs[0] as string) : null
874
+ )
875
+ const taskIdForLeftoverCheck = titleForLeftoverCheck ? taskIdFromTitle(titleForLeftoverCheck) : null
876
+ if (taskIdForLeftoverCheck !== null) {
877
+ printLeftoverStatus(labelSlug, taskIdForLeftoverCheck)
878
+ }
879
+ }
880
+
881
+ const title = extractTitle(bodyArgs)
882
+ if (title !== null) {
883
+ const t = checkForgeTitle(title)
884
+ if (t.status === 'fail') fail(t.errors[0] as string)
885
+ }
886
+ if (body === null) {
887
+ fail(
888
+ 'a task Issue (vinaya/tranche:* label) requires a `--body-file <path>` so the rationale gate can validate it.'
889
+ )
890
+ }
891
+ console.log('[open-issue] task Issue (tranche label) — validating the Planner rationale…')
892
+ const { status, errors } = checkIssueRationale(body)
893
+ if (status === 'fail') {
894
+ console.error(`\n[open-issue] FAILED — ${errors.length} rationale field(s) missing:\n`)
895
+ for (const e of errors) console.error(` ✗ ${e}`)
896
+ fail('the Issue body does not carry the full eight-field Planner rationale (planner-brief contract).')
897
+ }
898
+ console.log('[open-issue] rationale gate PASS.')
899
+
900
+ // ---- content gate: A/B/D block, C warns --------------------------------
901
+ // The rationale gate above proves the eight fields EXIST. These prove what
902
+ // they say is consistent with the surface the task touches — the three
903
+ // failure classes that passed the presence gate on #621/#622/#626.
904
+ const sharedPackages = readSharedPackages()
905
+ if (sharedPackages.length === 0) {
906
+ console.warn(
907
+ '[open-issue] no collision domains derived, defaulted, or declared (no `packages/*` workspace, no cross-cutting default present, no `vinaya.config.json` blastRadius.extraDomains) — blast-radius check (A) is dormant.'
908
+ )
909
+ }
910
+ const projectPaths = readProjectPaths()
911
+ if (projectPaths.length === 0) {
912
+ console.warn('[open-issue] no `.vinaya/projects.md` registry — the project-registry check is dormant.')
913
+ }
914
+ // checkIssueType is CREATE-ONLY, deliberately. "Forward-only, no
915
+ // backfill" (task 10's §10 answer) means the label is required on a
916
+ // task Issue from the moment it is CUT, not re-required every time it
917
+ // is later edited — `open-issue.ts` is the only sanctioned edit path
918
+ // for ANY Issue body, so running this check on `edit` too would refuse
919
+ // an unrelated edit (a typo fix, a dependency update) to any Issue that
920
+ // predates this axis, which is a de facto forced backfill through the
921
+ // back door. A task Issue created after this merges gets the label at
922
+ // creation and keeps it — nothing removes it — so skipping re-checks on
923
+ // edit costs nothing for the forward case and exempts every pre-merge
924
+ // Issue exactly as promised.
925
+ const typeErrors = isEdit ? [] : checkIssueType(body, labels).errors
926
+ // Three of the five write-only rules named apart:
927
+ // objectives numbering, Parts coverage, Surface glob resolution.
928
+ // `issueNumber` mirrors `apps/cli`'s own fail-closed-on-null posture
929
+ // (`checkIssueObjectives`'s own doc comment): `create` has no number
930
+ // until the write completes, and every Issue this repo can newly mint is
931
+ // already far past the Objectives cutover, so this never blocks a
932
+ // legitimate create. `checkPartsCiteDefinedObjectives`/
933
+ // `checkSurfaceGlobsResolve` are dormant when the Issue carries no
934
+ // `## Parts`/`## Surface` section at all. Title grammar is already
935
+ // enforced above. Milestone attach's validating half is NOT wired here:
936
+ // this script never re-attaches a Milestone on `edit` (its own
937
+ // `resolveMilestoneToAttach` design), and its `create` attach happens as
938
+ // part of this SAME write, so no moment here has an attach to verify.
939
+ const issueNumber = isEdit ? parseIssueNumberFromRef(ghArgs[0] as string) : null
940
+ const contentErrors = [
941
+ ...blastRadiusErrorsForWrite(body, labels, sharedPackages, projectPaths, isEdit ? (ghArgs[0] as string) : null),
942
+ ...checkProjectsRegistered(
943
+ body,
944
+ labels,
945
+ projectPaths.map((p) => p.name)
946
+ ).errors,
947
+ ...checkNoBriefContent(body).errors,
948
+ ...checkRationaleNamesDocs(body).errors,
949
+ ...checkIssueObjectives(body, issueNumber, readConfigObjectivesSinceIssue(REPO_ROOT)).errors,
950
+ ...checkPartsCiteDefinedObjectives(body).errors,
951
+ ...checkSurfaceGlobsResolve(body, globResolvesToFile).errors,
952
+ // The three Boundary/ownership/Parts-coverage predicates, wired here
953
+ // identically to `apps/cli`'s own `validateIssueContent` so this
954
+ // repo's own dogfooded Issue-write path (this script) and the
955
+ // packaged CLI's `issue create`/`edit` can never disagree about
956
+ // whether an Issue's Objectives/Boundary/Parts agree.
957
+ ...checkObjectivesRespectBoundary(body).errors,
958
+ ...checkNoForeignTaskOwnership(body).errors,
959
+ ...checkProseAllowsBeyondSurfaceEdit(body).errors,
960
+ ...checkPartsCoverageAndSequence(body).errors,
961
+ ...typeErrors
962
+ ]
963
+ if (contentErrors.length > 0) {
964
+ console.error(`\n[open-issue] FAILED — ${contentErrors.length} content check(s):\n`)
965
+ for (const e of contentErrors) console.error(` ✗ ${e}`)
966
+ fail('the Issue body fails the blast-radius / project-registry / brief-content / docs-read / task-type checks.')
967
+ }
968
+ console.log(
969
+ `[open-issue] content gate PASS (blast radius, project registry, brief content, docs read${isEdit ? '' : ', task type'}).`
970
+ )
971
+ if (isEdit) {
972
+ console.log('[open-issue] edit — task-type check skipped (create-only; forward-only enforcement, no backfill).')
973
+ }
974
+
975
+ // C — warn-only. Never blocks: an Issue declares no precise file surface,
976
+ // so an overlapping collision domain is a hint, not a fact.
977
+ const slug = trancheSlugFromLabels(labels)
978
+ if (slug) {
979
+ const selfRef = isEdit ? (ghArgs[0] as string) : null
980
+ const conflictWarnings = checkConflictCompleteness(
981
+ {
982
+ ref: selfRef ? `#${selfRef.replace(/^#/, '')}` : '(new)',
983
+ body,
984
+ conflictsWith: parseRationaleDeps(body).conflictsWith
985
+ },
986
+ fetchSiblingTaskIssues(slug, selfRef),
987
+ sharedPackages
988
+ )
989
+ for (const w of conflictWarnings) console.warn(`[open-issue] WARNING — ${w}`)
990
+ }
991
+ } else {
992
+ console.log('[open-issue] no tranche label — rationale gate does not apply, passing through.')
993
+ }
994
+
995
+ if (validateOnly) {
996
+ console.log('[open-issue] --validate-only: stopping before gh.')
997
+ process.exit(0)
998
+ }
999
+
1000
+ // Give the target tranche label a real chance to exist BEFORE `gh issue
1001
+ // create`/`edit` ships — otherwise a brand-new tranche's first Issue fails
1002
+ // outright at `gh` with `not found`, far from its actual cause.
1003
+ const labelSlugToEnsure = trancheSlugFromLabels(labels)
1004
+ if (labelSlugToEnsure) {
1005
+ ensureTrancheLabelExists(labelSlugToEnsure)
1006
+ }
1007
+
1008
+ const milestoneTitle = resolveMilestoneToAttach(labels, bodyArgs, isEdit, (slug) => {
1009
+ try {
1010
+ return findMilestoneAttachTargetForSlug('{owner}', '{repo}', slug)
1011
+ } catch {
1012
+ console.warn(`[open-issue] milestone lookup for "${slug}" failed (gh api) — creating without --milestone.`)
1013
+ return null
1014
+ }
1015
+ })
1016
+ const createArgs = milestoneTitle ? [...bodyArgs, '--milestone', milestoneTitle] : bodyArgs
1017
+ if (milestoneTitle) {
1018
+ console.log(`[open-issue] auto-attaching to open Milestone "${milestoneTitle}" (tranche label match).`)
1019
+ }
1020
+
1021
+ const { finalArgs, cleanup } = resolveShippableArgs(createArgs, bodyResult)
1022
+ try {
1023
+ const finalGhArgs = isEdit ? [ghArgs[0] as string, ...finalArgs] : finalArgs
1024
+ const ghCmd = isEdit ? ['issue', 'edit', ...finalGhArgs] : ['issue', 'create', ...finalGhArgs]
1025
+ const out = execFileSync('gh', ghCmd, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'inherit'] })
1026
+ console.log(out.trim())
1027
+ } finally {
1028
+ cleanup()
1029
+ }
1030
+ }
1031
+
1032
+ if (import.meta.main) {
1033
+ process.chdir(REPO_ROOT)
1034
+ main()
1035
+ }