mandrel 2.82.0 → 2.84.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 (60) hide show
  1. package/.agents/README.md +65 -20
  2. package/.agents/docs/configuration.md +40 -3
  3. package/.agents/docs/runbooks/mods.md +98 -54
  4. package/.agents/docs/workflows.md +14 -0
  5. package/.agents/instructions.md +4 -1
  6. package/.agents/mods/mandrel-status/hooks/register.tsx +579 -204
  7. package/.agents/mods/mandrel-status/types/index.d.ts +58 -13
  8. package/.agents/schemas/agentrc.schema.json +1 -1
  9. package/.agents/scripts/boot-sweep.js +42 -13
  10. package/.agents/scripts/coverage-capture.js +55 -24
  11. package/.agents/scripts/evidence-gate.js +7 -1
  12. package/.agents/scripts/generate-workflows-doc.js +14 -0
  13. package/.agents/scripts/lib/baselines/duplication-scanner.js +26 -2
  14. package/.agents/scripts/lib/bootstrap/agents-md-fold.js +99 -16
  15. package/.agents/scripts/lib/bootstrap/manifest.js +4 -4
  16. package/.agents/scripts/lib/bootstrap/project-bootstrap.js +16 -1
  17. package/.agents/scripts/lib/close-lock-events.js +109 -0
  18. package/.agents/scripts/lib/close-validation/commands.js +12 -0
  19. package/.agents/scripts/lib/close-validation/gates.js +6 -0
  20. package/.agents/scripts/lib/close-validation/process.js +5 -2
  21. package/.agents/scripts/lib/close-validation/runner.js +14 -4
  22. package/.agents/scripts/lib/codex/agents-projection.js +284 -0
  23. package/.agents/scripts/lib/codex/skills-projection.js +291 -0
  24. package/.agents/scripts/lib/config/agentrc-overlay.js +91 -0
  25. package/.agents/scripts/lib/config/sync-agentrc.js +39 -19
  26. package/.agents/scripts/lib/config-resolver.js +5 -42
  27. package/.agents/scripts/lib/config-settings-schema-quality.js +1 -1
  28. package/.agents/scripts/lib/config-settings-schema.js +1 -1
  29. package/.agents/scripts/lib/full-suite-lock.js +20 -0
  30. package/.agents/scripts/lib/full-suite-queue.js +24 -56
  31. package/.agents/scripts/lib/generated/agentrc-validator.js +1 -1
  32. package/.agents/scripts/lib/observability/source-classifier.js +2 -0
  33. package/.agents/scripts/lib/orchestration/review-providers/codex-cli.js +152 -0
  34. package/.agents/scripts/lib/orchestration/review-providers/codex.js +33 -105
  35. package/.agents/scripts/lib/orchestration/review-providers/provider-severity.js +30 -0
  36. package/.agents/scripts/lib/orchestration/review-providers/security-review.js +3 -17
  37. package/.agents/scripts/lib/orchestration/single-story-close/phases/close-validation.js +73 -63
  38. package/.agents/scripts/lib/orchestration/single-story-close/phases/reconcile-done.js +70 -0
  39. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +3 -0
  40. package/.agents/scripts/lib/single-story-sweep/reconcile-closing.js +89 -0
  41. package/.agents/scripts/lib/supervised-suite.js +8 -28
  42. package/.agents/scripts/single-story-init.js +20 -5
  43. package/.agents/scripts/sync-agentrc.js +5 -3
  44. package/.agents/scripts/sync-claude-agents.js +20 -0
  45. package/.agents/scripts/sync-claude-commands.js +64 -27
  46. package/.agents/scripts/sync-codex-agents.js +36 -0
  47. package/.agents/scripts/sync-codex-skills.js +36 -0
  48. package/.agents/workflows/helpers/mandrel-sync-config.md +16 -9
  49. package/.agents/workflows/mandrel-update.md +2 -1
  50. package/README.md +167 -216
  51. package/docs/CHANGELOG.md +25 -0
  52. package/lib/cli/guarded-sync.js +3 -2
  53. package/lib/cli/registry.js +248 -0
  54. package/lib/cli/sync-agents.js +5 -2
  55. package/lib/cli/sync-commands.js +5 -2
  56. package/lib/cli/sync.js +45 -14
  57. package/lib/cli/uninstall.js +8 -1
  58. package/lib/migrations/index.js +2 -0
  59. package/lib/migrations/steps/2.84.0-hoist-system-prompt-block.js +64 -0
  60. package/package.json +3 -2
