mandrel 2.110.0 → 2.112.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 (190) 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/audit-checklists/state-machines.md +21 -0
  6. package/.agents/docs/agentrc-reference.json +23 -10
  7. package/.agents/docs/configuration.md +362 -15
  8. package/.agents/docs/execution-reference.md +11 -0
  9. package/.agents/docs/workflows.md +2 -1
  10. package/.agents/rules/ci-remediation.md +28 -4
  11. package/.agents/rules/git-conventions-reference.md +7 -0
  12. package/.agents/schemas/agentrc.schema.json +179 -13
  13. package/.agents/schemas/audit-rules.json +28 -0
  14. package/.agents/schemas/baselines/baseline-envelope.schema.json +16 -4
  15. package/.agents/schemas/baselines/bundle-size.schema.json +1 -0
  16. package/.agents/schemas/baselines/coverage.schema.json +1 -0
  17. package/.agents/schemas/baselines/crap.schema.json +37 -10
  18. package/.agents/schemas/baselines/duplication.schema.json +1 -0
  19. package/.agents/schemas/baselines/maintainability.schema.json +1 -0
  20. package/.agents/schemas/baselines/mutation.schema.json +1 -0
  21. package/.agents/schemas/crap-report.schema.json +6 -5
  22. package/.agents/schemas/story-deliver-terminal.schema.json +49 -3
  23. package/.agents/schemas/story-progress.schema.json +1 -1
  24. package/.agents/schemas/validation-evidence.schema.json +2 -2
  25. package/.agents/scripts/boot-sweep.js +41 -3
  26. package/.agents/scripts/coverage-capture.js +39 -3
  27. package/.agents/scripts/coverage-ratchet.js +106 -0
  28. package/.agents/scripts/evidence-gate.js +84 -21
  29. package/.agents/scripts/file-ci-gap.js +220 -10
  30. package/.agents/scripts/lib/audit-baselines/read.js +8 -1
  31. package/.agents/scripts/lib/audit-baselines/trend.js +2 -1
  32. package/.agents/scripts/lib/audit-to-stories/audit-lenses.js +1 -0
  33. package/.agents/scripts/lib/baseline-loader.js +4 -2
  34. package/.agents/scripts/lib/baselines/codec.js +57 -0
  35. package/.agents/scripts/lib/baselines/crap-preview-incremental.js +8 -3
  36. package/.agents/scripts/lib/baselines/crap-preview-scan.js +10 -16
  37. package/.agents/scripts/lib/baselines/crap-updater-cli.js +4 -13
  38. package/.agents/scripts/lib/baselines/kernel.js +19 -1
  39. package/.agents/scripts/lib/baselines/kinds/_crap-codec.js +171 -0
  40. package/.agents/scripts/lib/baselines/kinds/_crap-read.js +56 -16
  41. package/.agents/scripts/lib/baselines/kinds/_shared-metric.js +0 -59
  42. package/.agents/scripts/lib/baselines/kinds/crap.js +283 -319
  43. package/.agents/scripts/lib/baselines/preview-gates.js +29 -10
  44. package/.agents/scripts/lib/baselines/reader.js +36 -9
  45. package/.agents/scripts/lib/baselines/refresh-service.js +79 -18
  46. package/.agents/scripts/lib/baselines/seat-missing.js +173 -7
  47. package/.agents/scripts/lib/baselines/writer.js +36 -21
  48. package/.agents/scripts/lib/changed-files.js +70 -6
  49. package/.agents/scripts/lib/child-exec.js +10 -0
  50. package/.agents/scripts/lib/claude/agents-projection.js +5 -5
  51. package/.agents/scripts/lib/close-lock-events.js +8 -3
  52. package/.agents/scripts/lib/close-validation/ci-deferral.js +40 -0
  53. package/.agents/scripts/lib/close-validation/gates.js +156 -32
  54. package/.agents/scripts/lib/close-validation/process.js +16 -7
  55. package/.agents/scripts/lib/close-validation/projections/crap.js +43 -10
  56. package/.agents/scripts/lib/close-validation/runner.js +160 -41
  57. package/.agents/scripts/lib/close-validation/skip-branch-test.js +144 -0
  58. package/.agents/scripts/lib/close-validation/test-delta.js +33 -8
  59. package/.agents/scripts/lib/codex/agents-projection.js +6 -0
  60. package/.agents/scripts/lib/config/agentrc-overlay.js +9 -5
  61. package/.agents/scripts/lib/config/explain.js +5 -2
  62. package/.agents/scripts/lib/config/gates/coverage.schema.js +53 -0
  63. package/.agents/scripts/lib/config/gates/crap-incremental-coverage.schema.js +1 -1
  64. package/.agents/scripts/lib/config/git-roots.js +38 -4
  65. package/.agents/scripts/lib/config/handoff.js +24 -0
  66. package/.agents/scripts/lib/config/quality.js +28 -12
  67. package/.agents/scripts/lib/config/worktree-isolation.js +2 -5
  68. package/.agents/scripts/lib/config-resolver.js +22 -2
  69. package/.agents/scripts/lib/config-settings-schema-delivery.js +87 -4
  70. package/.agents/scripts/lib/config-settings-schema-quality.js +36 -1
  71. package/.agents/scripts/lib/config-settings-schema.js +1 -1
  72. package/.agents/scripts/lib/coverage-capture-affected.js +1 -0
  73. package/.agents/scripts/lib/coverage-capture-delta.js +164 -32
  74. package/.agents/scripts/lib/coverage-capture-own-fix.js +232 -0
  75. package/.agents/scripts/lib/coverage-capture-usage.js +2 -2
  76. package/.agents/scripts/lib/coverage-capture.js +31 -0
  77. package/.agents/scripts/lib/coverage-deferral.js +96 -0
  78. package/.agents/scripts/lib/coverage-ratchet.js +187 -0
  79. package/.agents/scripts/lib/crap-baseline-join.js +5 -5
  80. package/.agents/scripts/lib/crap-engine.js +3 -3
  81. package/.agents/scripts/lib/crap-method-identity.js +104 -48
  82. package/.agents/scripts/lib/escomplex-anchor.js +135 -0
  83. package/.agents/scripts/lib/escomplex-kernel.js +30 -1
  84. package/.agents/scripts/lib/failure-rows.js +121 -0
  85. package/.agents/scripts/lib/full-suite-lock.js +44 -4
  86. package/.agents/scripts/lib/full-suite-queue.js +89 -13
  87. package/.agents/scripts/lib/generated/agentrc-validator.js +8 -2
  88. package/.agents/scripts/lib/gh-env.js +3 -6
  89. package/.agents/scripts/lib/gh-pr-rest.js +1 -0
  90. package/.agents/scripts/lib/git/base-sync-probe.js +182 -0
  91. package/.agents/scripts/lib/git-branch-lifecycle.js +9 -0
  92. package/.agents/scripts/lib/observability/close-telemetry.js +37 -2
  93. package/.agents/scripts/lib/observability/handoff-telemetry.js +170 -0
  94. package/.agents/scripts/lib/observability/review-dispositions.js +23 -6
  95. package/.agents/scripts/lib/observability/runtime-friction.js +17 -4
  96. package/.agents/scripts/lib/observability/source-classifier.js +3 -0
  97. package/.agents/scripts/lib/observability/story-outcome.js +393 -0
  98. package/.agents/scripts/lib/orchestration/check-baselines/phases/compare.js +2 -1
  99. package/.agents/scripts/lib/orchestration/check-baselines/phases/evaluate.js +19 -1
  100. package/.agents/scripts/lib/orchestration/check-baselines/phases/fail-detail.js +84 -0
  101. package/.agents/scripts/lib/orchestration/check-baselines/phases/pipeline.js +14 -5
  102. package/.agents/scripts/lib/orchestration/check-baselines/phases/refresh-ack.js +3 -2
  103. package/.agents/scripts/lib/orchestration/check-baselines/phases/report.js +26 -6
  104. package/.agents/scripts/lib/orchestration/ci-rerun-guard.js +124 -23
  105. package/.agents/scripts/lib/orchestration/code-review.js +223 -19
  106. package/.agents/scripts/lib/orchestration/handoff-gates.js +217 -44
  107. package/.agents/scripts/lib/orchestration/handoff-rescore.js +169 -0
  108. package/.agents/scripts/lib/orchestration/handoff-suite-of-record.js +45 -0
  109. package/.agents/scripts/lib/orchestration/plan-persist/run-plan-persist.js +5 -1
  110. package/.agents/scripts/lib/orchestration/plan-persist/source-rewrite.js +76 -4
  111. package/.agents/scripts/lib/orchestration/plan-persist/story-ops.js +2 -2
  112. package/.agents/scripts/lib/orchestration/preflight-lanes.js +208 -0
  113. package/.agents/scripts/lib/orchestration/review-base-ref.js +40 -17
  114. package/.agents/scripts/lib/orchestration/review-deposit.js +38 -12
  115. package/.agents/scripts/lib/orchestration/review-depth.js +21 -0
  116. package/.agents/scripts/lib/orchestration/review-history.js +124 -20
  117. package/.agents/scripts/lib/orchestration/review-providers/claude-verdict.js +23 -8
  118. package/.agents/scripts/lib/orchestration/review-providers/code-review.js +82 -39
  119. package/.agents/scripts/lib/orchestration/review-providers/critical-verifier.js +64 -11
  120. package/.agents/scripts/lib/orchestration/review-providers/degraded-gates.js +98 -3
  121. package/.agents/scripts/lib/orchestration/review-providers/finding-identity.js +6 -2
  122. package/.agents/scripts/lib/orchestration/review-providers/findings-renderer.js +55 -8
  123. package/.agents/scripts/lib/orchestration/review-providers/review-guidance.js +1 -0
  124. package/.agents/scripts/lib/orchestration/review-providers/review-provider-factory.js +42 -15
  125. package/.agents/scripts/lib/orchestration/review-providers/types.js +6 -0
  126. package/.agents/scripts/lib/orchestration/single-story-close/failed-terminal.js +10 -1
  127. package/.agents/scripts/lib/orchestration/single-story-close/gate-log.js +10 -0
  128. package/.agents/scripts/lib/orchestration/single-story-close/phases/base-sync.js +7 -4
  129. package/.agents/scripts/lib/orchestration/single-story-close/phases/close-validation.js +17 -2
  130. package/.agents/scripts/lib/orchestration/single-story-close/phases/code-review.js +59 -2
  131. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +13 -1
  132. package/.agents/scripts/lib/orchestration/single-story-close/phases/finish.js +15 -4
  133. package/.agents/scripts/lib/orchestration/single-story-close/phases/land-review-record.js +213 -0
  134. package/.agents/scripts/lib/orchestration/single-story-close/phases/normalize-pr-title.js +17 -2
  135. package/.agents/scripts/lib/orchestration/single-story-close/phases/open-pr.js +42 -20
  136. package/.agents/scripts/lib/orchestration/single-story-close/phases/post-land.js +51 -26
  137. package/.agents/scripts/lib/orchestration/single-story-close/phases/pre-push.js +3 -1
  138. package/.agents/scripts/lib/orchestration/single-story-close/phases/pull-request.js +51 -15
  139. package/.agents/scripts/lib/orchestration/single-story-close/phases/push.js +59 -11
  140. package/.agents/scripts/lib/orchestration/single-story-close/phases/reconcile-done.js +1 -0
  141. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-block.js +31 -13
  142. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-halt.js +29 -6
  143. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-outcome.js +10 -12
  144. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-override.js +19 -4
  145. package/.agents/scripts/lib/orchestration/single-story-close/result.js +43 -13
  146. package/.agents/scripts/lib/orchestration/single-story-close/review-overlap.js +73 -39
  147. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +11 -2
  148. package/.agents/scripts/lib/orchestration/story-close/baseline-upward-writeback.js +3 -2
  149. package/.agents/scripts/lib/orchestration/story-close/duplication-close-rescore.js +20 -8
  150. package/.agents/scripts/lib/orchestration/story-deliver-terminal.js +7 -0
  151. package/.agents/scripts/lib/orchestration/story-handoff.js +789 -196
  152. package/.agents/scripts/lib/orchestration/ticketing/reads.js +2 -0
  153. package/.agents/scripts/lib/pr-body-lines.js +32 -0
  154. package/.agents/scripts/lib/single-story/ci-ratchet-gate.js +140 -0
  155. package/.agents/scripts/lib/single-story/confirm-and-land.js +17 -7
  156. package/.agents/scripts/lib/single-story/confirm-merge.js +12 -3
  157. package/.agents/scripts/lib/single-story-sweep/report-stalled-executing.js +202 -0
  158. package/.agents/scripts/lib/standalone-ratchets.js +37 -0
  159. package/.agents/scripts/lib/suite-admission.js +20 -8
  160. package/.agents/scripts/lib/suite-sizing.js +146 -0
  161. package/.agents/scripts/lib/workspace-provisioner.js +2 -2
  162. package/.agents/scripts/merge-baseline.js +14 -3
  163. package/.agents/scripts/providers/github/comments.js +19 -3
  164. package/.agents/scripts/providers/github.js +1 -0
  165. package/.agents/scripts/review-dispositions-report.js +1 -1
  166. package/.agents/scripts/role-scope-guard.js +267 -0
  167. package/.agents/scripts/single-story-close.js +4 -4
  168. package/.agents/scripts/single-story-confirm-merge.js +31 -5
  169. package/.agents/scripts/single-story-init.js +24 -4
  170. package/.agents/scripts/story-handoff.js +3 -3
  171. package/.agents/scripts/story-outcomes-report.js +231 -0
  172. package/.agents/scripts/story-review-compute.js +9 -5
  173. package/.agents/scripts/update-coverage-baseline.js +12 -2
  174. package/.agents/scripts/update-crap-baseline.js +9 -1
  175. package/.agents/workflows/audit-state-machines.md +213 -0
  176. package/.agents/workflows/helpers/code-review.md +63 -9
  177. package/.agents/workflows/helpers/deliver-digest.md +53 -54
  178. package/.agents/workflows/helpers/deliver-reference.md +236 -63
  179. package/.agents/workflows/helpers/deliver-story-reference.md +19 -8
  180. package/.agents/workflows/helpers/deliver-story.md +7 -2
  181. package/.agents/workflows/helpers/parallel-tooling.md +29 -0
  182. package/.agents/workflows/helpers/plan-reference.md +10 -2
  183. package/docs/CHANGELOG.md +56 -0
  184. package/lib/cli/doctor-checks/coverage-ratchet.js +54 -0
  185. package/lib/cli/doctor-checks/effective-agentrc.js +23 -0
  186. package/lib/cli/doctor-checks/llm-review.js +2 -11
  187. package/lib/cli/doctor-checks/sync-parity.js +5 -1
  188. package/lib/cli/doctor-checks/test-credit-path.js +7 -2
  189. package/lib/cli/registry.js +5 -0
  190. package/package.json +1 -1
