mandrel 2.87.0 → 2.89.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 (170) hide show
  1. package/.agents/README.md +29 -0
  2. package/.agents/agents/auditor.md +4 -3
  3. package/.agents/docs/agentrc-reference.json +5 -2
  4. package/.agents/docs/configuration.md +14 -8
  5. package/.agents/docs/workflows.md +1 -1
  6. package/.agents/schemas/agentrc.schema.json +24 -5
  7. package/.agents/schemas/story-deliver-terminal.schema.json +1 -1
  8. package/.agents/schemas/story-progress.schema.json +5 -0
  9. package/.agents/scripts/audit-to-stories.js +3 -2
  10. package/.agents/scripts/boot-sweep.js +3 -2
  11. package/.agents/scripts/check-arch-cycles.js +19 -41
  12. package/.agents/scripts/check-context-budget.js +16 -44
  13. package/.agents/scripts/check-cyclomatic.js +13 -37
  14. package/.agents/scripts/check-dead-exports.js +16 -46
  15. package/.agents/scripts/clean-worktrees.js +1 -6
  16. package/.agents/scripts/coverage-capture.js +32 -49
  17. package/.agents/scripts/deliver-run.js +11 -0
  18. package/.agents/scripts/diagnose-friction.js +3 -3
  19. package/.agents/scripts/lib/audit-baselines/gate-surface.js +24 -11
  20. package/.agents/scripts/lib/audit-baselines/read.js +4 -2
  21. package/.agents/scripts/lib/audit-baselines/surface-entry.js +95 -11
  22. package/.agents/scripts/lib/baselines/coverage-updater-cli.js +6 -14
  23. package/.agents/scripts/lib/baselines/crap-preview-scan.js +3 -1
  24. package/.agents/scripts/lib/baselines/crap-updater-cli.js +38 -26
  25. package/.agents/scripts/lib/baselines/duplication-scanner.js +20 -1
  26. package/.agents/scripts/lib/baselines/env-overrides.js +39 -34
  27. package/.agents/scripts/lib/baselines/kernel.js +3 -2
  28. package/.agents/scripts/lib/baselines/kinds/crap.js +50 -53
  29. package/.agents/scripts/lib/baselines/preview-gates.js +5 -1
  30. package/.agents/scripts/lib/baselines/refresh-service.js +65 -22
  31. package/.agents/scripts/lib/baselines/writer.js +5 -1
  32. package/.agents/scripts/lib/bdd-runner-detect.js +7 -10
  33. package/.agents/scripts/lib/child-exec.js +14 -1
  34. package/.agents/scripts/lib/child-stream.js +122 -0
  35. package/.agents/scripts/lib/clean-temp.js +19 -13
  36. package/.agents/scripts/lib/cli-args.js +49 -0
  37. package/.agents/scripts/lib/close-validation/gates.js +40 -9
  38. package/.agents/scripts/lib/codex/skills-projection.js +1 -12
  39. package/.agents/scripts/lib/config/gates/crap.schema.js +15 -0
  40. package/.agents/scripts/lib/config/gates/mutation.schema.js +2 -2
  41. package/.agents/scripts/lib/config/gh-config-dir.js +63 -0
  42. package/.agents/scripts/lib/config/github.js +2 -0
  43. package/.agents/scripts/lib/config/paths.js +14 -3
  44. package/.agents/scripts/lib/config/quality.js +49 -1
  45. package/.agents/scripts/lib/config-resolver.js +78 -64
  46. package/.agents/scripts/lib/config-settings-schema-delivery.js +4 -3
  47. package/.agents/scripts/lib/config-settings-schema.js +7 -0
  48. package/.agents/scripts/lib/coverage-baseline.js +2 -2
  49. package/.agents/scripts/lib/coverage-capture-affected.js +2 -1
  50. package/.agents/scripts/lib/coverage-capture-fullscope.js +2 -2
  51. package/.agents/scripts/lib/coverage-capture-incremental.js +1 -1
  52. package/.agents/scripts/lib/coverage-capture-passes.js +143 -0
  53. package/.agents/scripts/lib/coverage-capture-usage.js +1 -1
  54. package/.agents/scripts/lib/coverage-capture.js +45 -15
  55. package/.agents/scripts/lib/crap-utils.js +65 -49
  56. package/.agents/scripts/lib/full-suite-lock.js +1 -10
  57. package/.agents/scripts/lib/gates/baseline-store.js +10 -0
  58. package/.agents/scripts/lib/generated/agentrc-validator.js +1 -1
  59. package/.agents/scripts/lib/gh-exec.js +45 -2
  60. package/.agents/scripts/lib/gh-transport.js +27 -0
  61. package/.agents/scripts/lib/git-utils.js +16 -9
  62. package/.agents/scripts/lib/maintainability-engine.js +27 -6
  63. package/.agents/scripts/lib/maintainability-utils.js +20 -2
  64. package/.agents/scripts/lib/orchestration/check-baselines/phases/evaluate.js +4 -1
  65. package/.agents/scripts/lib/orchestration/evidence-stream.js +186 -0
  66. package/.agents/scripts/lib/orchestration/file-assumptions.js +2 -19
  67. package/.agents/scripts/lib/orchestration/git-cleanup/phases/branches-reap.js +3 -7
  68. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes-ff.js +34 -40
  69. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes.js +4 -3
  70. package/.agents/scripts/lib/orchestration/plan-persist/persist-helpers.js +2 -19
  71. package/.agents/scripts/lib/orchestration/pr-watch.js +1 -5
  72. package/.agents/scripts/lib/orchestration/project-meta-cache.js +17 -4
  73. package/.agents/scripts/lib/orchestration/reassert-status-column.js +1 -8
  74. package/.agents/scripts/lib/orchestration/resolve-stories.js +1 -0
  75. package/.agents/scripts/lib/orchestration/review-providers/native.js +2 -2
  76. package/.agents/scripts/lib/orchestration/single-story-close/phase-timer.js +43 -0
  77. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +37 -13
  78. package/.agents/scripts/lib/orchestration/single-story-close/phases/finish.js +264 -0
  79. package/.agents/scripts/lib/orchestration/single-story-close/phases/open-pr.js +68 -0
  80. package/.agents/scripts/lib/orchestration/single-story-close/phases/pre-push.js +106 -0
  81. package/.agents/scripts/lib/orchestration/single-story-close/phases/reconcile-done.js +43 -35
  82. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-halt.js +52 -0
  83. package/.agents/scripts/lib/orchestration/single-story-close/result.js +273 -0
  84. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +68 -776
  85. package/.agents/scripts/lib/orchestration/story-close/context-budget-writeback.js +20 -9
  86. package/.agents/scripts/lib/orchestration/story-close/duplication-close-rescore.js +2 -2
  87. package/.agents/scripts/lib/orchestration/story-close/ratchet-shrink-writeback.js +20 -12
  88. package/.agents/scripts/lib/orchestration/story-handoff.js +50 -21
  89. package/.agents/scripts/lib/orchestration/story-progress.js +32 -12
  90. package/.agents/scripts/lib/orchestration/ticket-validator.js +3 -13
  91. package/.agents/scripts/lib/orchestration/verify-credit.js +4 -1
  92. package/.agents/scripts/lib/qa/resolve-selection.js +1 -8
  93. package/.agents/scripts/lib/single-story/confirm-and-land.js +33 -0
  94. package/.agents/scripts/lib/single-story-sweep/reconcile-closing.js +43 -11
  95. package/.agents/scripts/lib/single-story-sweep/sweep-lock.js +130 -30
  96. package/.agents/scripts/lib/skills/parse-skill.js +1 -4
  97. package/.agents/scripts/lib/story-body/story-body.js +12 -1
  98. package/.agents/scripts/lib/suite-admission.js +3 -11
  99. package/.agents/scripts/lib/temp-retention.js +25 -11
  100. package/.agents/scripts/lib/test-run-credit.js +2 -5
  101. package/.agents/scripts/lib/transpile.js +193 -31
  102. package/.agents/scripts/lib/util/paths.js +31 -0
  103. package/.agents/scripts/lib/util/sleep.js +15 -0
  104. package/.agents/scripts/lib/validation-evidence.js +29 -3
  105. package/.agents/scripts/lib/wave-runner/live-probe.js +24 -0
  106. package/.agents/scripts/lib/workers/crap-worker.js +23 -12
  107. package/.agents/scripts/lib/workers/maintainability-report-worker.js +18 -12
  108. package/.agents/scripts/lib/workflow-closure.js +1 -8
  109. package/.agents/scripts/notify.js +83 -90
  110. package/.agents/scripts/plan-context.js +8 -4
  111. package/.agents/scripts/providers/github/auth.js +14 -30
  112. package/.agents/scripts/providers/github/blocked-by-add.js +11 -27
  113. package/.agents/scripts/providers/github/compose.js +1 -0
  114. package/.agents/scripts/providers/github/gh-token-diagnostics.js +130 -0
  115. package/.agents/scripts/providers/github/identity.js +158 -0
  116. package/.agents/scripts/providers/github/issues.js +2 -2
  117. package/.agents/scripts/providers/github/mappers.js +16 -19
  118. package/.agents/scripts/providers/github/projects-v2-graphql.js +4 -36
  119. package/.agents/scripts/providers/github/request-helpers.js +44 -0
  120. package/.agents/scripts/providers/github/sub-issue-add.js +11 -28
  121. package/.agents/scripts/providers/github.js +10 -2
  122. package/.agents/scripts/quality-preview.js +6 -19
  123. package/.agents/scripts/single-story-confirm-merge.js +8 -20
  124. package/.agents/scripts/single-story-init.js +0 -1
  125. package/.agents/scripts/stories-wave-tick.js +60 -46
  126. package/.agents/scripts/story-handoff.js +2 -23
  127. package/.agents/scripts/story-review-compute.js +3 -22
  128. package/.agents/scripts/sync-claude-agents.js +1 -12
  129. package/.agents/scripts/sync-claude-commands.js +1 -12
  130. package/.agents/scripts/update-crap-baseline.js +11 -20
  131. package/.agents/scripts/update-ticket-state.js +44 -45
  132. package/.agents/templates/docs/audit-sweep-runbook.md +1 -1
  133. package/.agents/workflows/audit-accessibility.md +1 -1
  134. package/.agents/workflows/audit-adrs.md +1 -1
  135. package/.agents/workflows/audit-architecture.md +1 -1
  136. package/.agents/workflows/audit-baselines.md +9 -4
  137. package/.agents/workflows/audit-clean-code.md +1 -1
  138. package/.agents/workflows/audit-data-model.md +1 -1
  139. package/.agents/workflows/audit-dependencies.md +1 -1
  140. package/.agents/workflows/audit-devops.md +1 -1
  141. package/.agents/workflows/audit-documentation.md +1 -1
  142. package/.agents/workflows/audit-exceptions.md +2 -2
  143. package/.agents/workflows/audit-mobile.md +1 -1
  144. package/.agents/workflows/audit-navigability.md +1 -1
  145. package/.agents/workflows/audit-performance.md +1 -1
  146. package/.agents/workflows/audit-privacy.md +1 -1
  147. package/.agents/workflows/audit-quality.md +1 -1
  148. package/.agents/workflows/audit-security.md +1 -1
  149. package/.agents/workflows/audit-seo.md +1 -1
  150. package/.agents/workflows/audit-sre.md +1 -1
  151. package/.agents/workflows/audit-to-stories.md +9 -7
  152. package/.agents/workflows/audit-ux-ui.md +1 -1
  153. package/.agents/workflows/helpers/audit-lens-core.md +8 -5
  154. package/.agents/workflows/helpers/deliver-digest.md +4 -5
  155. package/.agents/workflows/helpers/deliver-story-reference.md +4 -4
  156. package/.agents/workflows/mandrel-deliver.md +3 -1
  157. package/README.md +6 -3
  158. package/docs/CHANGELOG.md +42 -0
  159. package/lib/cli/doctor-checks/codex.js +240 -0
  160. package/lib/cli/doctor-checks/merge-driver.js +79 -0
  161. package/lib/cli/doctor-checks/payload.js +201 -0
  162. package/lib/cli/doctor-checks/read-json.js +16 -0
  163. package/lib/cli/doctor-checks/runtime-deps.js +146 -0
  164. package/lib/cli/doctor-checks/spawn.js +18 -0
  165. package/lib/cli/doctor-checks/sync-parity.js +205 -0
  166. package/lib/cli/doctor-checks/test-credit-path.js +270 -0
  167. package/lib/cli/doctor-checks/toolchain.js +137 -0
  168. package/lib/cli/doctor-checks/version-current.js +82 -0
  169. package/lib/cli/registry.js +40 -1330
  170. package/package.json +1 -1
