@attalabs/vinaya 0.44.0 → 0.47.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 (144) hide show
  1. package/README.md +6 -4
  2. package/dist/checks/bin/check-body-bare-digits.js +262 -201
  3. package/dist/checks/bin/check-branch-topology.js +70 -23
  4. package/dist/checks/bin/check-brief-shape.js +262 -201
  5. package/dist/checks/bin/check-changeset-coverage.js +94 -16
  6. package/dist/checks/bin/check-ci-shard-coverage.js +3 -0
  7. package/dist/checks/bin/check-closes-n.js +157 -40
  8. package/dist/checks/bin/check-coherence.js +365 -251
  9. package/dist/checks/bin/check-dispatch-readiness.js +3654 -469
  10. package/dist/checks/bin/check-doc-claims.js +262 -201
  11. package/dist/checks/bin/check-doc-coverage-push.js +272 -202
  12. package/dist/checks/bin/check-doc-coverage.js +272 -202
  13. package/dist/checks/bin/check-doctrine-no-procedures.js +262 -201
  14. package/dist/checks/bin/check-doctrine-portability.js +262 -201
  15. package/dist/checks/bin/check-evidence-fresh.js +10138 -2126
  16. package/dist/checks/bin/check-exec-bits.js +3 -0
  17. package/dist/checks/bin/check-first-push-dispatch.js +330 -230
  18. package/dist/checks/bin/check-issue-milestone-attach.js +94 -16
  19. package/dist/checks/bin/check-issue-objectives-numbering.js +262 -201
  20. package/dist/checks/bin/check-issue-parts-coverage.js +94 -16
  21. package/dist/checks/bin/check-issue-surface-globs.js +1062 -242
  22. package/dist/checks/bin/check-issue-title-grammar.js +21 -5
  23. package/dist/checks/bin/check-no-disk-state.js +5 -1
  24. package/dist/checks/bin/check-pr-premise-reassert.js +22 -2
  25. package/dist/checks/bin/check-pr-report-density.js +5 -1
  26. package/dist/checks/bin/check-principal-test-plan-wait.js +282 -207
  27. package/dist/checks/bin/check-quoted-command.js +262 -201
  28. package/dist/checks/bin/check-reader-resolvable-prose.js +262 -201
  29. package/dist/checks/bin/check-registry-gates.js +131 -34
  30. package/dist/checks/bin/check-retired-vocabulary.js +262 -201
  31. package/dist/checks/bin/check-review-gate.js +262 -201
  32. package/dist/checks/bin/check-single-plan-pr.js +5 -1
  33. package/dist/checks/bin/check-surface-scope.js +136 -38
  34. package/dist/checks/bin/check-test-plan.js +282 -207
  35. package/dist/checks/bin/check-token-collection-wired.js +3 -0
  36. package/dist/checks/bin/check-workspace-escape.js +3 -0
  37. package/dist/checks/bin/verify-coherence.js +237 -148
  38. package/dist/checks/bin/verify-dispatch.js +870 -66
  39. package/dist/checks/bin/verify-docs.js +13 -6
  40. package/dist/harness.js +57 -10
  41. package/dist/index.js +16670 -7196
  42. package/dist/lib/pre-push-cache-test-run.js +4488 -2170
  43. package/dist/lib/pre-push-changed-files.js +251 -12
  44. package/dist/lib/pre-push-mode.js +69 -19
  45. package/dist/lib/pre-push-progress-dir.js +10265 -2853
  46. package/dist/lib/pre-push-record-tests.js +67 -19
  47. package/dist/lib/pre-push-select-tests.js +520 -222
  48. package/dist/lib/push-progress-observer.js +9176 -1757
  49. package/dist/process.js +2 -0
  50. package/dist/programs/archive.js +8948 -1547
  51. package/dist/programs/audit.js +9176 -1772
  52. package/dist/programs/check.js +9248 -1845
  53. package/dist/programs/commit-msg.js +8984 -1583
  54. package/dist/programs/dev-review-loop.js +15621 -7626
  55. package/dist/programs/dispatch.js +9977 -2726
  56. package/dist/programs/log-emit.js +9011 -1660
  57. package/dist/programs/log-selftest.js +8908 -1507
  58. package/dist/programs/log-send.js +9081 -1594
  59. package/dist/programs/pr-report.js +9477 -1820
  60. package/dist/programs/pr-snapshot.js +8916 -1515
  61. package/dist/programs/pr-verify-evidence.js +9482 -1825
  62. package/dist/programs/pr.js +11773 -4082
  63. package/dist/programs/review-post.js +11141 -3496
  64. package/dist/programs/review-status.js +8997 -1533
  65. package/dist/programs/run-engine.js +22149 -18798
  66. package/dist/programs/sync.js +9030 -1629
  67. package/dist/programs/task-brief.js +10234 -1827
  68. package/dist/programs/task-sweep.js +9267 -1621
  69. package/dist/programs/task-tools-serve.js +77141 -16659
  70. package/dist/programs/tokens.js +8966 -1565
  71. package/dist/programs/waiver.js +8983 -1582
  72. package/dist/types/harness/kernel/dev-process-socket/loader/load-process.d.ts +1 -1
  73. package/dist/types/harness/processes/vinaya-strict/tools/legacy-markers.d.ts +8 -0
  74. package/dist/types/harness/processes/vinaya-strict/tools/task-contract/brief-validation.d.ts +17 -10
  75. package/dist/types/harness/processes/vinaya-strict/tools/task-contract/objectives.d.ts +5 -6
  76. package/dist/types/harness/processes/vinaya-strict/tools/task-contract/premise-check.d.ts +14 -0
  77. package/dist/vinaya-strict/checks/registry.ts +2 -2
  78. package/dist/vinaya-strict/executing/developer/developer-doctrine-shape.test.ts +8 -0
  79. package/dist/vinaya-strict/executing/developer/developer-turn-result.ts +1 -1
  80. package/dist/vinaya-strict/executing/developer/evals/developer-capability-suite.test.ts +2 -2
  81. package/dist/vinaya-strict/executing/developer/evals/developer-capability-suite.ts +30 -20
  82. package/dist/vinaya-strict/executing/developer/reference.md +5 -3
  83. package/dist/vinaya-strict/integration/config/vinaya-config-section.ts +29 -7
  84. package/dist/vinaya-strict/integration/policies/vinaya-policies.ts +4 -4
  85. package/dist/vinaya-strict/integration/process/process-integration.ts +5 -1
  86. package/dist/vinaya-strict/process.yaml +6 -1
  87. package/dist/vinaya-strict/thinking/plan-reviewer/doctrine.md +68 -0
  88. package/dist/vinaya-strict/thinking/plan-reviewer/grants.yaml +19 -0
  89. package/dist/vinaya-strict/thinking/plan-reviewer/output.schema.json +388 -0
  90. package/dist/vinaya-strict/thinking/planner/doctrine.md +4 -1
  91. package/dist/vinaya-strict/thinking/planner/tools/amend-rationale-deps.test.ts +10 -2
  92. package/dist/vinaya-strict/thinking/planner/tools/amend-rationale-deps.ts +5 -1
  93. package/dist/vinaya-strict/thinking/planner/tools/open-issue.test.ts +198 -34
  94. package/dist/vinaya-strict/thinking/planner/tools/open-issue.ts +120 -193
  95. package/dist/vinaya-strict/thinking/planner/tools/planner-operations.test.ts +629 -15
  96. package/dist/vinaya-strict/thinking/planner/tools/planner-operations.ts +726 -62
  97. package/dist/vinaya-strict/thinking/planner/tools/planner-tools.test.ts +505 -5
  98. package/dist/vinaya-strict/thinking/planner/tools/planner-tools.ts +636 -21
  99. package/package.json +3 -2
  100. package/studio-standalone/apps/vinaya-studio/.next/BUILD_ID +1 -1
  101. package/studio-standalone/apps/vinaya-studio/.next/build-manifest.json +2 -2
  102. package/studio-standalone/apps/vinaya-studio/.next/prerender-manifest.json +3 -3
  103. package/studio-standalone/apps/vinaya-studio/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  104. package/studio-standalone/apps/vinaya-studio/.next/server/app/_global-error.html +1 -1
  105. package/studio-standalone/apps/vinaya-studio/.next/server/app/_global-error.rsc +1 -1
  106. package/studio-standalone/apps/vinaya-studio/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  107. package/studio-standalone/apps/vinaya-studio/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  108. package/studio-standalone/apps/vinaya-studio/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  109. package/studio-standalone/apps/vinaya-studio/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  110. package/studio-standalone/apps/vinaya-studio/.next/server/app/milestones/page_client-reference-manifest.js +1 -1
  111. package/studio-standalone/apps/vinaya-studio/.next/server/app/page_client-reference-manifest.js +1 -1
  112. package/studio-standalone/apps/vinaya-studio/.next/server/app/tasks/page_client-reference-manifest.js +1 -1
  113. package/studio-standalone/apps/vinaya-studio/.next/server/chunks/209.js +2 -2
  114. package/studio-standalone/apps/vinaya-studio/.next/server/chunks/951.js +1 -1
  115. package/studio-standalone/apps/vinaya-studio/.next/server/middleware-build-manifest.js +1 -1
  116. package/studio-standalone/apps/vinaya-studio/.next/server/pages/500.html +1 -1
  117. package/studio-standalone/apps/vinaya-studio/.next/server/preview-props.json +3 -3
  118. package/studio-standalone/apps/vinaya-studio/.next/server/server-reference-manifest.json +1 -1
  119. package/studio-standalone/apps/vinaya-studio/.next/static/chunks/151-c365f0ef8268ad13.js +1 -0
  120. package/studio-standalone/apps/vinaya-studio/.next/static/chunks/19-aa314f13784dcc58.js +4 -0
  121. package/studio-standalone/apps/vinaya-studio/.next/static/chunks/app/{layout-dfa2186095e797bd.js → layout-f038e8deecb2bf5f.js} +1 -1
  122. package/studio-standalone/apps/vinaya-studio/.next/static/chunks/app/milestones/{page-2fffb49104860a15.js → page-12314f4deb06a414.js} +1 -1
  123. package/studio-standalone/apps/vinaya-studio/.next/static/chunks/app/{page-6ae258f663623b2a.js → page-7a06aa3cdd046fa8.js} +1 -1
  124. package/studio-standalone/apps/vinaya-studio/.next/static/chunks/app/tasks/{page-2fffb49104860a15.js → page-12314f4deb06a414.js} +1 -1
  125. package/studio-standalone/apps/vinaya-studio/.next/static/css/8eb5ed5b65b9692e.css +1 -0
  126. package/studio-standalone/apps/vinaya-studio/log-follow.mjs +708 -93
  127. package/studio-standalone/apps/vinaya-studio/log-sync-folder-source.mjs +699 -84
  128. package/studio-standalone/apps/vinaya-studio/studio-server.mjs +4692 -3116
  129. package/vinaya-strict/artifacts/templates/brief-template.md +6 -0
  130. package/vinaya-strict/artifacts/templates/issue-rationale-template.md +7 -3
  131. package/vinaya-strict/artifacts/templates/pr-report-template.md +1 -1
  132. package/vinaya-strict/doctrine/contracts/planner-developer.md +4 -3
  133. package/vinaya-strict/doctrine/enforcement.md +4 -4
  134. package/vinaya-strict/doctrine/roles/principal.md +1 -1
  135. package/vinaya-strict/doctrine/state-machine.md +7 -2
  136. package/vinaya-strict/executing/developer/reference.md +5 -3
  137. package/vinaya-strict/thinking/plan-reviewer/doctrine.md +68 -0
  138. package/vinaya-strict/thinking/planner/doctrine.md +4 -1
  139. package/vinaya-strict/thinking/planner/reference.md +30 -9
  140. package/studio-standalone/apps/vinaya-studio/.next/static/chunks/151-23bea4cac9687151.js +0 -1
  141. package/studio-standalone/apps/vinaya-studio/.next/static/chunks/853-1d5548ff3a55a75f.js +0 -4
  142. package/studio-standalone/apps/vinaya-studio/.next/static/css/fb16828fc3128d4c.css +0 -1
  143. /package/studio-standalone/apps/vinaya-studio/.next/static/{_r9iZDxlkoek85d_3oaxL → bJrgAp9Kl4JsCUYkeAYez}/_buildManifest.js +0 -0
  144. /package/studio-standalone/apps/vinaya-studio/.next/static/{_r9iZDxlkoek85d_3oaxL → bJrgAp9Kl4JsCUYkeAYez}/_ssgManifest.js +0 -0