@@ -81,6 +81,8 @@ const FRAMEWORK_SCRIPT_BASENAMES = Object.freeze([
81
81
  'sync-agentrc.js',
82
82
  'sync-claude-agents.js',
83
83
  'sync-claude-commands.js',
84
+ 'sync-codex-agents.js',
85
+ 'sync-codex-skills.js',
84
86
  'test-wrapper.js',
85
87
  'update-coverage-baseline.js',
86
88
  'update-crap-baseline.js',
@@ -0,0 +1,152 @@
1
+ /**
2
+ * review-providers/codex-cli.js — the Codex CLI mechanics behind the `codex`
3
+ * provider: the `codex --version` probe and one `codex exec` review run
4
+ * (read-only sandbox, ephemeral, schema-constrained output).
5
+ *
6
+ * `codex exec review` is deliberately not used: its `--base` conflicts with a
7
+ * prompt (no depth directive) and it ignores `--output-schema`.
8
+ *
9
+ * @typedef {import('./types.js').Severity} Severity
10
+ * @typedef {import('./types.js').ReviewDepth} ReviewDepth
11
+ * @typedef {{ status: number, stdout: string, stderr: string }} InvokeResult
12
+ */
13
+
14
+ import fs from 'node:fs';
15
+ import path from 'node:path';
16
+ import { spawnCaptureAsync, spawnChild } from '../../child-exec.js';
17
+ import { resolvedTempRoot } from '../../config/temp-paths.js';
18
+ import { resolveConfig } from '../../config-resolver.js';
19
+ import { PROJECT_ROOT } from '../../project-root.js';
20
+ import { PROVIDER_SEVERITY_MAP } from './provider-severity.js';
21
+ import { renderDepthDirective } from './review-depth.js';
22
+
23
+ const PROBE_TIMEOUT_MS = 5000;
24
+ const INVOKE_TIMEOUT_MS = 15 * 60 * 1000;
25
+ const IS_WINDOWS = process.platform === 'win32';
26
+
27
+ /**
28
+ * Codex severity tokens (case-insensitive) → canonical `Severity`; an
29
+ * unnamed token falls through to `'suggestion'`. The keys are also the
30
+ * schema's severity enum.
31
+ *
32
+ * @type {Readonly<Record<string, Severity>>}
33
+ */
34
+ export const CODEX_SEVERITY_MAP = PROVIDER_SEVERITY_MAP;
35
+
36
+ /**
37
+ * Codex structured output is strict: every property required, no extras,
38
+ * nullable location.
39
+ */
40
+ const FINDINGS_SCHEMA = Object.freeze({
41
+ type: 'object',
42
+ additionalProperties: false,
43
+ required: ['findings'],
44
+ properties: {
45
+ findings: {
46
+ type: 'array',
47
+ items: {
48
+ type: 'object',
49
+ additionalProperties: false,
50
+ required: ['severity', 'title', 'body', 'file', 'line', 'category'],
51
+ properties: {
52
+ severity: { type: 'string', enum: Object.keys(CODEX_SEVERITY_MAP) },
53
+ title: { type: 'string' },
54
+ body: { type: 'string' },
55
+ file: { type: ['string', 'null'] },
56
+ line: { type: ['integer', 'null'] },
57
+ category: { type: 'string' },
58
+ },
59
+ },
60
+ },
61
+ },
62
+ });
63
+
64
+ /**
65
+ * Synchronous so a missing CLI surfaces at construction, not mid-review.
66
+ *
67
+ * @param {{ run?: Function }} [opts] - `(file, args, options)` spawn seam.
68
+ * @returns {boolean} true when `codex --version` exits 0.
69
+ */
70
+ export function defaultProbeCodexCommand(opts = {}) {
71
+ try {
72
+ const result = spawnChild('codex', ['--version'], {
73
+ shell: IS_WINDOWS,
74
+ timeout: PROBE_TIMEOUT_MS,
75
+ ...(opts.run ? { run: opts.run } : {}),
76
+ });
77
+ return (result?.status ?? 1) === 0;
78
+ } catch {
79
+ return false;
80
+ }
81
+ }
82
+
83
+ /**
84
+ * @param {{ baseRef: string, headRef: string, depth?: ReviewDepth }} args
85
+ * @returns {string}
86
+ */
87
+ function buildReviewPrompt({ baseRef, headRef, depth }) {
88
+ return (
89
+ `Review the code changes in the git diff \`${baseRef}...${headRef}\` ` +
90
+ `of this repository (run \`git diff ${baseRef}...${headRef}\` to read ` +
91
+ `it). ${renderDepthDirective(depth)}\n\n` +
92
+ 'Report correctness, security, reliability and maintainability problems ' +
93
+ 'the change introduces. For each one give the file and line in the new ' +
94
+ 'version when attributable (otherwise null), a short title, a markdown ' +
95
+ 'body explaining why it is wrong and how to fix it, and a category. ' +
96
+ 'Do not modify any file. Report findings ONLY through the required ' +
97
+ 'output schema; an empty `findings` array means no problems.\n'
98
+ );
99
+ }
100
+
101
+ /**
102
+ * @param {string} file
103
+ * @returns {string|null}
104
+ */
105
+ function readIfPresent(file) {
106
+ try {
107
+ return fs.readFileSync(file, 'utf8');
108
+ } catch {
109
+ return null;
110
+ }
111
+ }
112
+
113
+ /**
114
+ * Run one `codex exec` review in a per-run directory under the project
115
+ * tempRoot (removed afterwards). The prompt rides stdin; the last-message
116
+ * file becomes `stdout`.
117
+ *
118
+ * @param {{ baseRef: string, headRef: string, depth?: ReviewDepth }} args
119
+ * @param {{ run?: Function, tempRoot?: string, cwd?: string }} [deps]
120
+ * @returns {Promise<InvokeResult>}
121
+ */
122
+ export async function invokeCodexExec(args, deps = {}) {
123
+ const tempRoot = deps.tempRoot ?? resolvedTempRoot(resolveConfig());
124
+ fs.mkdirSync(tempRoot, { recursive: true });
125
+ const runDir = fs.mkdtempSync(path.join(tempRoot, 'codex-review-'));
126
+ try {
127
+ const schemaPath = path.join(runDir, 'findings.schema.json');
128
+ const lastMessagePath = path.join(runDir, 'last-message.json');
129
+ fs.writeFileSync(schemaPath, JSON.stringify(FINDINGS_SCHEMA));
130
+ const execArgs = ['exec', '--sandbox', 'read-only', '--ephemeral'];
131
+ execArgs.push('--output-schema', schemaPath, '-o', lastMessagePath, '-');
132
+ const result = await spawnCaptureAsync('codex', execArgs, {
133
+ cwd: deps.cwd ?? PROJECT_ROOT,
134
+ input: buildReviewPrompt(args),
135
+ shell: IS_WINDOWS,
136
+ timeout: INVOKE_TIMEOUT_MS,
137
+ ...(deps.run ? { run: deps.run } : {}),
138
+ });
139
+ if (result.status !== 0) return result;
140
+ const lastMessage = readIfPresent(lastMessagePath);
141
+ if (lastMessage === null) {
142
+ return {
143
+ status: 1,
144
+ stdout: '',
145
+ stderr: `codex exec wrote no last-message file. ${result.stderr}`,
146
+ };
147
+ }
148
+ return { status: 0, stdout: lastMessage, stderr: result.stderr };
149
+ } finally {
150
+ fs.rmSync(runDir, { recursive: true, force: true });
151
+ }
152
+ }
@@ -1,6 +1,8 @@
1
1
  /**
2
- * review-providers/codex.js — ReviewProvider over `/codex:review`. A missing
3
- * plugin hard-fails at construction; never a silent fallback to native.
2
+ * review-providers/codex.js — ReviewProvider over the Codex CLI (`codex
3
+ * exec`, see `codex-cli.js`), so a Codex-only host needs no `claude` binary.
4
+ * A missing CLI hard-fails at construction; never a silent fallback to
5
+ * native.
4
6
  *
5
7
  * @typedef {import('./types.js').Finding} Finding
6
8
  * @typedef {import('./types.js').ReviewInput} ReviewInput
@@ -8,81 +10,35 @@
8
10
  * @typedef {import('./types.js').Severity} Severity
9
11
  */
10
12
 
11
- import { spawnSync } from 'node:child_process';
12
- import fs from 'node:fs';
13
- import os from 'node:os';
14
- import path from 'node:path';
13
+ import {
14
+ CODEX_SEVERITY_MAP,
15
+ defaultProbeCodexCommand,
16
+ invokeCodexExec,
17
+ } from './codex-cli.js';
15
18
  import { parseProviderFindings } from './parse-findings.js';
16
- import { renderDepthDirective } from './review-depth.js';
19
+
20
+ export { CODEX_SEVERITY_MAP, defaultProbeCodexCommand };
17
21
 
18
22
  export const CODEX_REMEDIATIONS = Object.freeze({
19
23
  install:
20
- 'Install the Codex plugin (https://github.com/openai/codex-plugin-cc) ' +
21
- 'so the host registers the `/codex:review` slash command.',
24
+ 'Install the Codex CLI (`npm install -g @openai/codex`) and sign in ' +
25
+ 'with `codex login` so `codex --version` succeeds on PATH.',
22
26
  fallback:
23
27
  'Or set `codeReview.providers` to [{ name: "native" }] in .agentrc.json to use the ' +
24
28
  'in-process maintainability/lint provider instead.',
25
29
  });
26
30
 
27
- /** A present `codex-plugin-cc` directory means the slash command is registered. */
28
- const DEFAULT_PLUGIN_MARKERS = Object.freeze([
29
- path.join(os.homedir(), '.claude', 'plugins', 'codex-plugin-cc'),
30
- path.join(os.homedir(), '.claude', 'plugins', 'openai', 'codex-plugin-cc'),
31
- ]);
32
-
33
- /**
34
- * Synchronous so a missing plugin surfaces at construction, not mid-review.
35
- *
36
- * @param {{ markers?: readonly string[], existsFn?: (p: string) => boolean }} [opts]
37
- * @returns {boolean}
38
- */
39
- export function defaultProbeCodexCommand(opts = {}) {
40
- const markers = opts.markers ?? DEFAULT_PLUGIN_MARKERS;
41
- const existsFn = opts.existsFn ?? fs.existsSync;
42
- for (const marker of markers) {
43
- try {
44
- if (existsFn(marker)) return true;
45
- } catch (_err) {
46
- // An I/O error reads as absent.
47
- }
48
- }
49
- return false;
50
- }
51
-
52
31
  /**
53
32
  * @returns {Error}
54
33
  */
55
34
  export function buildCodexUnavailableError() {
56
35
  return new Error(
57
36
  '[ReviewProviderFactory] codeReview.providers includes "codex" but the ' +
58
- '`/codex:review` slash command is not registered on this host. ' +
37
+ 'Codex CLI is not available on this host (`codex --version` failed). ' +
59
38
  `${CODEX_REMEDIATIONS.install} ${CODEX_REMEDIATIONS.fallback}`,
60
39
  );
61
40
  }
62
41
 
63
- /**
64
- * Codex severity tokens (case-insensitive) → canonical `Severity`; an
65
- * unnamed token falls through to `'suggestion'`.
66
- *
67
- * @type {Readonly<Record<string, Severity>>}
68
- */
69
- export const CODEX_SEVERITY_MAP = Object.freeze({
70
- blocker: 'critical',
71
- critical: 'critical',
72
- fatal: 'critical',
73
- major: 'high',
74
- high: 'high',
75
- error: 'high',
76
- minor: 'medium',
77
- medium: 'medium',
78
- warning: 'medium',
79
- info: 'suggestion',
80
- nit: 'suggestion',
81
- style: 'suggestion',
82
- suggestion: 'suggestion',
83
- note: 'suggestion',
84
- });
85
-
86
42
  /**
87
43
  * @param {unknown} raw
88
44
  * @returns {Severity}
@@ -94,57 +50,23 @@ export function mapCodexSeverity(raw) {
94
50
  }
95
51
 
96
52
  /**
97
- * @param {string} rawStdout
53
+ * The shared parser omits the schema's `null` file/line.
54
+ *
55
+ * @param {string} rawOutput - The `codex exec` last-message contents.
98
56
  * @returns {Finding[]}
99
- * @throws {Error} when stdout is not parseable JSON.
57
+ * @throws {Error} when the output is not parseable JSON.
100
58
  */
101
- export function parseCodexFindings(rawStdout) {
102
- return parseProviderFindings(rawStdout, {
103
- errorPrefix: '[codex-review] Failed to parse /codex:review stdout as JSON',
59
+ export function parseCodexFindings(rawOutput) {
60
+ return parseProviderFindings(rawOutput, {
61
+ errorPrefix: '[codex-review] Failed to parse codex exec output as JSON',
104
62
  mapSeverity: mapCodexSeverity,
105
63
  });
106
64
  }
107
65
 
108
- /**
109
- * The depth directive rides as trailing prompt prose after the slash command.
110
- *
111
- * @param {{ baseRef: string, headRef: string, depth?: import('./types.js').ReviewDepth }} args
112
- * @returns {string}
113
- */
114
- function buildCodexReviewPrompt({ baseRef, headRef, depth }) {
115
- return (
116
- `/codex:review --base ${baseRef} --head ${headRef} --wait ` +
117
- `${renderDepthDirective(depth)}`
118
- );
119
- }
120
-
121
- /**
122
- * Run `/codex:review` through the host's `claude` CLI; `--wait` makes the
123
- * plugin print JSON to stdout.
124
- *
125
- * @param {{ baseRef: string, headRef: string, depth?: import('./types.js').ReviewDepth }} args
126
- * @returns {{ status: number, stdout: string, stderr: string }}
127
- */
128
- function defaultInvokeCodexReview({ baseRef, headRef, depth }) {
129
- const cliArgs = [
130
- '--print',
131
- buildCodexReviewPrompt({ baseRef, headRef, depth }),
132
- ];
133
- const result = spawnSync('claude', cliArgs, {
134
- encoding: 'utf-8',
135
- shell: process.platform === 'win32',
136
- });
137
- return {
138
- status: result.status ?? 1,
139
- stdout: result.stdout ?? '',
140
- stderr: result.stderr ?? '',
141
- };
142
- }
143
-
144
66
  /**
145
67
  * @param {{
146
68
  * probeFn?: () => boolean,
147
- * invokeFn?: (args: { baseRef: string, headRef: string, scope: string, ticketId: number, depth?: import('./types.js').ReviewDepth }) => { status: number, stdout: string, stderr: string },
69
+ * invokeFn?: (args: { baseRef: string, headRef: string, scope: string, ticketId: number, depth?: import('./types.js').ReviewDepth }) => { status: number, stdout: string, stderr: string } | Promise<{ status: number, stdout: string, stderr: string }>,
148
70
  * logger?: { info?: Function, warn?: Function, error?: Function },
149
71
  * }} [deps]
150
72
  * @returns {ReviewProvider}
@@ -155,7 +77,7 @@ export function createCodexProvider(deps = {}) {
155
77
  throw buildCodexUnavailableError();
156
78
  }
157
79
 
158
- const invokeFn = deps.invokeFn ?? defaultInvokeCodexReview;
80
+ const invokeFn = deps.invokeFn ?? invokeCodexExec;
159
81
  const logger = deps.logger;
160
82
 
161
83
  return {
@@ -177,14 +99,20 @@ export function createCodexProvider(deps = {}) {
177
99
  }
178
100
 
179
101
  logger?.info?.(
180
- `[codex-review] Invoking /codex:review --base ${baseRef} --head ${headRef} ` +
102
+ `[codex-review] Invoking codex exec on ${baseRef}...${headRef} ` +
181
103
  `for ${scope} #${ticketId}...`,
182
104
  );
183
105
 
184
- const result = invokeFn({ baseRef, headRef, scope, ticketId, depth });
106
+ const result = await invokeFn({
107
+ baseRef,
108
+ headRef,
109
+ scope,
110
+ ticketId,
111
+ depth,
112
+ });
185
113
  if (result.status !== 0) {
186
114
  throw new Error(
187
- `[codex-review] /codex:review exited with status ${result.status}: ${
115
+ `[codex-review] codex exec exited with status ${result.status}: ${
188
116
  result.stderr || result.stdout || '<no output>'
189
117
  }`,
190
118
  );
@@ -192,7 +120,7 @@ export function createCodexProvider(deps = {}) {
192
120
 
193
121
  const findings = parseCodexFindings(result.stdout);
194
122
  logger?.info?.(
195
- `[codex-review] Parsed ${findings.length} finding(s) from /codex:review.`,
123
+ `[codex-review] Parsed ${findings.length} finding(s) from codex exec.`,
196
124
  );
197
125
  return findings;
198
126
  },
@@ -0,0 +1,30 @@
1
+ /**
2
+ * review-providers/provider-severity.js — the severity vocabulary shared by
3
+ * the LLM-backed providers.
4
+ *
5
+ * @typedef {import('./types.js').Severity} Severity
6
+ */
7
+
8
+ /**
9
+ * Severity vocabulary shared by the LLM-backed providers (case-insensitive
10
+ * token → canonical `Severity`); an unnamed token falls through to
11
+ * `'suggestion'` in each provider's mapper.
12
+ *
13
+ * @type {Readonly<Record<string, Severity>>}
14
+ */
15
+ export const PROVIDER_SEVERITY_MAP = Object.freeze({
16
+ blocker: 'critical',
17
+ critical: 'critical',
18
+ fatal: 'critical',
19
+ major: 'high',
20
+ high: 'high',
21
+ error: 'high',
22
+ minor: 'medium',
23
+ medium: 'medium',
24
+ warning: 'medium',
25
+ info: 'suggestion',
26
+ nit: 'suggestion',
27
+ style: 'suggestion',
28
+ suggestion: 'suggestion',
29
+ note: 'suggestion',
30
+ });
@@ -11,6 +11,7 @@
11
11
 
12
12
  import { spawnSync } from 'node:child_process';
13
13
  import { parseProviderFindings } from './parse-findings.js';
14
+ import { PROVIDER_SEVERITY_MAP } from './provider-severity.js';
14
15
  import { renderDepthDirective } from './review-depth.js';
15
16
 
16
17
  export const SECURITY_REVIEW_REMEDIATIONS = Object.freeze({
@@ -55,26 +56,11 @@ export function buildSecurityReviewUnavailableError() {
55
56
  }
56
57
 
57
58
  /**
58
- * Mirrors `CODEX_SEVERITY_MAP` for a consistent vocabulary across adapters.
59
+ * The shared provider vocabulary, kept under this provider's export name.
59
60
  *
60
61
  * @type {Readonly<Record<string, Severity>>}
61
62
  */
62
- export const SECURITY_REVIEW_SEVERITY_MAP = Object.freeze({
63
- blocker: 'critical',
64
- critical: 'critical',
65
- fatal: 'critical',
66
- major: 'high',
67
- high: 'high',
68
- error: 'high',
69
- minor: 'medium',
70
- medium: 'medium',
71
- warning: 'medium',
72
- info: 'suggestion',
73
- nit: 'suggestion',
74
- style: 'suggestion',
75
- suggestion: 'suggestion',
76
- note: 'suggestion',
77
- });
63
+ export const SECURITY_REVIEW_SEVERITY_MAP = PROVIDER_SEVERITY_MAP;
78
64
 
79
65
  /**
80
66
  * @param {unknown} raw
@@ -6,13 +6,16 @@
6
6
  * replays its tail inline. Full-suite lock-wait lines are also teed to
7
7
  * `progress()` so a long wait doesn't read as a hang, and an expired wait
8
8
  * defers to `pending` rather than failing.
9
+ * `lockWait` / `suiteTimings` come from the lock-event channel, never output.
9
10
  */
10
11
 
12
+ import {
13
+ createLockEventChannel as defaultCreateLockEventChannel,
14
+ summarizeLockEvents,
15
+ } from '../../../close-lock-events.js';
11
16
  import { buildDefaultGates as defaultBuildDefaultGates } from '../../../close-validation/gates.js';
12
17
  import { runCloseValidation as defaultRunCloseValidation } from '../../../close-validation/runner.js';
13
18
  import { LOCK_WAIT_EXPIRED_EXIT_CODE } from '../../../full-suite-lock.js';
14
- import { parseLockWaitOutcome } from '../../../full-suite-queue.js';
15
- import { parseSuiteTimings } from '../../../supervised-suite.js';
16
19
  import { createGateLogSink as defaultCreateGateLogSink } from '../gate-log.js';
17
20
  import { runPreGateSteps as defaultRunPreGateSteps } from './pre-gate-steps.js';
18
21
 
@@ -36,6 +39,7 @@ import { runPreGateSteps as defaultRunPreGateSteps } from './pre-gate-steps.js';
36
39
  * runBaselineUpwardWriteback?: Function,
37
40
  * runContextBudgetWriteback?: Function,
38
41
  * createGateLogSink?: typeof defaultCreateGateLogSink,
42
+ * createLockEventChannel?: typeof defaultCreateLockEventChannel,
39
43
  * onPreGateStepsDone?: () => void,
40
44
  * }} args
41
45
  * @returns {Promise<{
@@ -61,29 +65,28 @@ export async function runCloseValidationPhase({
61
65
  runBaselineUpwardWriteback,
62
66
  runContextBudgetWriteback,
63
67
  createGateLogSink = defaultCreateGateLogSink,
68
+ createLockEventChannel = defaultCreateLockEventChannel,
64
69
  onPreGateStepsDone,
65
70
  }) {
66
- await runPreGateSteps({
67
- cwd,
68
- worktreePath,
69
- storyId,
70
- baseBranch,
71
- storyBranch,
72
- config,
73
- progress,
74
- runScopedFormatAutofix,
75
- runBaselineUpwardWriteback,
76
- runContextBudgetWriteback,
71
+ await prepareTree({
72
+ runPreGateSteps,
73
+ onPreGateStepsDone,
74
+ stepArgs: {
75
+ cwd,
76
+ worktreePath,
77
+ storyId,
78
+ baseBranch,
79
+ storyBranch,
80
+ config,
81
+ progress,
82
+ runScopedFormatAutofix,
83
+ runBaselineUpwardWriteback,
84
+ runContextBudgetWriteback,
85
+ },
77
86
  });
78
- onPreGateStepsDone?.();
79
-
80
- progress(
81
- 'VALIDATE',
82
- `Running close-validation gates against baseline ${baseBranch}${worktreePath ? ` in ${worktreePath}` : ''}...`,
83
- );
84
87
  // One sink for both `log` seams so nothing routes around the artifact.
85
88
  const gateLog = createGateLogSink({ storyId, config });
86
- const lockWaits = trackLockWaits({ sink: gateLog.log, progress });
89
+ const lockEvents = createLockEventChannel();
87
90
  const gateList = buildDefaultGates({
88
91
  config,
89
92
  baseBranch,
@@ -92,13 +95,15 @@ export async function runCloseValidationPhase({
92
95
  storyId,
93
96
  evidenceCwd: cwd,
94
97
  });
95
- let validation;
96
- try {
97
- validation = await runCloseValidation({
98
+ const { validation, lockWait, suiteTimings } = await runGateChain({
99
+ runCloseValidation,
100
+ gateLog,
101
+ lockEvents,
102
+ progress,
103
+ validationArgs: {
98
104
  cwd,
99
105
  worktreePath,
100
106
  gates: gateList,
101
- log: lockWaits.log,
102
107
  storyId,
103
108
  // Anchors the evidence cache on the Story id, so a re-close at an
104
109
  // unchanged HEAD skips already-passed gates.
@@ -107,13 +112,8 @@ export async function runCloseValidationPhase({
107
112
  baseBranch,
108
113
  storyBranch,
109
114
  config,
110
- });
111
- } finally {
112
- // The sink is async-buffered; settle it before anything reads it, on
113
- // the throw path too.
114
- await gateLog.flush();
115
- }
116
- const lockWait = lockWaits.summary();
115
+ },
116
+ });
117
117
  if (!validation.ok) {
118
118
  return settleFailedValidation({ validation, lockWait, gateLog, progress });
119
119
  }
@@ -121,11 +121,46 @@ export async function runCloseValidationPhase({
121
121
  return {
122
122
  gates: gateOutcomes(gateList, validation),
123
123
  lockWait,
124
- suiteTimings: lockWaits.suiteTimings(),
124
+ suiteTimings,
125
125
  pending: false,
126
126
  };
127
127
  }
128
128
 
129
+ async function prepareTree({ runPreGateSteps, onPreGateStepsDone, stepArgs }) {
130
+ await runPreGateSteps(stepArgs);
131
+ onPreGateStepsDone?.();
132
+ const { baseBranch, worktreePath, progress } = stepArgs;
133
+ progress(
134
+ 'VALIDATE',
135
+ `Running close-validation gates against baseline ${baseBranch}${worktreePath ? ` in ${worktreePath}` : ''}...`,
136
+ );
137
+ }
138
+
139
+ async function runGateChain({
140
+ runCloseValidation,
141
+ gateLog,
142
+ lockEvents,
143
+ progress,
144
+ validationArgs,
145
+ }) {
146
+ let validation;
147
+ let events;
148
+ try {
149
+ validation = await runCloseValidation({
150
+ ...validationArgs,
151
+ log: teeLockLines({ sink: gateLog.log, progress }),
152
+ lockEvents,
153
+ });
154
+ } finally {
155
+ // The sink is async-buffered; settle it before anything reads it, on
156
+ // the throw path too.
157
+ await gateLog.flush();
158
+ events = lockEvents.read();
159
+ lockEvents.dispose();
160
+ }
161
+ return { validation, ...summarizeLockEvents(events) };
162
+ }
163
+
129
164
  /**
130
165
  * Deferred on an expired lock wait → `pending`; otherwise throws.
131
166
  *
@@ -157,40 +192,15 @@ function settleFailedValidation({ validation, lockWait, gateLog, progress }) {
157
192
  }
158
193
 
159
194
  /**
160
- * Parsed from the gate log: the one place that sees waits and timings both
161
- * in-process and in gate children.
195
+ * Display only: no figure is read back from these lines.
162
196
  *
163
197
  * @param {{ sink: (m: string) => void, progress: (tag: string, msg: string) => void }} args
164
- * @returns {{ log: (m: string) => void, summary: () => { waitedSeconds: number, expired: boolean, holder?: object }|null, suiteTimings: () => object|null }}
165
- */
166
- function trackLockWaits({ sink, progress }) {
167
- let tally = null;
168
- let timings = null;
169
- return {
170
- log(line) {
171
- sink(line);
172
- timings = parseSuiteTimings(line) ?? timings;
173
- if (!String(line).includes('[full-suite-lock]')) return;
174
- progress('LOCK', line);
175
- const outcome = parseLockWaitOutcome(line);
176
- if (!outcome) return;
177
- tally = mergeLockWait(tally, outcome);
178
- },
179
- summary: () => tally,
180
- suiteTimings: () => timings,
181
- };
182
- }
183
-
184
- /**
185
- * @param {{ waitedSeconds: number, expired: boolean, holder?: object }|null} tally
186
- * @param {{ waitedSeconds: number, expired: boolean, holder?: object }} outcome
198
+ * @returns {(line: string) => void}
187
199
  */
188
- function mergeLockWait(tally, outcome) {
189
- const holder = outcome.holder ?? tally?.holder;
190
- return {
191
- waitedSeconds: (tally?.waitedSeconds ?? 0) + outcome.waitedSeconds,
192
- expired: Boolean(tally?.expired) || outcome.expired,
193
- ...(holder ? { holder } : {}),
200
+ function teeLockLines({ sink, progress }) {
201
+ return (line) => {
202
+ sink(line);
203
+ if (String(line).includes('[full-suite-lock]')) progress('LOCK', line);
194
204
  };
195
205
  }
196
206