mandrel 2.83.0 → 2.85.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 (54) hide show
  1. package/.agents/README.md +65 -20
  2. package/.agents/docs/configuration.md +36 -0
  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/story-deliver-terminal.schema.json +2 -2
  9. package/.agents/scripts/boot-sweep.js +42 -13
  10. package/.agents/scripts/coverage-capture.js +1 -0
  11. package/.agents/scripts/evidence-gate.js +1 -0
  12. package/.agents/scripts/generate-workflows-doc.js +14 -0
  13. package/.agents/scripts/lib/bootstrap/agents-md-fold.js +99 -16
  14. package/.agents/scripts/lib/bootstrap/manifest.js +4 -4
  15. package/.agents/scripts/lib/bootstrap/project-bootstrap.js +16 -1
  16. package/.agents/scripts/lib/close-lock-events.js +29 -9
  17. package/.agents/scripts/lib/codex/agents-projection.js +284 -0
  18. package/.agents/scripts/lib/codex/skills-projection.js +291 -0
  19. package/.agents/scripts/lib/config/agentrc-overlay.js +91 -0
  20. package/.agents/scripts/lib/config/sync-agentrc.js +39 -19
  21. package/.agents/scripts/lib/config-resolver.js +5 -42
  22. package/.agents/scripts/lib/config-settings-schema-quality.js +1 -1
  23. package/.agents/scripts/lib/full-suite-lock.js +2 -0
  24. package/.agents/scripts/lib/full-suite-queue.js +66 -26
  25. package/.agents/scripts/lib/observability/source-classifier.js +2 -0
  26. package/.agents/scripts/lib/orchestration/review-providers/claude-verdict.js +242 -0
  27. package/.agents/scripts/lib/orchestration/review-providers/code-review.js +151 -111
  28. package/.agents/scripts/lib/orchestration/review-providers/codex-cli.js +152 -0
  29. package/.agents/scripts/lib/orchestration/review-providers/codex.js +33 -105
  30. package/.agents/scripts/lib/orchestration/review-providers/provider-severity.js +30 -0
  31. package/.agents/scripts/lib/orchestration/review-providers/security-review.js +3 -17
  32. package/.agents/scripts/lib/orchestration/single-story-close/phases/reconcile-done.js +12 -5
  33. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +30 -4
  34. package/.agents/scripts/lib/orchestration/story-handoff.js +84 -10
  35. package/.agents/scripts/lib/single-story-sweep/reconcile-closing.js +89 -0
  36. package/.agents/scripts/single-story-init.js +20 -5
  37. package/.agents/scripts/sync-agentrc.js +5 -3
  38. package/.agents/scripts/sync-claude-agents.js +20 -0
  39. package/.agents/scripts/sync-claude-commands.js +64 -27
  40. package/.agents/scripts/sync-codex-agents.js +36 -0
  41. package/.agents/scripts/sync-codex-skills.js +36 -0
  42. package/.agents/workflows/helpers/deliver-story-reference.md +6 -0
  43. package/.agents/workflows/helpers/mandrel-sync-config.md +16 -9
  44. package/.agents/workflows/mandrel-update.md +2 -1
  45. package/docs/CHANGELOG.md +23 -0
  46. package/lib/cli/guarded-sync.js +3 -2
  47. package/lib/cli/registry.js +248 -0
  48. package/lib/cli/sync-agents.js +5 -2
  49. package/lib/cli/sync-commands.js +5 -2
  50. package/lib/cli/sync.js +45 -14
  51. package/lib/cli/uninstall.js +8 -1
  52. package/lib/migrations/index.js +2 -0
  53. package/lib/migrations/steps/2.84.0-hoist-system-prompt-block.js +64 -0
  54. package/package.json +3 -2
@@ -6,26 +6,58 @@
6
6
  * id and the diff text — never `acceptance[]` or the self-eval verdict: this
7
7
  * is a bug review, not a second acceptance scoring.
8
8
  *
9
- * A missing CLI throws at construction (the default chain entry is
10
- * `optional: true`, so hosts without it skip). A review that cannot run or
11
- * whose output does not parse degrades to one non-halting `suggestion`.
9
+ * Cost is bounded by stripping context, not by pinning a model: an empty
10
+ * OS temp cwd (no CLAUDE.md discovery), user-only settings, no MCP, no tools.
11
+ *
12
+ * A missing CLI throws at construction (the chain entry is optional). A
13
+ * review with no verdict records one degraded gate via `getDegradations()`
14
+ * and returns no findings, so "never ran" cannot read as "found nothing".
12
15
  *