@@ -12,7 +12,12 @@ import { spawnSync } from 'node:child_process';
12
12
  import { parseArgs } from 'node:util';
13
13
  import { runAsCli } from './lib/cli-utils.js';
14
14
  import { claimLockEventSink, lockEventHooks } from './lib/close-lock-events.js';
15
+ import {
16
+ changedSinceError,
17
+ scopedEvidenceRun,
18
+ } from './lib/close-validation/skip-branch-test.js';
15
19
  import { getQuality, resolveConfig } from './lib/config-resolver.js';
20
+ import { COVERAGE_HOST_RESOURCES_EXIT_CODE } from './lib/coverage-capture.js';
16
21
  import {
17
22
  fullSuiteLockPolicy,
18
23
  LOCK_WAIT_EXPIRED_EXIT_CODE,
@@ -53,6 +58,7 @@ export function parseWrapperArgs(argv) {
53
58
  standalone: { type: 'boolean', default: false },
54
59
  cwd: { type: 'string' },
55
60
  worktree: { type: 'string' },
61
+ 'changed-since': { type: 'string' },
56
62
  },
57
63
  strict: false,
58
64
  });
@@ -64,9 +70,37 @@ export function parseWrapperArgs(argv) {
64
70
  useEvidence: values['no-evidence'] !== true,
65
71
  cwd: values.cwd ?? PROJECT_ROOT,
66
72
  worktreePath: values.worktree ?? null,
73
+ changedSince: values['changed-since'] ?? null,
67
74
  };
