mandrel 2.111.0 → 2.113.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 (183) hide show
  1. package/.agents/agents/acceptance-critic.md +14 -0
  2. package/.agents/agents/auditor.md +14 -0
  3. package/.agents/agents/plan-critic.md +5 -0
  4. package/.agents/agents/story-worker.md +4 -1
  5. package/.agents/docs/agentrc-reference.json +22 -10
  6. package/.agents/docs/configuration.md +367 -37
  7. package/.agents/docs/execution-reference.md +11 -0
  8. package/.agents/rules/git-conventions-reference.md +7 -0
  9. package/.agents/schemas/agentrc.schema.json +174 -14
  10. package/.agents/schemas/baselines/baseline-envelope.schema.json +16 -4
  11. package/.agents/schemas/baselines/bundle-size.schema.json +1 -0
  12. package/.agents/schemas/baselines/coverage.schema.json +1 -0
  13. package/.agents/schemas/baselines/crap.schema.json +37 -10
  14. package/.agents/schemas/baselines/duplication.schema.json +1 -0
  15. package/.agents/schemas/baselines/maintainability.schema.json +1 -0
  16. package/.agents/schemas/baselines/mutation.schema.json +1 -0
  17. package/.agents/schemas/crap-report.schema.json +6 -5
  18. package/.agents/schemas/story-deliver-terminal.schema.json +41 -2
  19. package/.agents/schemas/story-progress.schema.json +1 -1
  20. package/.agents/schemas/validation-evidence.schema.json +2 -2
  21. package/.agents/scripts/boot-sweep.js +41 -3
  22. package/.agents/scripts/coverage-capture.js +37 -3
  23. package/.agents/scripts/coverage-ratchet.js +106 -0
  24. package/.agents/scripts/evidence-gate.js +84 -21
  25. package/.agents/scripts/lib/audit-baselines/read.js +8 -1
  26. package/.agents/scripts/lib/audit-baselines/trend.js +2 -1
  27. package/.agents/scripts/lib/baseline-loader.js +4 -2
  28. package/.agents/scripts/lib/baselines/codec.js +57 -0
  29. package/.agents/scripts/lib/baselines/crap-preview-incremental.js +8 -3
  30. package/.agents/scripts/lib/baselines/crap-preview-scan.js +10 -16
  31. package/.agents/scripts/lib/baselines/crap-updater-cli.js +4 -13
  32. package/.agents/scripts/lib/baselines/kernel.js +19 -1
  33. package/.agents/scripts/lib/baselines/kinds/_crap-codec.js +171 -0
  34. package/.agents/scripts/lib/baselines/kinds/_crap-read.js +56 -16
  35. package/.agents/scripts/lib/baselines/kinds/_shared-metric.js +0 -59
  36. package/.agents/scripts/lib/baselines/kinds/crap.js +283 -319
  37. package/.agents/scripts/lib/baselines/merge-envelopes.js +46 -1
  38. package/.agents/scripts/lib/baselines/preview-gates.js +29 -10
  39. package/.agents/scripts/lib/baselines/reader.js +36 -9
  40. package/.agents/scripts/lib/baselines/refresh-service.js +93 -21
  41. package/.agents/scripts/lib/baselines/seat-missing.js +173 -7
  42. package/.agents/scripts/lib/baselines/writer.js +36 -21
  43. package/.agents/scripts/lib/changed-files.js +70 -6
  44. package/.agents/scripts/lib/child-exec.js +10 -0
  45. package/.agents/scripts/lib/claude/agents-projection.js +5 -5
  46. package/.agents/scripts/lib/close-lock-events.js +8 -3
  47. package/.agents/scripts/lib/close-validation/ci-deferral.js +40 -0
  48. package/.agents/scripts/lib/close-validation/gates.js +111 -35
  49. package/.agents/scripts/lib/close-validation/process.js +16 -7
  50. package/.agents/scripts/lib/close-validation/projections/crap.js +43 -10
  51. package/.agents/scripts/lib/close-validation/runner.js +55 -23
  52. package/.agents/scripts/lib/close-validation/skip-branch-test.js +144 -0
  53. package/.agents/scripts/lib/close-validation/test-delta.js +33 -8
  54. package/.agents/scripts/lib/codex/agents-projection.js +6 -0
  55. package/.agents/scripts/lib/config/agentrc-overlay.js +9 -5
  56. package/.agents/scripts/lib/config/explain.js +5 -2
  57. package/.agents/scripts/lib/config/gates/coverage.schema.js +45 -1
  58. package/.agents/scripts/lib/config/gates/crap-incremental-coverage.schema.js +1 -1
  59. package/.agents/scripts/lib/config/git-roots.js +38 -4
  60. package/.agents/scripts/lib/config/handoff.js +24 -0
  61. package/.agents/scripts/lib/config/quality.js +26 -13
  62. package/.agents/scripts/lib/config/worktree-isolation.js +2 -5
  63. package/.agents/scripts/lib/config-resolver.js +22 -2
  64. package/.agents/scripts/lib/config-settings-schema-delivery.js +87 -4
  65. package/.agents/scripts/lib/config-settings-schema-quality.js +36 -1
  66. package/.agents/scripts/lib/config-settings-schema.js +1 -1
  67. package/.agents/scripts/lib/coverage-capture-affected.js +1 -0
  68. package/.agents/scripts/lib/coverage-capture-delta.js +164 -32
  69. package/.agents/scripts/lib/coverage-capture-own-fix.js +232 -0
  70. package/.agents/scripts/lib/coverage-capture-usage.js +2 -2
  71. package/.agents/scripts/lib/coverage-capture.js +15 -0
  72. package/.agents/scripts/lib/coverage-deferral.js +96 -0
  73. package/.agents/scripts/lib/coverage-ratchet.js +187 -0
  74. package/.agents/scripts/lib/crap-baseline-join.js +5 -5
  75. package/.agents/scripts/lib/crap-engine.js +3 -3
  76. package/.agents/scripts/lib/crap-method-identity.js +104 -48
  77. package/.agents/scripts/lib/error-redactor.js +20 -0
  78. package/.agents/scripts/lib/escomplex-anchor.js +135 -0
  79. package/.agents/scripts/lib/escomplex-kernel.js +30 -1
  80. package/.agents/scripts/lib/failure-rows.js +121 -0
  81. package/.agents/scripts/lib/full-suite-lock.js +44 -4
  82. package/.agents/scripts/lib/full-suite-queue.js +89 -13
  83. package/.agents/scripts/lib/generated/agentrc-validator.js +8 -2
  84. package/.agents/scripts/lib/gh-env.js +3 -6
  85. package/.agents/scripts/lib/gh-pr-rest.js +1 -0
  86. package/.agents/scripts/lib/git/base-sync-probe.js +182 -0
  87. package/.agents/scripts/lib/git/baseline-conflict-rows.js +60 -0
  88. package/.agents/scripts/lib/git/sync-from-base.js +18 -9
  89. package/.agents/scripts/lib/git-branch-lifecycle.js +9 -0
  90. package/.agents/scripts/lib/observability/close-telemetry.js +37 -2
  91. package/.agents/scripts/lib/observability/handoff-telemetry.js +170 -0
  92. package/.agents/scripts/lib/observability/review-dispositions.js +23 -6
  93. package/.agents/scripts/lib/observability/runtime-friction.js +17 -4
  94. package/.agents/scripts/lib/observability/source-classifier.js +3 -0
  95. package/.agents/scripts/lib/observability/story-outcome.js +393 -0
  96. package/.agents/scripts/lib/orchestration/check-baselines/phases/compare.js +2 -1
  97. package/.agents/scripts/lib/orchestration/check-baselines/phases/evaluate.js +19 -1
  98. package/.agents/scripts/lib/orchestration/check-baselines/phases/fail-detail.js +84 -0
  99. package/.agents/scripts/lib/orchestration/check-baselines/phases/pipeline.js +14 -5
  100. package/.agents/scripts/lib/orchestration/check-baselines/phases/refresh-ack.js +3 -2
  101. package/.agents/scripts/lib/orchestration/check-baselines/phases/report.js +26 -6
  102. package/.agents/scripts/lib/orchestration/code-review.js +223 -19
  103. package/.agents/scripts/lib/orchestration/handoff-gates.js +129 -62
  104. package/.agents/scripts/lib/orchestration/handoff-rescore.js +170 -0
  105. package/.agents/scripts/lib/orchestration/handoff-suite-of-record.js +45 -0
  106. package/.agents/scripts/lib/orchestration/preflight-lanes.js +208 -0
  107. package/.agents/scripts/lib/orchestration/review-base-ref.js +40 -17
  108. package/.agents/scripts/lib/orchestration/review-deposit.js +38 -12
  109. package/.agents/scripts/lib/orchestration/review-depth.js +21 -0
  110. package/.agents/scripts/lib/orchestration/review-history.js +124 -20
  111. package/.agents/scripts/lib/orchestration/review-providers/claude-verdict.js +41 -12
  112. package/.agents/scripts/lib/orchestration/review-providers/code-review.js +90 -39
  113. package/.agents/scripts/lib/orchestration/review-providers/critical-verifier.js +64 -11
  114. package/.agents/scripts/lib/orchestration/review-providers/degraded-gates.js +102 -3
  115. package/.agents/scripts/lib/orchestration/review-providers/finding-identity.js +6 -2
  116. package/.agents/scripts/lib/orchestration/review-providers/findings-renderer.js +55 -8
  117. package/.agents/scripts/lib/orchestration/review-providers/review-guidance.js +1 -0
  118. package/.agents/scripts/lib/orchestration/review-providers/review-provider-factory.js +42 -15
  119. package/.agents/scripts/lib/orchestration/review-providers/types.js +6 -0
  120. package/.agents/scripts/lib/orchestration/single-story-close/failed-terminal.js +10 -1
  121. package/.agents/scripts/lib/orchestration/single-story-close/gate-log.js +10 -0
  122. package/.agents/scripts/lib/orchestration/single-story-close/phases/base-sync.js +7 -4
  123. package/.agents/scripts/lib/orchestration/single-story-close/phases/close-validation.js +16 -3
  124. package/.agents/scripts/lib/orchestration/single-story-close/phases/code-review.js +59 -2
  125. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +6 -0
  126. package/.agents/scripts/lib/orchestration/single-story-close/phases/finish.js +15 -4
  127. package/.agents/scripts/lib/orchestration/single-story-close/phases/land-review-record.js +213 -0
  128. package/.agents/scripts/lib/orchestration/single-story-close/phases/normalize-pr-title.js +9 -12
  129. package/.agents/scripts/lib/orchestration/single-story-close/phases/open-pr.js +26 -12
  130. package/.agents/scripts/lib/orchestration/single-story-close/phases/post-land.js +51 -26
  131. package/.agents/scripts/lib/orchestration/single-story-close/phases/pre-gate-steps.js +2 -1
  132. package/.agents/scripts/lib/orchestration/single-story-close/phases/pre-push.js +3 -2
  133. package/.agents/scripts/lib/orchestration/single-story-close/phases/pull-request.js +50 -17
  134. package/.agents/scripts/lib/orchestration/single-story-close/phases/push.js +59 -11
  135. package/.agents/scripts/lib/orchestration/single-story-close/phases/reconcile-done.js +1 -0
  136. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-block.js +31 -13
  137. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-halt.js +29 -6
  138. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-outcome.js +10 -12
  139. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-override.js +19 -4
  140. package/.agents/scripts/lib/orchestration/single-story-close/result.js +30 -13
  141. package/.agents/scripts/lib/orchestration/single-story-close/review-overlap.js +73 -39
  142. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +11 -3
  143. package/.agents/scripts/lib/orchestration/story-close/baseline-upward-writeback.js +3 -2
  144. package/.agents/scripts/lib/orchestration/story-close/duplication-close-rescore.js +77 -15
  145. package/.agents/scripts/lib/orchestration/story-deliver-terminal.js +7 -0
  146. package/.agents/scripts/lib/orchestration/story-handoff.js +796 -196
  147. package/.agents/scripts/lib/orchestration/ticketing/reads.js +2 -0
  148. package/.agents/scripts/lib/pr-body-lines.js +32 -0
  149. package/.agents/scripts/lib/single-story/ci-ratchet-gate.js +140 -0
  150. package/.agents/scripts/lib/single-story/confirm-and-land.js +17 -7
  151. package/.agents/scripts/lib/single-story/confirm-merge.js +12 -3
  152. package/.agents/scripts/lib/single-story-sweep/report-stalled-executing.js +202 -0
  153. package/.agents/scripts/lib/standalone-ratchets.js +37 -0
  154. package/.agents/scripts/lib/suite-admission.js +20 -8
  155. package/.agents/scripts/lib/suite-sizing.js +146 -0
  156. package/.agents/scripts/lib/workspace-provisioner.js +2 -2
  157. package/.agents/scripts/merge-baseline.js +14 -3
  158. package/.agents/scripts/providers/github/comments.js +19 -3
  159. package/.agents/scripts/providers/github.js +1 -0
  160. package/.agents/scripts/review-dispositions-report.js +1 -1
  161. package/.agents/scripts/role-scope-guard.js +267 -0
  162. package/.agents/scripts/single-story-close.js +4 -4
  163. package/.agents/scripts/single-story-confirm-merge.js +31 -5
  164. package/.agents/scripts/single-story-init.js +24 -4
  165. package/.agents/scripts/story-handoff.js +3 -3
  166. package/.agents/scripts/story-outcomes-report.js +231 -0
  167. package/.agents/scripts/story-review-compute.js +9 -5
  168. package/.agents/scripts/update-coverage-baseline.js +12 -2
  169. package/.agents/scripts/update-crap-baseline.js +9 -1
  170. package/.agents/workflows/helpers/code-review.md +63 -9
  171. package/.agents/workflows/helpers/deliver-digest.md +53 -54
  172. package/.agents/workflows/helpers/deliver-reference.md +233 -67
  173. package/.agents/workflows/helpers/deliver-story-reference.md +19 -8
  174. package/.agents/workflows/helpers/deliver-story.md +7 -2
  175. package/.agents/workflows/helpers/parallel-tooling.md +29 -0
  176. package/docs/CHANGELOG.md +55 -0
  177. package/lib/cli/doctor-checks/coverage-ratchet.js +54 -0
  178. package/lib/cli/doctor-checks/effective-agentrc.js +23 -0
  179. package/lib/cli/doctor-checks/llm-review.js +2 -11
  180. package/lib/cli/doctor-checks/sync-parity.js +5 -1
  181. package/lib/cli/doctor-checks/test-credit-path.js +7 -2
  182. package/lib/cli/registry.js +5 -0
  183. package/package.json +1 -1
