@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,815 @@
1
+ /**
2
+ * The Planner's Issue, surface, objectives and brief operations as a library.
3
+ * Each operation returns an outcome — the written Issue's link, the rendered
4
+ * text, or the findings that refused it — and never ends the process: the
5
+ * Planner role tools call one operation here and return its outcome. Every refusal reached beneath an
6
+ * operation (however deep) is captured as a finding, not an exit.
7
+ */
8
+
9
+ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
10
+ import { tmpdir } from 'node:os'
11
+ import { join } from 'node:path'
12
+ import {
13
+ isForgeReadOversize,
14
+ readIssueComments,
15
+ readIssueFields
16
+ } from '../../../../../kernel/adapters/code-host/github/forge-read.js'
17
+ import { assembleAndRenderBrief } from '../../../tools/task-contract/brief-assembly.js'
18
+ import { type FrozenBriefCandidate, resolveNewestFrozenBrief } from '../../../tools/task-contract/brief-validation'
19
+ import { prepareTaskOrIssue } from '../../../tools/task-contract/dispatch-task.js'
20
+ import { findTrancheSlug } from '../../../tools/task-contract/forge/labels'
21
+ import { resolveTaskIssueRef } from '../../../tools/task-contract/forge/list-tasks'
22
+ import {
23
+ type BodyResult,
24
+ ForgeArgError,
25
+ captureRefusal,
26
+ countMarkerComments,
27
+ ensureTrancheLabelExistsOutcome,
28
+ extractLabels,
29
+ extractTitle,
30
+ fetchForgeLabelsOutcome,
31
+ frozenSectionChangeOutcome,
32
+ issueSurfaceOutcome,
33
+ locateBody,
34
+ makeCheckError,
35
+ objectivesVersionMarkerPrefixes,
36
+ parseIssueNumberFromRef,
37
+ postMarkedComment,
38
+ refuse,
39
+ refuseUnlessPrincipal,
40
+ renderSurfaceForcedSet,
41
+ resolveMilestoneAttachOutcome,
42
+ resolvePrincipalsOrRefuse,
43
+ runGhWriteOutcome,
44
+ validateTaskIssueOutcome
45
+ } from '../../../tools/task-contract/forge/forge-write'
46
+ import type { CheckError } from '../../../../../kernel/gates/checks/contract'
47
+ import {
48
+ isTaskIssueBodyShaped,
49
+ isTaskIssueLabelSet,
50
+ parseIssueParts,
51
+ type SurfaceForcedSet
52
+ } from '../../../tools/task-contract/issue-validation'
53
+ import {
54
+ type Objective,
55
+ objectivesOf,
56
+ objectivesVersion,
57
+ renderObjectives
58
+ } from '../../../tools/task-contract/objectives'
59
+
60
+ export const RETRY_CREATE = 'task_issue_create'
61
+ export const RETRY_EDIT = 'task_issue_edit'
62
+
63
+ // --- outcomes ----------------------------------------------------------------
64
+
65
+ /** What a refused operation returns: the findings, in the order the gate produced them. `forgeError` is the raw error of a `gh` write that failed after every gate passed. */
66
+ export type Refused = {
67
+ ok: false
68
+ findings: CheckError[]
69
+ /** Warning-severity findings the gates raised before the refusal. */
70
+ warnings: CheckError[]
71
+ forgeError?: unknown
72
+ }
73
+
74
+ /** Where an operation reports what is not part of its outcome, at the moment it happens. */
75
+ export interface PlannerIo {
76
+ warning?: (finding: CheckError) => void
77
+ notice?: (text: string) => void
78
+ }
79
+
80
+ /** The forge-touching steps an Issue write runs, replaceable so a test stubs the forge. */
81
+ export interface PlannerForge {
82
+ fetchLabels: typeof fetchForgeLabelsOutcome
83
+ frozenSectionChange: typeof frozenSectionChangeOutcome
84
+ validate: typeof validateTaskIssueOutcome
85
+ ensureTrancheLabel: typeof ensureTrancheLabelExistsOutcome
86
+ milestoneArgs: typeof resolveMilestoneAttachOutcome
87
+ ghWrite: typeof runGhWriteOutcome
88
+ }
89
+
90
+ export const realPlannerForge: PlannerForge = {
91
+ fetchLabels: fetchForgeLabelsOutcome,
92
+ frozenSectionChange: frozenSectionChangeOutcome,
93
+ validate: validateTaskIssueOutcome,
94
+ ensureTrancheLabel: ensureTrancheLabelExistsOutcome,
95
+ milestoneArgs: resolveMilestoneAttachOutcome,
96
+ ghWrite: runGhWriteOutcome
97
+ }
98
+
99
+ export type IssueWriteOutcome =
100
+ | {
101
+ ok: true
102
+ /** `true` when the forge was written; `false` for a validate-only pass. */
103
+ written: boolean
104
+ /** The link `gh` printed (empty when it printed none, or nothing was written). */
105
+ url: string
106
+ /** Non-null when the brief render never ran — a pass that must not be claimed as a full one. */
107
+ renderSkipped: string | null
108
+ warnings: CheckError[]
109
+ }
110
+ | Refused
111
+
112
+ const refusedWith = (findings: CheckError[], warnings: CheckError[], forgeError?: unknown): Refused => ({
113
+ ok: false,
114
+ findings,
115
+ warnings,
116
+ ...(forgeError !== undefined ? { forgeError } : {})
117
+ })
118
+
119
+ function locateBodyOutcome(
120
+ ghArgs: string[],
121
+ retryCommand: string
122
+ ): { ok: true; bodyResult: BodyResult | null } | { ok: false; findings: CheckError[] } {
123
+ try {
124
+ return { ok: true, bodyResult: locateBody(ghArgs) }
125
+ } catch (e) {
126
+ if (e instanceof ForgeArgError) {
127
+ return {
128
+ ok: false,
129
+ findings: [makeCheckError('forge-args', e.message, `Fix the invocation, then re-run \`${retryCommand}\`.`)]
130
+ }
131
+ }
132
+ throw e
133
+ }
134
+ }
135
+
136
+ /** Runs the gate once and splits its findings; a blocking one refuses, a warning is reported and passes. */
137
+ async function gate(
138
+ forge: PlannerForge,
139
+ io: PlannerIo,
140
+ args: Parameters<PlannerForge['validate']>
141
+ ): Promise<{ ok: true; renderSkipped: string | null; warnings: CheckError[] } | Refused> {
142
+ const r = await forge.validate(...args)
143
+ if (r.blocking) {
144
+ return refusedWith(
145
+ r.errors,
146
+ r.errors.filter((e) => e.severity === 'warning')
147
+ )
148
+ }
149
+ for (const e of r.errors) io.warning?.(e)
150
+ return { ok: true, renderSkipped: r.renderSkipped, warnings: r.errors }
151
+ }
152
+
153
+ // --- create ------------------------------------------------------------------
154
+
155
+ /**
156
+ * Creates a task Issue: the same gates as `task_issue_create`, then the
157
+ * tranche label, the Milestone attach and the `gh` write. `validateOnly` runs
158
+ * every gate and returns without touching the forge.
159
+ */
160
+ export async function createIssue(
161
+ input: { ghArgs: string[]; validateOnly?: boolean },
162
+ io: PlannerIo = {},
163
+ forge: PlannerForge = realPlannerForge
164
+ ): Promise<IssueWriteOutcome> {
165
+ const { ghArgs } = input
166
+ const located = locateBodyOutcome(ghArgs, RETRY_CREATE)
167
+ if (!located.ok) return refusedWith(located.findings, [])
168
+ const { bodyResult } = located
169
+ const body = bodyResult?.body ?? null
170
+ const title = extractTitle(ghArgs)
171
+ const labels = extractLabels(ghArgs)
172
+
173
+ let renderSkipped: string | null = null
174
+ let warnings: CheckError[] = []
175
+ if (isTaskIssueLabelSet(labels) || (body !== null && isTaskIssueBodyShaped(body))) {
176
+ // No number exists until the write completes — null is fail-closed, never "old enough to skip".
177
+ const g = await gate(forge, io, [body, title, labels, RETRY_CREATE, null, { kind: 'create', ghArgs }])
178
+ if (!g.ok) return g
179
+ renderSkipped = g.renderSkipped
180
+ warnings = g.warnings
181
+ }
182
+
183
+ if (input.validateOnly) return { ok: true, written: false, url: '', renderSkipped, warnings }
184
+
185
+ const slugToEnsure = findTrancheSlug(labels)
186
+ if (slugToEnsure) {
187
+ const errors = forge.ensureTrancheLabel(slugToEnsure)
188
+ if (errors.length > 0) return refusedWith(errors, warnings)
189
+ }
190
+
191
+ const milestone = forge.milestoneArgs(ghArgs, labels)
192
+ if (milestone.notice) io.notice?.(milestone.notice)
193
+ const written = forge.ghWrite(['issue', 'create'], milestone.args, bodyResult)
194
+ if (!written.ok) return refusedWith(written.errors, warnings, written.cause)
195
+ return { ok: true, written: true, url: written.url, renderSkipped, warnings }
196
+ }
197
+
198
+ // --- edit --------------------------------------------------------------------
199
+
200
+ /**
201
+ * Edits an Issue: `args` is the target Issue ref followed by the `gh issue
202
+ * edit` flags. The same gates as `task_issue_edit`; `validateOnly` stops
203
+ * after them. `skipFrozenSectionsCheck` is the objectives edit's own escape
204
+ * hatch; `retryCommand` names the command a refusal tells the caller to re-run.
205
+ */
206
+ export async function editIssue(
207
+ input: {
208
+ args: string[]
209
+ validateOnly?: boolean
210
+ retryCommand?: string
211
+ skipFrozenSectionsCheck?: boolean
212
+ },
213
+ io: PlannerIo = {},
214
+ forge: PlannerForge = realPlannerForge
215
+ ): Promise<IssueWriteOutcome> {
216
+ const retry = input.retryCommand ?? RETRY_EDIT
217
+ const issueRef = input.args[0]
218
+ if (!issueRef || issueRef.startsWith('-')) {
219
+ return refusedWith(
220
+ [
221
+ makeCheckError(
222
+ 'forge-args',
223
+ '`task_issue_edit` requires the target Issue number/URL as the first argument.',
224
+ 'Call `task_issue_edit` with the `issue` number and the fields to change.'
225
+ )
226
+ ],
227
+ []
228
+ )
229
+ }
230
+ const ghArgs = input.args.slice(1)
231
+ const located = locateBodyOutcome(ghArgs, retry)
232
+ if (!located.ok) return refusedWith(located.findings, [])
233
+ return editLocated(
234
+ {
235
+ issueRef,
236
+ ghArgs,
237
+ bodyResult: located.bodyResult,
238
+ validateOnly: input.validateOnly,
239
+ retryCommand: retry,
240
+ skipFrozenSectionsCheck: input.skipFrozenSectionsCheck
241
+ },
242
+ io,
243
+ forge
244
+ )
245
+ }
246
+
247
+ /** The edit once its body is located — shared with the objectives edit, which writes a body it built itself. */
248
+ async function editLocated(
249
+ input: {
250
+ issueRef: string
251
+ ghArgs: string[]
252
+ bodyResult: BodyResult | null
253
+ validateOnly?: boolean
254
+ retryCommand: string
255
+ skipFrozenSectionsCheck?: boolean
256
+ },
257
+ io: PlannerIo,
258
+ forge: PlannerForge
259
+ ): Promise<IssueWriteOutcome> {
260
+ const { issueRef, ghArgs, bodyResult, retryCommand } = input
261
+ const body = bodyResult?.body ?? null
262
+ const title = extractTitle(ghArgs)
263
+
264
+ // Union the forge's real labels with any passed on argv — argv is normally
265
+ // silent on edit, so the forge is what decides task-Issue applicability.
266
+ const fetched = forge.fetchLabels(issueRef, retryCommand)
267
+ if ('errors' in fetched) return refusedWith(fetched.errors, [])
268
+ const labels = [...new Set([...fetched.labels, ...extractLabels(ghArgs)])]
269
+
270
+ let renderSkipped: string | null = null
271
+ let warnings: CheckError[] = []
272
+ if (isTaskIssueLabelSet(labels) || (body !== null && isTaskIssueBodyShaped(body))) {
273
+ const frozen = forge.frozenSectionChange(issueRef, body, retryCommand, input.skipFrozenSectionsCheck ?? false)
274
+ if (frozen.length > 0) return refusedWith(frozen, [])
275
+ const g = await gate(forge, io, [
276
+ body,
277
+ title,
278
+ labels,
279
+ retryCommand,
280
+ parseIssueNumberFromRef(issueRef),
281
+ { kind: 'edit', issueRef, ghArgs }
282
+ ])
283
+ if (!g.ok) return g
284
+ renderSkipped = g.renderSkipped
285
+ warnings = g.warnings
286
+ }
287
+
288
+ if (input.validateOnly) return { ok: true, written: false, url: '', renderSkipped, warnings }
289
+
290
+ const slugToEnsure = findTrancheSlug(labels)
291
+ if (slugToEnsure) {
292
+ const errors = forge.ensureTrancheLabel(slugToEnsure)
293
+ if (errors.length > 0) return refusedWith(errors, warnings)
294
+ }
295
+ const written = forge.ghWrite(['issue', 'edit', issueRef], ghArgs, bodyResult)
296
+ if (!written.ok) return refusedWith(written.errors, warnings, written.cause)
297
+ return { ok: true, written: true, url: written.url, renderSkipped, warnings }
298
+ }
299
+
300
+ // --- surface -----------------------------------------------------------------
301
+
302
+ export type SurfaceOutcome =
303
+ | { ok: true; set: SurfaceForcedSet; json: boolean; text: string }
304
+ | { ok: false; exitCode: 2; message: string }
305
+
306
+ /** What a draft Issue's Boundary pins force on its Surface. Writes nothing. */
307
+ export function printIssueSurface(args: string[]): SurfaceOutcome {
308
+ const r = issueSurfaceOutcome(args)
309
+ if (!r.ok) return { ok: false, exitCode: 2, message: r.message }
310
+ return { ok: true, set: r.set, json: r.json, text: renderSurfaceForcedSet(r.set) }
311
+ }
312
+
313
+ // --- brief -------------------------------------------------------------------
314
+
315
+ export type BriefOutcome = { ok: true; brief: string } | { ok: false; missing: string[] }
316
+
317
+ /** Renders a task's brief; a refusal lists the facts it could not find. */
318
+ export async function renderBrief(
319
+ input: {
320
+ trancheSlug: string
321
+ taskId: string
322
+ globs?: string[]
323
+ },
324
+ assemble: typeof assembleAndRenderBrief = assembleAndRenderBrief
325
+ ): Promise<BriefOutcome> {
326
+ const result = await assemble(input.trancheSlug, input.taskId, input.globs)
327
+ if (!result.ok) return { ok: false, missing: result.missing }
328
+ return { ok: true, brief: result.brief }
329
+ }
330
+
331
+ // --- objectives edit ---------------------------------------------------------
332
+
333
+ const RETRY = 'task_objectives_edit'
334
+ /** The objectives-version marker's opening, in every spelling, the current one first — the writer posts the first; `k` counts them all, so a version posted before the rename is never reused. */
335
+ const MARKER_PREFIXES = objectivesVersionMarkerPrefixes()
336
+ const MARKER_PREFIX = MARKER_PREFIXES[0] as string
337
+
338
+ type EditOp =
339
+ | { kind: 'add'; sentence: string }
340
+ | { kind: 'drop'; id: string }
341
+ | { kind: 'replace'; id: string; sentence: string }
342
+
343
+ /**
344
+ * The same `## Objectives` heading/next-heading boundary `objectivesOf`
345
+ * itself locates (that scanner is internal to the objectives package, never
346
+ * exported — the parsed `Objective[]` list is the public surface, not the
347
+ * raw span). Re-deriving the SAME regex here only decides where to splice
348
+ * text back in; it never re-implements the grammar `objectivesOf` already
349
+ * validated.
350
+ */
351
+ const HEADING_RE = /^##[ \t]*Objectives[ \t]*$/im
352
+ const NEXT_HEADING_RE = /^##[ \t]/m
353
+
354
+ /**
355
+ * Replaces the `## Objectives` section (heading through the next `##`
356
+ * heading, or end of body) with `renderedSection`, leaving every other byte
357
+ * of `body` untouched — the before-heading and after-next-heading slices are
358
+ * copied verbatim, never re-derived.
359
+ */
360
+ export function spliceObjectivesSection(body: string, renderedSection: string): string {
361
+ const heading = HEADING_RE.exec(body)
362
+ if (!heading) {
363
+ throw new Error(
364
+ 'spliceObjectivesSection: no `## Objectives` heading — caller must validate with objectivesOf first.'
365
+ )
366
+ }
367
+ const before = body.slice(0, heading.index)
368
+ const afterHeadingStart = heading.index + heading[0].length
369
+ const afterHeading = body.slice(afterHeadingStart)
370
+ const next = NEXT_HEADING_RE.exec(afterHeading)
371
+ if (!next) return `${before}${renderedSection}\n`
372
+ const tail = afterHeading.slice(next.index)
373
+ return `${before}${renderedSection}\n\n${tail}`
374
+ }
375
+
376
+ /** The body with its `## Objectives` section blanked out — used to assert the edit touched nothing else. */
377
+ export function withoutObjectivesSection(body: string): string {
378
+ const heading = HEADING_RE.exec(body)
379
+ if (!heading) return body
380
+ const before = body.slice(0, heading.index)
381
+ const afterHeadingStart = heading.index + heading[0].length
382
+ const afterHeading = body.slice(afterHeadingStart)
383
+ const next = NEXT_HEADING_RE.exec(afterHeading)
384
+ return next ? before + afterHeading.slice(next.index) : before
385
+ }
386
+
387
+ const PARTS_HEADING_RE = /^##[ \t]*Parts[ \t]*$/im
388
+
389
+ /** `{ headingEnd, sectionEnd }` byte offsets of the `## Parts` section's own content (heading excluded, next `##` heading excluded) — `null` when there is no `## Parts` heading at all. */
390
+ function partsSectionBounds(body: string): { headingEnd: number; sectionEnd: number } | null {
391
+ const heading = PARTS_HEADING_RE.exec(body)
392
+ if (!heading) return null
393
+ const headingEnd = heading.index + heading[0].length
394
+ const afterHeading = body.slice(headingEnd)
395
+ const next = NEXT_HEADING_RE.exec(afterHeading)
396
+ const sectionEnd = next ? headingEnd + next.index : body.length
397
+ return { headingEnd, sectionEnd }
398
+ }
399
+
400
+ /**
401
+ * Appends `partLine` as a new line at the end of the `## Parts` section —
402
+ * `--add`'s own write, in the SAME edit as the Objectives change.
403
+ * Throws when there is no `## Parts` heading at all: a pre-cutover Issue
404
+ * with no Parts section has no self-serve add path here — the same posture
405
+ * the brief-sections cutover already takes for a Surface-less Issue.
406
+ */
407
+ export function appendPartLine(body: string, partLine: string): string {
408
+ const bounds = partsSectionBounds(body)
409
+ if (!bounds) {
410
+ throw new Error('appendPartLine: no `## Parts` heading in this Issue body — cannot add a Part.')
411
+ }
412
+ const before = body.slice(0, bounds.headingEnd)
413
+ const section = body.slice(bounds.headingEnd, bounds.sectionEnd).replace(/\s+$/, '')
414
+ const tail = body.slice(bounds.sectionEnd)
415
+ return `${before}${section}\n${partLine}\n${tail}`
416
+ }
417
+
418
+ /**
419
+ * Removes every `## Parts` line whose citation is EXACTLY `droppedId` (and
420
+ * nothing else) — `--drop`'s own write. A Part citing the dropped
421
+ * objective alongside another is left untouched, unchanged from before this
422
+ * edit: narrowing a multi-objective citation is out of this rule's scope. If
423
+ * that leaves a Part citing an objective no longer defined,
424
+ * `writeValidatedIssueEdit`'s own pre-existing `checkPartsCiteDefinedObjectives`
425
+ * gate refuses the write naming the dangling citation — the Planner resolves
426
+ * it by hand before the drop can proceed. A no-op when there is no
427
+ * `## Parts` heading.
428
+ */
429
+ export function removePartLinesCitingOnly(body: string, droppedId: string): string {
430
+ const bounds = partsSectionBounds(body)
431
+ if (!bounds) return body
432
+ const droppedN = Number.parseInt(droppedId.replace(/^O/i, ''), 10)
433
+ const before = body.slice(0, bounds.headingEnd)
434
+ const section = body.slice(bounds.headingEnd, bounds.sectionEnd)
435
+ const tail = body.slice(bounds.sectionEnd)
436
+ const kept = section.split('\n').filter((line) => {
437
+ const m = /^Part\s+\d+\s*\(([^)]*)\)\s*[-—–]/i.exec(line.trim())
438
+ if (!m) return true
439
+ const refs = [...(m[1] as string).matchAll(/O(\d+)/gi)].map((r) => Number.parseInt(r[1] as string, 10))
440
+ return !(refs.length === 1 && refs[0] === droppedN)
441
+ })
442
+ return `${before}${kept.join('\n')}${tail}`
443
+ }
444
+
445
+ function formatList(objectives: Objective[]): string {
446
+ return objectives.map((o) => `${o.id}. ${o.text}`).join('\n')
447
+ }
448
+
449
+ function parseArgs(args: string[]): { json: boolean; issueRef: string; op: EditOp; reason: string; part?: string } {
450
+ const json = args.includes('--json')
451
+ const rest = args.filter((a) => a !== '--json')
452
+
453
+ const issueRef = rest[0]
454
+ if (!issueRef || issueRef.startsWith('-')) {
455
+ refuse([
456
+ makeCheckError(
457
+ 'forge-args',
458
+ '`task_objectives_edit` requires the target Issue number as the first argument.',
459
+ `Pass the Issue number, e.g. \`${RETRY}\`.`
460
+ )
461
+ ])
462
+ }
463
+
464
+ const ops: EditOp[] = []
465
+ let reason: string | undefined
466
+ let part: string | undefined
467
+ const flagArgs = rest.slice(1)
468
+ for (let i = 0; i < flagArgs.length; i++) {
469
+ const a = flagArgs[i] as string
470
+ if (a === '--add') {
471
+ ops.push({ kind: 'add', sentence: flagArgs[++i] ?? '' })
472
+ } else if (a === '--drop') {
473
+ ops.push({ kind: 'drop', id: flagArgs[++i] ?? '' })
474
+ } else if (a === '--replace') {
475
+ const id = flagArgs[++i] ?? ''
476
+ const sentence = flagArgs[++i] ?? ''
477
+ ops.push({ kind: 'replace', id, sentence })
478
+ } else if (a === '--reason') {
479
+ reason = flagArgs[++i]
480
+ } else if (a === '--part') {
481
+ part = flagArgs[++i]
482
+ }
483
+ }
484
+
485
+ if (ops.length !== 1) {
486
+ refuse([
487
+ makeCheckError(
488
+ 'forge-args',
489
+ `\`task_objectives_edit\` requires exactly one of --add, --drop, --replace (found ${ops.length}).`,
490
+ `Pass exactly one edit flag, e.g. \`${RETRY}\`.`
491
+ )
492
+ ])
493
+ }
494
+ if (!reason || reason.trim().length === 0) {
495
+ refuse([
496
+ makeCheckError(
497
+ 'forge-args',
498
+ '`task_objectives_edit` requires a non-empty `--reason "<text>"`.',
499
+ `Add \`--reason "<text>"\`, then re-run \`${RETRY}\`.`
500
+ )
501
+ ])
502
+ }
503
+ // Security review, round 2, HIGH: this same reason is later
504
+ // handed to `prepareTask`'s own O6 supersede call, which refuses a
505
+ // `\r`/`\n` reason for the header-corruption hazard `dispatch-task.ts`
506
+ // documents at its own check. Checked here too, before ANY write, so a
507
+ // bad reason never gets past the point where the Objectives comment has
508
+ // already posted — `prepareTask`'s refusal would otherwise fire only
509
+ // after that comment exists, leaving the Issue and its frozen brief
510
+ // disagreeing with no disclosure.
511
+ if (/[\r\n]/.test(reason as string)) {
512
+ refuse([
513
+ makeCheckError(
514
+ 'forge-args',
515
+ "`--reason` must be a single line — it becomes one line of the frozen comment header this edit may supersede, and a newline in it would corrupt every reader's header-line count for that version.",
516
+ `Remove the newline from --reason, then re-run \`${RETRY}\`.`
517
+ )
518
+ ])
519
+ }
520
+
521
+ // O5: `--add` without a `--part` would freeze an
522
+ // objective no `## Parts` line ever cites — `checkPartsCiteDefinedObjectives`
523
+ // stays silent about it (it only checks a citation names a REAL objective,
524
+ // never the reverse), so a frozen brief re-issued after this edit would
525
+ // simply omit the new objective from every Part with nothing to fail on.
526
+ // Refused here, naming the rule, rather than discovered downstream.
527
+ if (ops[0]?.kind === 'add' && (!part || part.trim().length === 0)) {
528
+ refuse([
529
+ makeCheckError(
530
+ 'objectives-part-required',
531
+ '`--add` requires `--part "Part <n> (O<k>) — <outcome>"` for the objective it adds — an objective with no citing Part is never covered by a frozen brief re-issued after this edit.',
532
+ `Pass --part "Part <n> (O<k>) — <outcome>", then re-run \`${RETRY}\`.`
533
+ )
534
+ ])
535
+ }
536
+ if (ops[0]?.kind !== 'add' && part !== undefined) {
537
+ refuse([
538
+ makeCheckError(
539
+ 'forge-args',
540
+ '`--part` is only meaningful with `--add`.',
541
+ `Remove --part, then re-run \`${RETRY}\`.`
542
+ )
543
+ ])
544
+ }
545
+
546
+ return { json, issueRef, op: ops[0] as EditOp, reason: reason as string, part }
547
+ }
548
+
549
+ /** A comment reduced to what both `countMarkerComments` (body only) and `resolveNewestFrozenBrief` (body + author, O6) need, plus its own URL to name in a superseding-brief context. */
550
+ type IssueComment = FrozenBriefCandidate & { url: string }
551
+
552
+ export function fetchIssueBodyAndComments(issueRef: string): {
553
+ number: number
554
+ body: string
555
+ title: string
556
+ labels: string[]
557
+ comments: IssueComment[]
558
+ } {
559
+ try {
560
+ const parsed = readIssueFields<{
561
+ number?: number
562
+ body?: string
563
+ title?: string
564
+ labels?: Array<{ name: string }>
565
+ }>(issueRef, 'number,body,title,labels')
566
+ return {
567
+ number: parsed.number ?? Number.NaN,
568
+ body: parsed.body ?? '',
569
+ title: parsed.title ?? '',
570
+ labels: (parsed.labels ?? []).map((l) => l.name),
571
+ comments: readIssueComments(issueRef).map((c) => ({ body: c.body, url: c.url, author: c.author?.login ?? null }))
572
+ }
573
+ } catch (err) {
574
+ if (isForgeReadOversize(err)) {
575
+ refuse([makeCheckError('forge-fetch', err.message, `Trim the Issue's comments, then re-run \`${RETRY}\`.`)])
576
+ }
577
+ if (!(err instanceof SyntaxError)) {
578
+ refuse([
579
+ makeCheckError(
580
+ 'forge-fetch',
581
+ `Could not fetch Issue ${issueRef} (\`gh issue view\`): ${err instanceof Error ? err.message : String(err)}`,
582
+ `Check \`gh auth status\` and network, then re-run \`${RETRY}\`.`
583
+ )
584
+ ])
585
+ }
586
+ refuse([
587
+ makeCheckError(
588
+ 'forge-fetch',
589
+ `Could not parse \`gh issue view ${issueRef} --json number,body,title,labels,comments\` output.`,
590
+ `Re-run \`${RETRY}\`.`
591
+ )
592
+ ])
593
+ }
594
+ }
595
+
596
+ function applyOp(previous: Objective[], op: EditOp): Objective[] {
597
+ if (op.kind === 'add') {
598
+ if (op.sentence.trim().length === 0) {
599
+ refuse([
600
+ makeCheckError(
601
+ 'objectives-args',
602
+ '`--add` requires a non-empty sentence.',
603
+ `Pass a sentence, then re-run \`${RETRY}\`.`
604
+ )
605
+ ])
606
+ }
607
+ const maxN = previous.reduce((m, o) => Math.max(m, Number.parseInt(o.id.slice(1), 10)), 0)
608
+ return [...previous, { id: `O${maxN + 1}`, text: op.sentence }]
609
+ }
610
+
611
+ const idx = previous.findIndex((o) => o.id === op.id)
612
+ if (idx === -1) {
613
+ refuse([
614
+ makeCheckError(
615
+ 'objectives-args',
616
+ `${op.id} does not exist in the current Objectives list.`,
617
+ `Check the current list, then re-run \`${RETRY}\` with an existing id.`
618
+ )
619
+ ])
620
+ }
621
+
622
+ if (op.kind === 'replace') {
623
+ if (op.sentence.trim().length === 0) {
624
+ refuse([
625
+ makeCheckError(
626
+ 'objectives-args',
627
+ '`--replace` requires a non-empty sentence.',
628
+ `Pass a sentence, then re-run \`${RETRY}\`.`
629
+ )
630
+ ])
631
+ }
632
+ return previous.map((o, i) => (i === idx ? { id: o.id, text: op.sentence } : o))
633
+ }
634
+
635
+ // --drop: remove the line, never renumber the survivors. If the parser then
636
+ // refuses the result (a real numbering gap), that is a live contradiction
637
+ // between the rationale's never-renumber rule and `objectivesOf`'s
638
+ // contiguous-from-O1 grammar — report it verbatim and stop; do not change
639
+ // `objectives.ts` to paper over it (§10).
640
+ const dropped = previous.filter((o) => o.id !== op.id)
641
+ const check = objectivesOf(renderObjectives(dropped))
642
+ if (!check.ok) {
643
+ refuse([
644
+ makeCheckError(
645
+ 'objectives-drop-contiguity',
646
+ `${check.errors.join(' ')} Dropping ${op.id} never renumbers the surviving objectives, but the result no longer parses — the Principal must rule on this contradiction (contiguous-from-O1 grammar vs. never-renumber rationale) before this drop can proceed.`,
647
+ 'Escalate to the Principal; do not change `objectives.ts`.'
648
+ )
649
+ ])
650
+ }
651
+ return dropped
652
+ }
653
+
654
+ export type ObjectivesOutcome =
655
+ | { ok: true; version: string; url: string; supersedeUrl: string | null }
656
+ | { ok: false; findings: CheckError[] }
657
+
658
+ /**
659
+ * Edits an Issue's `## Objectives`: `args` is the Issue ref followed by exactly
660
+ * one of `--add`, `--drop`, `--replace`, plus `--reason` (and `--part` for
661
+ * `--add`). Principal-only. Writes the Issue, supersedes a frozen brief when
662
+ * one exists, and posts the audit comment. A refusal anywhere beneath — an
663
+ * argument, the Principal gate, a parse, a gate, a forge call — comes back as
664
+ * findings.
665
+ */
666
+ export async function editObjectives(
667
+ args: string[],
668
+ io: PlannerIo = {},
669
+ deps: ObjectivesDeps = realObjectivesDeps
670
+ ): Promise<ObjectivesOutcome> {
671
+ const r = await captureRefusal(() => editObjectivesOrRefuse(args, io, deps))
672
+ return r.ok ? r.value : { ok: false, findings: r.errors }
673
+ }
674
+
675
+ /** The forge-touching steps the objectives edit runs, replaceable so a test stubs the forge. */
676
+ export interface ObjectivesDeps {
677
+ forge: PlannerForge
678
+ requirePrincipal: (retryCommand: string) => void
679
+ resolvePrincipals: (check: string, retryCommand: string) => string[]
680
+ fetchIssue: typeof fetchIssueBodyAndComments
681
+ supersede: typeof prepareTaskOrIssue
682
+ postComment: typeof postMarkedComment
683
+ }
684
+
685
+ export const realObjectivesDeps: ObjectivesDeps = {
686
+ forge: realPlannerForge,
687
+ requirePrincipal: refuseUnlessPrincipal,
688
+ resolvePrincipals: resolvePrincipalsOrRefuse,
689
+ fetchIssue: (ref) => fetchIssueBodyAndComments(ref),
690
+ supersede: prepareTaskOrIssue,
691
+ postComment: postMarkedComment
692
+ }
693
+
694
+ async function editObjectivesOrRefuse(args: string[], io: PlannerIo, deps: ObjectivesDeps): Promise<ObjectivesOutcome> {
695
+ const { issueRef, op, reason, part } = parseArgs(args)
696
+ deps.requirePrincipal(RETRY)
697
+
698
+ const { number, body, title, labels, comments } = deps.fetchIssue(issueRef)
699
+ // Resolved before the edit below is written, so a Principal list that does
700
+ // not resolve refuses with nothing changed on the forge.
701
+ const allowlist = deps.resolvePrincipals('principal-only', RETRY)
702
+ const parsed = objectivesOf(body)
703
+ if (!parsed.ok) {
704
+ refuse([
705
+ makeCheckError(
706
+ 'objectives-parse',
707
+ `Issue ${issueRef}'s \`## Objectives\` section does not parse: ${parsed.errors.join(' ')}`,
708
+ "Fix the Issue body's Objectives section by hand, then retry."
709
+ )
710
+ ])
711
+ }
712
+ const previous = parsed.objectives
713
+
714
+ const updated = applyOp(previous, op)
715
+ const objectivesBody = spliceObjectivesSection(body, renderObjectives(updated))
716
+
717
+ // `--add` writes its `--part` line into `## Parts` in this SAME edit, so a
718
+ // frozen brief re-issued right after this command always passes
719
+ // `checkObjectivesCoverage`/`checkPartsCiteDefinedObjectives`.
720
+ // `--drop` removes the Part lines that cited only the dropped objective.
721
+ let finalBody = objectivesBody
722
+ if (op.kind === 'add') {
723
+ finalBody = appendPartLine(finalBody, part as string)
724
+ const reparsedParts = parseIssueParts(finalBody)
725
+ if (!reparsedParts.ok) {
726
+ refuse([
727
+ makeCheckError(
728
+ 'objectives-part-malformed',
729
+ `--part "${part}" produced a malformed \`## Parts\` section: ${reparsedParts.errors.join(' ')}`,
730
+ `Fix --part to match \`Part <n> (O<k>) — <outcome>\`, then re-run \`${RETRY}\`.`
731
+ )
732
+ ])
733
+ }
734
+ const addedId = (updated[updated.length - 1] as Objective).id
735
+ const addedN = Number.parseInt(addedId.slice(1), 10)
736
+ if (!reparsedParts.value.some((p) => p.objectiveIds.includes(addedN))) {
737
+ refuse([
738
+ makeCheckError(
739
+ 'objectives-part-mismatch',
740
+ `--part "${part}" does not cite ${addedId}, the objective this --add just created.`,
741
+ `Pass --part "Part <n> (${addedId}) — <outcome>", then re-run \`${RETRY}\`.`
742
+ )
743
+ ])
744
+ }
745
+ } else if (op.kind === 'drop') {
746
+ finalBody = removePartLinesCitingOnly(finalBody, op.id)
747
+ }
748
+
749
+ const dir = mkdtempSync(join(tmpdir(), 'vinaya-objectives-edit-'))
750
+ const tmp = join(dir, 'body.md')
751
+ writeFileSync(tmp, finalBody, 'utf8')
752
+ try {
753
+ const ghArgs = ['--body-file', tmp]
754
+ // This command IS the sanctioned Objectives-change path the frozen-section
755
+ // gate names as its escape hatch: it rewrites `## Parts` in the same edit
756
+ // and posts its own superseding brief below.
757
+ const written = await editLocated(
758
+ {
759
+ issueRef,
760
+ ghArgs,
761
+ bodyResult: locateBody(ghArgs),
762
+ retryCommand: RETRY,
763
+ skipFrozenSectionsCheck: true
764
+ },
765
+ io,
766
+ deps.forge
767
+ )
768
+ if (!written.ok) {
769
+ if (written.forgeError !== undefined) throw written.forgeError
770
+ return { ok: false, findings: written.findings }
771
+ }
772
+ } finally {
773
+ rmSync(dir, { recursive: true, force: true })
774
+ }
775
+
776
+ const newVersion = objectivesVersion(updated)
777
+
778
+ // If this task's brief is already frozen, the edit above just moved the
779
+ // Issue and the frozen brief out of agreement. Resolve and post the
780
+ // superseding brief BEFORE this edit's own audit comment below, so a
781
+ // failure here leaves no objectives comment behind at all. A
782
+ // tranche-labeled Issue supersedes through the tranche path; a backlog
783
+ // Issue (no tranche identity) through the `--issue` path.
784
+ let supersedeUrl: string | null = null
785
+ const frozen = resolveNewestFrozenBrief(comments, allowlist)
786
+ if (frozen !== null) {
787
+ const taskRef = resolveTaskIssueRef(title, labels)
788
+ const result = await deps.supersede(
789
+ taskRef !== null
790
+ ? { tranche: taskRef.trancheSlug, n: Number.parseInt(taskRef.taskId, 10), supersede: { reason } }
791
+ : { issue: number, supersede: { reason } }
792
+ )
793
+ supersedeUrl = result.commentUrl
794
+ }
795
+
796
+ const k =
797
+ countMarkerComments(
798
+ comments.map((c) => c.body),
799
+ MARKER_PREFIXES
800
+ ) + 1
801
+ const marker = `${MARKER_PREFIX}${k} -->`
802
+ const commentBody = [
803
+ 'Previous:',
804
+ formatList(previous),
805
+ '',
806
+ 'Now:',
807
+ formatList(updated),
808
+ '',
809
+ `Reason: ${reason}`,
810
+ `Version: ${newVersion}`
811
+ ].join('\n')
812
+ const url = deps.postComment('issue', issueRef, marker, commentBody)
813
+
814
+ return { ok: true, version: newVersion, url, supersedeUrl }
815
+ }