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
@@ -4,7 +4,7 @@
4
4
  * @module lib/orchestration/plan-persist/persist-helpers
5
5
  */
6
6
 
7
- import { gitSpawn } from '../../git-utils.js';
7
+ import { gitSpawn, pathExistsAtBase } from '../../git-utils.js';
8
8
  import { validateTaskBodies } from '../task-body-validator.js';
9
9
  import { validateAndNormalizeTickets } from '../ticket-validator.js';
10
10
  import { normalizeAcceptanceHandles } from './acceptance-handle-repair.js';
@@ -47,23 +47,6 @@ function resolveProbeRef({ baseBranch, cwd }) {
47
47
  return candidates.find((ref) => refResolves(ref, repo)) ?? null;
48
48
  }
49
49
 
50
- /**
51
- * The validator gates' own probe, so repair and gates agree on what is at
52
- * base.
53
- *
54
- * @param {{ baseBranchRef: string, path: string, cwd?: string }} opts
55
- * @returns {boolean}
56
- */
57
- function defaultGitRunner({ baseBranchRef, path, cwd }) {
58
- const result = gitSpawn(
59
- cwd ?? process.cwd(),
60
- 'cat-file',
61
- '-e',
62
- `${baseBranchRef}:${path}`,
63
- );
64
- return result.status === 0;
65
- }
66
-
67
50
  /**
68
51
  * With no base to read, a bare bullet is taken as an in-place edit.
69
52
  *
@@ -72,7 +55,7 @@ function defaultGitRunner({ baseBranchRef, path, cwd }) {
72
55
  */
73
56
  function makeExistsAtBase({ baseBranchRef, cwd, gitRunner }) {
74
57
  if (baseBranchRef === null) return () => true;
75
- const runner = gitRunner ?? defaultGitRunner;
58
+ const runner = gitRunner ?? pathExistsAtBase;
76
59
  return (path) => Boolean(runner({ baseBranchRef, path, cwd }));
77
60
  }
78
61
 
@@ -6,7 +6,7 @@
6
6
  */
7
7
 
8
8
  import { spawnSync } from 'node:child_process';
9
-
9
+ import { defaultSleep } from '../util/sleep.js';
10
10
  import { applyBehindUpdate } from './behind-recovery.js';
11
11
  import { createCancelledRunDiscount } from './cancelled-run-discount.js';
12
12
  import { checkVerdict } from './check-state.js';
@@ -88,10 +88,6 @@ function allGreen(outcomes) {
88
88
  return values.every((v) => checkVerdict(v) === 'pass');
89
89
  }
90
90
 
91
- function defaultSleep(ms) {
92
- return new Promise((resolve) => setTimeout(resolve, ms));
93
- }
94
-
95
91
  /**
96
92
  * Never poll an empty name set: `allTerminal({})` is vacuously true and would
97
93
  * report a red verdict with no failing check. `gh` overloads non-zero for
@@ -56,6 +56,21 @@ function readCacheFile(filePath) {
56
56
  }
57
57
  }
58
58
 
59
+ /** Tmp + rename: a reader never sees a partial write. Throws; reaps the tmp. */
60
+ function writeStoreAtomic(filePath, store) {
61
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
62
+ const tmp = `${filePath}.${process.pid}.tmp`;
63
+ try {
64
+ fs.writeFileSync(tmp, `${JSON.stringify(store, null, 2)}\n`, 'utf8');
65
+ fs.renameSync(tmp, filePath);
66
+ } catch (err) {
67
+ try {
68
+ fs.unlinkSync(tmp);
69
+ } catch {}
70
+ throw err;
71
+ }
72
+ }
73
+
59
74
  /**
60
75
  * A fresh entry with `options` re-hydrated to a Map, else `null`. Never throws.
61
76
  *
@@ -137,8 +152,7 @@ export function writeProjectMetaCache(opts = {}) {
137
152
  fieldId: meta.fieldId,
138
153
  options,
139
154
  };
140
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
141
- fs.writeFileSync(filePath, `${JSON.stringify(store, null, 2)}\n`, 'utf8');
155
+ writeStoreAtomic(filePath, store);
142
156
  return true;
143
157
  } catch {
144
158
  return false;
@@ -164,8 +178,7 @@ export function invalidateProjectMetaCache(opts = {}) {
164
178
  const store = readCacheFile(filePath);
165
179
  if (!(key in store)) return false;
166
180
  delete store[key];
167
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
168
- fs.writeFileSync(filePath, `${JSON.stringify(store, null, 2)}\n`, 'utf8');
181
+ writeStoreAtomic(filePath, store);
169
182
  return true;
170
183
  } catch {
171
184
  return false;
@@ -5,6 +5,7 @@
5
5
  * win that race; a one-shot mutation routinely lost it.
6
6
  */