@@ -63,6 +63,8 @@ export const STRUCTURED_COMMENT_TYPES = Object.freeze([
63
63
  // The source ticket's pre-plan title and body, posted once before a
64
64
  // one-for-one rewrite; first write wins, so re-plans keep the original.
65
65
  'plan-rewrite',
66
+ // Opt-in per-Story close outcome record, upserted on every close attempt.
67
+ 'story-outcome',
66
68
  ]);
67
69
 
68
70
  export const WAVE_TYPE_PATTERN = WAVE_MARKER_RE;
@@ -0,0 +1,32 @@
1
+ /** pr-body-lines.js — keep a block of owned PR-body lines beneath `Closes #<id>`. */
2
+
3
+ /** `lines` minus owned lines and the blank line each one follows. */
4
+ function withoutOwnedLines(lines, isOwned) {
5
+ const kept = [];
6
+ for (const line of lines) {
7
+ if (!isOwned(line)) kept.push(line);
8
+ else if (kept.at(-1) === '') kept.pop();
9
+ }
10
+ return kept;
11
+ }
12
+
13
+ /** The index just beneath `Closes #<id>`, else the end. */
14
+ function closesSlot(lines) {
15
+ const at = lines.findIndex((line) => /^Closes #\d+/.test(line));
16
+ return at === -1 ? lines.length : at + 1;
17
+ }
18
+
19
+ /**
20
+ * `body` with every line `isOwned` claims replaced by `block`, placed beneath
21
+ * `Closes #<id>` (appended when that line is missing).
22
+ *
23
+ * @param {string|null|undefined} body
24
+ * @param {(line: string) => boolean} isOwned
25
+ * @param {string[]} block
26
+ * @returns {string}
27
+ */
28
+ export function replaceBeneathCloses(body, isOwned, block) {
29
+ const kept = withoutOwnedLines(String(body ?? '').split(/\r?\n/), isOwned);
30
+ kept.splice(closesSlot(kept), 0, ...block);
31
+ return kept.join('\n');
32
+ }
@@ -0,0 +1,140 @@
1
+ /**
2
+ * ci-ratchet-gate.js — confirm-merge's hold on a PR whose coverage was
3
+ * deferred to CI. With `coverage.ciRatchetCheck` set, a merged PR carrying
4
+ * the `Coverage-deferred:` key line is confirmed only once that check is
5
+ * green on the PR head: absent or in flight stays pending; completed
6
+ * without success (failure, error, timed out, cancelled, startup failure,
7
+ * action required) blocks.
8
+ */
9
+
10
+ import { resolveQuality } from '../config/quality.js';
11
+ import { readDeferralMarker } from '../coverage-deferral.js';
12
+ import { gh as defaultGh } from '../gh-exec.js';
13
+ import { Logger } from '../Logger.js';
14
+ import {
15
+ checkVerdict,
16
+ classifyRollupEntry,
17
+ } from '../orchestration/check-state.js';
18
+ import { isRunInFlight, readRunName } from '../orchestration/merge-poll.js';
19
+ import {
20
+ STATE_LABELS,
21
+ transitionTicketState,
22
+ upsertStructuredComment,
23
+ } from '../orchestration/ticketing.js';
24
+
25
+ /** @param {object} run @returns {boolean} */
26
+ function isGreen(run) {
27
+ const verdict = String(run?.conclusion || run?.state || '').toUpperCase();
28
+ return verdict === 'SUCCESS';
29
+ }
30
+
31
+ /**
32
+ * The declared check's verdict on the PR head's rollup: a green re-run wins,
33
+ * then one in flight, then red; no matching run is `absent`.
34
+ *
35
+ * @param {Array<object>|null|undefined} rollup @param {string} checkName
36
+ * @returns {'green'|'in-flight'|'red'|'absent'}
37
+ */
38
+ function ratchetVerdict(rollup, checkName) {
39
+ const runs = (Array.isArray(rollup) ? rollup : []).filter(
40
+ (run) => readRunName(run) === checkName,
41
+ );
42
+ if (runs.some(isGreen)) return 'green';
43
+ if (runs.some(isRunInFlight)) return 'in-flight';
44
+ return runs.some((run) => checkVerdict(classifyRollupEntry(run)) === 'fail')
45
+ ? 'red'
46
+ : 'absent';
47
+ }
48
+
49
+ /** Post the friction comment and flip `agent::blocked`; each write best-effort. */
50
+ async function blockOnRedRatchet({ provider, storyId, detail }) {
51
+ try {
52
+ await upsertStructuredComment(
53
+ provider,
54
+ storyId,
55
+ 'friction',
56
+ `### confirm-merge blocked: ci-ratchet-red\n\n${detail}\n\nThe deferred code landed without its coverage and CRAP ratchet; an operator must decide, then re-run \`single-story-confirm-merge.js\`.`,
57
+ );
58
+ await transitionTicketState(provider, storyId, STATE_LABELS.BLOCKED, {});
59
+ } catch (err) {
60
+ Logger.warn(
61
+ `[single-story-confirm-merge] ⚠️ ci-ratchet block write failed: ${err?.message ?? err}`,
62
+ );
63
+ }
64
+ }
65
+
66
+ /**
67
+ * `null` when confirmation may proceed; otherwise the result to return in
68
+ * place of the `agent::done` flip.
69
+ *
70
+ * @param {{ config?: object, prNumber: number, storyId: number, provider: object,
71
+ * gh?: object, progress?: Function, blockFn?: typeof blockOnRedRatchet }} args
72
+ * @returns {Promise<object|null>}
73
+ */
74
+ export async function holdForCiRatchet({
75
+ config,
76
+ prNumber,
77
+ storyId,
78
+ provider,
79
+ gh = defaultGh,
80
+ progress,
81
+ blockFn = blockOnRedRatchet,
82
+ }) {
83
+ const coverage = config?.delivery?.quality?.gates?.coverage;
84
+ const { ciRatchetCheck } = resolveQuality({ gates: { coverage } }).coverage;
85
+ if (!ciRatchetCheck) return null;
86
+ const view = await gh.pr.view(prNumber, ['body', 'statusCheckRollup']);
87
+ if (!readDeferralMarker(view?.body)) return null;
88
+ const verdict = ratchetVerdict(view?.statusCheckRollup, ciRatchetCheck);
89
+ if (verdict === 'green') return null;
90
+ const named = `CI ratchet check "${ciRatchetCheck}" on PR #${prNumber}`;
91
+ if (verdict !== 'red') {
92
+ progress?.(
93
+ 'CONFIRM',
94
+ `⏳ ${named} is ${verdict}. Story stays at agent::closing.`,
95
+ );
96
+ return {
97
+ storyId,
98
+ action: 'pending',
99
+ reason: 'ci-ratchet-pending',
100
+ merged: false,
101
+ };
102
+ }
103
+ const detail = `${named} is red: the coverage was deferred to CI and its ratchet failed after the merge.`;
104
+ progress?.('CONFIRM', `🛑 ${detail} Story → agent::blocked.`);
105
+ await blockFn({ provider, storyId, detail });
106
+ return {
107
+ storyId,
108
+ action: 'blocked',
109
+ reason: 'ci-ratchet-red',
110
+ detail,
111
+ merged: false,
112
+ };
113
+ }
114
+
115
+ /**
116
+ * Close's merge-wait outcome for a confirmation the ratchet held, else
117
+ * `null`: `pending` (resumable) or `blocked` as `checks-failed`.
118
+ *
119
+ * @param {{ action: string, reason?: string, detail?: string }} confirmation
120
+ * @param {{ prProbe?: object, elapsedSeconds?: number }} wait
121
+ * @returns {object|null}
122
+ */
123
+ export function ratchetWaitOutcome(confirmation, { prProbe, elapsedSeconds }) {
124
+ if (!String(confirmation.reason ?? '').startsWith('ci-ratchet-')) return null;
125
+ const common = {
126
+ confirmed: false,
127
+ elapsedSeconds,
128
+ prProbe: { ...(prProbe ?? {}), state: 'MERGED' },
129
+ };
130
+ if (confirmation.action === 'pending') {
131
+ return { ...common, terminal: 'pending', reason: confirmation.reason };
132
+ }
133
+ return {
134
+ ...common,
135
+ terminal: 'blocked',
136
+ blockClass: 'checks-failed',
137
+ reason: confirmation.detail,
138
+ frictionCommentId: null,
139
+ };
140
+ }
@@ -1,6 +1,21 @@
1
1
  import { runPostLandTail as defaultRunPostLandTail } from '../orchestration/single-story-close/phases/post-land.js';
2
2
  import { confirmStoryMerged } from './confirm-merge.js';
3
3
 
4
+ /** The confirm arguments the land tail also takes. */
5
+ function landTailArgs({ storyId, prNumber, prUrl, injectedGh, ...rest }) {
6
+ const { cwd, provider, config, progress } = rest;
7
+ return {
8
+ storyId,
9
+ prNumber,
10
+ prUrl,
11
+ gh: injectedGh,
12
+ cwd,
13
+ provider,
14
+ config,
15
+ progress,
16
+ };
17
+ }
18
+
4
19
  /**
5
20
  * Confirm, then the land tail when merged — shared by every merged-Story
6
21
  * path, since a flip alone strands the lease and worktree.
@@ -19,15 +34,10 @@ export async function confirmAndLand({
19
34
  }) {
20
35
  const confirmation = await confirmStoryMerged(confirmArgs);
21
36
  if (confirmation.merged !== true) return { confirmation, tail: null };
22
- const { storyId, cwd, provider, config, progress } = confirmArgs;
23
37
  const tail = await runPostLandTailFn({
24
- storyId,
38
+ ...landTailArgs(confirmArgs),
25
39
  storyBranch,
26
- baseBranch: baseBranch ?? config?.project?.baseBranch ?? 'main',
27
- cwd,
28
- provider,
29
- config,
30
- progress,
40
+ baseBranch: baseBranch ?? confirmArgs.config?.project?.baseBranch ?? 'main',
31
41
  });
32
42
  return { confirmation, tail };
33
43
  }
@@ -17,6 +17,7 @@ import {
17
17
  transitionTicketState,
18
18
  } from '../orchestration/ticketing.js';
19
19
  import { sleep as defaultSleep } from '../util/poll-loop.js';
20
+ import { holdForCiRatchet } from './ci-ratchet-gate.js';
20
21
 
21
22
  /**
22
23
  * Backoff before each RETRY of the post-merge done flip (so attempts =
@@ -98,9 +99,11 @@ export async function confirmStoryMerged({
98
99
  gh: injectedGh,
99
100
  }));
100
101
 
101
- if (!isPrMerged({ state, mergedAt })) {
102
- return pendingResult({ storyId, prNumber, state, progress });
103
- }
102
+ const held = await unconfirmedResult({
103
+ pr: { state, mergedAt },
104
+ ratchet: { config, prNumber, storyId, provider, progress, gh: injectedGh },
105
+ });
106
+ if (held) return held;
104
107
 
105
108
  // Best-effort: a flaky API must not crash confirmation; re-runs are idempotent.
106
109
  const flipped = await flipDoneWithRetry({
@@ -127,6 +130,12 @@ export async function confirmStoryMerged({
127
130
  };
128
131
  }
129
132
 
133
+ /** Not merged, or merged but held for its CI ratchet; `null` confirms. */
134
+ async function unconfirmedResult({ pr, ratchet }) {
135
+ if (isPrMerged(pr)) return holdForCiRatchet(ratchet);
136
+ return pendingResult({ ...ratchet, state: pr.state });
137
+ }
138
+
130
139
  /** The PR is not merged yet: the Story stays at `agent::closing`. */
131
140
  function pendingResult({ storyId, prNumber, state, progress }) {
132
141
  const reason = state === 'CLOSED' ? 'pr-not-merged' : 'pr-open';
@@ -0,0 +1,202 @@
1
+ /**
2
+ * Report-only boot sweep: open `agent::executing` Stories whose `story-<id>`
3
+ * origin head has not moved (neither committed nor pushed) past the threshold
4
+ * and that have no open PR — a delivery session that died silently. Reads origin over REST (a checkout
5
+ * may hold no ref for another Story's branch); writes nothing; never throws.
6
+ */
7
+
8
+ import { gh as defaultGh, GhNotFoundError } from '../gh-exec.js';
9
+ import { getStoryBranch } from '../git-utils.js';
10
+ import { AGENT_LABELS, TYPE_LABELS } from '../label-constants.js';
11
+ import { NEXT_COMMANDS } from '../orchestration/story-deliver-terminal.js';
12
+
13
+ export const DEFAULT_STALLED_AFTER_HOURS = 6;
14
+
15
+ /** Stories probed per boot (up to three reads each); the rest are `unprobed`. */
16
+ export const DEFAULT_STALLED_PROBE_LIMIT = 20;
17
+
18
+ const HOUR_MS = 3_600_000;
19
+
20
+ /**
21
+ * A positive number of hours, else the default.
22
+ *
23
+ * @param {unknown} value
24
+ * @returns {number}
25
+ */
26
+ export function resolveStalledAfterHours(value) {
27
+ const hours = typeof value === 'string' ? Number(value) : value;
28
+ return typeof hours === 'number' && Number.isFinite(hours) && hours > 0
29
+ ? hours
30
+ : DEFAULT_STALLED_AFTER_HOURS;
31
+ }
32
+
33
+ function isExecutingStory(ticket) {
34
+ const labels = Array.isArray(ticket?.labels) ? ticket.labels : [];
35
+ return (
36
+ labels.includes(TYPE_LABELS.STORY) &&
37
+ labels.includes(AGENT_LABELS.EXECUTING)
38
+ );
39
+ }
40
+
41
+ function repoPath(config) {
42
+ const owner = config?.github?.owner || '{owner}';
43
+ const repo = config?.github?.repo || '{repo}';
44
+ return `/repos/${owner}/${repo}`;
45
+ }
46
+
47
+ /** Epoch ms of an ISO timestamp, `NaN` when absent or unparseable. */
48
+ function parseMs(iso) {
49
+ return Date.parse(iso ?? '');
50
+ }
51
+
52
+ /** `null` when the branch is absent on origin. */
53
+ async function readOriginHead({ gh, config, branch }) {
54
+ const endpoint = `${repoPath(config)}/branches/${encodeURIComponent(branch)}`;
55
+ try {
56
+ const { stdout } = await gh.api({ method: 'GET', endpoint });
57
+ const commit = JSON.parse(stdout)?.commit;
58
+ return {
59
+ sha: commit?.sha ?? null,
60
+ // Committer date: a rebase or base-sync moves it, author date stays.
61
+ committedAt: commit?.commit?.committer?.date ?? null,
62
+ };
63
+ } catch (err) {
64
+ if (err instanceof GhNotFoundError) return null;
65
+ throw err;
66
+ }
67
+ }
68
+
69
+ /** Latest push or branch creation on origin; `null` on any read failure. */
70
+ async function readLastPushAt({ gh, config, branch }) {
71
+ const ref = encodeURIComponent(`refs/heads/${branch}`);
72
+ const endpoint = `${repoPath(config)}/activity?ref=${ref}&per_page=1`;
73
+ try {
74
+ const { stdout } = await gh.api({ method: 'GET', endpoint });
75
+ const [latest] = JSON.parse(stdout);
76
+ return typeof latest?.timestamp === 'string' ? latest.timestamp : null;
77
+ } catch {
78
+ return null;
79
+ }
80
+ }
81
+
82
+ async function listBranchPrs(gh, branch) {
83
+ const rows = await gh.pr.list(
84
+ ['--head', branch, '--state', 'all'],
85
+ ['number', 'state'],
86
+ );
87
+ return Array.isArray(rows) ? rows : [];
88
+ }
89
+
90
+ function hasOpenPr(prs) {
91
+ return prs.some((pr) => pr?.state === 'OPEN');
92
+ }
93
+
94
+ /** Idle time since the later of the head commit and the last push. */
95
+ function idleSince(nowMs, committedMs, pushedAt) {
96
+ const pushedMs = parseMs(pushedAt);
97
+ return (
98
+ nowMs - Math.max(committedMs, Number.isFinite(pushedMs) ? pushedMs : 0)
99
+ );
100
+ }
101
+
102
+ function summarizePr(pr) {
103
+ return pr ? { number: Number(pr.number) || null, state: pr.state } : null;
104
+ }
105
+
106
+ function stalledRow({ storyId, head, pushedAt, idleMs, prs }) {
107
+ return {
108
+ storyId,
109
+ headSha: head.sha,
110
+ headCommittedAt: head.committedAt,
111
+ headPushedAt: pushedAt,
112
+ idleHours: Math.round((idleMs / HOUR_MS) * 10) / 10,
113
+ pr: summarizePr(prs[0]),
114
+ command: NEXT_COMMANDS.recover(storyId),
115
+ };
116
+ }
117
+
118
+ async function probeStory({ story, gh, config, nowMs, thresholdMs }) {
119
+ const storyId = story.id;
120
+ const branch = getStoryBranch(storyId);
121
+ const head = await readOriginHead({ gh, config, branch });
122
+ if (head === null) return null;
123
+ const committedMs = parseMs(head.committedAt);
124
+ if (!Number.isFinite(committedMs)) throw new Error('unreadable origin head');
125
+ if (nowMs - committedMs <= thresholdMs) return null;
126
+ const prs = await listBranchPrs(gh, branch);
127
+ if (hasOpenPr(prs)) return null;
128
+ const pushedAt = await readLastPushAt({ gh, config, branch });
129
+ const idleMs = idleSince(nowMs, committedMs, pushedAt);
130
+ if (idleMs <= thresholdMs) return null;
131
+ return stalledRow({ storyId, head, pushedAt, idleMs, prs });
132
+ }
133
+
134
+ /**
135
+ * @param {{
136
+ * provider: object,
137
+ * config?: object,
138
+ * gh?: object,
139
+ * logger?: { info?: Function, warn?: Function },
140
+ * now?: () => number,
141
+ * stalledAfterHours?: unknown,
142
+ * excludeStoryIds?: Array<number|null>,
143
+ * limit?: number,
144
+ * }} args
145
+ * @returns {Promise<{ ok: boolean, thresholdHours: number, stalled: object[], skipped: object[], unprobed: number, error?: string }>}
146
+ */
147
+ export async function reportStalledExecuting({
148
+ provider,
149
+ config,
150
+ gh = defaultGh,
151
+ logger = {},
152
+ now = Date.now,
153
+ stalledAfterHours,
154
+ excludeStoryIds = [],
155
+ limit = DEFAULT_STALLED_PROBE_LIMIT,
156
+ }) {
157
+ const thresholdHours = resolveStalledAfterHours(stalledAfterHours);
158
+ const outcome = {
159
+ ok: true,
160
+ thresholdHours,
161
+ stalled: [],
162
+ skipped: [],
163
+ unprobed: 0,
164
+ };
165
+ if (typeof provider?.listTicketsByLabel !== 'function') return outcome;
166
+ let tickets;
167
+ try {
168
+ tickets = await provider.listTicketsByLabel({
169
+ state: 'open',
170
+ labels: `${TYPE_LABELS.STORY},${AGENT_LABELS.EXECUTING}`,
171
+ });
172
+ } catch (err) {
173
+ const msg = err?.message ?? String(err);
174
+ logger.warn?.(
175
+ `open agent::executing listing failed (host continues): ${msg}`,
176
+ );
177
+ return { ...outcome, ok: false, error: msg };
178
+ }
179
+ const excluded = new Set(excludeStoryIds);
180
+ const candidates = (Array.isArray(tickets) ? tickets : [])
181
+ .filter((t) => isExecutingStory(t) && !excluded.has(t.id))
182
+ .sort((a, b) => a.id - b.id);
183
+ outcome.unprobed = Math.max(0, candidates.length - limit);
184
+ const nowMs = now();
185
+ const thresholdMs = thresholdHours * HOUR_MS;
186
+ for (const story of candidates.slice(0, limit)) {
187
+ try {
188
+ const row = await probeStory({ story, gh, config, nowMs, thresholdMs });
189
+ if (row === null) continue;
190
+ outcome.stalled.push(row);
191
+ logger.info?.(
192
+ `⏸️ Story #${row.storyId} agent::executing idle ${row.idleHours}h with no open PR — run ${row.command}`,
193
+ );
194
+ } catch (err) {
195
+ outcome.skipped.push({
196
+ storyId: story.id,
197
+ reason: err?.message ?? String(err),
198
+ });
199
+ }
200
+ }
201
+ return outcome;
202
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * standalone-ratchets.js — CI's standalone ratchets, stated once. The handoff
3
+ * preflight runs each whose baseline is committed, and the config schema's
4
+ * `delivery.quality.ratchets.coveredByLint` enum is these keys, so neither can
5
+ * gain a ratchet without the other. Imports nothing: the schema loads it.
6
+ */
7
+
8
+ export const STANDALONE_RATCHETS = Object.freeze([
9
+ Object.freeze({
10
+ key: 'dead-exports',
11
+ script: 'check-dead-exports.js',
12
+ args: Object.freeze([]),
13
+ baseline: 'baselines/dead-exports.json',
14
+ }),
15
+ Object.freeze({
16
+ key: 'dead-exports-production',
17
+ script: 'check-dead-exports.js',
18
+ args: Object.freeze(['--production']),
19
+ baseline: 'baselines/dead-exports-production.json',
20
+ }),
21
+ Object.freeze({
22
+ key: 'arch-cycles',
23
+ script: 'check-arch-cycles.js',
24
+ args: Object.freeze([]),
25
+ baseline: 'baselines/arch-cycles.json',
26
+ }),
27
+ Object.freeze({
28
+ key: 'cyclomatic',
29
+ script: 'check-cyclomatic.js',
30
+ args: Object.freeze([]),
31
+ baseline: 'baselines/cyclomatic.json',
32
+ }),
33
+ ]);
34
+
35
+ export const STANDALONE_RATCHET_KEYS = Object.freeze(
36
+ STANDALONE_RATCHETS.map((r) => r.key),
37
+ );
@@ -20,6 +20,7 @@ import {
20
20
  isHolderAlive,
21
21
  readLockHolderPid,
22
22
  } from './single-story-sweep/sweep-lock.js';
23
+ import { sizingFields } from './suite-sizing.js';
23
24
 
24
25
  /**
25
26
  * Set on every spawn made under a held lockfile or reservation, naming it, so
@@ -27,6 +28,9 @@ import {
27
28
  */
28
29
  export const SUITE_RESERVATION_ENV = 'MANDREL_SUITE_RESERVATION';
29
30
 
31
+ /** Beside a reservation marker: the weight it booked, to cap a worker pool. */
32
+ const SUITE_WEIGHT_ENV = 'MANDREL_SUITE_WEIGHT';
33
+
30
34
  /** `EX_CONFIG`: a declared weight the capacity can never admit. */
31
35
  export const ADMISSION_REFUSED_EXIT_CODE = 78;
32
36
 
@@ -91,6 +95,7 @@ function classifySuiteWorkload({ config, argv, capacity }) {
91
95
  command,
92
96
  weight: entry.weight,
93
97
  resources: [...(entry.resources ?? [])],
98
+ ...sizingFields(entry),
94
99
  };
95
100
  }
96
101
 
@@ -253,6 +258,11 @@ function reservationName({ weight, resources }) {
253
258
  return `w${weight}~${resources.join('+')}~${process.pid}-${rand}.lock`;
254
259
  }
255
260
 
261
+ function gated(gate, admit) {
262
+ const veto = gate?.();
263
+ return veto ? blocked(veto) : admit();
264
+ }
265
+
256
266
  /**
257
267
  * A declared run: admitted when no exclusive holder is live, no live
258
268
  * reservation shares a resource, and the live weights plus its own fit.
@@ -309,7 +319,8 @@ function createDeclaredAttempt(opts) {
309
319
  return result;
310
320
  };
311
321
  return {
312
- tryOnce: () => underAdmissionMutex(opts, admit),
322
+ /** `gate`, under the mutex: a blocking that vetoes, or null to admit. */
323
+ tryOnce: (gate) => underAdmissionMutex(opts, () => gated(gate, admit)),
313
324
  release: () => held?.release(),
314
325
  heldPath: () => heldPath,
315
326
  };
@@ -362,7 +373,14 @@ function createExclusiveAttempt(opts) {
362
373
 
363
374
  /** The child environment naming `heldPath`; empty when nothing is held. */
364
375
  export function reservationEnv(heldPath) {
365
- return heldPath ? { [SUITE_RESERVATION_ENV]: heldPath } : {};
376
+ return heldPath
377
+ ? { [SUITE_RESERVATION_ENV]: heldPath, ...weightEnv(heldPath) }
378
+ : {};
379
+ }
380
+
381
+ function weightEnv(heldPath) {
382
+ const match = RESERVATION_RE.exec(path.basename(heldPath));
383
+ return match ? { [SUITE_WEIGHT_ENV]: match[1] } : {};
366
384
  }
367
385
 
368
386
  /**
@@ -396,12 +414,6 @@ export function admissionWaitLine(workload, blocking, waitMs) {
396
414
  return `${LOCK_TAG} ⏳ waiting for admission of \`${workload.command}\` (weight ${workload.weight}; ${describeBlocking(blocking)}) — waiting up to ${Math.round(waitMs / 1000)}s before spawning.`;
397
415
  }
398
416
 
399
- /** The declared-run admitted line; `null` leaves the exclusive wording. */
400
- export function admittedLine(workload, waited) {
401
- if (workload?.kind !== 'declared') return null;
402
- return `${LOCK_TAG} ✅ admitted \`${workload.command}\` (weight ${workload.weight}, waited ${waited}s).`;
403
- }
404
-
405
417
  /** A reason worth naming over the holder pid; `null` for a plain queue. */
406
418
  export function blockingLabel(blocking) {
407
419
  return blocking && blocking.reason !== 'queue'