13
16
  * @typedef {import('./types.js').Finding} Finding
14
17
  * @typedef {import('./types.js').ReviewInput} ReviewInput
15
18
  * @typedef {import('./types.js').ReviewProvider} ReviewProvider
19
+ * @typedef {import('./degraded-gates.js').GateDegradation} GateDegradation
16
20
  */
17
21
 
22
+ import fs from 'node:fs';
23
+ import os from 'node:os';
24
+ import path from 'node:path';
18
25
  import { spawnCaptureAsync } from '../../child-exec.js';
19
26
  import { gitSpawn } from '../../git-utils.js';
20
27
  import { PROJECT_ROOT } from '../../project-root.js';
21
- import { parseProviderFindings } from './parse-findings.js';
28
+ import {
29
+ clip,
30
+ FINDINGS_SCHEMA_JSON,
31
+ readAuthStatus,
32
+ resolveVerdict,
33
+ } from './claude-verdict.js';
22
34
  import { renderDepthDirective } from './review-depth.js';
23
35
  import { probeClaudeCli } from './security-review.js';
24
36
 
25
- const CLAUDE_ARGS = Object.freeze(['--print', '--effort', 'low']);
37
+ const CLAUDE_ARGS = Object.freeze([
38
+ '--print',
39
+ '--effort',
40
+ 'low',
41
+ '--output-format',
42
+ 'json',
43
+ '--json-schema',
44
+ FINDINGS_SCHEMA_JSON,
45
+ '--setting-sources',
46
+ 'user',
47
+ '--strict-mcp-config',
48
+ '--tools',
49
+ '',
50
+ ]);
51
+ const AUTH_ARGS = Object.freeze(['auth', 'status', '--json']);
26
52
  const INVOKE_TIMEOUT_MS = 10 * 60 * 1000;
53
+ const AUTH_TIMEOUT_MS = 15 * 1000;
27
54
  /** Larger diffs are truncated; the reviewer is told so. */
28
55
  const MAX_DIFF_CHARS = 200_000;
56
+ const DEGRADATION_BASE = Object.freeze({
57
+ tool: 'code-review',
58
+ gate: 'codeReview',
59
+ surface: 'model-bug-review',
60
+ });
29
61
 
30
62
  const PROMPT_HEAD =
31
63
  'You are reviewing the diff `{baseRef}...{headRef}` for Story #{ticketId} ' +
@@ -37,11 +69,10 @@ const PROMPT_HEAD =
37
69
  'line in the new version, why it is wrong, and how to show it fails (an ' +
38
70
  'input, command or test that exposes it).\n\n' +
39
71
  'The diff below is authoritative — files on disk may not reflect it. ' +
40
- 'Emit ONLY a JSON array on stdout with this exact shape, no prose around ' +
41
- 'it:\n\n' +
42
- '[{"title":"...","body":"Why it is wrong: ... How to show it fails: ...",' +
43
- '"file":"...","line":1,"category":"bug"}]\n\n' +
44
- 'Emit [] if there is nothing you would block the merge for.\n\n';
72
+ 'Answer with a JSON object of this exact shape, no prose around it:\n\n' +
73
+ '{"findings":[{"title":"...","body":"Why it is wrong: ... How to show it ' +
74
+ 'fails: ...","file":"...","line":1,"category":"bug"}]}\n\n' +
75
+ 'Emit {"findings":[]} if there is nothing you would block the merge for.\n\n';
45
76
 
46
77
  /**
47
78
  * @param {ReviewInput} input
@@ -62,64 +93,37 @@ function buildPrompt(input, diff) {
62
93
  }
63
94
 
64
95
  /**
65
- * The prompt rides stdin so no shell ever quotes it. Asynchronous: the
66
- * review overlaps close's gate children, whose output must keep draining.
96
+ * A Windows shell joins argv unquoted, which would drop `--tools ""` and
97
+ * split the schema; quote each arg for the MSVCRT argv parser.
67
98
  *
68
- * @param {string} prompt
69
- * @param {Function} [run] - `(file, args, options)` seam for tests.
70
- * @returns {Promise<{ status: number, stdout: string, stderr: string }>}
71
- */
72
- function invokeClaude(prompt, run) {
73
- return spawnCaptureAsync('claude', [...CLAUDE_ARGS], {
74
- cwd: PROJECT_ROOT,
75
- input: prompt,
76
- shell: process.platform === 'win32',
77
- timeout: INVOKE_TIMEOUT_MS,
78
- ...(run ? { run } : {}),
79
- });
80
- }
81
-
82
- /** A model often fences its JSON; strip one surrounding fence. */
83
- function stripFence(text) {
84
- const match = /^\s*```[a-z]*\s*\n([\s\S]*?)\n\s*```\s*$/i.exec(text ?? '');
85
- return match ? match[1] : (text ?? '');
86
- }
87
-
88
- /**
89
- * @param {string} title
90
- * @param {string} detail
91
- * @returns {Finding}
99
+ * @param {string} arg
100
+ * @returns {string}
92
101
  */
