@sanqianx/ai-coding-workflow 0.1.2 → 0.2.1
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.
- package/docs/contract.md +19 -1
- package/package.json +1 -1
- package/src/bin.js +8 -6
- package/src/checks.js +32 -11
- package/src/consumer.js +10 -3
- package/src/domain.js +51 -1
- package/src/identity.js +2 -1
- package/src/review-native.js +396 -0
- package/src/server.js +403 -31
- package/src/snapshots.js +81 -20
- package/src/store.js +22 -0
- package/src/tasks.js +582 -27
- package/ui/app.css +96 -186
- package/ui/app.js +393 -624
- package/ui/index.html +21 -32
|
@@ -0,0 +1,396 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Native reviewer adapter (M1-A): an independent external CLI reviews the
|
|
4
|
+
// bounded material of a verified snapshot in its own empty work directory.
|
|
5
|
+
//
|
|
6
|
+
// Hard rules carried over from the plan:
|
|
7
|
+
// - The reviewer runs with a READ-ONLY sandbox, no user config, no rules,
|
|
8
|
+
// no MCP, no tools — it can read the material and answer, nothing else.
|
|
9
|
+
// The spawn is a fixed argv (no shell), bounded by a hard timeout.
|
|
10
|
+
// - Review material arrives on STDIN and is size-capped.
|
|
11
|
+
// - Login failure, timeout, non-zero exit, invalid JSON, truncated output
|
|
12
|
+
// and an unverified model identity NEVER form a pass receipt.
|
|
13
|
+
// - "Model identity" is taken from the RUN's own structured output (the CLI
|
|
14
|
+
// reporting which model actually executed) and must be one of the allowed
|
|
15
|
+
// models for that provider in the trusted reviewer config. CLI names,
|
|
16
|
+
// self-descriptions and config labels alone prove nothing — evidence
|
|
17
|
+
// short of that is MODEL_IDENTITY_UNVERIFIED, which blocks the verdict.
|
|
18
|
+
|
|
19
|
+
const { spawn } = require('child_process');
|
|
20
|
+
const fs = require('fs');
|
|
21
|
+
const os = require('os');
|
|
22
|
+
const path = require('path');
|
|
23
|
+
const crypto = require('crypto');
|
|
24
|
+
const { WorkflowError } = require('./errors');
|
|
25
|
+
|
|
26
|
+
const REVIEW_TIMEOUT_MS = 240_000;
|
|
27
|
+
const MAX_MATERIAL_BYTES = 512 * 1024;
|
|
28
|
+
const MAX_OUTPUT_BYTES = 4 * 1024 * 1024;
|
|
29
|
+
|
|
30
|
+
// The JSON contract the reviewer must answer with. Kept as a plain schema
|
|
31
|
+
// document so both CLIs can consume it verbatim.
|
|
32
|
+
const REVIEW_SCHEMA = {
|
|
33
|
+
type: 'object',
|
|
34
|
+
additionalProperties: false,
|
|
35
|
+
// OpenAI structured output requires 'required' to cover EVERY property;
|
|
36
|
+
// optional values are expressed as nulls and tolerated by the parser.
|
|
37
|
+
required: ['verdict', 'summary', 'findings'],
|
|
38
|
+
properties: {
|
|
39
|
+
verdict: { type: 'string', enum: ['pass', 'findings', 'blocked'] },
|
|
40
|
+
summary: { type: 'string', description: 'One-paragraph verdict summary; empty string when none.' },
|
|
41
|
+
findings: {
|
|
42
|
+
type: 'array',
|
|
43
|
+
maxItems: 50,
|
|
44
|
+
items: {
|
|
45
|
+
type: 'object',
|
|
46
|
+
additionalProperties: false,
|
|
47
|
+
required: ['file', 'line', 'severity', 'reason'],
|
|
48
|
+
properties: {
|
|
49
|
+
file: { type: 'string', description: 'Repository-relative path in the reviewed snapshot.' },
|
|
50
|
+
line: { type: ['integer', 'null'], minimum: 1, description: 'Null when not applicable.' },
|
|
51
|
+
severity: { type: ['string', 'null'], enum: ['error', 'warning', 'info', null] },
|
|
52
|
+
reason: { type: 'string' },
|
|
53
|
+
},
|
|
54
|
+
},
|
|
55
|
+
},
|
|
56
|
+
},
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
const PROVIDERS = {
|
|
60
|
+
codex: {
|
|
61
|
+
buildArgv({ entry, workDir, schemaPath, lastMessagePath, model }) {
|
|
62
|
+
const argv = [
|
|
63
|
+
entry, 'exec', '--sandbox', 'read-only', '--ignore-user-config', '--ignore-rules',
|
|
64
|
+
'--json', '--output-schema', schemaPath, '--output-last-message', lastMessagePath,
|
|
65
|
+
'--cd', workDir, '--skip-git-repo-check',
|
|
66
|
+
];
|
|
67
|
+
// The trusted reviewer config names the exact model (M1-A): a verified,
|
|
68
|
+
// pre-flighted model id from allowedModels — never a config-file guess.
|
|
69
|
+
if (model) argv.push('-m', String(model));
|
|
70
|
+
argv.push('-');
|
|
71
|
+
return argv;
|
|
72
|
+
},
|
|
73
|
+
/**
|
|
74
|
+
* Identity evidence from the RUN itself, in order: model fields in the
|
|
75
|
+
* CLI's --json stdout events, then the CLI's own session rollout record
|
|
76
|
+
* (session_meta.model) located by the exact thread id. A future CLI that
|
|
77
|
+
* reports the model on stdout needs no rollout; today's codex records it
|
|
78
|
+
* only there — either way the source is the executed CLI, never a label.
|
|
79
|
+
*/
|
|
80
|
+
extractIdentity({ stdout, codexHome }) {
|
|
81
|
+
let threadId = null;
|
|
82
|
+
let model = null;
|
|
83
|
+
for (const line of stdout.split('\n')) {
|
|
84
|
+
if (!line.trim()) continue;
|
|
85
|
+
try {
|
|
86
|
+
const event = JSON.parse(line);
|
|
87
|
+
if (event && event.type === 'thread.started' && event.thread_id) threadId = event.thread_id;
|
|
88
|
+
const candidate = event && (event.model || (event.thread && event.thread.model) || (event.response && event.response.model));
|
|
89
|
+
if (typeof candidate === 'string' && candidate) model = candidate;
|
|
90
|
+
} catch { /* not every line is JSON */ }
|
|
91
|
+
}
|
|
92
|
+
if (model) return model;
|
|
93
|
+
if (!threadId) return null;
|
|
94
|
+
const home = codexHome || process.env.CODEX_HOME || path.join(os.homedir(), '.codex');
|
|
95
|
+
const sessionsRoot = path.join(home, 'sessions');
|
|
96
|
+
let found = null;
|
|
97
|
+
const walk = (dir, depth) => {
|
|
98
|
+
if (found || depth > 8) return;
|
|
99
|
+
let entries;
|
|
100
|
+
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
|
|
101
|
+
for (const entry of entries) {
|
|
102
|
+
const full = path.join(dir, entry.name);
|
|
103
|
+
if (entry.isDirectory()) walk(full, depth + 1);
|
|
104
|
+
else if (entry.isFile() && entry.name.endsWith(`-${threadId}.jsonl`)) found = full;
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
walk(sessionsRoot, 0);
|
|
108
|
+
if (!found) return null;
|
|
109
|
+
try {
|
|
110
|
+
const firstLine = fs.readFileSync(found, 'utf8').split('\n')[0];
|
|
111
|
+
const meta = JSON.parse(firstLine);
|
|
112
|
+
// codex ≤0.16x wrote payload.model; 0.171 records it under
|
|
113
|
+
// base_instructions.provenance.model. Read both.
|
|
114
|
+
const payload = (meta && meta.payload) || {};
|
|
115
|
+
const rolloutModel = payload.model
|
|
116
|
+
|| (payload.base_instructions && payload.base_instructions.provenance && payload.base_instructions.provenance.model);
|
|
117
|
+
return typeof rolloutModel === 'string' && rolloutModel ? rolloutModel : null;
|
|
118
|
+
} catch { return null; }
|
|
119
|
+
},
|
|
120
|
+
readResult({ lastMessagePath }) {
|
|
121
|
+
const raw = fs.readFileSync(lastMessagePath, 'utf8');
|
|
122
|
+
return { result: JSON.parse(raw), raw };
|
|
123
|
+
},
|
|
124
|
+
},
|
|
125
|
+
claude: {
|
|
126
|
+
buildArgv({ entry, workDir, schemaPath, emptyMcpConfigPath }) {
|
|
127
|
+
return [
|
|
128
|
+
entry, '-p', '--output-format', 'json', '--json-schema', schemaPath,
|
|
129
|
+
'--tools', '', '--strict-mcp-config', '--mcp-config', emptyMcpConfigPath,
|
|
130
|
+
'--setting-sources', '', '--no-session-persistence', '--permission-mode', 'dontAsk',
|
|
131
|
+
];
|
|
132
|
+
},
|
|
133
|
+
extractIdentity({ stdout }) {
|
|
134
|
+
try {
|
|
135
|
+
const parsed = JSON.parse(stdout);
|
|
136
|
+
return typeof parsed.model === 'string' && parsed.model ? parsed.model : null;
|
|
137
|
+
} catch { return null; }
|
|
138
|
+
},
|
|
139
|
+
readResult({ stdout }) {
|
|
140
|
+
const parsed = JSON.parse(stdout);
|
|
141
|
+
// The structured answer lives in `result` (Claude -p json envelope).
|
|
142
|
+
const result = typeof parsed.result === 'string' ? JSON.parse(parsed.result) : parsed.result;
|
|
143
|
+
return { result, raw: stdout };
|
|
144
|
+
},
|
|
145
|
+
},
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
/** Verify the reviewer entry once per run: exists, runs, prints a version. */
|
|
149
|
+
async function verifyEntry(provider, entry, { versionTimeoutMs = 20_000 } = {}) {
|
|
150
|
+
if (!entry || typeof entry !== 'string') {
|
|
151
|
+
throw new WorkflowError('UNSUPPORTED', `reviewer config: ${provider} entry is not configured.`, { reason: 'reviewer-entry-missing' });
|
|
152
|
+
}
|
|
153
|
+
if (!fs.existsSync(entry)) {
|
|
154
|
+
throw new WorkflowError('UNSUPPORTED', `reviewer config: ${provider} entry not found at ${entry}.`, { reason: 'reviewer-entry-missing' });
|
|
155
|
+
}
|
|
156
|
+
// A .js entry must run under the verified Node; a native exe runs itself.
|
|
157
|
+
const argv = entry.toLowerCase().endsWith('.js') ? [process.execPath, entry, '--version'] : [entry, '--version'];
|
|
158
|
+
const probe = await spawnSyncSafe(argv);
|
|
159
|
+
if (probe.status !== 'ok' || !/v?\d+\.\d+/.test(probe.stdout || '')) {
|
|
160
|
+
throw new WorkflowError('UNSUPPORTED', `reviewer config: ${provider} entry did not answer --version.`, { reason: 'reviewer-entry-unverified' });
|
|
161
|
+
}
|
|
162
|
+
return { entry, version: (probe.stdout || '').trim().slice(0, 100) };
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function spawnSyncSafe(argv) {
|
|
166
|
+
return new Promise(resolve => {
|
|
167
|
+
const { spawn } = require('child_process');
|
|
168
|
+
const child = spawn(argv[0], argv.slice(1), { windowsHide: true, shell: false });
|
|
169
|
+
let stdout = '';
|
|
170
|
+
let settled = false;
|
|
171
|
+
child.stdout.on('data', d => { stdout += d; });
|
|
172
|
+
const timer = setTimeout(() => { try { child.kill(); } catch {} }, 20_000);
|
|
173
|
+
child.on('error', error => { if (settled) return; settled = true; clearTimeout(timer); resolve({ status: 'error', stdout, message: error.message }); });
|
|
174
|
+
child.on('close', code => { if (settled) return; settled = true; clearTimeout(timer); resolve({ status: code === 0 ? 'ok' : 'error', stdout }); });
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const MAX_DIFF_BYTES = 96 * 1024;
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* The bounded work-tree diff the reviewer actually reviews: HEAD..work-tree
|
|
182
|
+
* for tracked changes plus the full content of explicitly included
|
|
183
|
+
* untracked files. Content, not just the manifest — a business-boundary bug
|
|
184
|
+
* in an eslint-clean file must be visible to the reviewer.
|
|
185
|
+
*/
|
|
186
|
+
/**
|
|
187
|
+
* The bounded CONTENT of the reviewed tree: an eslint-clean committed bug
|
|
188
|
+
* has an empty HEAD..work-tree diff, so the reviewer must see the delivered
|
|
189
|
+
* files themselves, not just the manifest. Per-file and total caps keep the
|
|
190
|
+
* material bounded; deleted files contribute nothing.
|
|
191
|
+
*/
|
|
192
|
+
function captureReviewTree(repoPath, manifest = []) {
|
|
193
|
+
const parts = [];
|
|
194
|
+
let total = 0;
|
|
195
|
+
for (const file of manifest) {
|
|
196
|
+
if (file.origin === 'deleted' || !file.path) continue;
|
|
197
|
+
if (total >= MAX_DIFF_BYTES) { parts.push({ path: file.path, content: null, note: 'omitted: material budget exhausted' }); continue; }
|
|
198
|
+
const safe = String(file.path).replace(/\\/g, '/');
|
|
199
|
+
if (safe.includes('..')) continue;
|
|
200
|
+
let content;
|
|
201
|
+
try { content = fs.readFileSync(path.join(repoPath, safe), 'utf8'); } catch { continue; }
|
|
202
|
+
if (content.length > 32 * 1024) content = content.slice(0, 32 * 1024) + '\n... [truncated]';
|
|
203
|
+
total += content.length;
|
|
204
|
+
parts.push({ path: safe, content });
|
|
205
|
+
}
|
|
206
|
+
return { files: parts };
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function captureReviewDiff(repoPath, includedFiles = []) {
|
|
210
|
+
const { spawnSync } = require('child_process');
|
|
211
|
+
const parts = [];
|
|
212
|
+
console.error('[review-native] captureReviewDiff tracked diff start');
|
|
213
|
+
const trackedDiff = spawnSync('git', ['-C', repoPath, '--no-pager', 'diff', 'HEAD', '--'], { encoding: 'utf8', windowsHide: true, maxBuffer: 16 * 1024 * 1024 });
|
|
214
|
+
console.error('[review-native] tracked diff done, status', trackedDiff.status);
|
|
215
|
+
if (trackedDiff.status === 0 && trackedDiff.stdout) parts.push(trackedDiff.stdout);
|
|
216
|
+
const staged = spawnSync('git', ['-C', repoPath, '--no-pager', 'diff', '--cached', '--'], { encoding: 'utf8', windowsHide: true, maxBuffer: 16 * 1024 * 1024 });
|
|
217
|
+
console.error('[review-native] staged diff done, status', staged.status);
|
|
218
|
+
if (staged.status === 0 && staged.stdout) parts.push(staged.stdout);
|
|
219
|
+
for (const relativePath of includedFiles) {
|
|
220
|
+
const safe = String(relativePath).replace(/\\/g, '/');
|
|
221
|
+
if (safe.includes('..')) continue;
|
|
222
|
+
try {
|
|
223
|
+
const content = fs.readFileSync(require('path').join(repoPath, safe), 'utf8');
|
|
224
|
+
parts.push(`--- untracked: ${safe} ---\n${content}`);
|
|
225
|
+
} catch { /* unreadable untracked file: the snapshot already errored on it */ }
|
|
226
|
+
}
|
|
227
|
+
const text = parts.join('\n').slice(0, MAX_DIFF_BYTES);
|
|
228
|
+
return { text, truncated: parts.join('\n').length > MAX_DIFF_BYTES };
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Build the bounded review material for one review job. Only verified
|
|
233
|
+
* snapshot content, the real work-tree diff, the check receipts and the task
|
|
234
|
+
* contract go in — no absolute paths from the development tree beyond the
|
|
235
|
+
* snapshot manifest, no credentials, no other tasks.
|
|
236
|
+
*/
|
|
237
|
+
function buildReviewMaterial({ taskId, acceptanceRevision, snapshot, receipts, contract, policy, diff, tree }) {
|
|
238
|
+
const material = {
|
|
239
|
+
instructions: '你是独立代码审查者。material 是一次交付的有界审查材料:任务合同、已核验快照清单、tree(交付文件的实际内容)、工作树 diff 与程序检查收据。请独立审查交付的实现是否正确、完整并满足每个验收项,重点看业务边界、错误处理与遗漏场景;程序检查通过不代表没有业务缺陷。只输出符合 review schema 的 JSON(verdict: pass|findings|blocked;每条 finding 给出仓库相对路径 file、行号 line、严重度 severity、理由 reason)。',
|
|
240
|
+
task: {
|
|
241
|
+
taskId,
|
|
242
|
+
title: contract.title,
|
|
243
|
+
goal: contract.goal,
|
|
244
|
+
scope: contract.scope || null,
|
|
245
|
+
acceptance: contract.acceptance,
|
|
246
|
+
acceptanceRevision,
|
|
247
|
+
},
|
|
248
|
+
snapshot: {
|
|
249
|
+
snapshotId: snapshot.snapshotId,
|
|
250
|
+
head: snapshot.head,
|
|
251
|
+
files: snapshot.files.map(f => ({ path: f.path, origin: f.origin, hash: f.hash })),
|
|
252
|
+
},
|
|
253
|
+
diff: diff || null,
|
|
254
|
+
tree: tree || null,
|
|
255
|
+
receipts: (receipts || []).map(r => ({
|
|
256
|
+
toolId: r.toolId, verdict: r.verdict, findingCount: r.findingCount,
|
|
257
|
+
findings: (r.findings || []).slice(0, 50).map(f => ({ ruleId: f.ruleId, file: f.file, line: f.line, severity: f.severity, message: f.message })),
|
|
258
|
+
})),
|
|
259
|
+
policy: policy || null,
|
|
260
|
+
};
|
|
261
|
+
const json = JSON.stringify(material, null, 1);
|
|
262
|
+
if (Buffer.byteLength(json, 'utf8') > MAX_MATERIAL_BYTES) {
|
|
263
|
+
throw new WorkflowError('VALIDATION', 'review material exceeds the bounded size; narrow the snapshot or receipts.', { reason: 'material-too-large' });
|
|
264
|
+
}
|
|
265
|
+
return json;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* Run one native reviewer. `config` comes from the TRUSTED reviewer config:
|
|
270
|
+
* { provider, entry, allowedModels, model?, timeoutMs? }. Returns a review
|
|
271
|
+
* evidence object; verdict 'pass' requires a clean run AND a verified model
|
|
272
|
+
* identity.
|
|
273
|
+
*/
|
|
274
|
+
async function runNativeReviewer({ config, material }) {
|
|
275
|
+
const provider = PROVIDERS[config.provider];
|
|
276
|
+
if (!provider) {
|
|
277
|
+
throw new WorkflowError('UNSUPPORTED', `unknown reviewer provider ${config.provider}.`, { reason: 'reviewer-provider-unknown' });
|
|
278
|
+
}
|
|
279
|
+
const verified = await verifyEntry(config.provider, config.entry);
|
|
280
|
+
const allowedModels = Array.isArray(config.allowedModels) ? config.allowedModels.map(String) : [];
|
|
281
|
+
// The explicit -m model must be one of the allowed ones — the trusted
|
|
282
|
+
// config may not smuggle an unvetted model past the identity gate.
|
|
283
|
+
const model = config.model ? String(config.model) : null;
|
|
284
|
+
if (model && !allowedModels.includes(model)) {
|
|
285
|
+
throw new WorkflowError('VALIDATION', `reviewer config model ${model} is not in allowedModels.`, { reason: 'reviewer-model-not-allowed' });
|
|
286
|
+
}
|
|
287
|
+
const workDir = fs.mkdtempSync(path.join(os.tmpdir(), 'wf-review-'));
|
|
288
|
+
const schemaPath = path.join(workDir, 'review-schema.json');
|
|
289
|
+
const lastMessagePath = path.join(workDir, 'review-result.json');
|
|
290
|
+
fs.writeFileSync(schemaPath, JSON.stringify(REVIEW_SCHEMA, null, 1), 'utf8');
|
|
291
|
+
const emptyMcpConfigPath = config.provider === 'claude' ? path.join(workDir, 'empty-mcp.json') : null;
|
|
292
|
+
if (emptyMcpConfigPath) fs.writeFileSync(emptyMcpConfigPath, '{"mcpServers":{}}', 'utf8');
|
|
293
|
+
|
|
294
|
+
let argv = provider.buildArgv({
|
|
295
|
+
entry: verified.entry,
|
|
296
|
+
workDir,
|
|
297
|
+
schemaPath,
|
|
298
|
+
lastMessagePath,
|
|
299
|
+
emptyMcpConfigPath,
|
|
300
|
+
model,
|
|
301
|
+
});
|
|
302
|
+
// A .js entry cannot be exec'd directly on Windows — launch it under the
|
|
303
|
+
// verified Node with the entry as the first script argument.
|
|
304
|
+
if (verified.entry.toLowerCase().endsWith('.js')) argv = [process.execPath, ...argv];
|
|
305
|
+
const timeoutMs = Math.min(Number(config.timeoutMs) || REVIEW_TIMEOUT_MS, REVIEW_TIMEOUT_MS);
|
|
306
|
+
const startedAt = new Date().toISOString();
|
|
307
|
+
const executionRef = `rev_${crypto.randomBytes(8).toString('hex')}`;
|
|
308
|
+
|
|
309
|
+
const run = await new Promise(resolve => {
|
|
310
|
+
const child = spawn(argv[0], argv.slice(1), { cwd: workDir, windowsHide: true, shell: false });
|
|
311
|
+
let stdout = '';
|
|
312
|
+
let stderr = '';
|
|
313
|
+
let settled = false;
|
|
314
|
+
const timer = setTimeout(() => {
|
|
315
|
+
// Kill AND resolve now: codex.exe leaves grandchildren holding the
|
|
316
|
+
// stdio pipes, so waiting for 'close' would hang past the budget.
|
|
317
|
+
try { child.kill(); } catch {}
|
|
318
|
+
try { child.stdin.destroy(); child.stdout.destroy(); child.stderr.destroy(); } catch {}
|
|
319
|
+
finish({ status: 'timeout', stdout, stderr });
|
|
320
|
+
}, timeoutMs);
|
|
321
|
+
child.stdout.on('data', d => { stdout += d; if (stdout.length > MAX_OUTPUT_BYTES) { try { child.kill(); } catch {} } });
|
|
322
|
+
child.stderr.on('data', d => { stderr += d; if (stderr.length > MAX_OUTPUT_BYTES) { try { child.kill(); } catch {} } });
|
|
323
|
+
const finish = result => { if (settled) return; settled = true; clearTimeout(timer); resolve(result); };
|
|
324
|
+
child.on('error', error => finish({ status: 'error', errorCode: error.code || 'SPAWN_ERROR', stdout, stderr }));
|
|
325
|
+
child.on('exit', () => {
|
|
326
|
+
// The CLI can leave grandchildren holding the stdio pipes long after
|
|
327
|
+
// it exits; destroy them so 'close' completes promptly.
|
|
328
|
+
try { child.stdin.destroy(); child.stdout.destroy(); child.stderr.destroy(); } catch {}
|
|
329
|
+
});
|
|
330
|
+
child.on('close', (code, signal) => finish({
|
|
331
|
+
status: code === null ? (signal ? 'timeout' : 'error') : code === 0 ? 'ok' : 'error',
|
|
332
|
+
exitCode: code, signal: signal || null, stdout, stderr,
|
|
333
|
+
truncated: stdout.length >= MAX_OUTPUT_BYTES || stderr.length >= MAX_OUTPUT_BYTES,
|
|
334
|
+
}));
|
|
335
|
+
child.stdin.write(material);
|
|
336
|
+
child.stdin.end();
|
|
337
|
+
});
|
|
338
|
+
|
|
339
|
+
const evidence = {
|
|
340
|
+
executionRef,
|
|
341
|
+
reviewerRuntime: `${config.provider}:${verified.version || 'unknown'}`,
|
|
342
|
+
startedAt,
|
|
343
|
+
finishedAt: new Date().toISOString(),
|
|
344
|
+
durationMs: Date.now() - new Date(startedAt).getTime(),
|
|
345
|
+
workDir,
|
|
346
|
+
verdict: 'blocked',
|
|
347
|
+
findings: [],
|
|
348
|
+
identity: null,
|
|
349
|
+
identityVerified: false,
|
|
350
|
+
blockedReason: null,
|
|
351
|
+
};
|
|
352
|
+
try {
|
|
353
|
+
if (run.status !== 'ok') {
|
|
354
|
+
evidence.blockedReason = run.status === 'timeout' ? 'reviewer-timeout' : `reviewer-exit-${run.exitCode ?? run.errorCode ?? 'unknown'}`;
|
|
355
|
+
return evidence;
|
|
356
|
+
}
|
|
357
|
+
if (run.truncated) {
|
|
358
|
+
evidence.blockedReason = 'reviewer-output-truncated';
|
|
359
|
+
return evidence;
|
|
360
|
+
}
|
|
361
|
+
let parsed;
|
|
362
|
+
try {
|
|
363
|
+
parsed = provider.readResult(config.provider === 'codex' ? { lastMessagePath } : { stdout: run.stdout });
|
|
364
|
+
} catch {
|
|
365
|
+
evidence.blockedReason = 'reviewer-output-invalid-json';
|
|
366
|
+
return evidence;
|
|
367
|
+
}
|
|
368
|
+
const result = parsed.result;
|
|
369
|
+
if (!result || !['pass', 'findings', 'blocked'].includes(result.verdict) || !Array.isArray(result.findings)) {
|
|
370
|
+
evidence.blockedReason = 'reviewer-output-schema-invalid';
|
|
371
|
+
return evidence;
|
|
372
|
+
}
|
|
373
|
+
const model = provider.extractIdentity({ stdout: run.stdout, codexHome: config.codexHome });
|
|
374
|
+
if (!model || !allowedModels.includes(model)) {
|
|
375
|
+
evidence.blockedReason = 'MODEL_IDENTITY_UNVERIFIED';
|
|
376
|
+
evidence.identity = model;
|
|
377
|
+
evidence.findings = result.findings.slice(0, 50);
|
|
378
|
+
evidence.summary = result.summary || null;
|
|
379
|
+
return evidence;
|
|
380
|
+
}
|
|
381
|
+
evidence.identity = model;
|
|
382
|
+
evidence.identityVerified = true;
|
|
383
|
+
evidence.verdict = result.verdict === 'pass' ? 'pass' : result.verdict === 'blocked' ? 'blocked' : 'findings';
|
|
384
|
+
evidence.summary = result.summary || null;
|
|
385
|
+
evidence.findings = result.findings.slice(0, 50).map(f => ({
|
|
386
|
+
file: String(f.file || ''), line: Number.isInteger(f.line) ? f.line : null,
|
|
387
|
+
severity: ['error', 'warning', 'info'].includes(f.severity) ? f.severity : 'info',
|
|
388
|
+
reason: String(f.reason || '').slice(0, 500),
|
|
389
|
+
}));
|
|
390
|
+
return evidence;
|
|
391
|
+
} finally {
|
|
392
|
+
try { fs.rmSync(workDir, { recursive: true, force: true }); } catch { /* temp dir is disposable */ }
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
module.exports = { REVIEW_SCHEMA, PROVIDERS, verifyEntry, buildReviewMaterial, captureReviewDiff, captureReviewTree, runNativeReviewer, REVIEW_TIMEOUT_MS, MAX_MATERIAL_BYTES, MAX_DIFF_BYTES };
|