mandrel 2.111.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 (178) 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 +351 -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/preview-gates.js +29 -10
  38. package/.agents/scripts/lib/baselines/reader.js +36 -9
  39. package/.agents/scripts/lib/baselines/refresh-service.js +79 -18
  40. package/.agents/scripts/lib/baselines/seat-missing.js +173 -7
  41. package/.agents/scripts/lib/baselines/writer.js +36 -21
  42. package/.agents/scripts/lib/changed-files.js +70 -6
  43. package/.agents/scripts/lib/child-exec.js +10 -0
  44. package/.agents/scripts/lib/claude/agents-projection.js +5 -5
  45. package/.agents/scripts/lib/close-lock-events.js +8 -3
  46. package/.agents/scripts/lib/close-validation/ci-deferral.js +40 -0
  47. package/.agents/scripts/lib/close-validation/gates.js +111 -35
  48. package/.agents/scripts/lib/close-validation/process.js +16 -7
  49. package/.agents/scripts/lib/close-validation/projections/crap.js +43 -10
  50. package/.agents/scripts/lib/close-validation/runner.js +55 -23
  51. package/.agents/scripts/lib/close-validation/skip-branch-test.js +144 -0
  52. package/.agents/scripts/lib/close-validation/test-delta.js +33 -8
  53. package/.agents/scripts/lib/codex/agents-projection.js +6 -0
  54. package/.agents/scripts/lib/config/agentrc-overlay.js +9 -5
  55. package/.agents/scripts/lib/config/explain.js +5 -2
  56. package/.agents/scripts/lib/config/gates/coverage.schema.js +45 -1
  57. package/.agents/scripts/lib/config/gates/crap-incremental-coverage.schema.js +1 -1
  58. package/.agents/scripts/lib/config/git-roots.js +38 -4
  59. package/.agents/scripts/lib/config/handoff.js +24 -0
  60. package/.agents/scripts/lib/config/quality.js +26 -13
  61. package/.agents/scripts/lib/config/worktree-isolation.js +2 -5
  62. package/.agents/scripts/lib/config-resolver.js +22 -2
  63. package/.agents/scripts/lib/config-settings-schema-delivery.js +87 -4
  64. package/.agents/scripts/lib/config-settings-schema-quality.js +36 -1
  65. package/.agents/scripts/lib/config-settings-schema.js +1 -1
  66. package/.agents/scripts/lib/coverage-capture-affected.js +1 -0
  67. package/.agents/scripts/lib/coverage-capture-delta.js +164 -32
  68. package/.agents/scripts/lib/coverage-capture-own-fix.js +232 -0
  69. package/.agents/scripts/lib/coverage-capture-usage.js +2 -2
  70. package/.agents/scripts/lib/coverage-capture.js +15 -0
  71. package/.agents/scripts/lib/coverage-deferral.js +96 -0
  72. package/.agents/scripts/lib/coverage-ratchet.js +187 -0
  73. package/.agents/scripts/lib/crap-baseline-join.js +5 -5
  74. package/.agents/scripts/lib/crap-engine.js +3 -3
  75. package/.agents/scripts/lib/crap-method-identity.js +104 -48
  76. package/.agents/scripts/lib/escomplex-anchor.js +135 -0
  77. package/.agents/scripts/lib/escomplex-kernel.js +30 -1
  78. package/.agents/scripts/lib/failure-rows.js +121 -0
  79. package/.agents/scripts/lib/full-suite-lock.js +44 -4
  80. package/.agents/scripts/lib/full-suite-queue.js +89 -13
  81. package/.agents/scripts/lib/generated/agentrc-validator.js +8 -2
  82. package/.agents/scripts/lib/gh-env.js +3 -6
  83. package/.agents/scripts/lib/gh-pr-rest.js +1 -0
  84. package/.agents/scripts/lib/git/base-sync-probe.js +182 -0
  85. package/.agents/scripts/lib/git-branch-lifecycle.js +9 -0
  86. package/.agents/scripts/lib/observability/close-telemetry.js +37 -2
  87. package/.agents/scripts/lib/observability/handoff-telemetry.js +170 -0
  88. package/.agents/scripts/lib/observability/review-dispositions.js +23 -6
  89. package/.agents/scripts/lib/observability/runtime-friction.js +17 -4
  90. package/.agents/scripts/lib/observability/source-classifier.js +3 -0
  91. package/.agents/scripts/lib/observability/story-outcome.js +393 -0
  92. package/.agents/scripts/lib/orchestration/check-baselines/phases/compare.js +2 -1
  93. package/.agents/scripts/lib/orchestration/check-baselines/phases/evaluate.js +19 -1
  94. package/.agents/scripts/lib/orchestration/check-baselines/phases/fail-detail.js +84 -0
  95. package/.agents/scripts/lib/orchestration/check-baselines/phases/pipeline.js +14 -5
  96. package/.agents/scripts/lib/orchestration/check-baselines/phases/refresh-ack.js +3 -2
  97. package/.agents/scripts/lib/orchestration/check-baselines/phases/report.js +26 -6
  98. package/.agents/scripts/lib/orchestration/code-review.js +223 -19
  99. package/.agents/scripts/lib/orchestration/handoff-gates.js +129 -62
  100. package/.agents/scripts/lib/orchestration/handoff-rescore.js +169 -0
  101. package/.agents/scripts/lib/orchestration/handoff-suite-of-record.js +45 -0
  102. package/.agents/scripts/lib/orchestration/preflight-lanes.js +208 -0
  103. package/.agents/scripts/lib/orchestration/review-base-ref.js +40 -17
  104. package/.agents/scripts/lib/orchestration/review-deposit.js +38 -12
  105. package/.agents/scripts/lib/orchestration/review-depth.js +21 -0
  106. package/.agents/scripts/lib/orchestration/review-history.js +124 -20
  107. package/.agents/scripts/lib/orchestration/review-providers/claude-verdict.js +23 -8
  108. package/.agents/scripts/lib/orchestration/review-providers/code-review.js +82 -39
  109. package/.agents/scripts/lib/orchestration/review-providers/critical-verifier.js +64 -11
  110. package/.agents/scripts/lib/orchestration/review-providers/degraded-gates.js +98 -3
  111. package/.agents/scripts/lib/orchestration/review-providers/finding-identity.js +6 -2
  112. package/.agents/scripts/lib/orchestration/review-providers/findings-renderer.js +55 -8
  113. package/.agents/scripts/lib/orchestration/review-providers/review-guidance.js +1 -0
  114. package/.agents/scripts/lib/orchestration/review-providers/review-provider-factory.js +42 -15
  115. package/.agents/scripts/lib/orchestration/review-providers/types.js +6 -0
  116. package/.agents/scripts/lib/orchestration/single-story-close/failed-terminal.js +10 -1
  117. package/.agents/scripts/lib/orchestration/single-story-close/gate-log.js +10 -0
  118. package/.agents/scripts/lib/orchestration/single-story-close/phases/base-sync.js +7 -4
  119. package/.agents/scripts/lib/orchestration/single-story-close/phases/close-validation.js +15 -3
  120. package/.agents/scripts/lib/orchestration/single-story-close/phases/code-review.js +59 -2
  121. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +6 -0
  122. package/.agents/scripts/lib/orchestration/single-story-close/phases/finish.js +15 -4
  123. package/.agents/scripts/lib/orchestration/single-story-close/phases/land-review-record.js +213 -0
  124. package/.agents/scripts/lib/orchestration/single-story-close/phases/normalize-pr-title.js +9 -12
  125. package/.agents/scripts/lib/orchestration/single-story-close/phases/open-pr.js +26 -12
  126. package/.agents/scripts/lib/orchestration/single-story-close/phases/post-land.js +51 -26
  127. package/.agents/scripts/lib/orchestration/single-story-close/phases/pre-push.js +3 -2
  128. package/.agents/scripts/lib/orchestration/single-story-close/phases/pull-request.js +50 -17
  129. package/.agents/scripts/lib/orchestration/single-story-close/phases/push.js +59 -11
  130. package/.agents/scripts/lib/orchestration/single-story-close/phases/reconcile-done.js +1 -0
  131. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-block.js +31 -13
  132. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-halt.js +29 -6
  133. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-outcome.js +10 -12
  134. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-override.js +19 -4
  135. package/.agents/scripts/lib/orchestration/single-story-close/result.js +30 -13
  136. package/.agents/scripts/lib/orchestration/single-story-close/review-overlap.js +73 -39
  137. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +11 -3
  138. package/.agents/scripts/lib/orchestration/story-close/baseline-upward-writeback.js +3 -2
  139. package/.agents/scripts/lib/orchestration/story-close/duplication-close-rescore.js +20 -8
  140. package/.agents/scripts/lib/orchestration/story-deliver-terminal.js +7 -0
  141. package/.agents/scripts/lib/orchestration/story-handoff.js +774 -196
  142. package/.agents/scripts/lib/orchestration/ticketing/reads.js +2 -0
  143. package/.agents/scripts/lib/pr-body-lines.js +32 -0
  144. package/.agents/scripts/lib/single-story/ci-ratchet-gate.js +140 -0
  145. package/.agents/scripts/lib/single-story/confirm-and-land.js +17 -7
  146. package/.agents/scripts/lib/single-story/confirm-merge.js +12 -3
  147. package/.agents/scripts/lib/single-story-sweep/report-stalled-executing.js +202 -0
  148. package/.agents/scripts/lib/standalone-ratchets.js +37 -0
  149. package/.agents/scripts/lib/suite-admission.js +20 -8
  150. package/.agents/scripts/lib/suite-sizing.js +146 -0
  151. package/.agents/scripts/lib/workspace-provisioner.js +2 -2
  152. package/.agents/scripts/merge-baseline.js +14 -3
  153. package/.agents/scripts/providers/github/comments.js +19 -3
  154. package/.agents/scripts/providers/github.js +1 -0
  155. package/.agents/scripts/review-dispositions-report.js +1 -1
  156. package/.agents/scripts/role-scope-guard.js +267 -0
  157. package/.agents/scripts/single-story-close.js +4 -4
  158. package/.agents/scripts/single-story-confirm-merge.js +31 -5
  159. package/.agents/scripts/single-story-init.js +24 -4
  160. package/.agents/scripts/story-handoff.js +3 -3
  161. package/.agents/scripts/story-outcomes-report.js +231 -0
  162. package/.agents/scripts/story-review-compute.js +9 -5
  163. package/.agents/scripts/update-coverage-baseline.js +12 -2
  164. package/.agents/scripts/update-crap-baseline.js +9 -1
  165. package/.agents/workflows/helpers/code-review.md +63 -9
  166. package/.agents/workflows/helpers/deliver-digest.md +53 -54
  167. package/.agents/workflows/helpers/deliver-reference.md +233 -67
  168. package/.agents/workflows/helpers/deliver-story-reference.md +19 -8
  169. package/.agents/workflows/helpers/deliver-story.md +7 -2
  170. package/.agents/workflows/helpers/parallel-tooling.md +29 -0
  171. package/docs/CHANGELOG.md +46 -0
  172. package/lib/cli/doctor-checks/coverage-ratchet.js +54 -0
  173. package/lib/cli/doctor-checks/effective-agentrc.js +23 -0
  174. package/lib/cli/doctor-checks/llm-review.js +2 -11
  175. package/lib/cli/doctor-checks/sync-parity.js +5 -1
  176. package/lib/cli/doctor-checks/test-credit-path.js +7 -2
  177. package/lib/cli/registry.js +5 -0
  178. package/package.json +1 -1