7
7
 
8
+ import { defaultSleep } from '../util/sleep.js';
8
9
  import { ColumnSync, columnForLabels } from './column-sync.js';
9
10
 
10
11
  /** Four attempts at 5 s cover a ~15 s window past typical bot timing. */
@@ -12,14 +13,6 @@ const DEFAULT_POLL_ATTEMPTS = 4;
12
13
 
13
14
  const DEFAULT_POLL_DELAY_MS = 5000;
14
15
 
15
- /**
16
- * @param {number} ms
17
- * @returns {Promise<void>}
18
- */
19
- function defaultSleep(ms) {
20
- return new Promise((resolve) => setTimeout(resolve, ms));
21
- }
22
-
23
16
  function requirePositiveInt(value, name) {
24
17
  if (!Number.isInteger(value) || value <= 0) {
25
18
  throw new TypeError(
@@ -74,6 +74,7 @@ export function toStoryRecord(issue, requestedId, { allowUnlabelled } = {}) {
74
74
  url: issue?.html_url ?? issue?.url ?? null,
75
75
  labels,
76
76
  state: String(issue?.state ?? 'open').toLowerCase(),
77
+ stateReason: issue?.stateReason ?? issue?.state_reason ?? null,
77
78
  // The sole assignee is the Story lease holder; the live probe reads it to
78
79
  // withhold a Story another operator holds.
79
80
  assignees: Array.isArray(issue?.assignees)
@@ -17,7 +17,7 @@ import {
17
17
  classifyReport,
18
18
  } from '../../maintainability-engine.js';
19
19
  import { PROJECT_ROOT } from '../../project-root.js';
20
- import { transpileIfNeeded } from '../../transpile.js';
20
+ import { transpileForReport } from '../../transpile.js';
21
21
  import {
22
22
  resolveMaintainabilityIgnoreGlobs,
23
23
  scopeMaintainabilityFiles,
@@ -57,7 +57,7 @@ export function readHeadSource(relPath, headRef, gitSpawnFn = gitSpawn) {
57
57
  * @returns {ReturnType<typeof calculateReport>}
58
58
  */
59
59
  export function scoreSourceReport(source, relPath) {
60
- const prepared = transpileIfNeeded(relPath, source);
60
+ const prepared = transpileForReport(relPath, source);
61
61
  if (prepared === null) {
62
62
  return {
63
63
  moduleScore: 0,
@@ -0,0 +1,43 @@
1
+ import { Logger } from '../../Logger.js';
2
+
3
+ const progress = Logger.createProgress('single-story-close', { stderr: true });
4
+
5
+ /**
6
+ * Wall-clock seconds per named phase; each transition logs the phase it ends.
7
+ * Overlapping work `pause`s the clock and `record`s its own time.
8
+ *
9
+ * @param {() => number} [nowMs]
10
+ */
11
+ export function createPhaseTimer(nowMs = Date.now) {
12
+ const durations = {};
13
+ let current = null;
14
+ let since = 0;
15
+ const record = (phase, ms) => {
16
+ const seconds = Math.round(Math.max(0, ms) / 100) / 10;
17
+ durations[phase] = (durations[phase] ?? 0) + seconds;
18
+ progress('TIMING', `⏱ ${phase}: ${seconds}s`);
19
+ };
20
+ const end = () => {
21
+ if (current === null) return;
22
+ record(current, nowMs() - since);
23
+ current = null;
24
+ };
25
+ return {
26
+ enter(phase) {
27
+ end();
28
+ if (phase === 'init') return;
29
+ current = phase;
30
+ since = nowMs();
31
+ },
32
+ record,
33
+ pause: end,
34
+ finish() {
35
+ end();
36
+ return Object.keys(durations).length > 0 ? { ...durations } : null;
37
+ },
38
+ stamp(terminal) {
39
+ const phaseDurations = this.finish();
40
+ if (phaseDurations) terminal.phaseDurations = phaseDurations;
41
+ },
42
+ };
43
+ }
@@ -5,8 +5,11 @@
5
5
  * Two timing domains: `maxWaitSeconds` bounds THIS invocation (it must fit
6
6
  * the host's ~10-min tool ceiling after the close gates) and expires to a
7
7
  * resumable `pending` with no mutation; `maxBudgetSeconds` bounds the
8
- * cumulative wait, anchored at the PR's `createdAt` so resumes don't restart
9
- * it, and exhausting it is the real give-up (classify, emit, block). The
8
+ * cumulative wait, anchored at the latest auto-merge arm
9
+ * (`autoMergeRequest.enabledAt`, else the PR's `createdAt`): every close
10
+ * re-arms, so a re-close gets a fresh budget, while a `--wait` resume does
11
+ * not re-arm and keeps the clock. Exhausting it is the real give-up
12
+ * (classify, emit, block). The
10
13
  * poll is stateless and re-entrant. Async mode probes once (see
11
14
  * ASYNC_PROBE_WINDOW_SECONDS). Checks are probed every iteration so a red required
12
15
  * check fails fast instead of burning the budget.
@@ -25,6 +28,7 @@ import {
25
28
  readPrMergeState as defaultReadPrMergeState,
26
29
  } from '../../../single-story/confirm-merge.js';
27
30
  import { pollUntil } from '../../../util/poll-loop.js';
31
+ import { defaultSleep } from '../../../util/sleep.js';
28
32
  import { applyBehindUpdate } from '../../behind-recovery.js';
29
33
  import { isRerunPermitted } from '../../check-state.js';
30
34
  import { recordRequiredRed as defaultRecordRequiredRed } from '../../ci-red-handling.js';
@@ -78,7 +82,7 @@ export const DEFAULT_UPDATE_ATTEMPTS = 3;
78
82
 
79
83
  /**
80
84
  * Minimum polls before the cumulative budget may block: the clock is anchored
81
- * at `createdAt`, so a long-open PR is over budget on its first probe and
85
+ * at the latest arm, so a long-armed PR is over budget on its first probe and
82
86
  * would otherwise block without ever having waited.
83
87
  */
84
88
  export const MIN_POLLS_BEFORE_BUDGET_BLOCK = 2;
@@ -88,10 +92,6 @@ const CLOSED_UNMERGED_BLOCK_CLASS = 'api-race-other';
88
92
  const CLOSED_UNMERGED_REASON =
89
93
  'PR probe error: PR closed without merging (state=CLOSED)';
90
94
 
91
- function defaultSleep(ms) {
92
- return new Promise((resolve) => setTimeout(resolve, ms));
93
- }
94
-
95
95
  /** Spawn-level timeout kills a wedged `gh` child; injected `gh`s are bounded by withGhTimeout. */
96
96
  const defaultGh = createGh(undefined, { timeoutMs: MERGE_WAIT_GH_TIMEOUT_MS });
97
97
 
@@ -139,6 +139,17 @@ function readAutoMergeArmed(view) {
139
139
  return view.autoMergeRequest != null;
140
140
  }
141
141
 
142
+ /**
143
+ * When auto-merge was last armed — the budget anchor; `null` when disarmed
144
+ * or unreadable, so the anchor falls back to `createdAt`.
145
+ *
146
+ * @param {object|null|undefined} view
147
+ * @returns {string|null}
148
+ */
149
+ function readAutoMergeEnabledAt(view) {
150
+ return readString(view?.autoMergeRequest?.enabledAt, null);
151
+ }
152
+
142
153
  /**
143
154
  * `inMergeQueue` for a green open PR, the only state GitHub enqueues from;
144
155
  * `undefined` otherwise, so the common poll pays no extra call. An enqueued
@@ -197,6 +208,7 @@ export async function readPrWaitProbe({
197
208
  state: readString(view?.state, null),
198
209
  mergedAt: readString(view?.mergedAt, null),
199
210
  createdAt: readString(view?.createdAt, null),
211
+ autoMergeEnabledAt: readAutoMergeEnabledAt(view),
200
212
  mergeStateStatus: readString(view?.mergeStateStatus),
201
213
  reviewDecision: readString(view?.reviewDecision),
202
214
  checksStatus,
@@ -279,16 +291,27 @@ export function resolveMergeWaitConfig(
279
291
  };
280
292
  }
281
293
 
294
+ function parseTimestampMs(value) {
295
+ if (typeof value !== 'string' || !value) return null;
296
+ const parsed = Date.parse(value);
297
+ return Number.isFinite(parsed) ? parsed : null;
298
+ }
299
+
282
300
  /**
283
- * Budget anchor; without `createdAt` it falls back to this invocation's start
284
- * (worst case a fresh budget, never a premature block).
301
+ * Budget anchor: the later of `createdAt` and the auto-merge arm time
302
+ * (`enabledAt`), so a re-close that re-arms starts a fresh budget. With
303
+ * neither readable it falls back to this invocation's start (worst case a
304
+ * fresh budget, never a premature block).
285
305
  *
306
+ * @param {{ createdAt?: string|null, enabledAt?: string|null, fallbackMs: number }} args
286
307
  * @returns {number} epoch ms
287
308
  */
288
- export function resolveBudgetAnchorMs({ createdAt, fallbackMs }) {
289
- if (typeof createdAt !== 'string' || !createdAt) return fallbackMs;
290
- const parsed = Date.parse(createdAt);
291
- return Number.isFinite(parsed) ? parsed : fallbackMs;
309
+ export function resolveBudgetAnchorMs({ createdAt, enabledAt, fallbackMs }) {
310
+ const anchors = [
311
+ parseTimestampMs(createdAt),
312
+ parseTimestampMs(enabledAt),
313
+ ].filter((ms) => ms !== null);
314
+ return anchors.length > 0 ? Math.max(...anchors) : fallbackMs;
292
315
  }
293
316
 
294
317
  /**
@@ -1081,6 +1104,7 @@ export function decideMergeWaitPoll({
1081
1104
  }) {
1082
1105
  const anchorMs = resolveBudgetAnchorMs({
1083
1106
  createdAt: probe.createdAt,
1107
+ enabledAt: probe.autoMergeEnabledAt,
1084
1108
  fallbackMs: state.startedAtMs,
1085
1109
  });
1086
1110
  const waitedMs = nowMs - state.startedAtMs;
@@ -0,0 +1,264 @@
1
+ import { Logger } from '../../../Logger.js';
2
+ import {
3
+ buildTerminalEnvelope,
4
+ NEXT_COMMANDS,
5
+ terminalFromWaitOutcome,
6
+ } from '../../story-deliver-terminal.js';
7
+ import {
8
+ closeResult,
9
+ deriveObservedMerge,
10
+ elapsedSecondsSince,
11
+ emitTerminal,
12
+ } from '../result.js';
13
+ import { closeArmedPr, runAutoMergePhase } from './auto-merge.js';
14
+ import { lockWaitPending } from './lock-wait-pending.js';
15
+ import { runPostLandTail } from './post-land.js';
16
+
17
+ const progress = Logger.createProgress('single-story-close', { stderr: true });
18
+
19
+ /**
20
+ * An already-merged PR skips the arm (`gh pr merge` would fail and block it).
21
+ *
22
+ * @param {object} args
23
+ * @returns {Promise<{ autoMergeEnabled: boolean, autoMergeReason: string|null,
24
+ * localCleanupDeferred: boolean, directMerged: boolean }>}
25
+ */
26
+ export async function resolveAutoMergeOutcome({ alreadyMerged, ...phaseArgs }) {
27
+ if (alreadyMerged) {
28
+ return {
29
+ autoMergeEnabled: true,
30
+ autoMergeReason: null,
31
+ localCleanupDeferred: false,
32
+ directMerged: false,
33
+ advisoryGate: null,
34
+ };
35
+ }
36
+ return await runAutoMergePhase(phaseArgs);
37
+ }
38
+
39
+ /** One console line per non-landed wait ending, keyed by status. */
40
+ const WAIT_TERMINAL_LINES = Object.freeze({
41
+ pending: (terminal, { storyId, prUrl }) => [
42
+ 'PENDING',
43
+ `⏸ Story #${storyId}: PR ${prUrl} still in flight — resume with: ${terminal.nextCommand}`,
44
+ ],
45
+ failed: (terminal, { storyId, prUrl }) => [
46
+ 'FAILED',
47
+ `🛑 Story #${storyId}: PR ${prUrl} did not land (${terminal.phase}): ` +
48
+ `${terminal.failure?.reason}. Labels unchanged. Next: ${terminal.nextCommand}`,
49
+ ],
50
+ blocked: (terminal, { storyId, prUrl }) => [
51
+ 'BLOCKED',
52
+ `🛑 Story #${storyId}: PR ${prUrl} did not land ` +
53
+ `(blockClass=${terminal.blocked?.blockClass}). Story is at agent::blocked. ` +
54
+ `Next: ${terminal.nextCommand}`,
55
+ ],
56
+ landed: (_terminal, { storyId, prUrl }) => [
57
+ 'DONE',
58
+ `✅ Story #${storyId}: PR merged → ${prUrl}`,
59
+ ],
60
+ });
61
+
62
+ /**
63
+ * `pending` is not a failure: resumable, with its own CLI exit code.
64
+ *
65
+ * @param {{ status: string, nextCommand: string }} terminal
66
+ * @param {{ storyId: number, prUrl: string|null }} ctx
67
+ * @returns {void}
68
+ */
69
+ function reportWaitTerminal(terminal, ctx) {
70
+ const line =
71
+ WAIT_TERMINAL_LINES[terminal.status] ?? WAIT_TERMINAL_LINES.blocked;
72
+ progress(...line(terminal, ctx));
73
+ }
74
+
75
+ /**
76
+ * Reaped only by the post-land tail, and only when it actually removed the
77
+ * tree (a skipped reap reports ok with a detail).
78
+ *
79
+ * @param {object|null|undefined} tail
80
+ * @returns {boolean}
81
+ */
82
+ function tailReapedWorktree(tail) {
83
+ return tail?.worktreeReap === true && !tail?.details?.worktreeReap;
84
+ }
85
+
86
+ /**
87
+ * @param {object} prCtx
88
+ * @param {object} deps
89
+ * @returns {Promise<{ success: boolean, result: object, terminal: object }>}
90
+ */
91
+ export async function finishWithMergeWait(prCtx, deps) {
92
+ deps.setPhase('confirm-merge');
93
+ const waitOutcome = await deps.runConfirmMergePhase({
94
+ cwd: deps.cwd,
95
+ worktreePath: prCtx.worktreePath,
96
+ storyId: prCtx.storyId,
97
+ storyBranch: prCtx.storyBranch,
98
+ baseBranch: prCtx.baseBranch,
99
+ prNumber: prCtx.prNumber,
100
+ prUrl: prCtx.prUrl,
101
+ autoMergeEnabled: prCtx.autoMergeEnabled,
102
+ autoMergeReason: prCtx.autoMergeReason,
103
+ // Positive evidence for the re-arm rule: this close armed the PR.
104
+ closeArmed: closeArmedPr(prCtx),
105
+ advisoryGate: prCtx.advisoryGate,
106
+ provider: deps.provider,
107
+ config: prCtx.config,
108
+ maxWaitSeconds: deps.maxWaitSeconds,
109
+ mergeWatchMode: deps.mergeWatchMode,
110
+ rerunAdvisory: deps.rerunAdvisory,
111
+ progress,
112
+ injectedGh: deps.injectedGh,
113
+ injectedNotify: deps.injectedNotify,
114
+ runPostLandTailFn: (args) => {
115
+ deps.setPhase('post-land');
116
+ return runPostLandTail(args);
117
+ },
118
+ });
119
+ const terminal = terminalFromWaitOutcome({
120
+ waitOutcome,
121
+ storyId: prCtx.storyId,
122
+ storyBranch: prCtx.storyBranch,
123
+ baseBranch: prCtx.baseBranch,
124
+ prNumber: prCtx.prNumber,
125
+ prUrl: prCtx.prUrl,
126
+ autoMergeEnabled: prCtx.autoMergeEnabled,
127
+ autoMergeReason: prCtx.autoMergeReason,
128
+ gates: prCtx.gates,
129
+ lockWait: prCtx.lockWait,
130
+ suiteTimings: prCtx.suiteTimings,
131
+ elapsedSeconds: elapsedSecondsSince(prCtx.startedAtMs),
132
+ });
133
+ const result = closeResult({
134
+ storyId: prCtx.storyId,
135
+ storyBranch: prCtx.storyBranch,
136
+ baseBranch: prCtx.baseBranch,
137
+ prUrl: prCtx.prUrl,
138
+ prNumber: prCtx.prNumber,
139
+ autoMergeEnabled: prCtx.autoMergeEnabled,
140
+ autoMergeReason: prCtx.autoMergeReason,
141
+ worktreeReaped: tailReapedWorktree(waitOutcome.tail),
142
+ // Released by the post-land tail only; any other ending keeps the claim.
143
+ leaseReleased: waitOutcome.tail?.leaseRelease === true,
144
+ localCleanupDeferred: prCtx.localCleanupDeferred,
145
+ directMerged: prCtx.directMerged,
146
+ waitedForMerge: true,
147
+ merged: deriveObservedMerge({
148
+ waitOutcome,
149
+ directMerged: prCtx.directMerged,
150
+ }),
151
+ landCompleted: waitOutcome.confirmed === true,
152
+ });
153
+ await emitTerminal({
154
+ terminal,
155
+ result,
156
+ config: prCtx.config,
157
+ phaseTimer: prCtx.phaseTimer,
158
+ worker: prCtx.worker,
159
+ });
160
+ reportWaitTerminal(terminal, { storyId: prCtx.storyId, prUrl: prCtx.prUrl });
161
+ return { success: terminal.status === 'landed', result, terminal };
162
+ }
163
+
164
+ /**
165
+ * The no-wait ending: a human owns the land, so it is `pending` with one
166
+ * command to finish it. A direct merge by the arm is still observed.
167
+ *
168
+ * @param {object} prCtx
169
+ * @param {string} waitForMergeReason
170
+ * @returns {Promise<{ success: boolean, result: object, terminal: object }>}
171
+ */
172
+ export async function finishWithoutMergeWait(prCtx, waitForMergeReason) {
173
+ const merged = deriveObservedMerge({ directMerged: prCtx.directMerged });
174
+ const result = closeResult({
175
+ storyId: prCtx.storyId,
176
+ storyBranch: prCtx.storyBranch,
177
+ baseBranch: prCtx.baseBranch,
178
+ prUrl: prCtx.prUrl,
179
+ prNumber: prCtx.prNumber,
180
+ autoMergeEnabled: prCtx.autoMergeEnabled,
181
+ autoMergeReason: prCtx.autoMergeReason,
182
+ leaseReleased: false,
183
+ localCleanupDeferred: prCtx.localCleanupDeferred,
184
+ directMerged: prCtx.directMerged,
185
+ merged,
186
+ // The flip, issue close and tail belong to `nextCommand`.
187
+ landCompleted: false,
188
+ });
189
+ const terminal = buildTerminalEnvelope({
190
+ storyId: prCtx.storyId,
191
+ status: 'pending',
192
+ phase: 'auto-merge',
193
+ storyBranch: prCtx.storyBranch,
194
+ baseBranch: prCtx.baseBranch,
195
+ pr: {
196
+ number: prCtx.prNumber,
197
+ url: prCtx.prUrl ?? null,
198
+ state: merged ? 'MERGED' : 'OPEN',
199
+ autoMergeEnabled: Boolean(prCtx.autoMergeEnabled),
200
+ autoMergeReason: prCtx.autoMergeReason ?? null,
201
+ },
202
+ gates: prCtx.gates,
203
+ lockWait: prCtx.lockWait,
204
+ suiteTimings: prCtx.suiteTimings,
205
+ nextCommand: NEXT_COMMANDS.confirmMerge(prCtx.storyId),
206
+ elapsedSeconds: elapsedSecondsSince(prCtx.startedAtMs),
207
+ });
208
+ await emitTerminal({
209
+ terminal,
210
+ result,
211
+ config: prCtx.config,
212
+ phaseTimer: prCtx.phaseTimer,
213
+ worker: prCtx.worker,
214
+ });
215
+ progress(
216
+ 'DONE',
217
+ `✅ Story #${prCtx.storyId}: PR ready → ${prCtx.prUrl} (${waitForMergeReason})`,
218
+ );
219
+ return { success: true, result, terminal };
220
+ }
221
+
222
+ /**
223
+ * A full-suite lock wait expired: `pending`, nothing pushed.
224
+ *
225
+ * @param {{ waitedSeconds: number, expired: boolean }|null} lockWait
226
+ * @param {{ storyId: number, storyBranch: string, baseBranch: string,
227
+ * config: object, startedAtMs: number }} ctx
228
+ * @returns {Promise<{ success: false, result: object, terminal: object }>}
229
+ */
230
+ export async function finishDeferred(
231
+ lockWait,
232
+ { config, startedAtMs, phaseTimer, worker, ...ids },
233
+ ) {
234
+ const { result, terminal, note } = lockWaitPending({
235
+ ...ids,
236
+ lockWait,
237
+ elapsedSeconds: elapsedSecondsSince(startedAtMs),
238
+ });
239
+ await emitTerminal({ terminal, result, config, phaseTimer, worker });
240
+ progress('PENDING', note);
241
+ return { success: false, result, terminal };
242
+ }
243
+
244
+ /**
245
+ * @param {{ waitForMergeReason: string, autoMergeReason: string|null,
246
+ * storyId: number, waitForMergeExplicit?: boolean }} args
247
+ * @returns {void}
248
+ */
249
+ export function reportOperatorMergeSkip({
250
+ waitForMergeReason,
251
+ autoMergeReason,
252
+ storyId,
253
+ waitForMergeExplicit,
254
+ }) {
255
+ if (waitForMergeReason !== 'operator-merge') return;
256
+ progress(
257
+ 'MERGE',
258
+ `⏭ Not waiting for merge (${autoMergeReason}) — the operator owns this merge; ` +
259
+ `Story #${storyId} rests at agent::closing.` +
260
+ (waitForMergeExplicit === true
261
+ ? ' --wait-merge cannot land a PR that was deliberately left un-armed.'
262
+ : ''),
263
+ );
264
+ }
@@ -0,0 +1,68 @@
1
+ import { Logger } from '../../../Logger.js';
2
+ import { discardHeldReview, reviewAfterPrOpen } from '../review-overlap.js';
3
+ import { parsePrNumber } from './code-review.js';
4
+ import { ensurePullRequestWith } from './pull-request.js';
5
+ import { pushStoryBranch } from './push.js';
6
+ import { resolveReviewHalt } from './review-halt.js';
7
+
8
+ const progress = Logger.createProgress('single-story-close', { stderr: true });
9
+
10
+ export async function openAndReviewPr(ctx, deps) {
11
+ const { options, worktreePath, story, storyId, storyBranch, baseBranch } =
12
+ ctx;
13
+ const { cwd } = options;
14
+ ctx.setPhase('push');
15
+ // Push from the worktree so `pre-push` measures the tree being sent; the
16
+ // ref-based reads below resolve identically from the shared `.git`.
17
+ pushStoryBranch({
18
+ cwd,
19
+ worktreePath,
20
+ storyBranch,
21
+ gitSync: deps.git.gitSync,
22
+ progress,
23
+ });
24
+ ctx.setPhase('pull-request');
25
+ const { url: prUrl, alreadyMerged } = await ensurePullRequestWith({
26
+ cwd,
27
+ storyId,
28
+ storyTitle: story.title,
29
+ storyBody: story.body,
30
+ storyBranch,
31
+ baseBranch,
32
+ gh: deps.gh,
33
+ progress,
34
+ });
35
+ const prNumber = parsePrNumber(prUrl);
36
+ ctx.recordPrNumber(prNumber);
37
+ // Already merged (landed between invocations): skip review and arm; confirm observes it.
38
+ if (alreadyMerged) {
39
+ discardHeldReview(ctx.heldReview, 'PR already merged', progress);
40
+ return { prUrl, prNumber, alreadyMerged: true };
41
+ }
42
+ const reviewOutcome = await reviewAfterPrOpen({
43
+ held: ctx.heldReview,
44
+ cwd,
45
+ storyId,
46
+ storyBranch,
47
+ baseBranch,
48
+ prUrl,
49
+ prNumber,
50
+ provider: deps.provider,
51
+ runCodeReviewFn: deps.runCodeReview,
52
+ gitSpawnFn: deps.git.gitSpawn,
53
+ progress,
54
+ setPhase: ctx.setPhase,
55
+ pauseTimer: ctx.phaseTimer.pause,
56
+ recordDuration: ctx.phaseTimer.record,
57
+ });
58
+ const reviewOverride = reviewOutcome.halted
59
+ ? await resolveReviewHalt(ctx, deps, { prUrl, prNumber, reviewOutcome })
60
+ : null;
61
+ return {
62
+ prUrl,
63
+ prNumber,
64
+ alreadyMerged: false,
65
+ reviewOverride,
66
+ reviewDegraded: reviewOutcome.degraded === true,
67
+ };
68
+ }