@@ -0,0 +1,106 @@
1
+ import { Logger } from '../../../Logger.js';
2
+ import { discardHeldReview, startHeldReview } from '../review-overlap.js';
3
+ import { runBaseSyncPhase } from './base-sync.js';
4
+ import { runCloseValidationPhase } from './close-validation.js';
5
+ import { runWrongTreeGuardPhase } from './wrong-tree-guard.js';
6
+
7
+ const progress = Logger.createProgress('single-story-close', { stderr: true });
8
+
9
+ /**
10
+ * wrong-tree guard → base-sync → close-validation. Validation runs last so
11
+ * the validated tree is the pushed tree (base-sync's merge commit included),
12
+ * and a cheap conflict is found before the expensive gates.
13
+ *
14
+ * @param {object} ctx
15
+ * @param {object} deps
16
+ * @returns {Promise<{
17
+ * validationGates: Record<string, string>|null,
18
+ * lockWait: { waitedSeconds: number, expired: boolean }|null,
19
+ * suiteTimings: object|null,
20
+ * pending: boolean,
21
+ * }>} `validationGates` is null when skipped; `pending` means a full-suite
22
+ * lock wait expired and the gates deferred.
23
+ */
24
+ export async function runPrePushPhases(ctx, deps) {
25
+ const { options, worktreePath, baseBranch, storyBranch, storyId, setPhase } =
26
+ ctx;
27
+ const { cwd } = options;
28
+ setPhase('wrong-tree-guard');
29
+ await runWrongTreeGuardPhase({
30
+ cwd,
31
+ worktreePath,
32
+ baseBranch,
33
+ storyId,
34
+ provider: deps.provider,
35
+ progress,
36
+ gitSpawn: deps.gitSpawn,
37
+ });
38
+ if (!options.skipSync) {
39
+ setPhase('base-sync');
40
+ await runBaseSyncPhase({
41
+ cwd,
42
+ worktreePath,
43
+ baseBranch,
44
+ baseConfirmed: ctx.baseConfirmed,
45
+ storyBranch,
46
+ storyId,
47
+ provider: deps.provider,
48
+ injectedSync: deps.sync,
49
+ progress,
50
+ });
51
+ } else {
52
+ progress('SYNC', '⏭ Skipped (--skip-sync).');
53
+ }
54
+ if (options.skipValidation) {
55
+ progress('VALIDATE', '⏭ Skipped (--skip-validation).');
56
+ return {
57
+ validationGates: null,
58
+ lockWait: null,
59
+ suiteTimings: null,
60
+ pending: false,
61
+ };
62
+ }
63
+ setPhase('close-validation');
64
+ let validation;
65
+ try {
66
+ validation = await runCloseValidationPhase({
67
+ cwd,
68
+ worktreePath,
69
+ config: deps.config,
70
+ baseBranch,
71
+ storyBranch,
72
+ storyId,
73
+ progress,
74
+ runCloseValidation: deps.runCloseValidation,
75
+ buildDefaultGates: deps.buildDefaultGates,
76
+ onPreGateStepsDone: () => {
77
+ ctx.heldReview = startHeldReview({
78
+ cwd,
79
+ storyId,
80
+ storyBranch,
81
+ baseBranch,
82
+ provider: deps.provider,
83
+ runCodeReviewFn: deps.runCodeReview,
84
+ gitSpawnFn: deps.git.gitSpawn,
85
+ progress,
86
+ config: deps.config,
87
+ });
88
+ },
89
+ });
90
+ } catch (err) {
91
+ discardHeldReview(ctx.heldReview, 'validation failed', progress);
92
+ // The gate that died is all this run observed; the envelope claims no more.
93
+ if (typeof err?.closeGate === 'string') {
94
+ ctx.setObservedGates({ [err.closeGate]: 'failed' });
95
+ }
96
+ throw err;
97
+ }
98
+ const gates = validation?.gates ?? null;
99
+ ctx.setObservedGates(gates);
100
+ return {
101
+ validationGates: gates,
102
+ lockWait: validation?.lockWait ?? null,
103
+ suiteTimings: validation?.suiteTimings ?? null,
104
+ pending: validation?.pending === true,
105
+ };
106
+ }
@@ -1,16 +1,11 @@
1
1
  /**
2
- * phases/reconcile-done.js — a Story closed as completed can still carry a
3
- * stale lifecycle label: a close that blocked before auto-merge landed its
4
- * PR leaves `agent::blocked` on the closed issue, and the re-run takes the
5
- * already-closed early return. With merge evidence on the Story branch, this
6
- * finishes the flip through the shared `agent::done` confirm. Best-effort —
7
- * the land already happened, so nothing here may change the `landed`
8
- * terminal; every failure is logged and swallowed.
2
+ * phases/reconcile-done.js — finish a closed Story's stale label: with a
3
+ * MERGED PR, flip and run the land tail. Best-effort; failures are logged.
9
4
  */