93
- function advisory(title, detail) {
94
- return {
95
- severity: 'suggestion',
96
- title,
97
- body:
98
- `${detail} The model bug review did not produce a verdict — inspect ` +
99
- 'the diff manually before merging. Advisory only; the chain did not halt.',
100
- category: 'bug',
101
- };
102
+ function quoteWindowsArg(arg) {
103
+ const escaped = arg.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/, '$1$1');
104
+ return `"${escaped}"`;
102
105
  }
103
106
 
104
107
  /**
105
- * @param {string} stdout
106
- * @returns {Finding[]}
108
+ * Async, so close's concurrent gate children keep draining.
109
+ *
110
+ * @param {ReadonlyArray<string>} args
111
+ * @param {{ cwd: string, input?: string, timeout: number, run?: Function, platform: string }} opts
112
+ * @returns {Promise<{ status: number, stdout: string, stderr: string }>}
107
113
  */
108
- function parseFindings(stdout) {
109
- try {
110
- return parseProviderFindings(stripFence(stdout), {
111
- errorPrefix: '[code-review] Failed to parse reviewer stdout as JSON',
112
- mapSeverity: () => 'critical',
113
- defaultCategory: 'bug',
114
- });
115
- } catch (err) {
116
- return [
117
- advisory(
118
- 'Code review output not parseable as JSON',
119
- `The reviewer returned text that did not parse as a JSON findings array (${err.message}).`,
120
- ),
121
- ];
122
- }
114
+ function runClaude(args, { cwd, input, timeout, run, platform }) {
115
+ const shell = platform === 'win32';
116
+ return spawnCaptureAsync(
117
+ 'claude',
118
+ shell ? args.map(quoteWindowsArg) : [...args],
119
+ {
120
+ cwd,
121
+ input: input ?? '',
122
+ shell,
123
+ timeout,
124
+ ...(run ? { run } : {}),
125
+ },
126
+ );
123
127
  }
124
128
 
125
129
  /**
@@ -139,69 +143,105 @@ function assertInput(input) {
139
143
  }
140
144
  }
141
145
 
146
+ function runAuthStatus(runDir, deps) {
147
+ return runClaude(AUTH_ARGS, {
148
+ cwd: runDir,
149
+ timeout: AUTH_TIMEOUT_MS,
150
+ run: deps.authSpawnFn,
151
+ platform: deps.platform,
152
+ });
153
+ }
154
+
155
+ function runReviewer(runDir, prompt, deps) {
156
+ return runClaude(CLAUDE_ARGS, {
157
+ cwd: runDir,
158
+ input: prompt,
159
+ timeout: INVOKE_TIMEOUT_MS,
160
+ run: deps.spawnFn,
161
+ platform: deps.platform,
162
+ });
163
+ }
164
+
165
+ /**
166
+ * Preflight, then the review, both from a fresh OS temp dir removed after.
167
+ *
168
+ * @returns {Promise<{ findings: Finding[] } | { reason: string }>}
169
+ */
170
+ async function reviewInTempDir(prompt, deps) {
171
+ const runDir = fs.mkdtempSync(path.join(os.tmpdir(), 'mandrel-code-review-'));
172
+ try {
173
+ const auth = readAuthStatus(await runAuthStatus(runDir, deps));
174
+ if (!auth.ok) return auth;
175
+ deps.logger?.info?.(
176
+ `[code-review] Invoking claude --print --effort low (${auth.detail})...`,
177
+ );
178
+ return resolveVerdict(await runReviewer(runDir, prompt, deps));
179
+ } finally {
180
+ fs.rmSync(runDir, { recursive: true, force: true });
181
+ }
182
+ }
183
+
184
+ /**
185
+ * @returns {{ reason: string } | { text: string }}
186
+ */
187
+ function readDiff(gitSpawnFn, { baseRef, headRef }) {
188
+ const range = `${baseRef}...${headRef}`;
189
+ const diff = gitSpawnFn(PROJECT_ROOT, 'diff', '--no-color', range);
190
+ if (diff.status === 0) return { text: diff.stdout };
191
+ return {
192
+ reason: `git diff ${range} failed: ${clip(diff.stderr) || '<no output>'}`,
193
+ };
194
+ }
195
+
196
+ function assertCliPresent(probeFn) {
197
+ if (probeFn()) return;
198
+ throw new Error(
199
+ '[ReviewProviderFactory] codeReview provider "code-review" requires ' +
200
+ 'the `claude` CLI on PATH but it was not detected. Install the ' +
201
+ 'Claude Code CLI, or keep the entry `optional: true` so hosts ' +
202
+ 'without it skip the model bug review.',
203
+ );
204
+ }
205
+
142
206
  /**
143
207
  * @param {{
144
208
  * probeFn?: () => boolean,
145
209
  * gitSpawnFn?: typeof gitSpawn,
146
210
  * spawnFn?: Function,
211
+ * authSpawnFn?: Function,
212
+ * platform?: string,
147
213
  * logger?: { info?: Function, warn?: Function },
148
- * }} [deps] - `spawnFn` replaces the async runner for the `claude` call.
149
- * @returns {ReviewProvider}
214
+ * }} [deps] - `spawnFn` / `authSpawnFn` replace the async runner for the
215
+ * review and the `claude auth status` preflight.
216
+ * @returns {ReviewProvider & { getDegradations: () => GateDegradation[] }}
150
217
  */
151
218
  export function createCodeReviewProviderForRegistry(deps = {}) {
152
- const probeFn = deps.probeFn ?? probeClaudeCli;
153
- if (!probeFn()) {
154
- throw new Error(
155
- '[ReviewProviderFactory] codeReview provider "code-review" requires ' +
156
- 'the `claude` CLI on PATH but it was not detected. Install the ' +
157
- 'Claude Code CLI, or keep the entry `optional: true` so hosts ' +
158
- 'without it skip the model bug review.',
159
- );
160
- }
219
+ assertCliPresent(deps.probeFn ?? probeClaudeCli);
161
220
  const gitSpawnFn = deps.gitSpawnFn ?? gitSpawn;
162
- const { spawnFn, logger } = deps;
221
+ const runDeps = { ...deps, platform: deps.platform ?? process.platform };
222
+ /** @type {GateDegradation[]} */
223
+ let degradations = [];
224
+
225
+ function settle(verdict) {
226
+ if (!('reason' in verdict)) return verdict.findings;
227
+ degradations.push({ ...DEGRADATION_BASE, reason: verdict.reason });
228
+ deps.logger?.warn?.(`[code-review] No verdict: ${verdict.reason}.`);
229
+ return [];
230
+ }
163
231
 
164
232
  return {
165
233
  async runReview(input) {
234
+ degradations = [];
166
235
  assertInput(input);
167
- const { baseRef, headRef, ticketId } = input;
168
- const diff = gitSpawnFn(
169
- PROJECT_ROOT,
170
- 'diff',
171
- '--no-color',
172
- `${baseRef}...${headRef}`,
173
- );
174
- if (diff.status !== 0) {
175
- return [
176
- advisory(
177
- 'Code review could not read the diff',
178
- `\`git diff ${baseRef}...${headRef}\` failed: ${diff.stderr || '<no output>'}.`,
179
- ),
180
- ];
181
- }
182
- if (diff.stdout.trim().length === 0) return [];
183
-
184
- logger?.info?.(
185
- `[code-review] Invoking claude --print --effort low for Story #${ticketId} (${baseRef}...${headRef})...`,
186
- );
187
- const result = await invokeClaude(
188
- buildPrompt(input, diff.stdout),
189
- spawnFn,
236
+ const diff = readDiff(gitSpawnFn, input);
237
+ if ('reason' in diff) return settle(diff);
238
+ if (diff.text.trim().length === 0) return [];
239
+ return settle(
240
+ await reviewInTempDir(buildPrompt(input, diff.text), runDeps),
190
241
  );
191
- if (result.status !== 0) {
192
- logger?.warn?.(
193
- `[code-review] claude exited ${result.status}; emitting advisory.`,
194
- );
195
- return [
196
- advisory(
197
- 'Code review did not complete',
198
- `\`claude --print\` exited with status ${result.status}: ${
199
- result.stderr || result.stdout || '<no output>'
200
- }.`,
201
- ),
202
- ];
203
- }
204
- return parseFindings(result.stdout);
242
+ },
243
+ getDegradations() {
244
+ return degradations.map((d) => ({ ...d }));
205
245
  },
206
246
  };
207
247
  }
@@ -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
  },