@@ -6,6 +6,28 @@
6
6
  * operation (however deep) is captured as a finding, not an exit.
7
7
  */
8
8
 
9
+ import { runtimeDirForThisRepo } from '@harness/kernel/run-paths'
10
+ import { draftFingerprint, type PlanDraft, parsePlanDraft } from '@harness/workflow/tools/plan-draft/draft'
11
+ import { type DraftCheckReport, checkDraft } from '@harness/workflow/tools/plan-draft/check'
12
+ import { type DraftPreview, previewDraft, publishedIssueOf } from '@harness/workflow/tools/plan-draft/preview'
13
+ import { readPlanDraft, writePlanDraft } from '@harness/workflow/tools/plan-draft/store'
14
+ import {
15
+ type CoordinatorDeps,
16
+ type CoordinatorFinding,
17
+ type ApproveOutcome,
18
+ type DecideOutcome,
19
+ type DecisionChoice,
20
+ approvePlanReview,
21
+ decidePlanReview,
22
+ planReviewStatus,
23
+ resolveReviewerAgent,
24
+ type ReviewStatus,
25
+ type StartOutcome,
26
+ startPlanReview,
27
+ type StatusOutcome
28
+ } from '@harness/workflow/tools/plan-review/coordinator'
29
+ import type { PlanReviewAgent } from '@harness/workflow/tools/plan-review/launch'
30
+ import { loadConfig, resolveReviewAgent, resolveReviewRoundLimit } from '@harness/workflow/integration/config/compose'
9
31
  import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
10
32
  import { tmpdir } from 'node:os'
11
33
  import { join } from 'node:path'