10
5
 
11
6
  import { gh as defaultGh } from '../../../gh-exec.js';
12
7
  import { Logger } from '../../../Logger.js';
13
- import { confirmStoryMerged } from '../../../single-story/confirm-merge.js';
8
+ import { confirmAndLand } from '../../../single-story/confirm-and-land.js';
14
9
  import { STATE_LABELS } from '../../ticketing.js';
15
10
  import { parsePrNumber } from './code-review.js';
16
11
  import { pickHeadPullRequest } from './pull-request.js';
@@ -22,13 +17,13 @@ const UNLANDED_CLOSE_REASONS = new Set(['not_planned', 'duplicate']);
22
17
  * @param {{ storyId: number, storyBranch: string, options: { cwd: string },
23
18
  * story: { labels?: string[], stateReason?: string|null } }} ctx
24
19
  * @param {{ provider: object, config: object, gh?: object,
25
- * notify?: Function, sleep?: Function }} deps
20
+ * notify?: Function, sleep?: Function, runPostLandTail?: Function }} deps
26
21
  * @param {(tag: string, msg: string) => void} progress
27
22
  * @returns {Promise<string>} `skipped` | `no-merged-pr` | `error` | the
28
23
  * `confirmStoryMerged` action.
29
24
  */
30
25
  export async function reconcileDoneLabel(ctx, deps, progress) {
31
- const { storyId, story, storyBranch } = ctx;
26
+ const { storyId, story } = ctx;
32
27
  if (
33
28
  UNLANDED_CLOSE_REASONS.has(story.stateReason) ||
34
29
  story.labels?.includes(STATE_LABELS.DONE)
@@ -36,31 +31,7 @@ export async function reconcileDoneLabel(ctx, deps, progress) {
36
31
  return 'skipped';
37
32
  }
38
33
  try {
39
- const rows = await (deps.gh ?? defaultGh).pr.list(
40
- ['--head', storyBranch, '--state', 'all'],
41
- ['url', 'state', 'mergedAt'],
42
- );
43
- const head = pickHeadPullRequest(rows);
44
- if (head?.state !== 'MERGED') {
45
- progress(
46
- 'NOOP',
47
- `No merged PR on ${storyBranch} — leaving Story #${storyId}'s labels as they are.`,
48
- );
49
- return 'no-merged-pr';
50
- }
51
- const confirmed = await confirmStoryMerged({
52
- provider: deps.provider,
53
- storyId,
54
- prNumber: parsePrNumber(head.url),
55
- prUrl: head.url,
56
- cwd: ctx.options.cwd,
57
- config: deps.config,
58
- progress,
59
- injectedNotify: deps.notify,
60
- prState: { state: 'MERGED', mergedAt: null },
61
- sleepFn: deps.sleep,
62
- });
63
- return confirmed.action;
34
+ return await reconcileFromMergedHead(ctx, deps, progress);
64
35
  } catch (err) {
65
36
  Logger.warn(
66
37
  `[single-story-close] ⚠️ Could not reconcile Story #${storyId} to agent::done: ${err?.message ?? err}`,
@@ -68,3 +39,40 @@ export async function reconcileDoneLabel(ctx, deps, progress) {
68
39
  return 'error';
69
40
  }
70
41
  }
42
+
43
+ /** The Story branch's head PR, or `null` when it is not MERGED. */
44
+ async function readMergedHead(storyBranch, gh) {
45
+ const rows = await (gh ?? defaultGh).pr.list(
46
+ ['--head', storyBranch, '--state', 'all'],
47
+ ['url', 'state', 'mergedAt'],
48
+ );
49
+ const head = pickHeadPullRequest(rows);
50
+ return head?.state === 'MERGED' ? head : null;
51
+ }
52
+
53
+ async function reconcileFromMergedHead(ctx, deps, progress) {
54
+ const { storyId, storyBranch } = ctx;
55
+ const head = await readMergedHead(storyBranch, deps.gh);
56
+ if (!head) {
57
+ progress(
58
+ 'NOOP',
59
+ `No merged PR on ${storyBranch} — leaving Story #${storyId}'s labels as they are.`,
60
+ );
61
+ return 'no-merged-pr';
62
+ }
63
+ const { confirmation } = await confirmAndLand({
64
+ provider: deps.provider,
65
+ storyId,
66
+ prNumber: parsePrNumber(head.url),
67
+ prUrl: head.url,
68
+ cwd: ctx.options.cwd,
69
+ config: deps.config,
70
+ progress,
71
+ injectedNotify: deps.notify,
72
+ prState: { state: 'MERGED', mergedAt: null },
73
+ sleepFn: deps.sleep,
74
+ storyBranch,
75
+ runPostLandTailFn: deps.runPostLandTail,
76
+ });
77
+ return confirmation.action;
78
+ }
@@ -0,0 +1,52 @@
1
+ import { emitReviewBlockedFriction } from '../../../observability/close-telemetry.js';
2
+ import { handleCriticalReviewBlock } from './review-block.js';
3
+ import { handleOverriddenReviewBlock } from './review-override.js';
4
+
5
+ /**
6
+ * An overridden Story proceeds; anything else emits friction, blocks, throws.
7
+ *
8
+ * @param {object} ctx
9
+ * @param {object} deps
10
+ * @param {{ prUrl: string, prNumber: number|null, reviewOutcome: object }} pr
11
+ * @returns {Promise<object>}
12
+ */
13
+ export async function resolveReviewHalt(
14
+ ctx,
15
+ deps,
16
+ { prUrl, prNumber, reviewOutcome },
17
+ ) {
18
+ const { storyId } = ctx;
19
+ const criticalCount = reviewOutcome.severity?.critical ?? 0;
20
+ // Checked before the blocked transition: an overridden Story proceeds.
21
+ if (ctx.options.overrideReviewBlock) {
22
+ return await handleOverriddenReviewBlock({
23
+ provider: deps.provider,
24
+ storyId,
25
+ prUrl,
26
+ prNumber,
27
+ criticalCount,
28
+ criticalByProvider: reviewOutcome.criticalByProvider,
29
+ reason: ctx.options.overrideReviewBlock,
30
+ config: deps.config,
31
+ });
32
+ }
33
+ await emitReviewBlockedFriction({
34
+ storyId,
35
+ prNumber,
36
+ criticalCount,
37
+ criticalByProvider: reviewOutcome.criticalByProvider,
38
+ config: deps.config,
39
+ });
40
+ await handleCriticalReviewBlock({
41
+ provider: deps.provider,
42
+ storyId,
43
+ prUrl,
44
+ criticalCount,
45
+ });
46
+ throw new Error(
47
+ `[single-story-close] Story-scope review reported ${criticalCount} critical blocker(s) on PR ${prUrl}. ` +
48
+ 'Auto-merge was not enabled. Remediate the findings posted to the PR and re-run `/mandrel-deliver`. ' +
49
+ 'If you have reviewed a finding and judged it wrong, re-run with ' +
50
+ '`--override-review-block "<reason>"` rather than merging by hand.',
51
+ );
52
+ }
@@ -0,0 +1,273 @@
1
+ import { BASELINES_GATE_NAMES } from '../../close-validation/gates.js';
2
+ import { Logger } from '../../Logger.js';
3
+ import { recordCloseTelemetry } from '../../observability/close-telemetry.js';
4
+ import { emitTerminalFriction } from '../../observability/runtime-friction.js';
5
+ import { emitTerseResult } from '../../observability/terse-result.js';
6
+ import { MERGED_FLIP_FAILED_BLOCK_CLASS } from '../lifecycle/emit-merge-flip-failed.js';
7
+ import {
8
+ buildTerminalEnvelope,
9
+ emitTerminalEnvelope,
10
+ NEXT_COMMANDS,
11
+ } from '../story-deliver-terminal.js';
12
+ import { deriveCloseNote } from './close-note.js';
13
+
14
+ const progress = Logger.createProgress('single-story-close', { stderr: true });
15
+
16
+ const UNTIMED = Object.freeze({ stamp() {} });
17
+
18
+ /** No worker figures: an inline close, or an ending before they resolve. */
19
+ const NO_WORKER = Object.freeze({
20
+ workerTokens: null,
21
+ workerModel: null,
22
+ workerEffort: null,
23
+ });
24
+
25
+ /**
26
+ * The single terminal writer: the retry signal, the result summary (with its
27
+ * `telemetry`), the envelope callers parse, and terminal friction — so no
28
+ * ending can forget one. Must be awaited: the CLI `process.exit`s as soon as
29
+ * `main` resolves.
30
+ */
31
+ export async function emitTerminal({
32
+ terminal,
33
+ result,
34
+ config,
35
+ phaseTimer = UNTIMED,
36
+ worker = NO_WORKER,
37
+ }) {
38
+ phaseTimer.stamp(terminal);
39
+ await recordCloseTelemetry({ terminal, result, config, ...worker });
40
+ if (result) {
41
+ emitTerseResult({
42
+ label: 'STORY CLOSE RESULT',
43
+ result,
44
+ scope: result.storyId,
45
+ summary: {
46
+ storyId: result.storyId,
47
+ action: result.action,
48
+ reason: result.reason,
49
+ prNumber: result.prNumber,
50
+ status: terminal?.status,
51
+ },
52
+ });
53
+ }
54
+ emitTerminalEnvelope(terminal, { config });
55
+ await emitTerminalFriction({ envelope: terminal, config });
56
+ }
57
+
58
+ /**
59
+ * @param {number} storyId
60
+ * @param {string} reason
61
+ * @returns {{ storyId: number, standalone: true, action: 'noop', reason: string }}
62
+ */
63
+ function noopResult(storyId, reason) {
64
+ return { storyId, standalone: true, action: 'noop', reason };
65
+ }
66
+
67
+ /** Close reasons meaning nothing merged — superseded or abandoned. */
68
+ const UNLANDED_CLOSE_REASONS = new Set(['not_planned', 'duplicate']);
69
+
70
+ /**
71
+ * Terminal for an already-closed Story. `not_planned` / `duplicate` mean
72
+ * nothing merged, so it fails rather than reporting `landed` (which would
73
+ * also unblock dependents); `completed` or null (GitHub's default) reads as
74
+ * landed.
75
+ */
76
+ export async function alreadyClosedResult(
77
+ storyId,
78
+ stateReason = null,
79
+ config,
80
+ worker = NO_WORKER,
81
+ ) {
82
+ if (UNLANDED_CLOSE_REASONS.has(stateReason)) {
83
+ progress(
84
+ 'NOOP',
85
+ `Story #${storyId} is closed as not planned — nothing to land.`,
86
+ );
87
+ const result = noopResult(storyId, 'closed-not-planned');
88
+ const terminal = buildTerminalEnvelope({
89
+ storyId,
90
+ status: 'failed',
91
+ phase: 'init',
92
+ failure: {
93
+ reason:
94
+ `Story #${storyId} is closed as not planned (superseded or abandoned) — ` +
95
+ 'there is nothing to land. Re-plan it as a new Story, or pass a Story that is still open.',
96
+ },
97
+ nextCommand: null,
98
+ elapsedSeconds: 0,
99
+ });
100
+ await emitTerminal({ terminal, result, config, worker });
101
+ return { success: false, result, terminal };
102
+ }
103
+
104
+ progress('NOOP', `Story #${storyId} is already closed. Nothing to do.`);
105
+ const result = noopResult(storyId, 'already-closed');
106
+ const terminal = buildTerminalEnvelope({
107
+ storyId,
108
+ status: 'landed',
109
+ phase: 'done',
110
+ nextCommand: null,
111
+ elapsedSeconds: 0,
112
+ });
113
+ await emitTerminal({ terminal, result, config, worker });
114
+ return { success: true, result, terminal };
115
+ }
116
+
117
+ /**
118
+ * Reuses the classifier's fallback class: the vocabulary is pinned by the
119
+ * terminal schema, so `reason` names the blocker instead.
120
+ */
121
+ const PREFLIGHT_BLOCK_CLASS = 'api-race-other';
122
+
123
+ /**
124
+ * Returned, not thrown: a classified block, not a crash (a throw surfaces as
125
+ * `failed`). The next command is the same close.
126
+ *
127
+ * @param {{ storyId: number, preflight: { verdict: string, reason: string },
128
+ * config: object, startedAtMs: number }} args
129
+ * @returns {Promise<{ success: false, result: object, terminal: object }>}
130
+ */
131
+ export async function preflightBlockedResult({
132
+ storyId,
133
+ preflight,
134
+ config,
135
+ startedAtMs,
136
+ worker = NO_WORKER,
137
+ }) {
138
+ const result = noopResult(storyId, `graphql-preflight-${preflight.verdict}`);
139
+ const terminal = buildTerminalEnvelope({
140
+ storyId,
141
+ status: 'blocked',
142
+ phase: 'init',
143
+ blocked: {
144
+ blockClass: PREFLIGHT_BLOCK_CLASS,
145
+ reason: preflight.reason,
146
+ frictionCommentId: null,
147
+ },
148
+ nextCommand: NEXT_COMMANDS.close(storyId),
149
+ elapsedSeconds: elapsedSecondsSince(startedAtMs),
150
+ });
151
+ await emitTerminal({ terminal, result, config, worker });
152
+ return { success: false, result, terminal };
153
+ }
154
+
155
+ /**
156
+ * The split baselines gates, by name; only registered ones, never a phantom key.
157
+ *
158
+ * @param {Record<string, string>|null|undefined} validationGates
159
+ * @returns {Record<string, string>}
160
+ */
161
+ function baselinesEnvelopeGates(validationGates) {
162
+ const registered = Object.values(BASELINES_GATE_NAMES);
163
+ const out = {};
164
+ for (const [name, outcome] of Object.entries(validationGates ?? {})) {
165
+ if (registered.includes(name)) out[name] = outcome;
166
+ }
167
+ return out;
168
+ }
169
+
170
+ /**
171
+ * `overridden` > `degraded` > `passed`: an override records the human
172
+ * decision on a failed review; `degraded` says a review surface produced no
173
+ * verdict (reported, not blocking — a secondary review does not gate merge).
174
+ *
175
+ * @param {object|null} reviewOverride
176
+ * @param {boolean} [reviewDegraded]
177
+ * @returns {'overridden'|'degraded'|'passed'}
178
+ */
179
+ function codeReviewGate(reviewOverride, reviewDegraded) {
180
+ if (reviewOverride) return 'overridden';
181
+ return reviewDegraded ? 'degraded' : 'passed';
182
+ }
183
+
184
+ /**
185
+ * @param {{ skipValidation?: boolean, skipSync?: boolean }} options
186
+ * @param {Record<string, string>|null} validationGates
187
+ * @param {object|null} reviewOverride
188
+ * @param {boolean} [reviewDegraded]
189
+ * @returns {Record<string, string>}
190
+ */
191
+ export function closeEnvelopeGates(
192
+ options,
193
+ validationGates,
194
+ reviewOverride,
195
+ reviewDegraded,
196
+ ) {
197
+ return {
198
+ validation: options.skipValidation ? 'skipped' : 'passed',
199
+ ...baselinesEnvelopeGates(validationGates),
200
+ baseSync: options.skipSync ? 'skipped' : 'passed',
201
+ codeReview: codeReviewGate(reviewOverride, reviewDegraded),
202
+ };
203
+ }
204
+
205
+ /**
206
+ * Did this run OBSERVE the merge — confirmed, merged-but-flip-failed, or
207
+ * direct-merged? Observation only, never intent.
208
+ *
209
+ * @param {{ waitOutcome?: object|null, directMerged?: boolean }} args
210
+ * @returns {boolean}
211
+ */
212
+ export function deriveObservedMerge({
213
+ waitOutcome = null,
214
+ directMerged = false,
215
+ }) {
216
+ return (
217
+ waitOutcome?.confirmed === true ||
218
+ waitOutcome?.blockClass === MERGED_FLIP_FAILED_BLOCK_CLASS ||
219
+ directMerged === true
220
+ );
221
+ }
222
+
223
+ export function closeResult({
224
+ storyId,
225
+ storyBranch,
226
+ baseBranch,
227
+ prUrl,
228
+ prNumber,
229
+ autoMergeEnabled,
230
+ autoMergeReason,
231
+ worktreeReaped = false,
232
+ leaseReleased,
233
+ localCleanupDeferred = false,
234
+ directMerged = false,
235
+ waitedForMerge = false,
236
+ merged = false,
237
+ landCompleted = merged,
238
+ }) {
239
+ return {
240
+ storyId,
241
+ standalone: true,
242
+ storyBranch,
243
+ baseBranch,
244
+ prUrl,
245
+ prNumber,
246
+ pushed: true,
247
+ autoMergeEnabled,
248
+ autoMergeReason,
249
+ worktreeReaped,
250
+ leaseReleased,
251
+ // `gh`'s local branch delete failed while the remote merge/arm stood.
252
+ localCleanupDeferred,
253
+ // No native auto-merge, so the arm squash-merged directly.
254
+ directMerged,
255
+ waitedForMerge,
256
+ merged,
257
+ // Never from `waitedForMerge`; `merged` can be true without a completed land.
258
+ note: deriveCloseNote({
259
+ merged,
260
+ directMerged,
261
+ autoMergeEnabled,
262
+ landCompleted,
263
+ }),
264
+ };
265
+ }
266
+
267
+ /**
268
+ * @param {number} startedAtMs
269
+ * @returns {number}
270
+ */
271
+ export function elapsedSecondsSince(startedAtMs) {
272
+ return Math.round((Date.now() - startedAtMs) / 1000);
273
+ }