@@ -7,11 +7,7 @@ import fs from 'node:fs';
7
7
  import path from 'node:path';
8
8
  import { applyLocalOverlay } from './config/agentrc-overlay.js';
9
9
  import { applyGhConfigDir } from './config/gh-config-dir.js';
10
- import {
11
- overlayRoot,
12
- resolveAgentrcRoot,
13
- storeRoot,
14
- } from './config/git-roots.js';
10
+ import { resolveAgentrcRoot, storeRoot } from './config/git-roots.js';
15
11
 
16
12
  /** Applied dir (or null) per anchor root. */
17
13
  const _ensuredByRoot = new Map();
@@ -40,8 +36,9 @@ export function ensureGhEnv(deps = {}) {
40
36
  if (memoize && _ensuredByRoot.has(root)) return _ensuredByRoot.get(root);
41
37
  const { effective } = applyLocalOverlay({
42
38
  fsImpl,
43
- projectRoot: overlayRoot(root, exec),
39
+ projectRoot: root,
44
40
  committed: readCommittedAgentrc(fsImpl, root),
41
+ exec,
45
42
  });
46
43
  const dir = applyGhConfigDir(effective?.github, storeRoot(root, exec), {
47
44
  env,
@@ -62,6 +62,7 @@ const PULL_FIELDS = Object.freeze({
62
62
  number: (p) => p.number,
63
63
  url: (p) => p.html_url,
64
64
  title: (p) => p.title,
65
+ body: (p) => p.body ?? '',
65
66
  state: (p) => (p.merged === true || p.merged_at ? 'MERGED' : upper(p.state)),
66
67
  mergedAt: (p) => p.merged_at ?? null,
67
68
  createdAt: (p) => p.created_at ?? null,
@@ -0,0 +1,182 @@
1
+ /**
2
+ * base-sync-probe.js — under `delivery.close.baseSync: "on-conflict"`, may a
3
+ * Story skip merging `origin/<baseBranch>`? Only a conflict-free merge whose
4
+ * incoming and Story paths are disjoint skips: git then takes every path
5
+ * from the one side that changed it and never runs a merge driver. Any
6
+ * other answer, or any git failure, means merge as usual.
7
+ */
8
+
9
+ import { resolveConfig } from '../config-resolver.js';
10
+ import {
11
+ gitFetchWithRetry as defaultGitFetchWithRetry,
12
+ gitSpawn as defaultGitSpawn,
13
+ } from '../git-utils.js';
14
+ import { syncBranchFromBase } from './sync-from-base.js';
15
+
16
+ function names(res) {
17
+ return (res.stdout ?? '')
18
+ .toString()
19
+ .split(/\r?\n/)
20
+ .map((s) => s.trim())
21
+ .filter((s) => s.length > 0);
22
+ }
23
+
24
+ /** `merge-tree` exits 1 on a conflict; any other non-zero is an old git. */
25
+ function mergeTreeVerdict(spawn, cwd, origin) {
26
+ const res = spawn(
27
+ cwd,
28
+ 'merge-tree',
29
+ '--write-tree',
30
+ '--no-messages',
31
+ origin,
32
+ 'HEAD',
33
+ );
34
+ if (res.status === 0) return null;
35
+ return res.status === 1 ? 'conflict' : 'unsupported';
36
+ }
37
+
38
+ /** Raw, rename-free paths each side changed since the merge-base. */
39
+ function sidePaths(spawn, cwd, origin) {
40
+ const mb = spawn(cwd, 'merge-base', origin, 'HEAD');
41
+ const mergeBase = (mb.stdout ?? '').toString().trim();
42
+ if (mb.status !== 0 || mergeBase.length === 0) return null;
43
+ const diff = (to) =>
44
+ spawn(cwd, 'diff', '--name-only', '--no-renames', mergeBase, to);
45
+ const incoming = diff(origin);
46
+ const story = diff('HEAD');
47
+ if (incoming.status !== 0 || story.status !== 0) return null;
48
+ return { mergeBase, incoming: names(incoming), story: names(story) };
49
+ }
50
+
51
+ /**
52
+ * @param {{ cwd: string, baseBranch: string, gitSpawn?: typeof defaultGitSpawn, gitFetchWithRetry?: typeof defaultGitFetchWithRetry }} opts
53
+ * @returns {Promise<
54
+ * | { skip: true, incoming: number, mergeBase: string }
55
+ * | { skip: false, reason: 'fetch-failed'|'already-current'|'conflict'|'unsupported'|'intersects', path?: string }
56
+ * >}
57
+ */
58
+ export async function probeBaseSync({
59
+ cwd,
60
+ baseBranch,
61
+ gitSpawn: spawn = defaultGitSpawn,
62
+ gitFetchWithRetry = defaultGitFetchWithRetry,
63
+ }) {
64
+ const origin = `origin/${baseBranch}`;
65
+ const fetch = await gitFetchWithRetry(cwd, 'origin', baseBranch);
66
+ if (fetch.status !== 0) return { skip: false, reason: 'fetch-failed' };
67
+ const current = spawn(cwd, 'merge-base', '--is-ancestor', origin, 'HEAD');
68
+ if (current.status === 0) return { skip: false, reason: 'already-current' };
69
+ const verdict = mergeTreeVerdict(spawn, cwd, origin);
70
+ if (verdict) return { skip: false, reason: verdict };
71
+ const sides = sidePaths(spawn, cwd, origin);
72
+ if (!sides) return { skip: false, reason: 'unsupported' };
73
+ const story = new Set(sides.story);
74
+ const shared = sides.incoming.find((p) => story.has(p));
75
+ if (shared) return { skip: false, reason: 'intersects', path: shared };
76
+ return {
77
+ skip: true,
78
+ incoming: sides.incoming.length,
79
+ mergeBase: sides.mergeBase,
80
+ };
81
+ }
82
+
83
+ /** One human line for a probe answer, naming the decision and its reason. */
84
+ function describeProbe(probe) {
85
+ if (probe.skip) {
86
+ return `skipped — merge is conflict-free and shares no path (${probe.incoming} incoming path(s))`;
87
+ }
88
+ const at = probe.path ? ` (${probe.path})` : '';
89
+ return `merging — probe answered ${probe.reason}${at}`;
90
+ }
91
+
92
+ /**
93
+ * The `baseSync` record the close envelope carries for a sync that ran.
94
+ *
95
+ * @param {{ mode: string, probe: object|null, kind?: string, changedPaths?: string[] }} args
96
+ * @returns {{ mode: string, outcome: 'merged'|'already-current'|'skipped', reason: string, incoming: number }}
97
+ */
98
+ function baseSyncDecision({ mode, probe, kind, changedPaths }) {
99
+ if (probe?.skip) {
100
+ return {
101
+ mode,
102
+ outcome: 'skipped',
103
+ reason: 'conflict-free',
104
+ incoming: probe.incoming,
105
+ };
106
+ }
107
+ return {
108
+ mode,
109
+ outcome: kind === 'noop-already-current' ? 'already-current' : 'merged',
110
+ reason: probe?.reason ?? mode,
111
+ incoming: Array.isArray(changedPaths) ? changedPaths.length : 0,
112
+ };
113
+ }
114
+
115
+ /** `delivery.close.baseSync`; an unresolvable config keeps today's `always`. */
116
+ function configuredMode(resolveConfigImpl, cwd) {
117
+ try {
118
+ return resolveConfigImpl({ cwd })?.delivery?.close?.baseSync ?? 'always';
119
+ } catch {
120
+ return 'always';
121
+ }
122
+ }
123
+
124
+ /**
125
+ * Close's sync: `syncBranchFromBase`, preceded under `on-conflict` by the
126
+ * probe. A skip is a `synced` result of kind `skipped` that carries the
127
+ * merge-base as `baselineRef`; every result carries its `decision`.
128
+ *
129
+ * @param {{ cwd: string, baseBranch: string, log?: (tag: string, msg: string) => void, resolveConfigImpl?: typeof resolveConfig, probeImpl?: typeof probeBaseSync, syncImpl?: typeof syncBranchFromBase }} opts
130
+ * @returns {Promise<object>} `syncBranchFromBase`'s result plus `decision`.
131
+ */
132
+ export async function syncFromBaseByMode({
133
+ cwd,
134
+ baseBranch,
135
+ log = () => {},
136
+ resolveConfigImpl = resolveConfig,
137
+ probeImpl = probeBaseSync,
138
+ syncImpl = syncBranchFromBase,
139
+ }) {
140
+ const mode = configuredMode(resolveConfigImpl, cwd);
141
+ const probe =
142
+ mode === 'on-conflict' ? await probeImpl({ cwd, baseBranch }) : null;
143
+ if (probe) log('SYNC', `baseSync on-conflict: ${describeProbe(probe)}`);
144
+ if (probe?.skip) {
145
+ const decision = baseSyncDecision({ mode, probe });
146
+ const base = { changedPaths: [], preSyncHead: null };
147
+ return {
148
+ synced: true,
149
+ kind: 'skipped',
150
+ ...base,
151
+ baselineRef: probe.mergeBase,
152
+ decision,
153
+ };
154
+ }
155
+ const result = await syncImpl({ cwd, baseBranch, log });
156
+ return { ...result, decision: baseSyncDecision({ mode, probe, ...result }) };
157
+ }
158
+
159
+ /**
160
+ * A handoff re-run's base-merge skip under `on-conflict`. Only a re-run (an
161
+ * earlier invocation settled the step, `state.baseMergeSettled`) probes; a
162
+ * skip pins the handoff's close gates to the merge-base, sets the envelope's
163
+ * `baseMerge` and returns the step detail; anything else returns `null` and the step merges as usual.
164
+ *
165
+ * @param {{ config: object, state: object, cwd: string, baseBranch: string, probeBaseSync?: typeof probeBaseSync, progress: Function }} ctx
166
+ * @returns {Promise<string|null>}
167
+ */
168
+ export async function handoffRerunSkip(ctx) {
169
+ const mode = ctx.config?.delivery?.close?.baseSync;
170
+ if (mode !== 'on-conflict' || !ctx.state.baseMergeSettled) return null;
171
+ const probe = await (ctx.probeBaseSync ?? probeBaseSync)({
172
+ cwd: ctx.cwd,
173
+ baseBranch: ctx.baseBranch,
174
+ });
175
+ ctx.progress('base-merge', `baseSync on-conflict: ${describeProbe(probe)}`);
176
+ if (!probe.skip) return null;
177
+ ctx.baselineRef = probe.mergeBase;
178
+ ctx.baseMergeEnvelope = {
179
+ baseMerge: { skipped: 'conflict-free', incoming: probe.incoming },
180
+ };
181
+ return `conflict-free and disjoint: ${probe.incoming} incoming path(s) from origin/${ctx.baseBranch} not merged`;
182
+ }
@@ -42,6 +42,15 @@ export function branchExistsRemotely(branch, cwd) {
42
42
  return result.status === 0 && result.stdout.length > 0;
43
43
  }
44
44
 
45
+ /** Origin's tip for `branch`: `sha` null when absent; never throws. */
46
+ export function remoteBranchSha(cwd, branch, git = gitSpawn) {
47
+ const res = git(cwd, 'ls-remote', 'origin', `refs/heads/${branch}`);
48
+ const detail = `${res?.stderr ?? ''}`.trim();
49
+ if (res?.status !== 0) return { reachable: false, sha: null, detail };
50
+ const sha = `${res.stdout ?? ''}`.trim().split(/\s+/)[0] || null;
51
+ return { reachable: true, sha, detail: '' };
52
+ }
53
+
45
54
  /**
46
55
  * Local-only; authoritative once `git fetch origin` has run.
47
56
  *
@@ -12,6 +12,7 @@ import { parseWorkerModel, parseWorkerTokens } from '../cli-args.js';
12
12
  import { Logger } from '../Logger.js';
13
13
  import { parseWorkerEffort } from '../orchestration/resume-effort.js';
14
14
  import { EVENT_KINDS } from '../signals/schema.js';
15
+ import { isHandoffRecord } from './handoff-telemetry.js';
15
16
  import {
16
17
  emitRuntimeFriction,
17
18
  emitTerminalFriction,
@@ -43,7 +44,7 @@ const FAILED_PHASE_CAUSES = Object.freeze({
43
44
  * @param {object|null|undefined} envelope
44
45
  * @returns {string|null} `null` for a landed or pending close.
45
46
  */
46
- function retryCauseForTerminal(envelope) {
47
+ export function retryCauseForTerminal(envelope) {
47
48
  const status = envelope?.status;
48
49
  if (status === 'blocked') {
49
50
  return (
@@ -132,9 +133,37 @@ function emptyTelemetryTally() {
132
133
  acceptanceRounds: 0,
133
134
  retries: { total: 0, byCause: {} },
134
135
  review: { haltsByProvider: {}, overridesByProvider: {} },
136
+ handoff: emptyHandoffTally(),
135
137
  };
136
138
  }
137
139
 
140
+ function emptyHandoffTally() {
141
+ return { attempts: 0, ready: 0, byFailedStep: {}, byCause: {}, stepMs: {} };
142
+ }
143
+
144
+ /** A story-handoff record, ready or not, counted apart from close's retries. */
145
+ function tallyHandoff(tally, { details = {} }) {
146
+ const handoff = tally.handoff;
147
+ handoff.attempts += 1;
148
+ if (details.status === 'ready') handoff.ready += 1;
149
+ else {
150
+ addCounts(handoff.byFailedStep, { [details.failedStep ?? 'unknown']: 1 });
151
+ addCounts(handoff.byCause, { [details.cause ?? RETRY_CAUSES.OTHER]: 1 });
152
+ }
153
+ for (const [step, ms] of Object.entries(details.stepDurationsMs ?? {})) {
154
+ if (Number.isFinite(ms)) addCounts(handoff.stepMs, { [step]: ms });
155
+ }
156
+ }
157
+
158
+ /** @param {ReturnType<typeof emptyHandoffTally>} into @param {ReturnType<typeof emptyHandoffTally>} from */
159
+ function mergeHandoffTally(into, from) {
160
+ into.attempts += from.attempts;
161
+ into.ready += from.ready;
162
+ addCounts(into.byFailedStep, from.byFailedStep);
163
+ addCounts(into.byCause, from.byCause);
164
+ addCounts(into.stepMs, from.stepMs);
165
+ }
166
+
138
167
  /**
139
168
  * One incident per provider that raised a critical finding, not per finding.
140
169
  *
@@ -152,6 +181,7 @@ function providerIncidents(details) {
152
181
 
153
182
  const RECORD_TALLIERS = Object.freeze({
154
183
  [EVENT_KINDS.RETRY]: (tally, record) => {
184
+ if (isHandoffRecord(record)) return tallyHandoff(tally, record);
155
185
  const cause =
156
186
  typeof record.details?.cause === 'string'
157
187
  ? record.details.cause
@@ -159,6 +189,9 @@ const RECORD_TALLIERS = Object.freeze({
159
189
  tally.retries.total += 1;
160
190
  addCounts(tally.retries.byCause, { [cause]: 1 });
161
191
  },
192
+ [EVENT_KINDS.TRACE]: (tally, record) => {
193
+ if (isHandoffRecord(record)) tallyHandoff(tally, record);
194
+ },
162
195
  [EVENT_KINDS.ACCEPTANCE_EVAL]: (tally, record) => {
163
196
  const round = Number(record.details?.round);
164
197
  const seen = Number.isInteger(round) && round > 0 ? round : 1;
@@ -186,7 +219,7 @@ const RECORD_TALLIERS = Object.freeze({
186
219
  * @param {Iterable<unknown>} records
187
220
  * @returns {ReturnType<typeof emptyTelemetryTally>}
188
221
  */
189
- function tallyStoryTelemetry(records) {
222
+ export function tallyStoryTelemetry(records) {
190
223
  const tally = emptyTelemetryTally();
191
224
  for (const record of records ?? []) {
192
225
  if (!record || typeof record !== 'object') continue;
@@ -207,6 +240,7 @@ function mergeTelemetryTallies(tallies) {
207
240
  addCounts(total.retries.byCause, t.retries.byCause);
208
241
  addCounts(total.review.haltsByProvider, t.review.haltsByProvider);
209
242
  addCounts(total.review.overridesByProvider, t.review.overridesByProvider);
243
+ mergeHandoffTally(total.handoff, t.handoff);
210
244
  }
211
245
  return total;
212
246
  }
@@ -268,6 +302,7 @@ async function buildCloseTelemetry({
268
302
  ...tally.review,
269
303
  confirmedHaltsByProvider: confirmedHalts(tally, landed),
270
304
  },
305
+ handoff: tally.handoff,
271
306
  workerTokens: Number.isInteger(workerTokens) ? workerTokens : null,
272
307
  workerModel,
273
308
  workerEffort,
@@ -0,0 +1,170 @@
1
+ /**
2
+ * One signal per story-handoff run: a `retry` naming the stopping step and
3
+ * cause, or a `trace` for a ready run. Best-effort — a failed read or write
4
+ * never changes the handoff's outcome. Details carry no file path.
5
+ *
6
+ * @module lib/observability/handoff-telemetry
7
+ */
8
+
9
+ import crypto from 'node:crypto';
10
+
11
+ import { EVENT_KINDS } from '../signals/schema.js';
12
+ import { appendSignal, forEachLine } from '../signals/write.js';
13
+
14
+ const HANDOFF_PHASE = 'handoff';
15
+ const HANDOFF_TOOL = 'story-handoff';
16
+
17
+ const HANDOFF_CAUSES = Object.freeze(
18
+ new Set([
19
+ 'precheck',
20
+ 'merge-driver-unregistered',
21
+ 'base-branch-unconfirmed',
22
+ 'base-merge-conflict',
23
+ 'base-merge-failed',
24
+ 'preflight-unresolved',
25
+ 'lint',
26
+ 'format',
27
+ 'quality-preview',
28
+ 'ratchet',
29
+ 'lock-wait-expired',
30
+ 'host-admission',
31
+ 'suite-timeout',
32
+ 'red-suite',
33
+ 'capture-over-budget',
34
+ 'no-credit-signal',
35
+ 'seat-refused',
36
+ 'seat-commit-failed',
37
+ 'post-capture',
38
+ 'remote-unreachable',
39
+ 'push-rejected',
40
+ 'push-unconfirmed',
41
+ 'ref-behind',
42
+ 'push-hook',
43
+ 'review-critical',
44
+ 'other',
45
+ ]),
46
+ );
47
+
48
+ /** @param {unknown} cause @returns {string} a closed-set cause, else `other`. */
49
+ export function handoffCause(cause) {
50
+ return HANDOFF_CAUSES.has(cause) ? cause : 'other';
51
+ }
52
+
53
+ /** @param {unknown} record */
54
+ export function isHandoffRecord(record) {
55
+ return (
56
+ record?.phase === HANDOFF_PHASE && record?.emitter?.tool === HANDOFF_TOOL
57
+ );
58
+ }
59
+
60
+ /** @param {Array<{ name: string, durationMs?: number|null }>} steps */
61
+ function stepDurations(steps) {
62
+ const out = {};
63
+ for (const step of steps ?? []) {
64
+ if (Number.isInteger(step.durationMs)) out[step.name] = step.durationMs;
65
+ }
66
+ return out;
67
+ }
68
+
69
+ const pick = (obj, keys) =>
70
+ obj ? Object.fromEntries(keys.map((k) => [k, obj[k] ?? null])) : null;
71
+
72
+ /** @param {object} envelope @returns {object} the record's kind-specific details. */
73
+ function recordDetails(envelope) {
74
+ const common = {
75
+ attempt: envelope.attempt,
76
+ stepDurationsMs: stepDurations(envelope.steps),
77
+ depositor: envelope.depositor ?? null,
78
+ headSha: envelope.headSha ?? null,
79
+ };
80
+ if (envelope.status === 'ready') {
81
+ return {
82
+ status: 'ready',
83
+ ...common,
84
+ suiteTimings: pick(envelope.suiteTimings, [
85
+ 'lockWaitMs',
86
+ 'hostWaitMs',
87
+ 'testRunMs',
88
+ ]),
89
+ lockWait: pick(envelope.lockWait, ['waitedSeconds', 'expired']),
90
+ reviewMs: envelope.reviewMs ?? null,
91
+ };
92
+ }
93
+ const stop = envelope.steps?.findLast((s) => s.name === envelope.failedStep);
94
+ return {
95
+ status: envelope.status,
96
+ failedStep: envelope.failedStep ?? null,
97
+ cause: handoffCause(envelope.cause),
98
+ ...(stop?.check ? { check: stop.check } : {}),
99
+ ...(stop?.gate ? { gate: stop.gate } : {}),
100
+ ...common,
101
+ };
102
+ }
103
+
104
+ /**
105
+ * @param {{ storyId: number, envelope: object, ts?: string }} args
106
+ * @returns {object} a schema-valid signal.
107
+ */
108
+ function buildHandoffRecord({ storyId, envelope, ts }) {
109
+ return {
110
+ kind: envelope.status === 'ready' ? EVENT_KINDS.TRACE : EVENT_KINDS.RETRY,
111
+ eventId: crypto.randomUUID(),
112
+ ts: ts ?? new Date().toISOString(),
113
+ epicId: null,
114
+ storyId,
115
+ taskId: null,
116
+ phase: HANDOFF_PHASE,
117
+ emitter: { tool: HANDOFF_TOOL },
118
+ details: recordDetails(envelope),
119
+ };
120
+ }
121
+
122
+ /**
123
+ * Prior handoff records in the Story's stream, plus one; `null` on a failed read.
124
+ *
125
+ * @param {{ storyId: number, config?: object, readFn?: typeof forEachLine }} args
126
+ * @returns {Promise<number|null>}
127
+ */
128
+ export async function nextHandoffAttempt({
129
+ storyId,
130
+ config,
131
+ readFn = forEachLine,
132
+ }) {
133
+ let prior = 0;
134
+ try {
135
+ await readFn(
136
+ null,
137
+ storyId,
138
+ (record) => {
139
+ if (isHandoffRecord(record)) prior += 1;
140
+ },
141
+ config,
142
+ );
143
+ } catch {
144
+ return null;
145
+ }
146
+ return prior + 1;
147
+ }
148
+
149
+ /**
150
+ * @param {{ storyId: number, envelope: object, config?: object,
151
+ * writeFn?: typeof appendSignal, warn?: (msg: string) => void }} args
152
+ * @returns {Promise<boolean>} true when the record was appended.
153
+ */
154
+ export async function emitHandoffRecord({
155
+ storyId,
156
+ envelope,
157
+ config,
158
+ writeFn = appendSignal,
159
+ warn = () => {},
160
+ }) {
161
+ try {
162
+ const signal = buildHandoffRecord({ storyId, envelope });
163
+ const ok = await writeFn({ epicId: null, storyId, signal, config });
164
+ if (!ok) warn('handoff signal not appended');
165
+ return ok === true;
166
+ } catch (err) {
167
+ warn(`handoff signal not appended: ${err?.message ?? err}`);
168
+ return false;
169
+ }
170
+ }
@@ -10,7 +10,10 @@ import fs from 'node:fs/promises';
10
10
  import path from 'node:path';
11
11
 
12
12
  import { anchorTempRoot, tempRootFrom } from '../config/temp-paths.js';
13
- import { readReviewHistory } from '../orchestration/review-history.js';
13
+ import {
14
+ earlierCriticals,
15
+ readReviewHistory,
16
+ } from '../orchestration/review-history.js';
14
17
  import { MAX_LEDGER_BYTES, rotateIfNeeded } from './metrics-ledger.js';
15
18
 
16
19
  export const DISPOSITIONS = [
@@ -28,15 +31,24 @@ function ledgerPath(config) {
28
31
  return path.join(anchorTempRoot(tempRootFrom(config)), LEDGER_BASENAME);
29
32
  }
30
33
 
31
- /** Precedence: overridden, then the final run's flags, then presence. */
32
- function dispositionOf(id, final, overridden) {
34
+ const RESOLVED = { fixed: 'fixed-on-branch', refuted: 'refuted-by-verifier' };
35
+
36
+ /**
37
+ * Precedence: overridden, the final run's flags, how an earlier CRITICAL was
38
+ * last resolved, then presence.
39
+ */
40
+ function dispositionOf(id, final, overridden, resolved) {
33
41
  if (overridden.has(id)) return 'overridden';
34
- if (!final) return 'fixed-on-branch';
42
+ if (!final) return resolvedOr(id, resolved, 'fixed-on-branch');
35
43
  if (final.ungrounded) return 'downgraded-ungrounded';
36
44
  if (final.unverified) return 'refuted-by-verifier';
37
- return 'open-at-merge';
45
+ return resolvedOr(id, resolved, 'open-at-merge');
38
46
  }
39
47
 
48
+ /** How an earlier CRITICAL was last resolved, else `fallback`. */
49
+ const resolvedOr = (id, resolved, fallback) =>
50
+ RESOLVED[resolved.get(id)] ?? fallback;
51
+
40
52
  /** @param {object} run @returns {object[]} */
41
53
  const runFindings = (run) => (Array.isArray(run?.findings) ? run.findings : []);
42
54
 
@@ -70,12 +82,17 @@ function deriveDispositions(history) {
70
82
  const runs = history.runs.map(runFindings);
71
83
  const finalRun = new Map((runs.at(-1) ?? []).map((f) => [f.id, f]));
72
84
  const overridden = new Set(history.overridden);
85
+ const resolved = new Map(
86
+ earlierCriticals(history)
87
+ .filter((e) => e.status in RESOLVED)
88
+ .map((e) => [e.id, e.status]),
89
+ );
73
90
  return [...firstSeen(runs)].map(([id, entry]) => ({
74
91
  findingId: id,
75
92
  provider: entry.first.provider ?? null,
76
93
  severity: entry.first.severity ?? null,
77
94
  class: entry.first.class ?? null,
78
- disposition: dispositionOf(id, finalRun.get(id), overridden),
95
+ disposition: dispositionOf(id, finalRun.get(id), overridden, resolved),
79
96
  runs: entry.runs,
80
97
  }));
81
98
  }
@@ -29,6 +29,12 @@ export const RUNTIME_FRICTION_CATEGORIES = Object.freeze({
29
29
  REVIEW_BLOCK_OVERRIDDEN: 'review-block-overridden',
30
30
  /** An `agent::*` flip outside `VALID_TRANSITIONS`; observed, never refused. */
31
31
  INVALID_AGENT_TRANSITION: 'invalid-agent-transition',
32
+ /** A Story landed without close; the land tail supplied its review record. */
33
+ REVIEW_RECORDED_AT_LAND: 'review-recorded-at-land',
34
+ /** A held CRITICAL reached the base branch with no override record. */
35
+ REVIEW_CRITICAL_MERGED: 'review-critical-merged',
36
+ /** A credited suite lost workers to host memory (consumer exit 77). */
37
+ HOST_RESOURCES: 'host-resources',
32
38
  });
33
39
 
34
40
  /**
@@ -330,6 +336,16 @@ export function isRecoveredSignal(signal) {
330
336
  );
331
337
  }
332
338
 
339
+ /** `baselinesKinds` rides along only when the failed terminal carried it. */
340
+ function closeFailedDetails(phase, failure) {
341
+ const kinds = failure?.baselinesKinds;
342
+ return {
343
+ phase: phase ?? null,
344
+ reason: preview(failure?.reason),
345
+ ...(kinds ? { baselinesKinds: kinds } : {}),
346
+ };
347
+ }
348
+
333
349
  /**
334
350
  * The friction a terminal envelope implies; each incident is emitted from one
335
351
  * place only. `blocked` → null (the transition mutator emits it); `failed` →
@@ -347,10 +363,7 @@ function frictionForTerminal(envelope) {
347
363
  if (status === 'failed') {
348
364
  return {
349
365
  category: RUNTIME_FRICTION_CATEGORIES.CLOSE_FAILED,
350
- details: {
351
- phase: phase ?? null,
352
- reason: preview(failure?.reason),
353
- },
366
+ details: closeFailedDetails(phase, failure),
354
367
  };
355
368
  }
356
369
 
@@ -43,6 +43,7 @@ const FRAMEWORK_SCRIPT_BASENAMES = Object.freeze([
43
43
  'clean-worktrees.js',
44
44
  'cleanup-repo-test-temp.js',
45
45
  'coverage-capture.js',
46
+ 'coverage-ratchet.js',
46
47
  'deliver-light.js',
47
48
  'deliver-recover.js',
48
49
  'deliver-run.js',
@@ -73,12 +74,14 @@ const FRAMEWORK_SCRIPT_BASENAMES = Object.freeze([
73
74
  'resolve-stories.js',
74
75
  'resync-status-column.js',
75
76
  'review-dispositions-report.js',
77
+ 'role-scope-guard.js',
76
78
  'run-tests.js',
77
79
  'single-story-close.js',
78
80
  'single-story-confirm-merge.js',
79
81
  'single-story-init.js',
80
82
  'stories-wave-tick.js',
81
83
  'story-handoff.js',
84
+ 'story-outcomes-report.js',
82
85
  'story-review-compute.js',
83
86
  'sync-agentrc.js',
84
87
  'sync-claude-agents.js',