@@ -13,17 +35,25 @@ import {
13
35
  isForgeReadOversize,
14
36
  readIssueComments,
15
37
  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'
38
+ } from '@harness/kernel/adapters/code-host/github/forge-read.js'
39
+ import {
40
+ assembleAndRenderBrief,
41
+ assembleAndRenderBriefForIssue
42
+ } from '@harness/workflow/tools/task-contract/brief-assembly.js'
43
+ import {
44
+ type FrozenBriefCandidate,
45
+ resolveNewestFrozenBrief
46
+ } from '@harness/workflow/tools/task-contract/brief-validation'
47
+ import { prepareTaskOrIssue } from '@harness/workflow/tools/task-contract/dispatch-task.js'
48
+ import { findTrancheSlug } from '@harness/workflow/tools/task-contract/forge/labels'
49
+ import { resolveTaskIssueRef } from '@harness/workflow/tools/task-contract/forge/list-tasks'
22
50
  import {
23
51
  type BodyResult,
52
+ type DraftRenderContext,
24
53
  ForgeArgError,
25
54
  captureRefusal,
26
55
  countMarkerComments,
56
+ documentationEditMarkerPrefixes,
27
57
  ensureTrancheLabelExistsOutcome,
28
58
  extractLabels,
29
59
  extractTitle,
@@ -42,20 +72,22 @@ import {
42
72
  resolvePrincipalsOrRefuse,
43
73
  runGhWriteOutcome,
44
74
  validateTaskIssueOutcome
45
- } from '../../../tools/task-contract/forge/forge-write'
46
- import type { CheckError } from '../../../../../kernel/gates/checks/contract'
75
+ } from '@harness/workflow/tools/task-contract/forge/forge-write'
76
+ import type { CheckError } from '@harness/kernel/gates/checks/contract'
77
+ import { topLevelSectionText } from '@attalabs/harness/issue-documentation'
47
78
  import {
79
+ frozenSectionsChanged,
48
80
  isTaskIssueBodyShaped,
49
81
  isTaskIssueLabelSet,
50
82
  parseIssueParts,
51
83
  type SurfaceForcedSet
52
- } from '../../../tools/task-contract/issue-validation'
84
+ } from '@harness/workflow/tools/task-contract/issue-validation'
53
85
  import {
54
86
  type Objective,
55
87
  objectivesOf,
56
88
  objectivesVersion,
57
89
  renderObjectives
58
- } from '../../../tools/task-contract/objectives'
90
+ } from '@harness/workflow/tools/task-contract/objectives'
59
91
 
60
92
  export const RETRY_CREATE = 'task_issue_create'
61
93
  export const RETRY_EDIT = 'task_issue_edit'
