mandrel 1.91.0 → 1.93.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 (112) hide show
  1. package/.agents/README.md +5 -5
  2. package/.agents/docs/SDLC.md +75 -107
  3. package/.agents/docs/configuration.md +1 -1
  4. package/.agents/docs/quality-gates.md +8 -7
  5. package/.agents/docs/workflows.md +4 -10
  6. package/.agents/instructions.md +2 -2
  7. package/.agents/schemas/agentrc.schema.json +1 -1
  8. package/.agents/schemas/lifecycle/README.md +2 -1
  9. package/.agents/schemas/lifecycle/ledger-record.schema.json +1 -1
  10. package/.agents/schemas/risk-verdict.schema.json +14 -1
  11. package/.agents/scripts/README.md +0 -46
  12. package/.agents/scripts/analyze-execution.js +76 -1
  13. package/.agents/scripts/check-doc-links.js +3 -0
  14. package/.agents/scripts/check-workflow-cli-lint.js +208 -0
  15. package/.agents/scripts/epic-audit-recheck.js +1 -1
  16. package/.agents/scripts/epic-plan-clarity.js +16 -6
  17. package/.agents/scripts/epic-plan-decompose.js +37 -59
  18. package/.agents/scripts/epic-plan-healthcheck.js +39 -6
  19. package/.agents/scripts/epic-plan-spec.js +41 -168
  20. package/.agents/scripts/epic-reconcile.js +7 -1
  21. package/.agents/scripts/lib/Logger.js +4 -4
  22. package/.agents/scripts/lib/audit-suite/index.js +4 -5
  23. package/.agents/scripts/lib/audit-suite/runner.js +6 -4
  24. package/.agents/scripts/lib/audit-suite/selector.js +2 -3
  25. package/.agents/scripts/lib/bdd-runner-detect.js +1 -1
  26. package/.agents/scripts/lib/command-header.js +20 -0
  27. package/.agents/scripts/lib/config/github.js +1 -3
  28. package/.agents/scripts/lib/config-settings-schema.js +4 -3
  29. package/.agents/scripts/lib/degraded-mode.js +1 -1
  30. package/.agents/scripts/lib/label-constants.js +18 -3
  31. package/.agents/scripts/lib/label-taxonomy.js +14 -3
  32. package/.agents/scripts/lib/mutation/baseline-snapshot.js +7 -6
  33. package/.agents/scripts/lib/orchestration/consolidation-precondition.js +18 -8
  34. package/.agents/scripts/lib/orchestration/context-hydration-engine.js +3 -4
  35. package/.agents/scripts/lib/orchestration/docs-digest.js +2 -2
  36. package/.agents/scripts/lib/orchestration/epic-plan-decompose/phases/persist-helpers.js +4 -0
  37. package/.agents/scripts/lib/orchestration/epic-plan-decompose/phases/persist.js +22 -12
  38. package/.agents/scripts/lib/orchestration/epic-plan-spec/phases/authoring-context.js +6 -1
  39. package/.agents/scripts/lib/orchestration/epic-spec-reconciler-diff.js +18 -2
  40. package/.agents/scripts/lib/orchestration/file-assumptions.js +68 -7
  41. package/.agents/scripts/{lifecycle-diff.js → lib/orchestration/lifecycle/ledger-diff.js} +10 -76
  42. package/.agents/scripts/lib/orchestration/lifecycle/listeners/acceptance-reconciler.js +1 -1
  43. package/.agents/scripts/lib/orchestration/plan-context.js +696 -0
  44. package/.agents/scripts/lib/orchestration/plan-critic-conditions.js +177 -0
  45. package/.agents/scripts/lib/orchestration/plan-critics-evaluate.js +99 -0
  46. package/.agents/scripts/lib/orchestration/plan-metrics.js +445 -0
  47. package/.agents/scripts/lib/orchestration/plan-persist/amend.js +359 -0
  48. package/.agents/scripts/lib/orchestration/plan-persist/delivery-mode.js +127 -0
  49. package/.agents/scripts/lib/orchestration/plan-persist/run-plan-persist.js +1015 -0
  50. package/.agents/scripts/lib/orchestration/plan-persist/summary.js +206 -0
  51. package/.agents/scripts/lib/orchestration/plan-reachability.js +160 -0
  52. package/.agents/scripts/lib/orchestration/plan-runner/worktree-sweep.js +3 -3
  53. package/.agents/scripts/lib/orchestration/planning-risk.js +1 -1
  54. package/.agents/scripts/lib/orchestration/spec-freshness.js +1 -1
  55. package/.agents/scripts/lib/orchestration/ticket-validator.js +18 -1
  56. package/.agents/scripts/lib/orchestration/ticketing/bulk.js +1 -1
  57. package/.agents/scripts/lib/orchestration/ticketing/reads.js +11 -2
  58. package/.agents/scripts/lib/plan-phase-cleanup.js +16 -0
  59. package/.agents/scripts/lib/presentation/manifest-persistence.js +2 -3
  60. package/.agents/scripts/lib/templates/spec-author-prompts.js +74 -0
  61. package/.agents/scripts/plan-context.js +204 -0
  62. package/.agents/scripts/plan-critics.js +199 -0
  63. package/.agents/scripts/plan-persist.js +383 -0
  64. package/.agents/scripts/pr-watch-with-update.js +8 -7
  65. package/.agents/scripts/run-lint.js +10 -11
  66. package/.agents/scripts/story-plan.js +19 -7
  67. package/.agents/scripts/sync-claude-commands.js +10 -5
  68. package/.agents/skills/core/knowledge-transfer/SKILL.md +11 -7
  69. package/.agents/workflows/audit-documentation.md +5 -7
  70. package/.agents/workflows/audit-lighthouse.md +1 -0
  71. package/.agents/workflows/audit-security.md +1 -0
  72. package/.agents/workflows/audit-to-stories.md +16 -5
  73. package/.agents/workflows/git-deliver.md +76 -243
  74. package/.agents/workflows/helpers/_merge-conflict-template.md +1 -1
  75. package/.agents/workflows/helpers/code-review.md +7 -6
  76. package/.agents/workflows/helpers/deliver-epic.md +5 -4
  77. package/.agents/workflows/helpers/plan-epic-reference.md +120 -96
  78. package/.agents/workflows/helpers/plan-epic.md +307 -994
  79. package/.agents/workflows/helpers/plan-story.md +14 -14
  80. package/.agents/workflows/helpers/scope-triage-gate.md +15 -4
  81. package/.agents/workflows/helpers/single-story-deliver.md +5 -4
  82. package/.agents/workflows/helpers/worktree-lifecycle.md +9 -7
  83. package/.agents/workflows/mandrel-update.md +144 -466
  84. package/.agents/workflows/plan.md +87 -145
  85. package/docs/CHANGELOG.md +20 -0
  86. package/lib/cli/registry.js +21 -3
  87. package/package.json +1 -1
  88. package/.agents/schemas/loop-unit.schema.json +0 -70
  89. package/.agents/scripts/assert-branch.js +0 -81
  90. package/.agents/scripts/check-loop-units.js +0 -204
  91. package/.agents/scripts/detect-merges.js +0 -111
  92. package/.agents/scripts/git-pr-quality-gate.js +0 -205
  93. package/.agents/scripts/git-rebase-and-resolve.js +0 -234
  94. package/.agents/scripts/hierarchy-gate.js +0 -192
  95. package/.agents/scripts/hydrate-context.js +0 -179
  96. package/.agents/scripts/lib/loop-units/validate-loop-unit.js +0 -197
  97. package/.agents/scripts/lib/orchestration/epic-plan-decompose/phases/cli.js +0 -167
  98. package/.agents/scripts/lib/orchestration/epic-plan-spec/phases/cli-args.js +0 -69
  99. package/.agents/scripts/lib/orchestration/plan-runner/plan-router.js +0 -86
  100. package/.agents/scripts/loc-delta.js +0 -205
  101. package/.agents/scripts/render-manifest.js +0 -143
  102. package/.agents/scripts/run-audit-suite.js +0 -97
  103. package/.agents/scripts/select-audits.js +0 -155
  104. package/.agents/scripts/update-mutation-baseline.js +0 -189
  105. package/.agents/workflows/explain.md +0 -118
  106. package/.agents/workflows/git-merge-pr.md +0 -377
  107. package/.agents/workflows/helpers/epic-plan-decompose.md +0 -22
  108. package/.agents/workflows/helpers/epic-plan-spec.md +0 -22
  109. package/.agents/workflows/loops/README.md +0 -65
  110. package/.agents/workflows/loops/fix-failing-tests.md +0 -74
  111. package/.agents/workflows/loops/nightly-audit.md +0 -81
  112. package/.agents/workflows/loops/watch-ci.md +0 -68
