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
@@ -27,7 +27,12 @@ import {
27
27
  classifyBranchSeed,
28
28
  seedStoryBranchRef,
29
29
  } from './lib/git-branch-lifecycle.js';
30
- import { getStoryBranch, gitSpawn, gitSync } from './lib/git-utils.js';
30
+ import {
31
+ getStoryBranch,
32
+ gitSpawn,
33
+ gitSync,
34
+ parseStoryBranch,
35
+ } from './lib/git-utils.js';
31
36
  import { Logger } from './lib/Logger.js';
32
37
  import { TYPE_LABELS } from './lib/label-constants.js';
33
38
  import { emitTerseResult } from './lib/observability/terse-result.js';
@@ -280,12 +285,13 @@ export async function reapClosedStoryWorktrees({
280
285
 
281
286
  /**
282
287
  * Reap merged `story-*` branches (excluding the current one), then the
283
- * closed-Story worktrees, then stranded `agent::closing` Stories. Never
288
+ * closed-Story worktrees, then stranded `agent::closing` Stories, then reports
289
+ * stalled `agent::executing` Stories (never this one). Never
284
290
  * blocks init. Protected candidates (unpushed work, dirty worktree, open
285
291
  * Story) are skipped; the lockfile is shared with `boot-sweep.js` via
286
292
  * `resolveSweepLockPath` so concurrent reaps cannot race.
287
293
  *
288
- * @returns {Promise<{ worktreeSweep: object, closingReconcile: object }>}
294
+ * @returns {Promise<{ worktreeSweep: object, closingReconcile: object, stalledExecuting: object }>}
289
295
  */
290
296
  export async function reapMergedStoryBranches({
291
297
  cwd,
@@ -297,6 +303,7 @@ export async function reapMergedStoryBranches({
297
303
  worktreeSweepFn,
298
304
  acquireLockFn,
299
305
  closingReconcileFn,
306
+ stalledExecutingFn,
300
307
  }) {
301
308
  const sweepFn =
302
309
  injectedSweep ??
@@ -336,7 +343,20 @@ export async function reapMergedStoryBranches({
336
343
  warn: (m) => progress('CLEANUP', `⚠️ ${m}`),
337
344
  },
338
345
  });
339
- return { worktreeSweep, closingReconcile };
346
+ const report =
347
+ stalledExecutingFn ??
348
+ (await import('./lib/single-story-sweep/report-stalled-executing.js'))
349
+ .reportStalledExecuting;
350
+ const stalledExecuting = await report({
351
+ provider,
352
+ config,
353
+ excludeStoryIds: [parseStoryBranch(storyBranch)],
354
+ logger: {
355
+ info: (m) => progress('CLEANUP', m),
356
+ warn: (m) => progress('CLEANUP', `⚠️ ${m}`),
357
+ },
358
+ });
359
+ return { worktreeSweep, closingReconcile, stalledExecuting };
340
360
  }
341
361
 
342
362
  async function reapMergedBranches({
@@ -2,8 +2,8 @@
2
2
 
3
3
  /**
4
4
  * story-handoff.js — the story-worker's whole post-implementation tail in one
5
- * command: preflight (lint + quality-preview + baselined ratchets) → merge
6
- * origin/<base> → the one credited run → `--seat-missing` baseline seating →
5
+ * command: merge origin/<base> → close's untagged duplication re-score →
6
+ * preflight (lint + quality-preview + baselined ratchets) → the one credited run → `--seat-missing` baseline seating →
7
7
  * push + remote-ref check → held Story-scope review. Prints one JSON envelope on stdout.
8
8
  *
9
9
  * Exit 0 `ready` (hand off) · 2 `fix-required` (fix, commit, re-run; labels
@@ -26,7 +26,7 @@ const USAGE = {
26
26
  invocation:
27
27
  'node .agents/scripts/story-handoff.js --story <id> [--cwd <workCwd>]',
28
28
  summary:
29
- "Run the story-worker's post-implementation tail — preflight, base merge, the one credited run, baseline seating, push and held review — and print one envelope: ready (exit 0), fix-required (exit 2) or blocked (exit 1).",
29
+ "Run the story-worker's post-implementation tail — base merge, duplication re-score, preflight, the one credited run, baseline seating, push and held review — and print one envelope: ready (exit 0), fix-required (exit 2) or blocked (exit 1).",
30
30
  flags: [
31
31
  ['--story <id>', 'Story issue number; the branch is story-<id>.'],
32
32
  ['--cwd <path>', "The Story's worktree (default: the current directory)."],
@@ -0,0 +1,231 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * story-outcomes-report.js — roll up the `story-outcome` records close writes
5
+ * when `delivery.feedbackLoop.outcomeRecord` is on: per-Story rows, first-pass
6
+ * rate, mean attempts to land, failed gates by count, and the same rates split
7
+ * by the mandrel version of each landing. Read-only; one paginated read.
8
+ */
9
+
10
+ import { parseArgs } from 'node:util';
11
+
12
+ import { runAsCli } from './lib/cli-utils.js';
13
+ import { resolveConfig } from './lib/config-resolver.js';
14
+ import {
15
+ OUTCOME_COMMENT_TYPE,
16
+ parseOutcomeBody,
17
+ } from './lib/observability/story-outcome.js';
18
+ import { structuredCommentMarker } from './lib/orchestration/ticketing/reads.js';
19
+ import { createProvider } from './lib/provider-factory.js';
20
+ import { alignRows } from './review-dispositions-report.js';
21
+
22
+ const USAGE = {
23
+ invocation:
24
+ 'node .agents/scripts/story-outcomes-report.js [--since <YYYY-MM-DD>] [--json]',
25
+ summary:
26
+ 'Summarize the per-Story close outcome records (story-outcome comments) updated in the window: per-Story rows, first-pass rate, mean attempts to land, blocked/failed share of attempts, failed gates ranked by count, and the same rates by landing mandrel version.',
27
+ flags: [
28
+ ['--since <YYYY-MM-DD>', 'Window start (default: 7 days ago).'],
29
+ ['--json', 'Emit the report as JSON instead of a table.'],
30
+ ],
31
+ };
32
+
33
+ const DATE = /^\d{4}-\d{2}-\d{2}$/;
34
+ const DEFAULT_WINDOW_DAYS = 7;
35
+ const DAY_MS = 86_400_000;
36
+
37
+ /** @param {number|null} r */
38
+ const pct = (r) => (r === null ? '-' : `${(r * 100).toFixed(1)}%`);
39
+ const ratio = (num, den) => (den > 0 ? num / den : null);
40
+ const mean = (values) =>
41
+ values.length > 0 ? values.reduce((a, b) => a + b, 0) / values.length : null;
42
+
43
+ function storyIdOf(comment) {
44
+ const match = /\/issues\/(\d+)$/.exec(String(comment?.issue_url ?? ''));
45
+ return match ? Number(match[1]) : null;
46
+ }
47
+
48
+ /** Latest outcome comment per Story, by `updated_at`. */
49
+ function latestPerStory(comments) {
50
+ const marker = structuredCommentMarker(OUTCOME_COMMENT_TYPE);
51
+ const byStory = new Map();
52
+ for (const comment of comments ?? []) {
53
+ if (!String(comment?.body ?? '').includes(marker)) continue;
54
+ const storyId = storyIdOf(comment);
55
+ const prior = byStory.get(storyId);
56
+ if (!prior || String(comment.updated_at) > String(prior.updated_at)) {
57
+ byStory.set(storyId, comment);
58
+ }
59
+ }
60
+ return byStory;
61
+ }
62
+
63
+ function landingVersion(record) {
64
+ const landing = record.attempts.findLast((a) => a?.status === 'landed');
65
+ return landing?.mandrelVersion ?? 'unknown';
66
+ }
67
+
68
+ function storyRow(storyId, record) {
69
+ const s = record.summary;
70
+ return {
71
+ storyId: record.storyId ?? storyId,
72
+ attempts: s.attempts ?? 0,
73
+ byStatus: s.byStatus ?? {},
74
+ landed: Boolean(s.landedAt),
75
+ firstPass: s.firstPass === true,
76
+ landedOnAttempt: s.landedOnAttempt ?? null,
77
+ failedGates: s.failedGates ?? {},
78
+ mandrelVersion: s.landedAt ? landingVersion(record) : null,
79
+ };
80
+ }
81
+
82
+ function landingRates(rows) {
83
+ const landed = rows.filter((r) => r.landed);
84
+ return {
85
+ landed: landed.length,
86
+ firstPassRate: ratio(
87
+ landed.filter((r) => r.firstPass).length,
88
+ landed.length,
89
+ ),
90
+ meanAttemptsToLand: mean(
91
+ landed.map((r) => r.landedOnAttempt).filter(Number.isInteger),
92
+ ),
93
+ };
94
+ }
95
+
96
+ /**
97
+ * @param {Array<object>} comments raw repo issue comments.
98
+ * @returns {object} the report.
99
+ */
100
+ export function summarizeOutcomes(comments) {
101
+ const rows = [];
102
+ const unreadable = [];
103
+ for (const [storyId, comment] of latestPerStory(comments)) {
104
+ const record = parseOutcomeBody(comment.body);
105
+ if (record) rows.push(storyRow(storyId, record));
106
+ else unreadable.push({ storyId, commentId: comment.id ?? null });
107
+ }
108
+ rows.sort((a, b) => a.storyId - b.storyId);
109
+ const totalAttempts = rows.reduce((n, r) => n + r.attempts, 0);
110
+ const sumStatus = (status) =>
111
+ rows.reduce((n, r) => n + (r.byStatus[status] ?? 0), 0);
112
+ const gateCounts = {};
113
+ for (const row of rows) {
114
+ for (const [gate, count] of Object.entries(row.failedGates)) {
115
+ gateCounts[gate] = (gateCounts[gate] ?? 0) + count;
116
+ }
117
+ }
118
+ const versions = [
119
+ ...new Set(rows.filter((r) => r.landed).map((r) => r.mandrelVersion)),
120
+ ];
121
+ return {
122
+ stories: rows.length,
123
+ ...landingRates(rows),
124
+ blockedShare: ratio(sumStatus('blocked'), totalAttempts),
125
+ failedShare: ratio(sumStatus('failed'), totalAttempts),
126
+ failedGates: Object.entries(gateCounts)
127
+ .map(([gate, count]) => ({ gate, count }))
128
+ .sort((a, b) => b.count - a.count || a.gate.localeCompare(b.gate)),
129
+ byMandrelVersion: Object.fromEntries(
130
+ versions
131
+ .sort()
132
+ .map((v) => [
133
+ v,
134
+ landingRates(rows.filter((r) => r.mandrelVersion === v)),
135
+ ]),
136
+ ),
137
+ unreadable,
138
+ rows,
139
+ };
140
+ }
141
+
142
+ function renderReport(report) {
143
+ const fmtMean = (m) => (m === null ? '-' : m.toFixed(2));
144
+ const storyTable = alignRows([
145
+ ['story', 'attempts', 'landed', 'first-pass', 'version', 'failed gates'],
146
+ ...report.rows.map((r) => [
147
+ `#${r.storyId}`,
148
+ String(r.attempts),
149
+ r.landed ? 'yes' : 'no',
150
+ r.firstPass ? 'yes' : 'no',
151
+ r.mandrelVersion ?? '-',
152
+ Object.keys(r.failedGates).join(', ') || '-',
153
+ ]),
154
+ ]);
155
+ const versionTable = alignRows([
156
+ ['version', 'landed', 'first-pass', 'mean attempts'],
157
+ ...Object.entries(report.byMandrelVersion).map(([v, r]) => [
158
+ v,
159
+ String(r.landed),
160
+ pct(r.firstPassRate),
161
+ fmtMean(r.meanAttemptsToLand),
162
+ ]),
163
+ ]);
164
+ return [
165
+ ...storyTable,
166
+ '',
167
+ `stories ${report.stories} · landed ${report.landed} · first-pass ${pct(report.firstPassRate)} · mean attempts to land ${fmtMean(report.meanAttemptsToLand)} · blocked ${pct(report.blockedShare)} · failed ${pct(report.failedShare)} of attempts`,
168
+ `failed gates: ${report.failedGates.map((g) => `${g.gate} ${g.count}`).join(', ') || 'none'}`,
169
+ '',
170
+ ...versionTable,
171
+ ...(report.unreadable.length > 0
172
+ ? [
173
+ '',
174
+ `unreadable: ${report.unreadable.map((u) => `#${u.storyId}`).join(', ')}`,
175
+ ]
176
+ : []),
177
+ '',
178
+ ].join('\n');
179
+ }
180
+
181
+ /**
182
+ * @param {string[]} [argv]
183
+ * @param {{ resolveConfigImpl?: typeof resolveConfig,
184
+ * providerFactory?: typeof createProvider,
185
+ * stdout?: { write: (s: string) => void }, cwd?: string, nowMs?: number }} [deps]
186
+ * @returns {Promise<object>} the report.
187
+ */
188
+ export async function runStoryOutcomesReport(
189
+ argv = process.argv.slice(2),
190
+ deps = {},
191
+ ) {
192
+ const {
193
+ resolveConfigImpl = resolveConfig,
194
+ providerFactory = createProvider,
195
+ stdout = process.stdout,
196
+ cwd = process.cwd(),
197
+ nowMs = Date.now(),
198
+ } = deps;
199
+ const { values } = parseArgs({
200
+ args: argv,
201
+ options: { since: { type: 'string' }, json: { type: 'boolean' } },
202
+ });
203
+ if (values.since !== undefined && !DATE.test(values.since)) {
204
+ throw new Error(
205
+ `story-outcomes-report: --since must be YYYY-MM-DD (got "${values.since}").`,
206
+ );
207
+ }
208
+ const since = values.since
209
+ ? `${values.since}T00:00:00Z`
210
+ : new Date(nowMs - DEFAULT_WINDOW_DAYS * DAY_MS).toISOString();
211
+ const provider = providerFactory(resolveConfigImpl({ cwd }));
212
+ const report = summarizeOutcomes(await provider.getRepoCommentsSince(since));
213
+ stdout.write(
214
+ values.json
215
+ ? `${JSON.stringify({ since, ...report }, null, 2)}\n`
216
+ : renderReport(report),
217
+ );
218
+ return report;
219
+ }
220
+
221
+ async function main() {
222
+ await runStoryOutcomesReport();
223
+ return 0;
224
+ }
225
+
226
+ runAsCli(import.meta.url, main, {
227
+ source: 'story-outcomes-report',
228
+ propagateExitCode: true,
229
+ errorPrefix: '[story-outcomes-report] ❌ Fatal error',
230
+ usage: USAGE,
231
+ });
@@ -54,6 +54,14 @@ function formatTally(severity) {
54
54
  return `critical=${s.critical ?? 0} high=${s.high ?? 0} medium=${s.medium ?? 0} suggestion=${s.suggestion ?? 0}`;
55
55
  }
56
56
 
57
+ /** A no-verdict halt is blocked (no code change resolves it); else CRITICAL. */
58
+ function haltLine(deposit) {
59
+ if (deposit.haltCause === 'no-verdict') {
60
+ return `[story-review-compute] ⛔ BLOCKED: ${deposit.blockerReason}\n`;
61
+ }
62
+ return `[story-review-compute] ❌ CRITICAL: fix, commit and re-push before hand-off. Report:\n${deposit.report}\n`;
63
+ }
64
+
57
65
  /**
58
66
  * @param {{ storyId: number, cwd: string, config: object }} input
59
67
  * @param {{
@@ -167,11 +175,7 @@ export async function runStoryReviewComputeCli(
167
175
  `[story-review-compute] ✅ Held review for Story #${storyId} written → ${outcome.path}\n` +
168
176
  `[story-review-compute] diff ${deposit.diffDigest.slice(0, 12)} @ ${deposit.headSha.slice(0, 12)} · ${formatTally(deposit.severity)}\n`,
169
177
  );
170
- if (deposit.halted) {
171
- stdout.write(
172
- `[story-review-compute] ❌ CRITICAL: fix, commit and re-push before hand-off. Report:\n${deposit.report}\n`,
173
- );
174
- }
178
+ if (deposit.halted) stdout.write(haltLine(deposit));
175
179
  return outcome;
176
180
  }
177
181
 
@@ -14,6 +14,7 @@ import {
14
14
  resolveCoverageUpdaterScope,
15
15
  } from './lib/baselines/coverage-updater-cli.js';
16
16
  import { refreshBaseline } from './lib/baselines/refresh-service.js';
17
+ import { seatCoverageBaseline } from './lib/baselines/seat-missing.js';
17
18
  import { runAsCli } from './lib/cli-utils.js';
18
19
  import { getQuality, resolveConfig } from './lib/config-resolver.js';
19
20
  import { Logger } from './lib/Logger.js';
@@ -21,7 +22,7 @@ import { Logger } from './lib/Logger.js';
21
22
  /** `runAsCli` answers `--help` before `main`, so a usage probe never writes. */
22
23
  const USAGE = {
23
24
  invocation:
24
- 'node .agents/scripts/update-coverage-baseline.js [--full-scope | --diff-scope <ref>]',
25
+ 'node .agents/scripts/update-coverage-baseline.js [--full-scope | --diff-scope <ref>] [--seat-missing]',
25
26
  summary:
26
27
  'Score → write the coverage baseline from the coverage artifact (`delivery.quality.gates.coverage.coveragePath`, Istanbul coverage-final.json) already on disk. With no scope flag the refresh is scoped to the files changed in `origin/main..HEAD`; out-of-scope rows are preserved verbatim.',
27
28
  flags: [
@@ -33,6 +34,10 @@ const USAGE = {
33
34
  '--diff-scope <ref>',
34
35
  'Scope the refresh to files changed between <ref> and HEAD. Incompatible with --full-scope.',
35
36
  ],
37
+ [
38
+ '--seat-missing',
39
+ 'Insert-only: write rows ONLY for changed files (merge-base of `--diff-scope <ref>`, default `origin/<baseBranch>`) that have no baseline row; every existing row stays byte-identical. Refuses unless a coverage capture stamp is fresh for the current tree; a changed file the artifact did not measure is logged, never seated. Prints `seated: N`. Incompatible with --full-scope.',
40
+ ],
36
41
  ],
37
42
  notes: [
38
43
  "Run the coverage gate's `captureScript` first (`delivery.quality.gates.coverage.captureScript`) — this script never runs the suite itself.",
@@ -67,7 +72,12 @@ function main() {
67
72
  });
68
73
  }
69
74
 
70
- runAsCli(import.meta.url, main, {
75
+ async function seat() {
76
+ process.exitCode = await seatCoverageBaseline(process.argv.slice(2));
77
+ }
78
+
79
+ const seating = process.argv.includes('--seat-missing');
80
+ runAsCli(import.meta.url, seating ? seat : main, {
71
81
  source: 'coverage-baseline',
72
82
  usage: USAGE,
73
83
  onError: (err) => {
@@ -78,9 +78,17 @@ async function main() {
78
78
  epsilon: getBaselineEpsilon('crap'),
79
79
  }),
80
80
  );
81
+ logRefresh(result, options.absBaselinePath);
82
+ }
81
83
 
84
+ /** An ahead baseline was left untouched; otherwise report the write. */
85
+ function logRefresh(result, baselinePath) {
86
+ if (result.ahead) {
87
+ Logger.info(result.ahead.message);
88
+ return;
89
+ }
82
90
  Logger.info(
83
- `[CRAP] ✅ Baseline updated (kernelVersion=${result.envelope.kernelVersion}, escomplexVersion=${resolveEscomplexVersion()}, tsTranspilerVersion=${result.envelope.tsTranspilerVersion}). Wrote to ${options.absBaselinePath}.`,
91
+ `[CRAP] ✅ Baseline updated (kernelVersion=${result.envelope.kernelVersion}, escomplexVersion=${resolveEscomplexVersion()}, tsTranspilerVersion=${result.envelope.tsTranspilerVersion}). Wrote to ${baselinePath}.`,
84
92
  );
85
93
  Logger.info(
86
94
  `[CRAP] Wrote ${result.envelope.rows.length} row(s). scope=${result.scope.mode}, wrote=${result.wrote}.`,
@@ -0,0 +1,213 @@
1
+ ---
2
+ description: >-
3
+ Audit implicit state machines — co-varying flags, status sidecar fields,
4
+ scattered transitions, state split across systems — and report only the
5
+ impossible or unhandled combinations the code can reach, each with a traced
6
+ write path and a sketch of the explicit form.
7
+ ---
8
+
9
+ # State Machine Audit
10
+
11
+ You are a Staff Engineer hunting the states nobody designed. Most code tracks
12
+ state in loose variables: a few booleans, a status string with fields that
13
+ only make sense in some statuses, a label on a ticket plus a file on disk.
14
+ Together those variables form a state machine that exists only by implication,
15
+ and it usually admits combinations its authors never meant to allow. This lens
16
+ names those machines, proves which bad combinations are reachable, and
17
+ sketches the explicit form — a discriminated union, a tagged object with one
18
+ guard, or a transition table — that would make them unrepresentable. A
19
+ machine's writers rarely sit in one file, so the lens is cumulative.
20
+
21
+ The shared lens machinery lives in
22
+ [`helpers/audit-lens-core.md`](helpers/audit-lens-core.md). Write the report to
23
+ `{{auditResultsDir}}/audit-state-machines-results.md`. Dimension values:
24
+ `Boolean Soup | Status Sidecar | Scattered Transitions | Unhandled State | Distributed State`.
25
+ Extra finding fields: **Variables:** (the co-varying set, `path:line` each),
26
+ **Reachable Path:** (the traced write sequence that produces the bad
27
+ combination) and **Explicit Form:** (a few lines naming the replacement
28
+ shape). The report adds two mandatory sections, **State Inventory** and
29
+ **Refactor Sketch** (see Report additions).
30
+
31
+ > **Prove reachability before you judge.** Every object with two fields is
32
+ > technically a state machine. A finding is a claim that a specific bad
33
+ > combination can happen, so it carries the write path that produces it; a
34
+ > combination you cannot trace is inventoried, never reported.
35
+
36
+ ## Boundaries
37
+
38
+ Four lenses border this one. Report a finding **here** only when the fix is
39
+ "change the shape of the state so the bad combination cannot be written";
40
+ defer the rest so the suite never double-reports:
41
+
42
+ - `audit-resilience` keeps whether a reconcile job's filter covers every state
43
+ a failure can leave. This lens reports the state shape that makes the
44
+ combination possible, and defers when the only gap is the reconciler's
45
+ filter.
46
+ - `audit-data-model` keeps database enums, `CHECK` constraints and DB-level
47
+ invariants. This lens reports application-level state, and a DB-backed
48
+ status only when the application writes combinations the schema permits.
49
+ - `audit-performance` keeps interleaving and concurrency races (TOCTOU, lost
50
+ updates). This lens reports combinations reachable on a single thread of
51
+ execution, with no interleaving required.
52
+ - `audit-clean-code` keeps complexity hotspots, naming and stale feature
53
+ flags. A long if-chain is reported here only when it misses a reachable
54
+ state.
55
+
56
+ ## Scope
57
+
58
+ Per the core's Scope interpretation:
59
+
60
+ ```text
61
+ {{changedFiles}}
62
+ ```
63
+
64
+ When the fence resolves to a file list, take the state variables those files
65
+ read or write as the candidates, but trace every writer and reader across the
66
+ **whole tree** — a machine's other writers usually sit outside the change set.
67
+ When the fence renders literally, run codebase-wide.
68
+
69
+ ## Execution strategy
70
+
71
+ Run this lens as one `subagent_type: auditor` dispatch per the core's
72
+ Execution strategy. It never fans out on its own judgment.
73
+
74
+ ## Step 0: Qualifying bar (mandatory)
75
+
76
+ A candidate is an implicit state machine only when **both** parts hold:
77
+
78
+ 1. **Shape: the variables move together.** Two or more variables change
79
+ together to encode one logical state: a set of booleans, a status value plus fields whose validity depends
80
+ on it, or one logical state held in two systems (labels, files on disk, git
81
+ refs, a database row plus a cache, a lease assignee).
82
+ 2. **Consequence: a bad combination is reachable.** At least one combination of those variables that the code
83
+ does not intend is reachable, or one reachable value is not handled by a
84
+ consumer — shown with a traced path: the entry point, then each write by
85
+ `path:line` in the order it executes, then the bad combination it leaves.
86
+
87
+ A candidate that clears part 1 but not part 2 is recorded in the State
88
+ Inventory with `reachable: no` and produces **no finding**. A combination that
89
+ only a test fixture or a hand-edited file can produce is not reachable.
90
+
91
+ ## Step 1: Find candidates (tool-first)
92
+
93
+ Run the greps, then group hits by the object or module that owns them — a
94
+ candidate is a group, not a line. Adapt the patterns to the project's
95
+ languages per the core's ecosystem-detection rule:
96
+
97
+ - Run the candidate greps:
98
+
99
+ ```bash
100
+ git grep -nE '\b(is|has|was|did|should)[A-Z][A-Za-z]*\s*[:=]\s*(true|false)\b'
101
+ git grep -nE "\b(status|state|phase|stage|mode|kind)\s*[:=]\s*['\"][A-Za-z_-]+['\"]"
102
+ git grep -nE '\.(status|state|phase|stage)\s*=[^=]'
103
+ git grep -nE 'switch\s*\(\s*[A-Za-z_.]*(status|state|phase|stage|kind)\s*\)'
104
+ ```
105
+
106
+ - For each status variable, count its writer sites; three or more writers with
107
+ no shared guard is a Scattered Transitions candidate.
108
+
109
+ ## Step 2: Judge each candidate
110
+
111
+ ### Boolean Soup
112
+
113
+ - **Flags that encode one enum:** booleans that together stand for one state
114
+ (`isLoading` / `isError` / `isDone`, `started` / `finished` / `cancelled`)
115
+ where some true/false product is meaningless yet writable — both
116
+ `isLoading` and `isError` true, or `finished` without `started`.
117
+
118
+ ### Status Sidecar
119
+
120
+ - **Fields valid only in some statuses:** a status field plus nullable fields
121
+ whose meaning depends on it — an `error` set while status is `ok`, a
122
+ `result` null while status is `done`, a `mergedAt` while status is `open`.
123
+ Report the write that leaves the sidecar stale when the status moves.
124
+
125
+ ### Scattered Transitions
126
+
127
+ - **Transitions with no single guard:** a state written from many sites, so
128
+ an illegal transition (`done` back to `executing`) or a re-entry that
129
+ repeats a side effect is reachable. Name every writer site and the one
130
+ that skips the check the others make.
131
+
132
+ ### Unhandled State
133
+
134
+ - **Consumers that miss a value:** a `switch`, if-chain or lookup table over a
135
+ status that omits a reachable value and has no exhaustiveness check, or
136
+ falls through to a silent default that treats the missing value as another.
137
+
138
+ ### Distributed State
139
+
140
+ - **One state, two stores:** one logical state spread across systems that can
141
+ disagree — two lifecycle labels at once, a lease held after its branch is
142
+ gone, a marker file that outlives the work it marks — with no reconciler,
143
+ or with a reconciler that cannot see the disagreeing combination (then
144
+ name the combination and defer the filter to `audit-resilience`).
145
+
146
+ ## Step 3: Evidence and severity
147
+
148
+ - **Second read of the write order.** Every finding's Reachable Path is
149
+ re-checked by a second read of the actual write order — the call sequence,
150
+ the early returns, the guards upstream — not of a comment, a type
151
+ annotation, or one file. A path an upstream guard actually blocks is
152
+ dropped and counted in the kept/dropped line.
153
+ - **Severity calibration.** Grade on the core scale with these anchors:
154
+ - `Critical` or `High` — the reachable state loses or corrupts data, repeats
155
+ an external side effect (a double charge, a double merge, a double post),
156
+ or wedges a lifecycle with no recovery path.
157
+ - `Medium` — a wrong user-visible result, or a stuck state that a retry or
158
+ an operator clears.
159
+ - `Low` — a reachable but cosmetic mismatch.
160
+
161
+ ## Report additions
162
+
163
+ Beyond the core's shared skeleton, this lens adds its title, the two mandatory
164
+ sections and the three finding fields. Write `_No findings._` under a section
165
+ rather than omitting it.
166
+
167
+ The **State Inventory** comes before any finding, one row per candidate that
168
+ cleared part 1 of the qualifying bar; every finding cites a row.
169
+
170
+ The **Refactor Sketch** covers the single most critical finding only: a
171
+ before/after sketch in the project's own language — a discriminated union in
172
+ TypeScript, a JSDoc `@typedef` union plus one guard function in JavaScript, a
173
+ tagged class or an `enum` plus an exhaustive `match` in other languages, or a transition table with one
174
+ `transition(state, event)` function every writer goes through. It names which
175
+ writer sites move behind the guard and which combination becomes
176
+ unrepresentable. It is a sketch inside the report: this lens edits no code,
177
+ per the core's read-only constraint, and the fix lands through
178
+ `/audit-to-stories`.
179
+
180
+ ```markdown
181
+ # State Machine Audit Report
182
+
183
+ ## Executive Summary
184
+
185
+ [Headline read.]
186
+
187
+ Self-cross-check: kept <k> / dropped <d>.
188
+ Severity tally: Critical <n> / High <n> / Medium <n> / Low <n>
189
+
190
+ ## State Inventory
191
+
192
+ | Candidate | Variables | Implicit states | Transitions (writers) | Impossible or unhandled combinations | Reachable |
193
+ | --- | --- | --- | --- | --- | --- |
194
+ | [name] | `path:line`, … | [states] | `path:line`, … | [combination] | [yes — finding title / no] |
195
+
196
+ ## Detailed Findings
197
+
198
+ ### `path/to/primary-file.ext` — [Short title of the issue]
199
+
200
+ - **Dimension:** [Boolean Soup | Status Sidecar | Scattered Transitions | Unhandled State | Distributed State]
201
+ - **Severity:** [Critical | High | Medium | Low | Info]
202
+ - **Variables:** [the co-varying set, `path:line` each]
203
+ - **Reachable Path:** [entry point → write at `path:line` → write at `path:line` → the bad combination]
204
+ - **Explicit Form:** [the replacement shape in a few lines]
205
+ - [Location, Current State, Recommendation & Rationale, Acceptance signal —
206
+ per the core skeleton]
207
+
208
+ ## Refactor Sketch
209
+
210
+ [The most critical finding's title. Before: the loose variables and their
211
+ writers. After: the explicit form and the one guard every writer calls. The
212
+ combination that becomes unrepresentable.]
213
+ ```