@@ -158,9 +190,32 @@ async function gate(
158
190
  * every gate and returns without touching the forge.
159
191
  */
160
192
  export async function createIssue(
161
- input: { ghArgs: string[]; validateOnly?: boolean },
193
+ input: {
194
+ ghArgs: string[]
195
+ validateOnly?: boolean
196
+ /** The tasks of the plan this Issue belongs to: given, a bare task number in its edges resolves against them. */
197
+ draftTasks?: DraftRenderContext['tasks']
198
+ },
162
199
  io: PlannerIo = {},
163
200
  forge: PlannerForge = realPlannerForge
201
+ ): Promise<IssueWriteOutcome> {
202
+ return writeIssue(input, io, forge, false)
203
+ }
204
+
205
+ /**
206
+ * The create path. `publishing` is set only by `publishApprovedTasks`: a hand
207
+ * create of a tranche-labelled Issue is refused after the gates and the
208
+ * validate-only return, so those still grade such a draft.
209
+ */
210
+ async function writeIssue(
211
+ input: {
212
+ ghArgs: string[]
213
+ validateOnly?: boolean
214
+ draftTasks?: DraftRenderContext['tasks']
215
+ },
216
+ io: PlannerIo,
217
+ forge: PlannerForge,
218
+ publishing: boolean
164
219
  ): Promise<IssueWriteOutcome> {
165
220
  const { ghArgs } = input
166
221
  const located = locateBodyOutcome(ghArgs, RETRY_CREATE)
@@ -174,7 +229,14 @@ export async function createIssue(
174
229
  let warnings: CheckError[] = []
175
230
  if (isTaskIssueLabelSet(labels) || (body !== null && isTaskIssueBodyShaped(body))) {
176
231
  // 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 }])
232
+ const createSource = { kind: 'create', ghArgs } as const
233
+ const g = await gate(
234
+ forge,
235
+ io,
236
+ input.draftTasks === undefined
237
+ ? [body, title, labels, RETRY_CREATE, null, createSource]
238
+ : [body, title, labels, RETRY_CREATE, null, createSource, input.draftTasks]
239
+ )
178
240
  if (!g.ok) return g
179
241
  renderSkipped = g.renderSkipped
180
242
  warnings = g.warnings
@@ -183,6 +245,18 @@ export async function createIssue(
183
245
  if (input.validateOnly) return { ok: true, written: false, url: '', renderSkipped, warnings }
184
246
 
185
247
  const slugToEnsure = findTrancheSlug(labels)
248
+ if (!publishing && slugToEnsure) {
249
+ return refusedWith(
250
+ [
251
+ makeCheckError(
252
+ 'plan-publish-only',
253
+ 'a tranche task is written only by `plan_publish`, from the approved plan draft; `task_issue_create` does not create an Issue that carries a `vinaya/tranche:*` label',
254
+ 'Submit and review the plan draft, then publish its approved tasks with `plan_publish`. A create without a tranche label, and `validateOnly`, are unchanged.'
255
+ )
256
+ ],
257
+ warnings
258
+ )
259
+ }
186
260
  if (slugToEnsure) {
187
261
  const errors = forge.ensureTrancheLabel(slugToEnsure)
188
262
  if (errors.length > 0) return refusedWith(errors, warnings)
@@ -312,20 +386,28 @@ export function printIssueSurface(args: string[]): SurfaceOutcome {
312
386
 
313
387
  // --- brief -------------------------------------------------------------------
314
388
 
315
- export type BriefOutcome = { ok: true; brief: string } | { ok: false; missing: string[] }
389
+ /** `waiting` lists each reason the task cannot start yet; empty when it can. */
390
+ export type BriefOutcome = { ok: true; brief: string; waiting: string[] } | { ok: false; missing: string[] }
391
+
392
+ /** One address per render: a tranche task, or a single Issue by its number. */
393
+ export type BriefInput = { trancheSlug: string; taskId: string; globs?: string[] } | { issue: number }
316
394
 
317
- /** Renders a task's brief; a refusal lists the facts it could not find. */
395
+ /**
396
+ * Previews a task's brief; a refusal lists the facts it could not find. A task
397
+ * waiting on an unmerged dependency or an open conflicting task still renders
398
+ * in full, with each waiting reason beside the brief.
399
+ */
318
400
  export async function renderBrief(
319
- input: {
320
- trancheSlug: string
321
- taskId: string
322
- globs?: string[]
323
- },
324
- assemble: typeof assembleAndRenderBrief = assembleAndRenderBrief
401
+ input: BriefInput,
402
+ assemble: typeof assembleAndRenderBrief = assembleAndRenderBrief,
403
+ assembleIssue: typeof assembleAndRenderBriefForIssue = assembleAndRenderBriefForIssue
325
404
  ): Promise<BriefOutcome> {
326
- const result = await assemble(input.trancheSlug, input.taskId, input.globs)
405
+ const result =
406
+ 'issue' in input
407
+ ? await assembleIssue(input.issue, undefined, { preview: true })
408
+ : await assemble(input.trancheSlug, input.taskId, input.globs, undefined, { preview: true })
327
409
  if (!result.ok) return { ok: false, missing: result.missing }
328
- return { ok: true, brief: result.brief }
410
+ return { ok: true, brief: result.brief, waiting: result.waiting ?? [] }
329
411
  }
330
412
 
331
413
  // --- objectives edit ---------------------------------------------------------
@@ -358,12 +440,21 @@ const NEXT_HEADING_RE = /^##[ \t]/m
358
440
  * copied verbatim, never re-derived.
359
441
  */
360
442
  export function spliceObjectivesSection(body: string, renderedSection: string): string {
361
- const heading = HEADING_RE.exec(body)
362
- if (!heading) {
443
+ if (!HEADING_RE.test(body)) {
363
444
  throw new Error(
364
445
  'spliceObjectivesSection: no `## Objectives` heading — caller must validate with objectivesOf first.'
365
446
  )
366
447
  }
448
+ return spliceSection(body, 'Objectives', renderedSection)
449
+ }
450
+
451
+ /**
452
+ * Replaces the `## <headingName>` section (heading through the next `##`
453
+ * heading, or end of body) with `renderedSection`, copying every other byte of
454
+ * `body` verbatim. The caller has checked the heading exists.
455
+ */
456
+ function spliceSection(body: string, headingName: string, renderedSection: string): string {
457
+ const heading = new RegExp(`^##[ \\t]*${headingName}[ \\t]*$`, 'im').exec(body) as RegExpExecArray
367
458
  const before = body.slice(0, heading.index)
368
459
  const afterHeadingStart = heading.index + heading[0].length
369
460
  const afterHeading = body.slice(afterHeadingStart)
@@ -500,7 +591,7 @@ function parseArgs(args: string[]): { json: boolean; issueRef: string; op: EditO
500
591
  )
501
592
  ])
502
593
  }
503
- // Security review, round 2, HIGH: this same reason is later
594
+ // This same reason is later
504
595
  // handed to `prepareTask`'s own O6 supersede call, which refuses a
505
596
  // `\r`/`\n` reason for the header-corruption hazard `dispatch-task.ts`
506
597
  // documents at its own check. Checked here too, before ANY write, so a
@@ -691,6 +782,36 @@ export const realObjectivesDeps: ObjectivesDeps = {
691
782
  postComment: postMarkedComment
692
783
  }
693
784
 
785
+ /**
786
+ * Writes `body` back to the Issue after a later step of a frozen section's
787
+ * change failed. A restore that itself fails throws one error naming both
788
+ * failures, so the caller learns the Issue and its frozen brief now disagree
789
+ * on `sectionNoun`.
790
+ */
791
+ function restoreIssueBody(
792
+ forge: PlannerForge,
793
+ issueRef: string,
794
+ body: string,
795
+ cause: unknown,
796
+ sectionNoun: string
797
+ ): void {
798
+ const dir = mkdtempSync(join(tmpdir(), 'vinaya-frozen-section-restore-'))
799
+ const tmp = join(dir, 'body.md')
800
+ writeFileSync(tmp, body, 'utf8')
801
+ try {
802
+ const ghArgs = ['--body-file', tmp]
803
+ const written = forge.ghWrite(['issue', 'edit', issueRef], ghArgs, locateBody(ghArgs))
804
+ if (!written.ok) {
805
+ const why = cause instanceof Error ? cause.message : String(cause)
806
+ throw new Error(
807
+ `${why}\nRestoring Issue ${issueRef}'s previous body also failed (${written.errors.map((e) => e.message).join('; ')}): the Issue now holds the new ${sectionNoun} and its frozen brief the previous ${sectionNoun}.`
808
+ )
809
+ }
810
+ } finally {
811
+ rmSync(dir, { recursive: true, force: true })
812
+ }
813
+ }
814
+
694
815
  async function editObjectivesOrRefuse(args: string[], io: PlannerIo, deps: ObjectivesDeps): Promise<ObjectivesOutcome> {
695
816
  const { issueRef, op, reason, part } = parseArgs(args)
696
817
  deps.requirePrincipal(RETRY)
@@ -746,20 +867,88 @@ async function editObjectivesOrRefuse(args: string[], io: PlannerIo, deps: Objec
746
867
  finalBody = removePartLinesCitingOnly(finalBody, op.id)
747
868
  }
748
869
 
749
- const dir = mkdtempSync(join(tmpdir(), 'vinaya-objectives-edit-'))
870
+ const newVersion = objectivesVersion(updated)
871
+ const k =
872
+ countMarkerComments(
873
+ comments.map((c) => c.body),
874
+ MARKER_PREFIXES
875
+ ) + 1
876
+ const written = await writeFrozenSection(
877
+ {
878
+ issueRef,
879
+ number,
880
+ title,
881
+ labels,
882
+ previousBody: body,
883
+ newBody: finalBody,
884
+ reason,
885
+ frozen: resolveNewestFrozenBrief(comments, allowlist),
886
+ retryCommand: RETRY,
887
+ sectionNoun: 'objectives',
888
+ recordMarker: `${MARKER_PREFIX}${k} -->`,
889
+ recordBody: [
890
+ 'Previous:',
891
+ formatList(previous),
892
+ '',
893
+ 'Now:',
894
+ formatList(updated),
895
+ '',
896
+ `Reason: ${reason}`,
897
+ `Version: ${newVersion}`
898
+ ].join('\n')
899
+ },
900
+ io,
901
+ deps
902
+ )
903
+ if (!written.ok) return written
904
+
905
+ return { ok: true, version: newVersion, url: written.url, supersedeUrl: written.supersedeUrl }
906
+ }
907
+
908
+ /** One frozen section's change, as the shared write path takes it. */
909
+ type FrozenSectionWrite = {
910
+ issueRef: string
911
+ number: number
912
+ title: string
913
+ labels: string[]
914
+ /** The Issue body as read, put back when the superseding brief cannot be posted. */
915
+ previousBody: string
916
+ newBody: string
917
+ /** One line: it becomes the superseding brief's reason line. */
918
+ reason: string
919
+ /** The newest frozen brief, or `null` when the brief is not frozen yet — only a frozen brief is superseded. */
920
+ frozen: FrozenBriefCandidate | null
921
+ retryCommand: string
922
+ /** What a failed restore says the Issue and its frozen brief now disagree on. */
923
+ sectionNoun: string
924
+ recordMarker: string
925
+ recordBody: string
926
+ }
927
+
928
+ /**
929
+ * The write every Principal-only change of a frozen section shares: writes the
930
+ * new body through the whole Issue write gate with the frozen-section check
931
+ * skipped (the caller is the sanctioned path that check names), supersedes the
932
+ * frozen brief so it is rendered again from the written Issue, puts the
933
+ * previous body back when that supersede fails, and only then posts the record
934
+ * comment — so a failure before the record leaves no record behind.
935
+ */
936
+ async function writeFrozenSection(
937
+ w: FrozenSectionWrite,
938
+ io: PlannerIo,
939
+ deps: ObjectivesDeps
940
+ ): Promise<{ ok: true; url: string; supersedeUrl: string | null } | { ok: false; findings: CheckError[] }> {
941
+ const dir = mkdtempSync(join(tmpdir(), 'vinaya-frozen-section-edit-'))
750
942
  const tmp = join(dir, 'body.md')
751
- writeFileSync(tmp, finalBody, 'utf8')
943
+ writeFileSync(tmp, w.newBody, 'utf8')
752
944
  try {
753
945
  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
946
  const written = await editLocated(
758
947
  {
759
- issueRef,
948
+ issueRef: w.issueRef,
760
949
  ghArgs,
761
950
  bodyResult: locateBody(ghArgs),
762
- retryCommand: RETRY,
951
+ retryCommand: w.retryCommand,
763
952
  skipFrozenSectionsCheck: true
764
953
  },
765
954
  io,
@@ -773,43 +962,518 @@ async function editObjectivesOrRefuse(args: string[], io: PlannerIo, deps: Objec
773
962
  rmSync(dir, { recursive: true, force: true })
774
963
  }
775
964
 
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.
965
+ // The write above moved the Issue and its frozen brief out of agreement.
966
+ // The superseding brief is posted BEFORE the record comment, so a failure
967
+ // here leaves no record behind at all. A tranche-labeled Issue supersedes
968
+ // through the tranche path; a backlog Issue (no tranche identity) through
969
+ // the Issue path.
784
970
  let supersedeUrl: string | null = null
971
+ if (w.frozen !== null) {
972
+ const taskRef = resolveTaskIssueRef(w.title, w.labels)
973
+ const supersede = { reason: w.reason }
974
+ try {
975
+ const result = await deps.supersede(
976
+ taskRef !== null
977
+ ? { tranche: taskRef.trancheSlug, n: Number.parseInt(taskRef.taskId, 10), supersede }
978
+ : { issue: w.number, supersede }
979
+ )
980
+ supersedeUrl = result.commentUrl
981
+ } catch (err) {
982
+ // The superseding brief could not be posted: put the Issue body back, so
983
+ // the Issue and its frozen brief keep agreeing.
984
+ restoreIssueBody(deps.forge, w.issueRef, w.previousBody, err, w.sectionNoun)
985
+ throw err
986
+ }
987
+ }
988
+
989
+ const url = deps.postComment('issue', w.issueRef, w.recordMarker, w.recordBody)
990
+ return { ok: true, url, supersedeUrl }
991
+ }
992
+
993
+ // --- Documentation correction ------------------------------------------------
994
+
995
+ const RETRY_DOCUMENTATION = 'task_documentation_edit'
996
+ /** The Documentation record marker's opening, in every spelling, the current one first. */
997
+ const DOCUMENTATION_MARKER_PREFIXES = documentationEditMarkerPrefixes()
998
+ const DOCUMENTATION_MARKER_PREFIX = DOCUMENTATION_MARKER_PREFIXES[0] as string
999
+
1000
+ const DOCUMENTATION_HEADING_LINE_RE = /^##[ \t]*Documentation[ \t]*$/i
1001
+
1002
+ /** The Issue, the whole new Documentation section (its heading optional) and the one-line reason. */
1003
+ export type DocumentationEditInput = { issue: number; documentation: string; reason: string }
1004
+
1005
+ export type DocumentationOutcome =
1006
+ | { ok: true; briefUrl: string; recordUrl: string }
1007
+ | { ok: false; findings: CheckError[] }
1008
+
1009
+ /**
1010
+ * Replaces the `## Documentation` section of a task Issue whose brief is
1011
+ * frozen. Principal-only. The new body passes the whole Issue write gate, every
1012
+ * other frozen section stays as it was, the frozen brief is superseded with
1013
+ * `reason`, and a marked record holds the previous lines, the new ones and the
1014
+ * reason. A refusal anywhere beneath comes back as findings with nothing
1015
+ * written.
1016
+ */
1017
+ export async function editDocumentation(
1018
+ input: DocumentationEditInput,
1019
+ io: PlannerIo = {},
1020
+ deps: ObjectivesDeps = realObjectivesDeps
1021
+ ): Promise<DocumentationOutcome> {
1022
+ const r = await captureRefusal(() => editDocumentationOrRefuse(input, io, deps))
1023
+ return r.ok ? r.value : { ok: false, findings: r.errors }
1024
+ }
1025
+
1026
+ /** The section's lines below its heading, trimmed at both ends; a leading `## Documentation` heading is dropped. */
1027
+ function documentationLines(section: string): string {
1028
+ const lines = section.replace(/\r\n/g, '\n').trim().split('\n')
1029
+ if (DOCUMENTATION_HEADING_LINE_RE.test((lines[0] ?? '').trim())) lines.shift()
1030
+ return lines.join('\n').trim()
1031
+ }
1032
+
1033
+ function refuseDocumentationArgs(message: string, recovery: string): never {
1034
+ refuse([makeCheckError('forge-args', message, `${recovery} Then re-run \`${RETRY_DOCUMENTATION}\`.`)])
1035
+ }
1036
+
1037
+ async function editDocumentationOrRefuse(
1038
+ input: DocumentationEditInput,
1039
+ io: PlannerIo,
1040
+ deps: ObjectivesDeps
1041
+ ): Promise<DocumentationOutcome> {
1042
+ const { reason } = input
1043
+ if (reason.trim().length === 0) {
1044
+ refuseDocumentationArgs(
1045
+ '`task_documentation_edit` requires a non-empty `reason`.',
1046
+ 'Give a one-line reason for the correction.'
1047
+ )
1048
+ }
1049
+ if (/[\r\n]/.test(reason)) {
1050
+ refuseDocumentationArgs(
1051
+ "`reason` must be a single line — it becomes one line of the superseding brief's header, and a newline in it would corrupt every reader's header-line count for that version.",
1052
+ 'Remove the newline from the reason.'
1053
+ )
1054
+ }
1055
+ const lines = documentationLines(input.documentation)
1056
+ if (lines.length === 0) {
1057
+ refuseDocumentationArgs(
1058
+ '`task_documentation_edit` requires the new `## Documentation` section: its source lines, or the `None` sentinel.',
1059
+ 'Give the whole new section.'
1060
+ )
1061
+ }
1062
+ if (lines.split('\n').some((l) => /^##[ \t]/.test(l))) {
1063
+ refuseDocumentationArgs(
1064
+ 'The new `## Documentation` section holds a `##` heading of its own, which would change another section of the Issue.',
1065
+ 'Give the Documentation lines only.'
1066
+ )
1067
+ }
1068
+
1069
+ deps.requirePrincipal(RETRY_DOCUMENTATION)
1070
+
1071
+ const issueRef = String(input.issue)
1072
+ const { number, body, title, labels, comments } = deps.fetchIssue(issueRef)
1073
+ const allowlist = deps.resolvePrincipals('principal-only', RETRY_DOCUMENTATION)
785
1074
  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 } }
1075
+ if (frozen === null) {
1076
+ refuse([
1077
+ makeCheckError(
1078
+ 'documentation-not-frozen',
1079
+ `Issue ${issueRef} has no frozen brief, so its \`## Documentation\` section is not locked.`,
1080
+ 'Change the section with `task_issue_edit`, which edits any section before the brief is frozen.'
1081
+ )
1082
+ ])
1083
+ }
1084
+ const previousSection = topLevelSectionText(body, 'Documentation')
1085
+ if (previousSection === null) {
1086
+ refuse([
1087
+ makeCheckError(
1088
+ 'documentation-parse',
1089
+ `Issue ${issueRef} has no \`## Documentation\` section to correct.`,
1090
+ 'Escalate to the Principal: a frozen task Issue without a Documentation section cannot be corrected here.'
1091
+ )
1092
+ ])
1093
+ }
1094
+ const previous = documentationLines(previousSection)
1095
+ if (previous === lines) {
1096
+ refuseDocumentationArgs(
1097
+ `The new \`## Documentation\` section of Issue ${issueRef} is the one it already holds.`,
1098
+ 'Give the corrected section.'
792
1099
  )
793
- supersedeUrl = result.commentUrl
1100
+ }
1101
+
1102
+ const newBody = spliceSection(body, 'Documentation', `## Documentation\n\n${lines}`)
1103
+ // The frozen-section check is skipped for the write below, and that skip
1104
+ // covers every frozen section: refuse here unless the Documentation section
1105
+ // is the only one that moved.
1106
+ const others = frozenSectionsChanged(body, newBody).filter((s) => s !== 'Documentation')
1107
+ if (others.length > 0) {
1108
+ refuse([
1109
+ makeCheckError(
1110
+ 'issue-frozen-brief',
1111
+ `Correcting the \`## Documentation\` section of Issue ${issueRef} would also change ${others.map((s) => `\`## ${s}\``).join(', ')}, which stays locked once frozen.`,
1112
+ `Give the Documentation lines only, then re-run \`${RETRY_DOCUMENTATION}\`.`
1113
+ )
1114
+ ])
794
1115
  }
795
1116
 
796
1117
  const k =
797
1118
  countMarkerComments(
798
1119
  comments.map((c) => c.body),
799
- MARKER_PREFIXES
1120
+ DOCUMENTATION_MARKER_PREFIXES
800
1121
  ) + 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 }
1122
+ const written = await writeFrozenSection(
1123
+ {
1124
+ issueRef,
1125
+ number,
1126
+ title,
1127
+ labels,
1128
+ previousBody: body,
1129
+ newBody,
1130
+ reason,
1131
+ frozen,
1132
+ retryCommand: RETRY_DOCUMENTATION,
1133
+ sectionNoun: 'Documentation section',
1134
+ recordMarker: `${DOCUMENTATION_MARKER_PREFIX}${k} -->`,
1135
+ recordBody: ['Previous:', previous, '', 'Now:', lines, '', `Reason: ${reason}`].join('\n')
1136
+ },
1137
+ io,
1138
+ deps
1139
+ )
1140
+ if (!written.ok) return written
1141
+ return { ok: true, briefUrl: written.supersedeUrl as string, recordUrl: written.url }
1142
+ }
1143
+
1144
+ // --- the plan draft --------------------------------------------------------------
1145
+
1146
+ /** What storing a draft returns: the one fingerprint covering all of it, or why it was refused. */
1147
+ export type DraftSubmitOutcome =
1148
+ | { ok: true; tranche: string; fingerprint: string; tasks: number }
1149
+ | { ok: false; errors: string[] }
1150
+
1151
+ /** What reading a draft back returns. */
1152
+ export type DraftReadOutcome = { ok: true; draft: PlanDraft; fingerprint: string } | { ok: false; message: string }
1153
+
1154
+ /** Validates `input` as a whole draft and stores it on this machine, replacing any earlier draft of the same tranche. */
1155
+ export function submitPlanDraft(input: unknown, runtimeDir: string = runtimeDirForThisRepo()): DraftSubmitOutcome {
1156
+ const parsed = parsePlanDraft(input)
1157
+ if (!parsed.ok) return { ok: false, errors: parsed.errors }
1158
+ writePlanDraft(runtimeDir, parsed.draft)
1159
+ return {
1160
+ ok: true,
1161
+ tranche: parsed.draft.tranche,
1162
+ fingerprint: draftFingerprint(parsed.draft),
1163
+ tasks: parsed.draft.tasks.length
1164
+ }
1165
+ }
1166
+
1167
+ /** The stored draft of `tranche`, with its fingerprint. */
1168
+ export function readStoredPlanDraft(tranche: string, runtimeDir: string = runtimeDirForThisRepo()): DraftReadOutcome {
1169
+ if (!/^[a-z0-9][a-z0-9-]*$/i.test(tranche)) {
1170
+ return { ok: false, message: `"${tranche}" is not a tranche slug (letters, digits and hyphens)` }
1171
+ }
1172
+ const draft = readPlanDraft(runtimeDir, tranche)
1173
+ if (draft === null) return { ok: false, message: `no draft is stored for tranche "${tranche}" on this machine` }
1174
+ return { ok: true, draft, fingerprint: draftFingerprint(draft) }
1175
+ }
1176
+
1177
+ /** What checking the stored draft of a tranche returns: the findings of the whole plan, or why it could not be read. */
1178
+ export type DraftCheckOutcome = { ok: true; report: DraftCheckReport } | { ok: false; message: string }
1179
+
1180
+ /** What previewing the stored draft of a tranche returns. */
1181
+ export type DraftPreviewOutcome = { ok: true; preview: DraftPreview } | { ok: false; message: string }
1182
+
1183
+ /** Runs the full Issue write gate on every task of the tranche's stored draft, and the checks only the whole plan has. Writes nothing. */
1184
+ export async function checkStoredPlanDraft(
1185
+ tranche: string,
1186
+ runtimeDir: string = runtimeDirForThisRepo()
1187
+ ): Promise<DraftCheckOutcome> {
1188
+ const stored = readStoredPlanDraft(tranche, runtimeDir)
1189
+ if (!stored.ok) return stored
1190
+ return { ok: true, report: await checkDraft(stored.draft) }
1191
+ }
1192
+
1193
+ /** The exact Issue and brief of each task of the tranche's stored draft (one task when `task` is given). Writes nothing. */
1194
+ export async function previewStoredPlanDraft(
1195
+ tranche: string,
1196
+ task?: number,
1197
+ runtimeDir: string = runtimeDirForThisRepo()
1198
+ ): Promise<DraftPreviewOutcome> {
1199
+ const stored = readStoredPlanDraft(tranche, runtimeDir)
1200
+ if (!stored.ok) return stored
1201
+ if (task !== undefined && !stored.draft.tasks.some((t) => t.number === task)) {
1202
+ return { ok: false, message: `the draft of "${tranche}" holds no task ${task}` }
1203
+ }
1204
+ return { ok: true, preview: await previewDraft(stored.draft, task === undefined ? null : [task]) }
1205
+ }
1206
+
1207
+ // --- publishing an approved plan ---------------------------------------------------
1208
+
1209
+ const CHECK_PUBLISH = 'plan-publish'
1210
+
1211
+ /** One task of a publication: its number in the plan, the Issue it is, and the link the forge returned (absent for a task published earlier). */
1212
+ export type PublishedTask = { task: number; issue: number; url: string | null; alreadyPublished: boolean }
1213
+
1214
+ export type PublishOutcome =
1215
+ | { ok: true; tasks: PublishedTask[]; warnings: CheckError[] }
1216
+ | {
1217
+ ok: false
1218
+ findings: CheckError[]
1219
+ warnings: CheckError[]
1220
+ /** The tasks written before the refusal; their Issue numbers stay recorded in the stored draft. */
1221
+ published: PublishedTask[]
1222
+ }
1223
+
1224
+ /** The number the forge gave a written Issue, read from the link it returned; `null` when the link carries none. */
1225
+ function issueNumberOfLink(url: string): number | null {
1226
+ const m = /\/issues\/(\d+)\/?\s*$/.exec(url.trim())
1227
+ return m === null ? null : Number(m[1])
1228
+ }
1229
+
1230
+ /**
1231
+ * Writes the approved tasks of a tranche's stored draft as Issues, in task
1232
+ * order: exactly the title, body and labels the preview shows, through the same
1233
+ * write gate `task_issue_create` runs, with the draft's tasks given to the brief
1234
+ * render so a bare task number in an edge resolves. Nothing is written unless
1235
+ * the stored draft's current fingerprint is approved by the review and by the
1236
+ * Principal, and every named task is an approved task. A task that already has
1237
+ * an Issue number is reported, never written again. After each write the new
1238
+ * Issue's number is recorded on that task in the stored draft; a refusal stops
1239
+ * the publication at its task and keeps the numbers already recorded.
1240
+ * Recording a number leaves the approval in force.
1241
+ */
1242
+ export async function publishApprovedTasks(
1243
+ input: { tranche: string; tasks?: readonly number[] },
1244
+ io: PlannerIo = {},
1245
+ forge: PlannerForge = realPlannerForge,
1246
+ runtimeDir: string = runtimeDirForThisRepo(),
1247
+ deps: Pick<CoordinatorDeps, 'runtimeDir' | 'readDraft' | 'roundLimit'> = realCoordinatorDeps(runtimeDir)
1248
+ ): Promise<PublishOutcome> {
1249
+ const stop = (message: string, recovery: string): PublishOutcome => ({
1250
+ ok: false,
1251
+ findings: [makeCheckError(CHECK_PUBLISH, message, recovery)],
1252
+ warnings: [],
1253
+ published: []
1254
+ })
1255
+ const stored = readStoredPlanDraft(input.tranche, runtimeDir)
1256
+ if (!stored.ok) return stop(stored.message, 'Submit the draft with `plan_draft_submit` first.')
1257
+ const reviewed = readStoredPlanReviewStatus(input.tranche, deps)
1258
+ if (!reviewed.ok) return stop(reviewed.findings.map((f) => f.message).join('; '), 'Submit the draft first.')
1259
+ const { status } = reviewed
1260
+ if (!status.approved) {
1261
+ return stop(
1262
+ `the draft of "${input.tranche}" at ${status.fingerprint} is not approved, so nothing was written`,
1263
+ 'Review the draft with `plan_review_start` until `plan_review_status` reports its current fingerprint approved.'
1264
+ )
1265
+ }
1266
+ if (!status.principalApproved) {
1267
+ return stop(
1268
+ `the Principal has not approved the draft of "${input.tranche}" at ${status.fingerprint}${status.principalApprovalStale ? ' (an approval for an earlier fingerprint does not apply)' : ''}, so nothing was written`,
1269
+ 'Show the Principal the approved plan; once they approve this fingerprint, record it with `plan_approve`.'
1270
+ )
1271
+ }
1272
+ const approved = new Set(status.approvedTasks)
1273
+ const named = [...new Set(input.tasks ?? [...approved])].sort((a, b) => a - b)
1274
+ const notApproved = named.filter((n) => !approved.has(n))
1275
+ if (notApproved.length > 0) {
1276
+ return stop(
1277
+ `task ${notApproved.join(', ')} of "${input.tranche}" ${notApproved.length === 1 ? 'is' : 'are'} not an approved task, so nothing was written`,
1278
+ 'Name only tasks `plan_review_status` lists as approved, or name none to publish every approved task.'
1279
+ )
1280
+ }
1281
+
1282
+ let draft = stored.draft
1283
+ const published: PublishedTask[] = []
1284
+ const warnings: CheckError[] = []
1285
+ const stopAt = (findings: CheckError[]): PublishOutcome => ({ ok: false, findings, warnings, published })
1286
+
1287
+ for (const number of named) {
1288
+ const task = draft.tasks.find((t) => t.number === number)
1289
+ if (task === undefined) continue
1290
+ if (task.issue !== null) {
1291
+ published.push({ task: number, issue: task.issue, url: null, alreadyPublished: true })
1292
+ continue
1293
+ }
1294
+ const issue = publishedIssueOf(draft, task)
1295
+ const dir = mkdtempSync(join(tmpdir(), 'plan-publish-'))
1296
+ let written: IssueWriteOutcome
1297
+ try {
1298
+ const bodyFile = join(dir, 'body.md')
1299
+ writeFileSync(bodyFile, issue.body, 'utf8')
1300
+ written = await writeIssue(
1301
+ {
1302
+ ghArgs: ['--title', issue.title, '--body-file', bodyFile, ...issue.labels.flatMap((l) => ['--label', l])],
1303
+ draftTasks: draft.tasks.map((t) => ({ id: String(t.number), issue: t.issue }))
1304
+ },
1305
+ io,
1306
+ forge,
1307
+ true
1308
+ )
1309
+ } finally {
1310
+ rmSync(dir, { recursive: true, force: true })
1311
+ }
1312
+ if (!written.ok) {
1313
+ warnings.push(...written.warnings)
1314
+ return stopAt(written.findings)
1315
+ }
1316
+ warnings.push(...written.warnings)
1317
+ const issueNumber = issueNumberOfLink(written.url)
1318
+ if (issueNumber === null) {
1319
+ return stopAt([
1320
+ makeCheckError(
1321
+ CHECK_PUBLISH,
1322
+ `task ${number} was written as ${written.url === '' ? 'an Issue whose link the forge did not return' : written.url}, but its Issue number could not be read from that link, so the publication stopped`,
1323
+ `Record the number by hand on task ${number} of the draft with \`plan_draft_submit\`, then publish the remaining tasks.`
1324
+ )
1325
+ ])
1326
+ }
1327
+ draft = { ...draft, tasks: draft.tasks.map((t) => (t.number === number ? { ...t, issue: issueNumber } : t)) }
1328
+ writePlanDraft(runtimeDir, draft)
1329
+ published.push({ task: number, issue: issueNumber, url: written.url, alreadyPublished: false })
1330
+ }
1331
+ return { ok: true, tasks: published, warnings }
1332
+ }
1333
+
1334
+ // --- the plan review -------------------------------------------------------------
1335
+
1336
+ /** How long one review round may run before it is stopped and not counted. */
1337
+ const REVIEW_ROUND_TIMEOUT_MS = 20 * 60 * 1000
1338
+
1339
+ /**
1340
+ * The agent the Planner runs on, read from the environment its own CLI gives a
1341
+ * tool server: Codex marks its sessions with a `CODEX_` variable of its own, and
1342
+ * anything else is Claude Code. No model is chosen here.
1343
+ */
1344
+ export function plannerAgentFromEnv(env: Record<string, string | undefined> = process.env): PlanReviewAgent {
1345
+ const codex = ['CODEX_THREAD_ID', 'CODEX_SANDBOX', 'CODEX_CI', 'CODEX_SANDBOX_NETWORK_DISABLED']
1346
+ return codex.some((k) => (env[k] ?? '') !== '') && (env.CLAUDECODE ?? '') === '' ? 'codex' : 'claude-code'
1347
+ }
1348
+
1349
+ /** The coordinator's dependencies as this repository and this machine give them. */
1350
+ export function realCoordinatorDeps(runtimeDir: string = runtimeDirForThisRepo()): CoordinatorDeps {
1351
+ const config = loadConfig()
1352
+ return {
1353
+ runtimeDir,
1354
+ readDraft: (tranche) => readPlanDraft(runtimeDir, tranche),
1355
+ check: (draft) => checkDraft(draft),
1356
+ repoRoot: process.cwd(),
1357
+ roundLimit: resolveReviewRoundLimit(config),
1358
+ agent: resolveReviewerAgent(resolveReviewAgent(config), plannerAgentFromEnv()),
1359
+ timeoutMs: REVIEW_ROUND_TIMEOUT_MS
1360
+ }
1361
+ }
1362
+
1363
+ const isSlug = (tranche: string): boolean => /^[a-z0-9][a-z0-9-]*$/i.test(tranche)
1364
+ const notSlug = (tranche: string): { ok: false; findings: CoordinatorFinding[] } => ({
1365
+ ok: false,
1366
+ findings: [
1367
+ {
1368
+ check: 'plan-review',
1369
+ message: `"${tranche}" is not a tranche slug (letters, digits and hyphens)`,
1370
+ recovery: 'Name the tranche slug of the stored draft.'
1371
+ }
1372
+ ]
1373
+ })
1374
+
1375
+ /** Starts one review round of the tranche's stored draft; refuses unless the draft was checked and a round is allowed. */
1376
+ export async function startStoredPlanReview(
1377
+ tranche: string,
1378
+ deps: CoordinatorDeps = realCoordinatorDeps()
1379
+ ): Promise<StartOutcome> {
1380
+ if (!isSlug(tranche)) return { ok: false, reason: 'no_draft', findings: notSlug(tranche).findings }
1381
+ return startPlanReview(deps, tranche)
1382
+ }
1383
+
1384
+ /** The stored review state of the tranche's draft, read for this draft's fingerprint. */
1385
+ export function readStoredPlanReviewStatus(
1386
+ tranche: string,
1387
+ deps: Pick<CoordinatorDeps, 'runtimeDir' | 'readDraft' | 'roundLimit'> = realCoordinatorDeps()
1388
+ ): StatusOutcome {
1389
+ if (!isSlug(tranche)) return notSlug(tranche)
1390
+ return planReviewStatus(deps, tranche)
1391
+ }
1392
+
1393
+ /** Where the live Issues of a draft's published tasks stand against the text the draft shows for them. */
1394
+ export type PublishedDrift = {
1395
+ /** Tasks whose Issue still equals the draft's title and body. */
1396
+ matching: number[]
1397
+ /** Tasks whose Issue differs, and what differs. */
1398
+ drifted: Array<{ task: number; issue: number; differs: 'title' | 'body' | 'both' }>
1399
+ /** Tasks whose Issue could not be read: not compared, so neither matching nor drifted. */
1400
+ unread: Array<{ task: number; issue: number; reason: string }>
1401
+ }
1402
+
1403
+ export type StatusWithDriftOutcome =
1404
+ | { ok: true; status: ReviewStatus & { drift: PublishedDrift } }
1405
+ | { ok: false; findings: CoordinatorFinding[] }
1406
+
1407
+ const normalizeLineEndings = (text: string): string => text.replace(/\r\n?/g, '\n')
1408
+
1409
+ /** Reads one Issue's live title and body; throws when it cannot be read. */
1410
+ export type IssueTextReader = (issue: number) => { title: string; body: string }
1411
+
1412
+ const readLiveIssueText: IssueTextReader = (issue) => {
1413
+ const fields = readIssueFields<{ title?: string; body?: string }>(String(issue), 'title,body')
1414
+ return { title: fields.title ?? '', body: fields.body ?? '' }
1415
+ }
1416
+
1417
+ /**
1418
+ * Compares each task of the draft that has an Issue number with the title and
1419
+ * body the draft shows for it (line endings normalized; labels are not
1420
+ * compared). Reads the forge only; writes nothing.
1421
+ */
1422
+ export function publishedIssueDrift(draft: PlanDraft, read: IssueTextReader = readLiveIssueText): PublishedDrift {
1423
+ const drift: PublishedDrift = { matching: [], drifted: [], unread: [] }
1424
+ for (const task of [...draft.tasks].sort((a, b) => a.number - b.number)) {
1425
+ if (task.issue === null) continue
1426
+ const expected = publishedIssueOf(draft, task)
1427
+ let live: { title: string; body: string }
1428
+ try {
1429
+ live = read(task.issue)
1430
+ } catch (err) {
1431
+ drift.unread.push({
1432
+ task: task.number,
1433
+ issue: task.issue,
1434
+ reason: err instanceof Error ? err.message : String(err)
1435
+ })
1436
+ continue
1437
+ }
1438
+ const titleDiffers = normalizeLineEndings(live.title) !== normalizeLineEndings(expected.title)
1439
+ const bodyDiffers = normalizeLineEndings(live.body) !== normalizeLineEndings(expected.body)
1440
+ if (!titleDiffers && !bodyDiffers) drift.matching.push(task.number)
1441
+ else {
1442
+ const differs = titleDiffers && bodyDiffers ? 'both' : titleDiffers ? 'title' : 'body'
1443
+ drift.drifted.push({ task: task.number, issue: task.issue, differs })
1444
+ }
1445
+ }
1446
+ return drift
1447
+ }
1448
+
1449
+ /** The stored review status, with the drift of the draft's published tasks. */
1450
+ export function readStoredPlanReviewStatusWithDrift(
1451
+ tranche: string,
1452
+ deps: Pick<CoordinatorDeps, 'runtimeDir' | 'readDraft' | 'roundLimit'> = realCoordinatorDeps(),
1453
+ read: IssueTextReader = readLiveIssueText
1454
+ ): StatusWithDriftOutcome {
1455
+ const outcome = readStoredPlanReviewStatus(tranche, deps)
1456
+ if (!outcome.ok) return outcome
1457
+ const draft = deps.readDraft(tranche)
1458
+ const drift: PublishedDrift =
1459
+ draft === null ? { matching: [], drifted: [], unread: [] } : publishedIssueDrift(draft, read)
1460
+ return { ok: true, status: { ...outcome.status, drift } }
1461
+ }
1462
+
1463
+ /** Records the Principal's decision at the round limit. */
1464
+ export function decideStoredPlanReview(
1465
+ input: { tranche: string; fingerprint: string; choice: DecisionChoice },
1466
+ deps: Pick<CoordinatorDeps, 'runtimeDir' | 'readDraft' | 'roundLimit'> = realCoordinatorDeps()
1467
+ ): DecideOutcome {
1468
+ if (!isSlug(input.tranche)) return notSlug(input.tranche)
1469
+ return decidePlanReview(deps, input)
1470
+ }
1471
+
1472
+ /** Records the Principal's approval of the reviewed draft's current fingerprint. */
1473
+ export function approveStoredPlanReview(
1474
+ input: { tranche: string; fingerprint: string },
1475
+ deps: Pick<CoordinatorDeps, 'runtimeDir' | 'readDraft' | 'roundLimit'> = realCoordinatorDeps()
1476
+ ): ApproveOutcome {
1477
+ if (!isSlug(input.tranche)) return notSlug(input.tranche)
1478
+ return approvePlanReview(deps, input)
815
1479
  }