68
75
  }
69
76
 
77
+ const USAGE =
78
+ 'Usage: node evidence-gate.js --standalone --scope-id <id> --gate <name> [--worktree <path>] [--no-evidence] [--changed-since <sha>] -- <cmd> [args...]';
79
+
80
+ /** The usage refusal, or `null` when the params may run. */
81
+ function usageError({ scopeId, standalone, gate, runnerArgs, changedSince }) {
82
+ if (!scopeId || !standalone || !gate || !runnerArgs?.length) return USAGE;
83
+ const scoped = changedSinceError(gate, changedSince);
84
+ return scoped ? `[evidence-gate] ${scoped}` : null;
85
+ }
86
+
87
+ /** The spawned argv and evidence identity; `--changed-since` scopes a `test` run. */
88
+ function resolveRun({ runnerArgs, changedSince }, cwd, loadConfigFn) {
89
+ const [cmd, ...args] = runnerArgs;
90
+ return changedSince
91
+ ? scopedRun({ cmd, args, since: changedSince, cwd, loadConfigFn })
92
+ : plainRun(cmd, args, cwd);
93
+ }
94
+
95
+ function scopedRun({ loadConfigFn, ...run }) {
96
+ return scopedEvidenceRun({ ...run, config: loadConfigFn(run.cwd) });
97
+ }
98
+
99
+ function plainRun(cmd, args, cwd) {
100
+ const configHash = hashCommandConfig({ cmd, args, cwd });
101
+ return { cmd, cmdArgs: args, configHash, note: {} };
102
+ }
103
+
70
104
  function resolveHeadShaDefault(cwd, gitSpawnFn) {
71
105
  const res = gitSpawnFn(cwd, 'rev-parse', 'HEAD');
72
106
  if (res.status !== 0) return null;
@@ -98,6 +132,7 @@ function resolveEvidenceKeys({ spawnCwd, gitSpawnFn, useEvidence }) {
98
132
  * @param {string} params.cwd — evidence cwd (locates the temp tree)
99
133
  * @param {string|null} [params.worktreePath] — spawn cwd and HEAD source
100
134
  * @param {string[]} params.runnerArgs
135
+ * @param {string|null} [params.changedSince] — skip-branch scoped `test` deposit
101
136
  * @param {object} [deps]
102
137
  * @param {Function} [deps.gitSpawnFn]
103
138
  * @param {Function} [deps.spawnFn]
@@ -105,6 +140,7 @@ function resolveEvidenceKeys({ spawnCwd, gitSpawnFn, useEvidence }) {
105
140
  * @param {Function} [deps.recordPassFn]
106
141
  * @param {object} [deps.logger]
107
142
  * @param {Function} [deps.runSuiteFn]
143
+ * @param {Function} [deps.loadConfigFn]
108
144
  * @returns {{ status: number, skipped: boolean }}
109
145
  */
110
146
  export async function runEvidenceGate(params, deps = {}) {
@@ -115,6 +151,7 @@ export async function runEvidenceGate(params, deps = {}) {
115
151
  recordPassFn = recordPass,
116
152
  logger = Logger,
117
153
  runSuiteFn = runLockedSuite,
154
+ loadConfigFn = loadConfig,
118
155
  } = deps;
119
156
  const {
120
157
  scopeId,
@@ -123,19 +160,11 @@ export async function runEvidenceGate(params, deps = {}) {
123
160
  useEvidence,
124
161
  cwd,
125
162
  worktreePath,
126
- runnerArgs,
127
163
  } = params ?? {};
128
164
 
129
- if (
130
- !scopeId ||
131
- !standalone ||
132
- !gate ||
133
- !runnerArgs ||
134
- runnerArgs.length === 0
135
- ) {
136
- logger.fatal(
137
- 'Usage: node evidence-gate.js --standalone --scope-id <id> --gate <name> [--worktree <path>] [--no-evidence] -- <cmd> [args...]',
138
- );
165
+ const usage = usageError(params ?? {});
166
+ if (usage) {
167
+ logger.fatal(usage);
139
168
  return { status: 1, skipped: false };
140
169
  }
141
170
  const evidenceStoreOpts = { cwd, standalone };
@@ -143,8 +172,11 @@ export async function runEvidenceGate(params, deps = {}) {
143
172
  // The gate runs in the worktree; evidence stays anchored to the main
144
173
  // checkout so the temp tree resolves under the main `.git/`.
145
174
  const spawnCwd = worktreePath ?? cwd;
146
- const [cmd, ...cmdArgs] = runnerArgs;
147
- const configHash = hashCommandConfig({ cmd, args: cmdArgs, cwd: spawnCwd });
175
+ const { cmd, cmdArgs, env, note, configHash } = resolveRun(
176
+ params,
177
+ spawnCwd,
178
+ loadConfigFn,
179
+ );
148
180
  const { headSha, inputFingerprint } = resolveEvidenceKeys({
149
181
  spawnCwd,
150
182
  gitSpawnFn,
@@ -179,6 +211,7 @@ export async function runEvidenceGate(params, deps = {}) {
179
211
  gate,
180
212
  cmd,
181
213
  cmdArgs,
214
+ env,
182
215
  spawnCwd,
183
216
  logger,
184
217
  spawnFn,
@@ -202,6 +235,7 @@ export async function runEvidenceGate(params, deps = {}) {
202
235
  exitCode: 0,
203
236
  durationMs: Date.now() - startedAt,
204
237
  inputFingerprint,
238
+ ...note,
205
239
  },
206
240
  evidenceStoreOpts,
207
241
  );
@@ -215,12 +249,12 @@ export async function runEvidenceGate(params, deps = {}) {
215
249
  }
216
250
 
217
251
  /**
218
- * @param {{ cmd: string, args: string[], cwd: string, log: (m: string) => void }} run
252
+ * @param {{ cmd: string, args: string[], cwd: string, log: (m: string) => void, childEnv?: Record<string, string> }} run
219
253
  * @param {{ config?: object|null, env?: object, lockOptions?: object, runSuiteImpl?: typeof runSupervisedSuite }} [seams]
220
254
  * @returns {Promise<number>} 75 when the lock wait expired.
221
255
  */
222
256
  export function runLockedSuite(
223
- { cmd, args, cwd, log },
257
+ { cmd, args, cwd, log, childEnv },
224
258
  {
225
259
  config = loadConfig(cwd),
226
260
  env = process.env,
@@ -247,6 +281,7 @@ export function runLockedSuite(
247
281
  cwd,
248
282
  timeoutMs,
249
283
  ...lock,
284
+ env: { ...childEnv, ...lock.env },
250
285
  onTimings: (t) => {
251
286
  log(`[evidence-gate] ${formatSuiteTimings(t)}`);
252
287
  lockHooks.onTimings(t);
@@ -264,6 +299,7 @@ async function runGateCommand({
264
299
  gate,
265
300
  cmd,
266
301
  cmdArgs,
302
+ env,
267
303
  spawnCwd,
268
304
  logger,
269
305
  spawnFn,
@@ -271,7 +307,13 @@ async function runGateCommand({
271
307
  }) {
272
308
  if (gate === FULL_SUITE_GATE) {
273
309
  const log = (m) => logger.info(m);
274
- return await runSuiteFn({ cmd, args: cmdArgs, cwd: spawnCwd, log });
310
+ return await runSuiteFn({
311
+ cmd,
312
+ args: cmdArgs,
313
+ cwd: spawnCwd,
314
+ log,
315
+ childEnv: env,
316
+ });
275
317
  }
276
318
  const result = spawnFn(cmd, cmdArgs, {
277
319
  cwd: spawnCwd,
@@ -281,11 +323,28 @@ async function runGateCommand({
281
323
  return result.status ?? 1;
282
324
  }
283
325
 
326
+ function deferredLine(gate, status) {
327
+ return `⏸ ${gate} deferred (exit ${status}) — another full suite still holds the host lock, so nothing ran and no evidence was recorded.`;
328
+ }
329
+
330
+ function hostResourcesLine(gate, status) {
331
+ return `⛔ ${gate} lost workers to host memory (exit ${status}) — no test failed and no evidence was recorded.`;
332
+ }
333
+
334
+ /** Suite-gate exits that are not a failed gate, each logged as what happened. */
335
+ const NON_FAILURE_EXITS = {
336
+ [LOCK_WAIT_EXPIRED_EXIT_CODE]: ['info', deferredLine],
337
+ [COVERAGE_HOST_RESOURCES_EXIT_CODE]: ['error', hostResourcesLine],
338
+ };
339
+
340
+ function nonFailureExit(gate, status) {
341
+ return gate === FULL_SUITE_GATE ? NON_FAILURE_EXITS[status] : undefined;
342
+ }
343
+
284
344
  function reportGateExit({ gate, status, spawnCwd, logger }) {
285
- if (status === LOCK_WAIT_EXPIRED_EXIT_CODE) {
286
- logger.info(
287
- `[evidence-gate] ⏸ ${gate} deferred (exit ${status}) — another full suite still holds the host lock, so nothing ran and no evidence was recorded.`,
288
- );
345
+ const exit = nonFailureExit(gate, status);
346
+ if (exit) {
347
+ logger[exit[0]](`[evidence-gate] ${exit[1](gate, status)}`);
289
348
  return;
290
349
  }
291
350
  logger.error(
@@ -312,7 +371,7 @@ runAsCli(import.meta.url, main, {
312
371
  source: 'evidence-gate',
313
372
  usage: {
314
373
  invocation:
315
- 'node .agents/scripts/evidence-gate.js --scope-id <id> --gate <name> [--standalone] [--no-evidence] [--cwd <path>] [--worktree <path>] -- <cmd> [args...]',
374
+ 'node .agents/scripts/evidence-gate.js --scope-id <id> --gate <name> [--standalone] [--no-evidence] [--cwd <path>] [--worktree <path>] [--changed-since <sha>] -- <cmd> [args...]',
316
375
  summary:
317
376
  'Run one named gate, reusing a prior evidence stamp for the same HEAD instead of re-running it.',
318
377
  flags: [
@@ -325,6 +384,10 @@ runAsCli(import.meta.url, main, {
325
384
  ],
326
385
  ['--cwd <path>', 'Repository root (default: project root).'],
327
386
  ['--worktree <path>', 'Worktree the gate runs in.'],
387
+ [
388
+ '--changed-since <sha>',
389
+ "With --gate test only: substitute $MANDREL_CHANGED_SINCE in the command, set it in the env, and credit the run as close's full-suite test (scope: delta).",
390
+ ],
328
391
  [
329
392
  '-- <cmd> [args...]',
330
393
  'Required. The command this gate runs, passed through verbatim (never via a shell).',
@@ -4,6 +4,8 @@
4
4
  * delivery's to fix, files (or updates, by fingerprint) an intake issue in
5
5
  * the owning repo, comments `friction` on the Story, and optionally blocks it.
6
6
  * It files intake, never a Story, so delivery never blocks on planning.
7
+ * `governance-label` is the one non-filing verdict: an audited recovery for
8
+ * a fresh green run an operator-approved label started on the red head.
7
9
  */
8
10
 
9
11
  import { parseArgs } from 'node:util';
@@ -16,6 +18,7 @@ import {
16
18
  updateFollowUpIssue,
17
19
  } from './lib/feedback-loop/graduator-core.js';
18
20
  import { issueNumberFromUrl } from './lib/feedback-loop/retro-proposals-graduator.js';
21
+ import { runGh } from './lib/gh-exec.js';
19
22
  import {
20
23
  resolveOwnershipRepos,
21
24
  routeOwnership,
@@ -27,9 +30,10 @@ import {
27
30
  REFUSED_VERDICT,
28
31
  } from './lib/orchestration/ci-gap-intake.js';
29
32
  import {
30
- RERUN_ALLOWANCE_VERDICTS,
33
+ GOVERNANCE_LABEL_VERDICT,
31
34
  readCiDigest,
32
35
  recordRerunAllowance,
36
+ resolvePassingCheckRun,
33
37
  } from './lib/orchestration/ci-rerun-guard.js';
34
38
  import {
35
39
  STATE_LABELS,
@@ -40,7 +44,7 @@ import { createProvider } from './lib/provider-factory.js';
40
44
 
41
45
  const USAGE = {
42
46
  invocation:
43
- 'node .agents/scripts/file-ci-gap.js --story <id> --verdict <verdict> --owner <bucket> [--evidence "<proof reading>"] [--pr <n>] [--block] [--dry-run]',
47
+ 'node .agents/scripts/file-ci-gap.js --story <id> --verdict <verdict> --owner <bucket> [--evidence "<proof reading>"] [--pr <n>] [--block] [--dry-run]\n node .agents/scripts/file-ci-gap.js --story <id> --verdict governance-label --label <name> [--pr <n>] [--dry-run]',
44
48
  summary:
45
49
  'File (or update) the CI-gap intake issue for an Option-2 verdict in .agents/rules/ci-remediation.md, routed to the repository that owns the fault and deduped by failure signature.',
46
50
  flags: [
@@ -50,7 +54,11 @@ const USAGE = {
50
54
  ],
51
55
  [
52
56
  '--verdict <verdict>',
53
- `One of ${INTAKE_VERDICTS.join(' | ')}. "${REFUSED_VERDICT}" is refused: it routes to Option 1, fix at source. ${RERUN_ALLOWANCE_VERDICTS.join(' / ')} also record the one-rerun allowance on the CI digest.`,
57
+ `One of ${INTAKE_VERDICTS.join(' | ')} | ${GOVERNANCE_LABEL_VERDICT}. "${REFUSED_VERDICT}" is refused: it routes to Option 1, fix at source. capacity / unreproducible-tier also record the one-rerun allowance on the CI digest. ${GOVERNANCE_LABEL_VERDICT} files nothing: it proves --label was added after the red and records the allowance for that fresh run.`,
58
+ ],
59
+ [
60
+ '--label <name>',
61
+ `The operator-approved governance label (${GOVERNANCE_LABEL_VERDICT} only).`,
54
62
  ],
55
63
  [
56
64
  '--owner <bucket>',
@@ -60,7 +68,10 @@ const USAGE = {
60
68
  '--evidence <text>',
61
69
  "The verdict's proof reading (the exhausted-limit log line, the failed attach). Recorded in the body.",
62
70
  ],
63
- ['--pr <n>', 'PR number the red check ran on; recorded as an occurrence.'],
71
+ [
72
+ '--pr <n>',
73
+ 'PR number the red check ran on; recorded as an occurrence. Defaults to the digest PR.',
74
+ ],
64
75
  [
65
76
  '--block',
66
77
  'Also flip the Story to agent::blocked. Without it the friction comment is posted but the Story is left where it is.',
@@ -166,6 +177,18 @@ function renderRerunLine(rerunAllowance) {
166
177
  : 'This verdict does **not** license a re-run of the failed job.';
167
178
  }
168
179
 
180
+ /** The injected digest, else the Story's on-disk one; throws when absent. */
181
+ function loadCiDigest({ sid, digest, digestRoot, cwd }) {
182
+ const ciDigest =
183
+ digest ?? readCiDigest({ storyId: sid, tempRoot: digestRoot, cwd });
184
+ if (!ciDigest) {
185
+ throw new Error(
186
+ `no CI digest for Story #${sid}. The digest is written by \`pr-watch-with-update.js --story ${sid}\` on the first red; without it there is no run link or failure signature to file.`,
187
+ );
188
+ }
189
+ return ciDigest;
190
+ }
191
+
169
192
  /**
170
193
  * @param {object} opts
171
194
  * @returns {Promise<object>}
@@ -186,6 +209,9 @@ export async function runFileCiGap({
186
209
  cwd = process.cwd(),
187
210
  logger = Logger,
188
211
  now,
212
+ label = null,
213
+ labelHistoryFn = readPrLabelHistory,
214
+ greenRunFn = resolvePassingCheckRun,
189
215
  } = {}) {
190
216
  const sid = Number(storyId);
191
217
  if (!Number.isInteger(sid) || sid <= 0) {
@@ -194,12 +220,22 @@ export async function runFileCiGap({
194
220
  const resolved = config ?? resolveConfig();
195
221
  // Must resolve exactly as `pr-watch-with-update.js` does when writing it.
196
222
  const digestRoot = tempRoot ?? resolved?.project?.paths?.tempRoot ?? 'temp';
197
- const ciDigest =
198
- digest ?? readCiDigest({ storyId: sid, tempRoot: digestRoot, cwd });
199
- if (!ciDigest) {
200
- throw new Error(
201
- `no CI digest for Story #${sid}. The digest is written by \`pr-watch-with-update.js --story ${sid}\` on the first red; without it there is no run link or failure signature to file.`,
202
- );
223
+ const ciDigest = loadCiDigest({ sid, digest, digestRoot, cwd });
224
+
225
+ if (verdict === GOVERNANCE_LABEL_VERDICT) {
226
+ return runGovernanceRecovery({
227
+ sid,
228
+ label,
229
+ prNumber,
230
+ digest: ciDigest,
231
+ digestRoot,
232
+ cwd,
233
+ dryRun,
234
+ provider,
235
+ config: resolved,
236
+ labelHistoryFn,
237
+ greenRunFn,
238
+ });
203
239
  }
204
240
 
205
241
  const repos = resolveOwnershipRepos(resolved);
@@ -273,6 +309,178 @@ export async function runFileCiGap({
273
309
  return { storyId: sid, verdict, ...result, actions, rerunAllowance };
274
310
  }
275
311
 
312
+ /** Parsed JSON of a `gh api` read; `null` on a failed or unparseable one. */
313
+ function readGhApi(args, cwd) {
314
+ const res = runGh(['api', ...args], { cwd });
315
+ if ((res?.status ?? 1) !== 0) return null;
316
+ try {
317
+ return JSON.parse((res.stdout ?? '').trim() || 'null');
318
+ } catch {
319
+ return null;
320
+ }
321
+ }
322
+
323
+ /**
324
+ * The PR's current label names and every issue event; `null` when a read
325
+ * fails (the recovery then refuses).
326
+ *
327
+ * @returns {{ labels: string[], events: object[] } | null}
328
+ */
329
+ function readPrLabelHistory({ prNumber, cwd }) {
330
+ const labels = readGhApi(
331
+ [`repos/{owner}/{repo}/issues/${prNumber}/labels?per_page=100`],
332
+ cwd,
333
+ );
334
+ const pages = readGhApi(
335
+ [
336
+ '--paginate',
337
+ '--slurp',
338
+ `repos/{owner}/{repo}/issues/${prNumber}/events?per_page=100`,
339
+ ],
340
+ cwd,
341
+ );
342
+ if (!Array.isArray(labels) || !Array.isArray(pages)) return null;
343
+ return {
344
+ labels: labels.map((l) => l?.name).filter(Boolean),
345
+ events: pages.flat(),
346
+ };
347
+ }
348
+
349
+ /**
350
+ * The newest `labeled` event for `label` after `since`, while the label is
351
+ * still on the PR; `null` when the transition is unproven.
352
+ *
353
+ * @returns {{ label: string, actor: string|null, labeledAt: string } | null}
354
+ */
355
+ export function proveLabelTransition({ history, label, since }) {
356
+ const sinceMs = Date.parse(since ?? '');
357
+ if (!history || !Number.isFinite(sinceMs)) return null;
358
+ if (!history.labels.includes(label)) return null;
359
+ const hits = history.events.filter(
360
+ (e) =>
361
+ e?.event === 'labeled' &&
362
+ e?.label?.name === label &&
363
+ Date.parse(e?.created_at ?? '') > sinceMs,
364
+ );
365
+ const latest = hits.sort(
366
+ (a, b) => Date.parse(b.created_at) - Date.parse(a.created_at),
367
+ )[0];
368
+ return latest
369
+ ? {
370
+ label,
371
+ actor: latest.actor?.login ?? null,
372
+ labeledAt: latest.created_at,
373
+ }
374
+ : null;
375
+ }
376
+
377
+ /**
378
+ * @param {{ digest: object, evidence: object }} opts
379
+ * @returns {string}
380
+ */
381
+ export function renderGovernanceComment({ digest, evidence }) {
382
+ const red = digest?.runUrl ?? `run id ${digest?.runId ?? 'unresolved'}`;
383
+ const green =
384
+ evidence.greenRun?.url ??
385
+ `run id ${evidence.greenRun?.runId ?? 'unresolved'}`;
386
+ return [
387
+ `### CI recovery recorded — verdict \`${GOVERNANCE_LABEL_VERDICT}\``,
388
+ '',
389
+ `- **Failing check:** \`${digest?.failingCheck ?? 'unknown'}\``,
390
+ `- **Red run:** ${red}`,
391
+ `- **Green run:** ${green}`,
392
+ `- **Label:** \`${evidence.label}\` added by ${evidence.actor ? `@${evidence.actor}` : 'an unknown actor'} at ${evidence.labeledAt} (PR #${evidence.prNumber})`,
393
+ `- **Head SHA:** \`${digest?.headSha ?? 'unresolved'}\``,
394
+ '',
395
+ 'An operator-approved governance label started a fresh run on the red head,',
396
+ 'so **one** green on that head is admitted. No intake issue was filed: this',
397
+ 'is a recovery, not a CI gap. A second red after it is real and routes to',
398
+ 'Option 1.',
399
+ ].join('\n');
400
+ }
401
+
402
+ /**
403
+ * `governance-label`: prove the label transition, record the allowance and
404
+ * post the audit comment. Throws (non-zero exit, nothing written) when the
405
+ * transition is unproven.
406
+ *
407
+ * @returns {Promise<object>}
408
+ */
409
+ async function runGovernanceRecovery({
410
+ sid,
411
+ label,
412
+ prNumber: prFlag,
413
+ digest,
414
+ digestRoot,
415
+ cwd,
416
+ dryRun,
417
+ provider,
418
+ config,
419
+ labelHistoryFn,
420
+ greenRunFn,
421
+ }) {
422
+ const prNumber = prFlag ?? digest.prNumber ?? null;
423
+ if (!label) {
424
+ throw new Error(
425
+ `--verdict ${GOVERNANCE_LABEL_VERDICT} requires --label <name>: the operator-approved label that started the fresh run.`,
426
+ );
427
+ }
428
+ if (!prNumber) {
429
+ throw new Error('no PR number: pass --pr <n> (the digest records none).');
430
+ }
431
+ const proof = proveLabelTransition({
432
+ history: labelHistoryFn({ prNumber, cwd }),
433
+ label,
434
+ since: digest.generatedAt,
435
+ });
436
+ if (!proof) {
437
+ throw new Error(
438
+ `refused: PR #${prNumber} shows no \`labeled\` event for "${label}" after the red (${digest.generatedAt ?? 'unrecorded'}), or the label is no longer on it — nothing recorded.`,
439
+ );
440
+ }
441
+ const greenRun = greenRunFn({
442
+ prRef: String(prNumber),
443
+ checkName: digest.failingCheck,
444
+ cwd,
445
+ });
446
+ const evidence = { ...proof, prNumber, greenRun };
447
+ const body = renderGovernanceComment({ digest, evidence });
448
+ const result = {
449
+ storyId: sid,
450
+ verdict: GOVERNANCE_LABEL_VERDICT,
451
+ decision: dryRun ? 'dry-run' : 'recovered',
452
+ issue: null,
453
+ errors: [],
454
+ actions: { commented: false, blocked: false },
455
+ rerunAllowance: null,
456
+ evidence,
457
+ comment: body,
458
+ };
459
+ if (dryRun) return result;
460
+ result.rerunAllowance = recordRerunAllowance({
461
+ storyId: sid,
462
+ verdict: GOVERNANCE_LABEL_VERDICT,
463
+ tempRoot: digestRoot,
464
+ cwd,
465
+ evidence,
466
+ });
467
+ if (!result.rerunAllowance) {
468
+ throw new Error(
469
+ `could not record the allowance on the CI digest for Story #${sid}.`,
470
+ );
471
+ }
472
+ const ticketing = provider ?? createProvider(config);
473
+ if (ticketing) {
474
+ try {
475
+ await upsertStructuredComment(ticketing, sid, 'friction', body);
476
+ result.actions.commented = true;
477
+ } catch (err) {
478
+ result.errors.push(`friction comment failed: ${err?.message ?? err}`);
479
+ }
480
+ }
481
+ return result;
482
+ }
483
+
276
484
  /**
277
485
  * @returns {Promise<void>}
278
486
  */
@@ -285,6 +493,7 @@ async function main() {
285
493
  owner: { type: 'string' },
286
494
  evidence: { type: 'string' },
287
495
  pr: { type: 'string' },
496
+ label: { type: 'string' },
288
497
  block: { type: 'boolean', default: false },
289
498
  'dry-run': { type: 'boolean', default: false },
290
499
  },
@@ -298,6 +507,7 @@ async function main() {
298
507
  prNumber: values.pr ? Number(values.pr) : null,
299
508
  dryRun: values['dry-run'],
300
509
  block: values.block,
510
+ label: values.label ?? null,
301
511
  });
302
512
 
303
513
  process.stdout.write(`${JSON.stringify(result)}\n`);
@@ -7,9 +7,12 @@
7
7
 
8
8
  import fs from 'node:fs';
9
9
  import path from 'node:path';
10
+ import { decodeEnvelope } from '../baselines/codec.js';
10
11
  import { toPosix } from '../util/paths.js';
11
12
 
12
13
  /**
14
+ * A baseline envelope comes back decoded by the layout codec.
15
+ *
13
16
  * @param {string} absolutePath
14
17
  * @returns {{ exists: boolean, parsed: object | null, parseError: string | null }}
15
18
  */
@@ -21,7 +24,11 @@ export function readJsonFile(absolutePath) {
21
24
  return { exists: false, parsed: null, parseError: null };
22
25
  }
23
26
  try {
24
- return { exists: true, parsed: JSON.parse(raw), parseError: null };
27
+ return {
28
+ exists: true,
29
+ parsed: decodeEnvelope(JSON.parse(raw)),
30
+ parseError: null,
31
+ };
25
32
  } catch (err) {
26
33
  return {
27
34
  exists: true,
@@ -6,6 +6,7 @@
6
6
  * @module lib/audit-baselines/trend
7
7
  */
8
8
 
9
+ import { decodeEnvelope } from '../baselines/codec.js';
9
10
  import { execFileCapture } from '../child-exec.js';
10
11
  import { trendRollupOf } from './kinds.js';
11
12
 
@@ -52,7 +53,7 @@ function rollupAt({ cwd, kind, sha, relPath, run }) {
52
53
  return null;
53
54
  }
54
55
  try {
55
- return trendRollupOf(kind, JSON.parse(stdout));
56
+ return trendRollupOf(kind, decodeEnvelope(JSON.parse(stdout)));
56
57
  } catch {
57
58
  return null;
58
59
  }
@@ -32,6 +32,7 @@ export const AUDIT_LENSES = Object.freeze([
32
32
  'security',
33
33
  'seo',
34
34
  'sre',
35
+ 'state-machines',
35
36
  'ux-ui',
36
37
  ]);
37
38
 
@@ -1,3 +1,4 @@
1
+ import { decodeEnvelope } from './baselines/codec.js';
1
2
  import { createGitInterface } from './git-utils.js';
2
3
 
3
4
  /**
@@ -30,7 +31,8 @@ export function clearBaselineCache() {
30
31
  * @param {object} [opts]
31
32
  * @param {string} [opts.cwd]
32
33
  * @param {ReturnType<typeof createGitInterface>} [opts.git]
33
- * @returns {unknown} Parsed JSON; the schema is the caller's contract.
34
+ * @returns {unknown} Parsed JSON, decoded by the layout codec; the schema is
35
+ * the caller's contract.
34
36
  * @throws {Error} Naming ref and path, on an unresolvable blob or bad JSON.
35
37
  */
36
38
  export function readBaselineAtRef(ref, path, opts = {}) {
@@ -57,7 +59,7 @@ export function readBaselineAtRef(ref, path, opts = {}) {
57
59
  const raw = res.stdout ?? '';
58
60
  let parsed;
59
61
  try {
60
- parsed = JSON.parse(raw);
62
+ parsed = decodeEnvelope(JSON.parse(raw));
61
63
  } catch (err) {
62
64
  throw new Error(
63
65
  `[baseline-loader] parse-error reading "${path}" at ref "${ref}": ${err?.message ?? err}`,
@@ -0,0 +1,57 @@
1
+ /**
2
+ * The one baseline layout codec: every path that turns baseline JSON into
3
+ * rows, or rows into JSON, goes through here. CRAP persists rows grouped by
4
+ * path under `files`; every other kind persists `rows[]` verbatim.
5
+ *
6
+ * @module lib/baselines/codec
7
+ */
8
+
9
+ import { decodeCrapFiles, encodeCrapFiles } from './kinds/_crap-codec.js';
10
+
11
+ /** Fixed top-level order; a stamp reaches disk only if named here. */
12
+ const STAMP_KEYS = Object.freeze([
13
+ '$schema',
14
+ 'kernelVersion',
15
+ 'scoringSemantics',
16
+ 'tsTranspilerVersion',
17
+ ]);
18
+
19
+ function isCrapEnvelope(value) {
20
+ return (
21
+ typeof value?.$schema === 'string' &&
22
+ /(?:^|\/)crap\.schema\.json$/.test(value.$schema)
23
+ );
24
+ }
25
+
26
+ /**
27
+ * In-memory envelope to its on-disk object. Unset stamps stay undefined, so
28
+ * JSON omits them.
29
+ *
30
+ * @param {{rows: Array<object>}} envelope
31
+ * @returns {object}
32
+ */
33
+ export function encodeEnvelope(envelope) {
34
+ const out = {};
35
+ for (const key of STAMP_KEYS) out[key] = envelope[key];
36
+ if (isCrapEnvelope(envelope)) out.files = encodeCrapFiles(envelope.rows);
37
+ else out.rows = envelope.rows;
38
+ return out;
39
+ }
40
+
41
+ /**
42
+ * Parsed baseline JSON to the in-memory `rows` envelope. Anything that is
43
+ * not a grouped CRAP envelope — another kind, the previous CRAP `rows[]`
44
+ * layout, unparseable junk — is returned unchanged, so an old layout reaches
45
+ * the compat axes rather than a shape error.
46
+ *
47
+ * @param {unknown} parsed
48
+ * @returns {unknown}
49
+ */
50
+ export function decodeEnvelope(parsed) {
51
+ if (!isCrapEnvelope(parsed)) return parsed;
52
+ const { files, ...stamps } = parsed;
53
+ if (!files || typeof files !== 'object' || Array.isArray(files)) {
54
+ return parsed;
55
+ }
56
+ return { ...stamps, rows: decodeCrapFiles(files) };
57
+ }