@@ -0,0 +1,1015 @@
1
+ /**
2
+ * run-plan-persist.js — single GitHub-write surface for the /plan collapse
3
+ * (Epic #4474, PR3 + PR4 modes).
4
+ *
5
+ * Implements the ordered, fail-closed superset persist that replaced the
6
+ * retired 12-phase pipeline's separate persist halves
7
+ * (design §1 Step 3 + §2 mode matrix, issue #4474):
8
+ *
9
+ * 1. args (owned by the `plan-persist.js` CLI shell)
10
+ * 2. section gate — `validateSpecSections` runs BEFORE the lease and
11
+ * BEFORE any provider call; a rejection makes zero GitHub calls.
12
+ * 3. risk-verdict validation (CLI-owned `loadRiskVerdict`) +
13
+ * mode-coherence hard error (`resolveDeliveryMode`): fan-out requires
14
+ * tickets; `deliveryShape: "single"` refuses any tickets payload —
15
+ * the single mode's validator/DAG skip is fenced by construction,
16
+ * unreachable when tickets are present; `--amend` requires tickets
17
+ * carrying `op` fields and refuses the single shape.
18
+ * 4. ticket validator + file-assumption gate + DAG + sizing + budget
19
+ * (fan-out and amend; amend validates the MERGED set — existing
20
+ * keeps + adds + modifies, closes excluded; all git-local, still
21
+ * zero provider calls). Skipped entirely in single mode (no tickets
22
+ * exist to validate).
23
+ * 4.5. deterministic draft reachability (Epic #4474 PR6, design §4 —
24
+ * the 8.4 critic demoted into persist): route-glob scan of the
25
+ * draft set vs `planning.navigation.navRegistry`, mirroring the
26
+ * `--paranoid` F7 healthcheck mechanics. Orphan surfaces are a
27
+ * NAMED SOFT FAILURE (`code: PLAN_REACHABILITY_ORPHANS`, CLI exit
28
+ * 3) raised before any provider call — the author appends the
29
+ * single reachability Story in one targeted amend and re-runs the
30
+ * persist once. Silent no-op when `planning.navigation` is
31
+ * unconfigured; skip decisions are appended to the plan-metrics
32
+ * ledger (`kind: critic-skip`) for audit.
33
+ * 5. ideation fold — `renderEpicBody` / `openEpicFromOnePager` create
34
+ * the Epic when the run starts from a one-pager (the first provider
35
+ * call of the run). Amend additionally resolves every
36
+ * modify/keep/close slug to its live issue and enforces the close-op
37
+ * confirmation gate (exit 2 without `--explicit-delete`) BEFORE the
38
+ * lease and before any mutation.
39
+ * 6. Epic lease (KEEP — documented double-create at ~80 creations).
40
+ * From here the lease is released on EVERY exit path (success, gate
41
+ * failure, throw) via try/finally.
42
+ * 7. managed Tech Spec / Acceptance Table sections + risk-verdict
43
+ * structured comment + spec-freshness advisory.
44
+ * 8. mode-split mutation:
45
+ * - fan-out: story creation via the structural reconciler
46
+ * (idempotent per-slug creation; the reconciler's state file is
47
+ * the per-slug resume ledger), bracketed by checkpoint-v2 writes
48
+ * so a rate-limit crash resumes losslessly with `--resume`;
49
+ * - single: NO story tree — the `delivery::single` routing marker is
50
+ * applied instead (inert until #4475 lands the deliver-side
51
+ * reader), and `decompose = { ticketCount: 0, shape: "single" }`
52
+ * is checkpointed so delivery-time consumers never misread absence
53
+ * as unplanned;
54
+ * - amend: op-mapped delta — close ops close, modify ops
55
+ * close-and-recreate, add ops create, keep ops are untouched by
56
+ * construction; the state ledger and blocked-by edges are rebuilt
57
+ * over the merged set.
58
+ * 9. inline post-plan healthcheck (the `agent::ready` exit condition,
59
+ * Story #2921).
60
+ * 10. single terminal `agent::ready` flip — the intermediate
61
+ * `agent::review-spec` flip is retired on this surface (its readers
62
+ * were visibility-only; the /deliver start gate needs only
63
+ * `agent::ready`).
64
+ * 11. checkpoint v2 + single `plan-summary` comment carrying the dry-run
65
+ * wave table as closing text (replaces the Phase 9 dispatcher
66
+ * round-trip and the Phase 12 notify). The single-mode summary
67
+ * records `{ deliveryShape: "single", sliceCount, routingReasons }`.
68
+ * 12. temp cleanup ONLY at terminal success — a failed run leaves
69
+ * techspec/acceptance/risk-verdict/tickets artifacts on disk so a
70
+ * `--force`/`--resume` re-persist reuses them (fixes the
71
+ * `plan-phase-cleanup.js` mid-pipeline deletion defect).
72
+ *
73
+ * Checkpoint v2: same `epic-plan-state` structured comment, `version: 2`,
74
+ * with the `planningRisk` / `riskVerdict` / `reviewRouting` / `spec` /
75
+ * `decompose` fields byte-compatible with v1 so the four delivery-time
76
+ * consumers — `lib/orchestration/code-review.js` (review depth),
77
+ * `epic-audit-prepare.js` (audit-lens routing),
78
+ * `story-close/phases/locked-pipeline.js` (parent-risk inheritance), and
79
+ * the decompose context reader — read it without modification. The only
80
+ * additions are the `version` bump and the additive `persist` progress
81
+ * block; consumers key on field presence, never on `version`.
82
+ *
83
+ * @module lib/orchestration/plan-persist/run-plan-persist
84
+ */
85
+
86
+ import { spawnSync as defaultSpawnSync } from 'node:child_process';
87
+ import path from 'node:path';
88
+
89
+ import { runPlanHealthcheck as defaultRunPlanHealthcheck } from '../../../epic-plan-healthcheck.js';
90
+ import { verifyBddRunnerPendingTag } from '../../bdd-runner-detect.js';
91
+ import { getLimits, PROJECT_ROOT } from '../../config-resolver.js';
92
+ import { openEpicFromOnePager } from '../../epic-plan-ideation.js';
93
+ import { gitSpawn } from '../../git-utils.js';
94
+ import { Logger } from '../../Logger.js';
95
+ import {
96
+ AGENT_LABELS,
97
+ DELIVERY_LABELS,
98
+ TYPE_LABELS,
99
+ } from '../../label-constants.js';
100
+ import { cleanupPhaseTempFiles } from '../../plan-phase-cleanup.js';
101
+ import { loadState, writeSpec, writeState } from '../../spec/index.js';
102
+ import {
103
+ reconcileSubIssueLinks,
104
+ setBlockedByDependencies,
105
+ setEpicLabel,
106
+ warnTicketCapNearLimit,
107
+ } from '../epic-plan-decompose/phases/creation.js';
108
+ import {
109
+ enforceFanOutGate,
110
+ runHealthcheckGate,
111
+ surfaceSoftConflictFindings,
112
+ } from '../epic-plan-decompose/phases/persist.js';
113
+ import {
114
+ buildEpicSpecInput,
115
+ validateTickets,
116
+ } from '../epic-plan-decompose/phases/persist-helpers.js';
117
+ import {
118
+ RECONCILE_CLI,
119
+ spawnReconcilerApply,
120
+ } from '../epic-plan-decompose/phases/reconcile-spawn.js';
121
+ import {
122
+ acquireEpicPlanLease,
123
+ assertNoOpenPlanChildren,
124
+ releaseEpicPlanLease,
125
+ } from '../epic-plan-lease-guard.js';
126
+ import { planEpic } from '../epic-plan-spec/phases/plan-epic.js';
127
+ import { runSpecFreshnessCheck } from '../epic-plan-spec/phases/spec-freshness.js';
128
+ import {
129
+ initialize as initializePlanState,
130
+ read as readPlanState,
131
+ write as writePlanState,
132
+ } from '../epic-plan-state-store.js';
133
+ import { evaluatePlanCritics } from '../plan-critics-evaluate.js';
134
+ import {
135
+ appendCriticSkip,
136
+ readPlanMetrics,
137
+ renderPlanMetricsSummaryLine,
138
+ summarizePlanMetrics,
139
+ } from '../plan-metrics.js';
140
+ import {
141
+ evaluateDraftReachability,
142
+ renderReachabilityOrphans,
143
+ } from '../plan-reachability.js';
144
+ import { resolveReviewRouting } from '../plan-review-routing.js';
145
+ import { deriveRiskEnvelope } from '../planning-risk.js';
146
+ import { renderSpec } from '../spec-renderer.js';
147
+ import {
148
+ formatMissingSectionMessage,
149
+ validateSpecSections,
150
+ } from '../spec-section-validator.js';
151
+ import { upsertStructuredComment } from '../ticketing.js';
152
+ import {
153
+ applyAmendOps,
154
+ buildMergedTicketSet,
155
+ enforceAmendCloseGate,
156
+ partitionAmendTickets,
157
+ renderAmendPlanDiff,
158
+ resolveAmendTargets,
159
+ } from './amend.js';
160
+ import { countDeliverySlices, resolveDeliveryMode } from './delivery-mode.js';
161
+ import {
162
+ buildPlanSummaryCommentBody,
163
+ buildWaveTable,
164
+ PLAN_SUMMARY_COMMENT_TYPE,
165
+ } from './summary.js';
166
+
167
+ /** Checkpoint schema version written by this surface. */
168
+ export const PLAN_CHECKPOINT_SCHEMA_VERSION_V2 = 2;
169
+
170
+ // Mode-coherence resolution (design §1 Step 3 item 3 + §2 mode matrix)
171
+ // lives in `delivery-mode.js`; re-exported here so the CLI's stable public
172
+ // API keeps a single import root for the persist surface.
173
+ export { resolveDeliveryMode };
174
+
175
+ /**
176
+ * Merge-write the epic-plan-state checkpoint at schema v2. Reads the
177
+ * current checkpoint (or initializes a fresh skeleton), shallow-merges
178
+ * `patch`, and stamps `version: 2`. Field shapes for `planningRisk`,
179
+ * `riskVerdict`, `reviewRouting`, `spec`, and `decompose` are byte-compatible
180
+ * with v1 — v2 is additive only.
181
+ *
182
+ * @param {object} provider
183
+ * @param {number} epicId
184
+ * @param {object} patch
185
+ * @returns {Promise<object>} the written checkpoint payload
186
+ */
187
+ export async function writeCheckpointV2(provider, epicId, patch) {
188
+ const current =
189
+ (await readPlanState({ provider, epicId })) ??
190
+ (await initializePlanState({ provider, epicId }));
191
+ // One-level deep merge for object-valued blocks (`spec`, `decompose`,
192
+ // `persist`, …) so a partial patch (e.g. `persist: { completedAt }`)
193
+ // refines rather than replaces the block — same discipline the v1
194
+ // writers applied by hand with `...currentState.decompose`.
195
+ const merged = { ...current };
196
+ for (const [key, value] of Object.entries(patch ?? {})) {
197
+ const existing = merged[key];
198
+ if (
199
+ value !== null &&
200
+ typeof value === 'object' &&
201
+ !Array.isArray(value) &&
202
+ existing !== null &&
203
+ typeof existing === 'object' &&
204
+ !Array.isArray(existing)
205
+ ) {
206
+ merged[key] = { ...existing, ...value };
207
+ } else {
208
+ merged[key] = value;
209
+ }
210
+ }
211
+ return writePlanState({
212
+ provider,
213
+ epicId,
214
+ state: {
215
+ ...merged,
216
+ version: PLAN_CHECKPOINT_SCHEMA_VERSION_V2,
217
+ },
218
+ });
219
+ }
220
+
221
+ /**
222
+ * Resolve (or create) the Epic this persist run targets.
223
+ *
224
+ * Ideation mode (`onePagerContent` present): folds the former Phase 3/4
225
+ * ideation steps in — `openEpicFromOnePager` renders the Epic body from the
226
+ * one-pager via the canonical template and opens the Issue with the
227
+ * `type::epic` label. This is deliberately the FIRST provider call of the
228
+ * run (after every deterministic gate), so a gate rejection never leaves an
229
+ * orphaned Epic behind.
230
+ *
231
+ * Existing-Epic mode: fetches and type-asserts the Epic.
232
+ *
233
+ * @returns {Promise<{ epicId: number, epic: object, created: boolean }>}
234
+ */
235
+ async function resolveTargetEpic({
236
+ epicId,
237
+ onePagerContent,
238
+ templateContent,
239
+ provider,
240
+ }) {
241
+ if (onePagerContent) {
242
+ if (typeof provider.createIssue !== 'function') {
243
+ throw new Error(
244
+ '[plan-persist] provider does not expose createIssue; cannot open ' +
245
+ 'an Epic from a one-pager.',
246
+ );
247
+ }
248
+ const created = await openEpicFromOnePager({
249
+ onePager: onePagerContent,
250
+ template: templateContent,
251
+ createIssue: (payload) => provider.createIssue(payload),
252
+ });
253
+ Logger.info(
254
+ `[plan-persist] Opened Epic #${created.id} from one-pager ("${created.title}").`,
255
+ );
256
+ const epic = await provider.getEpic(created.id);
257
+ if (!epic) {
258
+ throw new Error(
259
+ `[plan-persist] Epic #${created.id} was created but could not be re-fetched.`,
260
+ );
261
+ }
262
+ return { epicId: created.id, epic, created: true };
263
+ }
264
+
265
+ const epic = await provider.getEpic(epicId);
266
+ if (!epic) {
267
+ throw new Error(`[plan-persist] Epic #${epicId} not found.`);
268
+ }
269
+ if (!epic.labels?.includes(TYPE_LABELS.EPIC)) {
270
+ throw new Error(
271
+ `[plan-persist] Ticket #${epicId} is not a ${TYPE_LABELS.EPIC}.`,
272
+ );
273
+ }
274
+ return { epicId, epic, created: false };
275
+ }
276
+
277
+ /**
278
+ * Execute the collapsed persist end to end (module doc has the 12-step
279
+ * order). Modes: fan-out (default), single (`deliveryShape: "single"`),
280
+ * amend (`--amend`).
281
+ *
282
+ * @param {{
283
+ * epicId?: number|null,
284
+ * provider: import('../../ITicketingProvider.js').ITicketingProvider,
285
+ * artifacts: {
286
+ * techSpecContent: string,
287
+ * acceptanceSpecContent?: string|null,
288
+ * riskVerdict: import('../planning-risk.js').RiskVerdict,
289
+ * tickets?: Array<object>|null,
290
+ * onePagerContent?: string|null,
291
+ * templateContent?: string|null,
292
+ * },
293
+ * config?: object,
294
+ * settings?: { baseBranch?: string, paths?: { tempRoot?: string } },
295
+ * opts?: {
296
+ * force?: boolean,
297
+ * resume?: boolean,
298
+ * amend?: boolean,
299
+ * explicitDelete?: boolean,
300
+ * steal?: boolean,
301
+ * forceReview?: boolean,
302
+ * allowOverBudget?: boolean,
303
+ * allowLargeFanOut?: boolean,
304
+ * // test seams (production callers must not set these)
305
+ * skipHealthcheck?: boolean,
306
+ * skipCleanup?: boolean,
307
+ * spawnSync?: typeof defaultSpawnSync,
308
+ * reconcileCli?: string,
309
+ * writeSpecFn?: typeof writeSpec,
310
+ * renderSpecFn?: typeof renderSpec,
311
+ * loadStateFn?: typeof loadState,
312
+ * writeStateFn?: typeof writeState,
313
+ * runHealthcheckFn?: typeof defaultRunPlanHealthcheck,
314
+ * bddProbeFn?: typeof verifyBddRunnerPendingTag,
315
+ * fanOutCounter?: (arg: { path: string }) => number,
316
+ * cwd?: string,
317
+ * },
318
+ * }} input
319
+ */
320
+ export async function runPlanPersist({
321
+ epicId: requestedEpicId = null,
322
+ provider,
323
+ artifacts,
324
+ config = {},
325
+ settings = {},
326
+ opts = {},
327
+ }) {
328
+ const {
329
+ techSpecContent,
330
+ acceptanceSpecContent = null,
331
+ riskVerdict,
332
+ tickets = null,
333
+ onePagerContent = null,
334
+ templateContent = null,
335
+ } = artifacts ?? {};
336
+ const {
337
+ force = false,
338
+ resume = false,
339
+ amend = false,
340
+ explicitDelete = false,
341
+ steal = false,
342
+ forceReview = false,
343
+ allowOverBudget = false,
344
+ allowLargeFanOut = false,
345
+ skipHealthcheck = false,
346
+ skipCleanup = false,
347
+ spawnSync = defaultSpawnSync,
348
+ reconcileCli = RECONCILE_CLI,
349
+ writeSpecFn = writeSpec,
350
+ renderSpecFn = renderSpec,
351
+ loadStateFn = loadState,
352
+ writeStateFn = writeState,
353
+ runHealthcheckFn = defaultRunPlanHealthcheck,
354
+ bddProbeFn = verifyBddRunnerPendingTag,
355
+ fanOutCounter = undefined,
356
+ cwd = PROJECT_ROOT,
357
+ } = opts;
358
+
359
+ // ---- Step 1: argument coherence (flag parsing itself is CLI-owned). ----
360
+ if (force && resume) {
361
+ throw new Error(
362
+ '[plan-persist] --force and --resume are mutually exclusive.',
363
+ );
364
+ }
365
+ if (amend && (force || resume)) {
366
+ throw new Error(
367
+ '[plan-persist] --amend is mutually exclusive with --force/--resume ' +
368
+ '— the amend delta is already an incremental re-persist.',
369
+ );
370
+ }
371
+ if (amend && onePagerContent) {
372
+ throw new Error(
373
+ '[plan-persist] --amend requires --epic <id> — there is no existing ' +
374
+ 'plan to amend in ideation mode.',
375
+ );
376
+ }
377
+ if (onePagerContent && resume) {
378
+ throw new Error(
379
+ '[plan-persist] --resume requires --epic <id> — the Epic already ' +
380
+ "exists after the first attempt (its number is in the failed run's " +
381
+ 'output); an ideation --resume would open a duplicate.',
382
+ );
383
+ }
384
+ if (onePagerContent && !templateContent) {
385
+ throw new Error(
386
+ '[plan-persist] ideation mode requires the epic-from-idea template ' +
387
+ 'content (templateContent).',
388
+ );
389
+ }
390
+ if (!onePagerContent && !Number.isInteger(requestedEpicId)) {
391
+ throw new Error(
392
+ '[plan-persist] either --epic <id> or --one-pager <path> is required.',
393
+ );
394
+ }
395
+
396
+ // ---- Step 2: section gate — BEFORE the lease, BEFORE any provider call.
397
+ // A rejection here has made zero GitHub calls (locked in by the
398
+ // fail-closed-ordering test).
399
+ const sectionCheck = validateSpecSections({ body: techSpecContent });
400
+ if (!sectionCheck.ok) {
401
+ throw new Error(
402
+ formatMissingSectionMessage({
403
+ techspecPath: 'authored Tech Spec (--tech-spec)',
404
+ missing: sectionCheck.missing,
405
+ }),
406
+ );
407
+ }
408
+
409
+ // ---- Step 3: risk-verdict presence (schema validation is CLI-owned via
410
+ // loadRiskVerdict) + mode-coherence hard error. ----
411
+ if (!riskVerdict || !Array.isArray(riskVerdict.axes)) {
412
+ throw new Error(
413
+ '[plan-persist] risk verdict is required — author risk-verdict.json ' +
414
+ 'and pass it with --risk-verdict.',
415
+ );
416
+ }
417
+ const mode = resolveDeliveryMode(riskVerdict, tickets, { amend });
418
+
419
+ // ---- Step 4: ticket validator + file-assumption gate + DAG + sizing +
420
+ // budget (fan-out and amend; git-local — still no provider call). In
421
+ // amend mode every gate runs over the MERGED set — keeps + adds +
422
+ // modifies, closes excluded — so the DAG is validated against the tree
423
+ // that will actually exist post-amend. The skip branch below is fenced
424
+ // by construction: `resolveDeliveryMode` hard-refuses `deliveryShape:
425
+ // "single"` with any tickets payload, so single mode can only reach here
426
+ // with no tickets to validate. ----
427
+ let validated = null;
428
+ let amendPartition = null;
429
+ let reachability = null;
430
+ let gateSet = null;
431
+ if (mode !== 'single') {
432
+ amendPartition = mode === 'amend' ? partitionAmendTickets(tickets) : null;
433
+ gateSet = mode === 'amend' ? buildMergedTicketSet(tickets) : tickets;
434
+ const maxTickets = getLimits(config).maxTickets;
435
+ if (gateSet.length > maxTickets && !allowOverBudget) {
436
+ throw new Error(
437
+ `[plan-persist] Tickets (${gateSet.length}) exceed the reviewability ` +
438
+ `budget (${maxTickets}). Re-scope the Epic into a smaller plan, or ` +
439
+ 'rerun with --allow-over-budget after confirming the over-budget ' +
440
+ 'rationale on the Epic.',
441
+ );
442
+ }
443
+ warnTicketCapNearLimit(gateSet, maxTickets, 'plan-persist');
444
+ if (gateSet.length > maxTickets && allowOverBudget) {
445
+ Logger.warn(
446
+ `[plan-persist] Persisting an over-budget decomposition: ${gateSet.length} ` +
447
+ `tickets vs. budget ${maxTickets} (operator override --allow-over-budget).`,
448
+ );
449
+ }
450
+ Logger.info(
451
+ `[plan-persist] Running cross-validation on ${gateSet.length} tickets` +
452
+ `${mode === 'amend' ? ' (merged amend set)' : ''}...`,
453
+ );
454
+ validated = validateTickets(gateSet, config, { fanOutCounter, cwd });
455
+ enforceFanOutGate(validated.findings, allowLargeFanOut, 'plan-persist');
456
+ surfaceSoftConflictFindings(validated.findings, 'plan-persist');
457
+
458
+ // File-assumption gate (#4474 PR7 — coverage regression fix). The
459
+ // validator batches per-Story `{ path, assumption }` mismatches against
460
+ // the base branch onto `validated.errors`; the retired 12-phase flow
461
+ // gated that channel in the workflow's re-prompt loop, so the collapsed
462
+ // CLI must gate it here or the check is silently advisory. Fan-out and
463
+ // shared-editor findings keep their own policy channels above — this
464
+ // rejects only the deterministic assumption mismatches, still before
465
+ // any provider call. Guarded on ref resolvability: in a checkout where
466
+ // the base branch ref does not resolve (shallow CI fetches, detached
467
+ // test sandboxes) every path probes "absent" and the findings are
468
+ // noise, so they downgrade to warnings instead of hard-failing.
469
+ const assumptionFailures = (validated.errors ?? []).filter((e) =>
470
+ e.startsWith('File assumption mismatch:'),
471
+ );
472
+ if (assumptionFailures.length > 0) {
473
+ const gateBaseRef = config?.baseBranch ?? 'main';
474
+ const refResolves =
475
+ gitSpawn(
476
+ cwd ?? process.cwd(),
477
+ 'rev-parse',
478
+ '--verify',
479
+ '--quiet',
480
+ `${gateBaseRef}^{commit}`,
481
+ ).status === 0;
482
+ if (refResolves) {
483
+ throw new Error(
484
+ `[plan-persist] file-assumption gate: ${assumptionFailures.length} ` +
485
+ `mismatch(es) between declared assumptions and the base branch:\n` +
486
+ `${assumptionFailures.map((e) => ` - ${e}`).join('\n')}\n` +
487
+ 'Fix the Story change declarations (or the plan) and re-run the persist.',
488
+ );
489
+ }
490
+ Logger.warn(
491
+ `[plan-persist] file-assumption gate skipped: base ref '${gateBaseRef}' ` +
492
+ `does not resolve in this checkout — ${assumptionFailures.length} ` +
493
+ 'finding(s) downgraded to warnings.',
494
+ );
495
+ for (const e of assumptionFailures) {
496
+ Logger.warn(`[plan-persist] ${e}`);
497
+ }
498
+ }
499
+
500
+ // ---- Step 4.5: deterministic draft reachability (#4474 PR6 — the 8.4
501
+ // critic demoted into persist). Still git-local, zero provider calls,
502
+ // so the one-targeted-amend recovery re-runs a clean persist. ----
503
+ reachability = evaluateDraftReachability({ tickets: gateSet, config });
504
+ if (reachability.status === 'orphans') {
505
+ const err = new Error(renderReachabilityOrphans(reachability));
506
+ err.code = 'PLAN_REACHABILITY_ORPHANS';
507
+ err.orphans = reachability.orphans;
508
+ throw err;
509
+ }
510
+ Logger.info(`[plan-persist] reachability: ${reachability.reasons[0]}`);
511
+ } else {
512
+ reachability = {
513
+ status: 'skipped',
514
+ reasons: [
515
+ 'single-delivery shape — no draft story tree to scan for orphan surfaces.',
516
+ ],
517
+ orphans: [],
518
+ scanned: 0,
519
+ };
520
+ }
521
+ if (reachability.status === 'skipped') {
522
+ // Audit trail for the skip decision (#4474 PR6). Best-effort by
523
+ // contract — a failed append never fails the persist. Logged before
524
+ // the first provider call so even an ideation run that later fails
525
+ // still records the decision (ideation has no Epic id yet, so the
526
+ // record lands on the standalone stream).
527
+ await appendCriticSkip(
528
+ {
529
+ critic: 'reachability',
530
+ reasons: reachability.reasons,
531
+ cli: 'plan-persist',
532
+ epicId: requestedEpicId,
533
+ },
534
+ config,
535
+ );
536
+ }
537
+
538
+ // ---- Step 4.7: folded critic dispatch evaluation (#4496 fix 6 — the
539
+ // former standalone `plan-critics.js` turn). Deterministic and git-local,
540
+ // still zero provider calls: the verdicts are printed (and returned on
541
+ // the result) as part of the pre-write phase, and every skip decision is
542
+ // appended to the plan-metrics ledger exactly as the standalone CLI did,
543
+ // so under-firing stays auditable without a separate invocation on the
544
+ // headless path. Advisory by construction — the deterministic validators
545
+ // above remain the unchanged hard gates. ----
546
+ const critics = evaluatePlanCritics({
547
+ techSpecContent,
548
+ riskVerdict,
549
+ tickets: gateSet,
550
+ config,
551
+ });
552
+ for (const decision of [critics.consolidation, critics.premortem]) {
553
+ Logger.info(
554
+ `[plan-persist] critic ${decision.critic}: ` +
555
+ `${decision.dispatch ? 'dispatch' : 'skip'} — ` +
556
+ decision.reasons.join('; '),
557
+ );
558
+ if (!decision.dispatch) {
559
+ // Best-effort by contract — a failed append never fails the persist.
560
+ await appendCriticSkip(
561
+ {
562
+ critic: decision.critic,
563
+ reasons: decision.reasons,
564
+ cli: 'plan-persist',
565
+ epicId: requestedEpicId,
566
+ },
567
+ config,
568
+ );
569
+ }
570
+ }
571
+
572
+ // ---- Step 5: ideation fold / Epic resolution (first provider call). ----
573
+ const { epicId, epic, created } = await resolveTargetEpic({
574
+ epicId: requestedEpicId,
575
+ onePagerContent,
576
+ templateContent,
577
+ provider,
578
+ });
579
+
580
+ // Amend pre-mutation resolution: every modify/keep/close slug must
581
+ // resolve to a live issue, and close ops require --explicit-delete
582
+ // (exit 2 with the dry-run diff otherwise — the epic-reconcile.js
583
+ // contract). Runs BEFORE the lease and before any mutation.
584
+ let amendTargets = null;
585
+ if (mode === 'amend') {
586
+ const priorState = loadStateFn(epicId);
587
+ amendTargets = await resolveAmendTargets({
588
+ partition: amendPartition,
589
+ stateMapping: priorState.mapping,
590
+ provider,
591
+ });
592
+ enforceAmendCloseGate({
593
+ epicId,
594
+ targets: amendTargets,
595
+ adds: amendPartition.add,
596
+ explicitDelete,
597
+ });
598
+ Logger.info(
599
+ renderAmendPlanDiff({
600
+ epicId,
601
+ targets: amendTargets,
602
+ adds: amendPartition.add,
603
+ }),
604
+ );
605
+ }
606
+
607
+ // ---- Step 6: Epic lease. Every path after a successful acquire runs
608
+ // through the finally below, so the lease is released on success, on a
609
+ // gate failure, and on a throw alike. ----
610
+ await acquireEpicPlanLease({ provider, epicId, config, steal });
611
+
612
+ try {
613
+ // Refuse a duplicate story tree unless this is a deliberate re-persist
614
+ // (`--force` closes + recreates via the reconciler's close ops;
615
+ // `--resume` continues a partial persist). Amend is exempt by
616
+ // definition — its whole purpose is mutating the existing open tree.
617
+ if (mode !== 'amend') {
618
+ await assertNoOpenPlanChildren({
619
+ provider,
620
+ epicId,
621
+ force: force || resume,
622
+ });
623
+ }
624
+
625
+ await initializePlanState({ provider, epicId });
626
+
627
+ // ---- Step 7: managed sections + risk comment + freshness advisory. ----
628
+ // BDD-runner probe (Story #4145): best-effort; a probe failure degrades
629
+ // to "runner present" and never blocks the persist.
630
+ let bddRunner = null;
631
+ try {
632
+ bddRunner = await bddProbeFn({ cwd: PROJECT_ROOT });
633
+ } catch (err) {
634
+ Logger.warn(
635
+ `[plan-persist] BDD runner probe skipped (${err.message}); ` +
636
+ 'acceptance disposition derived from risk axes only.',
637
+ );
638
+ }
639
+ const planningRisk = deriveRiskEnvelope(riskVerdict, { bddRunner });
640
+ if (planningRisk.acceptanceWaivedReason) {
641
+ Logger.info(
642
+ `[plan-persist] Acceptance disposition forced to not-applicable for ` +
643
+ `Epic #${epicId}: ${planningRisk.acceptanceWaivedReason}`,
644
+ );
645
+ }
646
+
647
+ // Amend always overwrites the managed sections — the amended Tech Spec
648
+ // IS the delta's spec half (planEpic would otherwise short-circuit
649
+ // `already-planned` on the pre-amend sections).
650
+ const planResult = await planEpic(
651
+ epicId,
652
+ provider,
653
+ { techSpecContent, acceptanceSpecContent },
654
+ settings,
655
+ { force: force || mode === 'amend', planningRisk },
656
+ );
657
+
658
+ const reviewRouting = resolveReviewRouting({ planningRisk, forceReview });
659
+ Logger.info(`[plan-persist] Review routing: ${reviewRouting.decision}.`);
660
+
661
+ await upsertStructuredComment(
662
+ provider,
663
+ epicId,
664
+ 'risk-verdict',
665
+ buildRiskVerdictCommentBody({ epicId, riskVerdict, planningRisk }),
666
+ );
667
+
668
+ const baseBranchRef = settings?.baseBranch ?? 'main';
669
+ const tempRoot = path.resolve(
670
+ PROJECT_ROOT,
671
+ settings?.paths?.tempRoot ?? 'temp',
672
+ );
673
+ const freshness = await runSpecFreshnessCheck({
674
+ epicId,
675
+ techSpecContent,
676
+ baseBranchRef,
677
+ tempRoot,
678
+ provider,
679
+ });
680
+
681
+ // Spec-half checkpoint (v2). A crash after this point resumes with the
682
+ // sections already folded (planEpic short-circuits `already-planned`).
683
+ await writeCheckpointV2(provider, epicId, {
684
+ planningRisk,
685
+ riskVerdict,
686
+ reviewRouting: {
687
+ decision: reviewRouting.decision,
688
+ requiresStop: reviewRouting.requiresStop,
689
+ forceReviewApplied: reviewRouting.forceReviewApplied,
690
+ },
691
+ spec: {
692
+ techSpecPersisted:
693
+ planResult?.techSpecPersisted === true ||
694
+ planResult?.reason === 'already-planned',
695
+ acceptanceTable: planResult?.acceptanceTable ?? 'none',
696
+ completedAt: new Date().toISOString(),
697
+ },
698
+ persist: {
699
+ mode,
700
+ cli: 'plan-persist',
701
+ startedAt: new Date().toISOString(),
702
+ completedAt: null,
703
+ },
704
+ });
705
+
706
+ // ---- Step 8: mode-split mutation. ----
707
+ let reconcile = null;
708
+ let specFilePath = null;
709
+ let ticketCount = 0;
710
+ let single = null;
711
+ let amendSummary = null;
712
+
713
+ if (mode === 'fan-out') {
714
+ // Story creation via the structural reconciler.
715
+ Logger.info(
716
+ `[plan-persist] Rendering spec for Epic #${epicId} (${validated.length} tickets)...`,
717
+ );
718
+ const spec = renderSpecFn(validated, {
719
+ epic: buildEpicSpecInput(epic, epicId),
720
+ });
721
+ specFilePath = writeSpecFn(epicId, spec, { epicsDir: undefined });
722
+ Logger.info(`[plan-persist] Wrote spec → ${specFilePath}`);
723
+
724
+ // Pre-creation checkpoint: marks creation in flight so a rate-limit
725
+ // crash mid-creation leaves a checkpoint pointing at the spec + the
726
+ // reconciler's per-slug state file (the resume ledger). `--resume`
727
+ // re-runs the reconciler, which creates only the missing slugs.
728
+ await writeCheckpointV2(provider, epicId, {
729
+ decompose: { ticketCount: null, completedAt: null },
730
+ });
731
+
732
+ Logger.info(
733
+ `[plan-persist] Spawning epic-reconcile.js --apply --yes for Epic #${epicId}...`,
734
+ );
735
+ reconcile = spawnReconcilerApply({
736
+ spawnSync,
737
+ reconcileCli,
738
+ epicId,
739
+ cwd,
740
+ explicitDelete: force,
741
+ });
742
+
743
+ await reconcileSubIssueLinks(epicId, provider);
744
+
745
+ const postReconcileState = loadStateFn(epicId);
746
+ await setBlockedByDependencies(
747
+ epicId,
748
+ provider,
749
+ spec,
750
+ postReconcileState.mapping,
751
+ );
752
+
753
+ ticketCount = tickets.length;
754
+ // Post-creation checkpoint (the former recordCheckpoint half).
755
+ await writeCheckpointV2(provider, epicId, {
756
+ decompose: {
757
+ ticketCount,
758
+ shape: 'fan-out',
759
+ completedAt: new Date().toISOString(),
760
+ },
761
+ });
762
+
763
+ // A force re-persist over a former single-delivery plan flips the
764
+ // routing shape — drop the stale marker so #4475's reader never sees
765
+ // a fan-out tree labelled single.
766
+ await removeSingleDeliveryMarker(provider, epicId, epic);
767
+ } else if (mode === 'single') {
768
+ // Single-delivery: NO story tree. The delivery::single routing
769
+ // marker (inert until #4475's deliver-side reader) plus the Delivery
770
+ // Slicing table of the persisted Tech Spec are the plan.
771
+ single = {
772
+ deliveryShape: 'single',
773
+ sliceCount: countDeliverySlices(techSpecContent),
774
+ routingReasons: riskVerdict.deliveryShapeRationale
775
+ ? [riskVerdict.deliveryShapeRationale]
776
+ : [],
777
+ };
778
+ Logger.info(
779
+ `[plan-persist] Single-delivery mode: applying ${DELIVERY_LABELS.SINGLE} ` +
780
+ `to Epic #${epicId} (no story tree).`,
781
+ );
782
+ await provider.updateTicket(epicId, {
783
+ labels: { add: [DELIVERY_LABELS.SINGLE], remove: [] },
784
+ });
785
+ // Explicit zero-ticket checkpoint so delivery-time consumers read a
786
+ // deliberate single-shape plan, never an unplanned absence.
787
+ await writeCheckpointV2(provider, epicId, {
788
+ decompose: {
789
+ ticketCount: 0,
790
+ shape: 'single',
791
+ completedAt: new Date().toISOString(),
792
+ },
793
+ });
794
+ } else {
795
+ // Amend delta: close-and-recreate is scoped to modify/close slugs
796
+ // only; keeps are untouched by construction (no code path receives
797
+ // them); adds are created fresh. The state ledger and blocked-by
798
+ // edges are rebuilt over the merged set.
799
+ const spec = renderSpecFn(validated, {
800
+ epic: buildEpicSpecInput(epic, epicId),
801
+ });
802
+ specFilePath = writeSpecFn(epicId, spec, { epicsDir: undefined });
803
+ Logger.info(`[plan-persist] Wrote amended spec → ${specFilePath}`);
804
+
805
+ await writeCheckpointV2(provider, epicId, {
806
+ decompose: { ticketCount: null, completedAt: null },
807
+ });
808
+
809
+ const validatedBySlug = new Map(validated.map((t) => [t.slug, t]));
810
+ const applied = await applyAmendOps({
811
+ epicId,
812
+ provider,
813
+ targets: amendTargets,
814
+ validatedBySlug,
815
+ });
816
+
817
+ // Rebuild the state ledger over the merged set: prior mapping minus
818
+ // closed/replaced slugs, plus the fresh create/recreate numbers.
819
+ const priorState = loadStateFn(epicId);
820
+ const mergedMapping = { ...(priorState.mapping ?? {}) };
821
+ for (const slug of applied.closedSlugs) delete mergedMapping[slug];
822
+ Object.assign(mergedMapping, applied.mapping);
823
+ writeStateFn(epicId, {
824
+ epicId,
825
+ mapping: mergedMapping,
826
+ lastReconciledAt: new Date().toISOString(),
827
+ });
828
+
829
+ await reconcileSubIssueLinks(epicId, provider);
830
+ await setBlockedByDependencies(epicId, provider, spec, mergedMapping);
831
+
832
+ ticketCount = validated.length;
833
+ amendSummary = {
834
+ closed: applied.closed,
835
+ recreated: applied.recreated,
836
+ created: applied.created,
837
+ keptCount: amendTargets.keep.length,
838
+ };
839
+ await writeCheckpointV2(provider, epicId, {
840
+ decompose: {
841
+ ticketCount,
842
+ shape: 'fan-out',
843
+ completedAt: new Date().toISOString(),
844
+ },
845
+ });
846
+
847
+ // An amended plan is fan-out-shaped; drop a stale single marker.
848
+ await removeSingleDeliveryMarker(provider, epicId, epic);
849
+ }
850
+
851
+ // ---- Step 9: inline healthcheck — the agent::ready exit condition. ----
852
+ const healthcheck = skipHealthcheck
853
+ ? { ok: true, skipped: true }
854
+ : await runHealthcheckGate({
855
+ epicId,
856
+ epic,
857
+ runHealthcheckFn,
858
+ tag: 'plan-persist',
859
+ });
860
+
861
+ // ---- Step 10: single terminal agent::ready flip. This surface never
862
+ // writes agent::review-spec — the HITL review gate sits BEFORE persist
863
+ // in the collapsed flow, so the intermediate label has no reader. ----
864
+ Logger.info(
865
+ `[plan-persist] Flipping Epic #${epicId} to ${AGENT_LABELS.READY}...`,
866
+ );
867
+ await setEpicLabel(provider, epicId, AGENT_LABELS.READY);
868
+
869
+ // ---- Step 11: final checkpoint v2 + single plan-summary comment with
870
+ // the dry-run wave table as closing text (single mode records the
871
+ // { deliveryShape, sliceCount, routingReasons } routing record
872
+ // instead). ----
873
+ const waveTable = mode === 'single' ? [] : buildWaveTable(validated);
874
+ const checkpoint = await writeCheckpointV2(provider, epicId, {
875
+ persist: { completedAt: new Date().toISOString() },
876
+ });
877
+ // G2 measurement receipt (Epic #4474 PR7): roll the plan-metrics ledger
878
+ // into the summary comment so turns-per-plan / per-mode counts / critic
879
+ // skips are readable off the Epic. Best-effort — a missing ledger
880
+ // yields no line. The in-flight persist invocation itself is stamped by
881
+ // the CLI wrapper *after* this function returns, so it appears in the
882
+ // stdout JSON (and any later re-persist), not in this comment.
883
+ let planMetricsLine = null;
884
+ try {
885
+ const metricsSummary = summarizePlanMetrics(
886
+ await readPlanMetrics(epicId, config),
887
+ );
888
+ if (metricsSummary) {
889
+ planMetricsLine = renderPlanMetricsSummaryLine(metricsSummary);
890
+ }
891
+ } catch (err) {
892
+ Logger.warn(
893
+ `[plan-persist] plan-metrics summary line skipped: ${err.message}`,
894
+ );
895
+ }
896
+ await upsertStructuredComment(
897
+ provider,
898
+ epicId,
899
+ PLAN_SUMMARY_COMMENT_TYPE,
900
+ buildPlanSummaryCommentBody({
901
+ epicId,
902
+ ticketCount,
903
+ planningRisk,
904
+ reviewRouting,
905
+ freshness,
906
+ healthcheck,
907
+ waveTable,
908
+ mode,
909
+ planMetricsLine,
910
+ single,
911
+ amend: amendSummary,
912
+ }),
913
+ );
914
+
915
+ // ---- Step 12: temp cleanup ONLY at terminal success. A failed run
916
+ // leaves every authored artifact on disk for --force/--resume reuse. ----
917
+ const cleanup = skipCleanup
918
+ ? { deleted: [], missing: [], failed: [], skipped: true }
919
+ : await cleanupPhaseTempFiles({ phase: 'persist', epicId });
920
+ Logger.info(
921
+ `[plan-persist] ✅ Persist complete for Epic #${epicId} (${mode}). ` +
922
+ `${ticketCount} ticket(s) persisted; Epic is ${AGENT_LABELS.READY}.`,
923
+ );
924
+ if (cleanup.deleted.length > 0) {
925
+ Logger.info(
926
+ `[plan-persist] 🧹 Cleaned up ${cleanup.deleted.length} temp file(s).`,
927
+ );
928
+ }
929
+
930
+ return {
931
+ epicId,
932
+ epicCreated: created,
933
+ mode,
934
+ ticketCount,
935
+ checkpoint,
936
+ planningRisk,
937
+ reviewRouting,
938
+ freshness,
939
+ healthcheck,
940
+ reachability,
941
+ critics,
942
+ reconcile,
943
+ specPath: specFilePath,
944
+ waveTable,
945
+ single,
946
+ amend: amendSummary,
947
+ cleanup,
948
+ labelTransition: 'ready',
949
+ };
950
+ } finally {
951
+ // Lease release on EVERY exit path (success, gate failure, throw).
952
+ // Best-effort by contract — releaseEpicPlanLease never throws.
953
+ await releaseEpicPlanLease({ provider, epicId, config });
954
+ }
955
+ }
956
+
957
+ /**
958
+ * Drop a stale `delivery::single` marker when a fan-out-shaped persist
959
+ * (full re-persist or amend) lands over a formerly single-delivery plan.
960
+ * No-op — and no API call — when the fetched Epic never carried it.
961
+ *
962
+ * @param {object} provider
963
+ * @param {number} epicId
964
+ * @param {{ labels?: string[] }} epic the Epic as fetched at step 5
965
+ */
966
+ async function removeSingleDeliveryMarker(provider, epicId, epic) {
967
+ if (!epic?.labels?.includes(DELIVERY_LABELS.SINGLE)) return;
968
+ Logger.info(
969
+ `[plan-persist] Removing stale ${DELIVERY_LABELS.SINGLE} marker from ` +
970
+ `Epic #${epicId} (plan is fan-out-shaped now).`,
971
+ );
972
+ await provider.updateTicket(epicId, {
973
+ labels: { add: [], remove: [DELIVERY_LABELS.SINGLE] },
974
+ });
975
+ }
976
+
977
+ /**
978
+ * Render the `risk-verdict` structured-comment body. Lifted from
979
+ * `epic-plan-spec/phases/run-spec-phase.js` so the collapsed surface posts
980
+ * the byte-identical audit-trail comment (axis table + fenced-JSON record)
981
+ * downstream tooling parses.
982
+ *
983
+ * @param {{ epicId: number, riskVerdict: import('../planning-risk.js').RiskVerdict, planningRisk: import('../planning-risk.js').PlanningRiskEnvelope }} input
984
+ * @returns {string}
985
+ */
986
+ function buildRiskVerdictCommentBody({ epicId, riskVerdict, planningRisk }) {
987
+ const axisRows = planningRisk.axes.map(
988
+ (entry) => `| ${entry.axis} | ${entry.level} | ${entry.rationale} |`,
989
+ );
990
+ const axisTable =
991
+ axisRows.length > 0
992
+ ? ['| Axis | Level | Rationale |', '| --- | --- | --- |', ...axisRows]
993
+ : ['_No risk axes apply (planner-asserted)._'];
994
+ const record = {
995
+ kind: 'risk-verdict',
996
+ epicId,
997
+ verdict: riskVerdict,
998
+ planningRisk,
999
+ };
1000
+ const waiverNote = planningRisk.acceptanceWaivedReason
1001
+ ? ['', `> ⚠️ **Acceptance waived** — ${planningRisk.acceptanceWaivedReason}`]
1002
+ : [];
1003
+ return [
1004
+ `### 🧭 Planning Risk Verdict — ${planningRisk.overallLevel} · ${planningRisk.gateDecision}`,
1005
+ '',
1006
+ riskVerdict.summary,
1007
+ '',
1008
+ ...axisTable,
1009
+ ...waiverNote,
1010
+ '',
1011
+ '```json',
1012
+ JSON.stringify(record, null, 2),
1013
+ '```',
1014
+ ].join('\n');
1015
+ }