diffpact 0.0.0-stage → 0.4.2

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.
@@ -0,0 +1,348 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import {
5
+ evaluatePathBoundary,
6
+ evaluateShellCommand,
7
+ extractCodexApplyPatchPaths
8
+ } from '../boundaries.js';
9
+ import { collectRepoChanges, resolveHeadSha, resolveRepoRoot } from '../git.js';
10
+ import { checkStatus, runReview } from '../review.js';
11
+ import { validateContract } from '../schema.js';
12
+ import { EXIT_INCOMPLETE, EXIT_VIOLATION, } from '../types.js';
13
+ import { evaluateBoundedStopGate, } from './claude-code.js';
14
+
15
+ export function handleCodexHook(
16
+ payload ,
17
+ contractPath ,
18
+ cwdOverride
19
+ ) {
20
+ const cwd = cwdOverride ?? (typeof payload.cwd === 'string' ? payload.cwd : process.cwd());
21
+ const contractAbs = path.resolve(cwd, contractPath);
22
+ if (!fs.existsSync(contractAbs)) {
23
+ return { exitCode: 2, stderr: `diffpact [codex]: missing contract "${contractAbs}"` };
24
+ }
25
+
26
+ let contract;
27
+ try {
28
+ contract = validateContract(JSON.parse(fs.readFileSync(contractAbs, 'utf8')));
29
+ } catch (err) {
30
+ return { exitCode: 2, stderr: `diffpact [codex]: ${(err ).message}` };
31
+ }
32
+
33
+ const repoRoot = resolveRepoRoot(cwd);
34
+ const eventName = String(payload.hook_event_name ?? payload.event ?? 'PreToolUse');
35
+ const toolName = String(payload.tool_name ?? '');
36
+ const toolInput =
37
+ typeof payload.tool_input === 'object' && payload.tool_input !== null
38
+ ? (payload.tool_input )
39
+ : {};
40
+
41
+ if (eventName === 'PreToolUse') {
42
+ if (toolName === 'apply_patch') {
43
+ const patchText =
44
+ typeof payload.tool_input === 'string'
45
+ ? payload.tool_input
46
+ : String(toolInput.patch ?? toolInput.input ?? toolInput.content ?? '');
47
+ const targets = extractCodexApplyPatchPaths(patchText);
48
+ if (targets.length === 0) {
49
+ return {
50
+ exitCode: 2,
51
+ stderr: 'diffpact BLOCKED apply_patch: unable to extract target file headers'
52
+ };
53
+ }
54
+ for (const t of targets) {
55
+ const v = evaluatePathBoundary(t, repoRoot, contract);
56
+ if (v) {
57
+ return {
58
+ exitCode: 2,
59
+ stderr: `diffpact BLOCKED apply_patch (${v.code}): ${v.message}`
60
+ };
61
+ }
62
+ }
63
+ return { exitCode: 0 };
64
+ }
65
+
66
+ if (toolName === 'Bash' || toolName === 'shell' || toolName === 'exec_command') {
67
+ const cmd =
68
+ typeof payload.tool_input === 'string'
69
+ ? payload.tool_input
70
+ : String(toolInput.command ?? toolInput.cmd ?? '');
71
+ const v = evaluateShellCommand(cmd, contract);
72
+ if (v) {
73
+ return {
74
+ exitCode: 2,
75
+ stderr: `diffpact BLOCKED ${toolName} (${v.code}): ${v.message}`
76
+ };
77
+ }
78
+ return { exitCode: 0 };
79
+ }
80
+ }
81
+
82
+ if (eventName === 'Stop' || eventName === 'SubagentStop') {
83
+ const sessionId = typeof payload.session_id === 'string' ? payload.session_id : 'codex-default';
84
+ const gate = evaluateBoundedStopGate({
85
+ contractAbs,
86
+ repoRoot,
87
+ sessionId,
88
+ isContinuation: payload.stop_hook_active === true
89
+ });
90
+ if (gate.action === 'pass') return { exitCode: 0 };
91
+ if (gate.action === 'capped') {
92
+ return {
93
+ exitCode: 0,
94
+ stderr: `diffpact [codex] WARNING: Stop hook block cap (${gate.maxBlocks}) reached; allowing exit without passing receipt.`
95
+ };
96
+ }
97
+ return {
98
+ exitCode: 2,
99
+ stderr: `diffpact [codex] Stop gate failed (exit ${gate.exitCode}): ${gate.details}. Fix violations before finishing.`
100
+ };
101
+ }
102
+
103
+ return { exitCode: 0 };
104
+ }
105
+
106
+ export function handleCodexNotify(
107
+ payload ,
108
+ contractPath ,
109
+ cwdOverride
110
+ ) {
111
+ const cwd = cwdOverride ?? (typeof payload.cwd === 'string' ? payload.cwd : process.cwd());
112
+ const status = checkStatus({ contractPath, cwd, requireReview: false });
113
+ if (status.exit_code === 0) {
114
+ return {
115
+ exitCode: 0,
116
+ stderr: `diffpact [codex-notify]: PASS (candidate=${status.candidate_sha?.slice(0, 8)})`
117
+ };
118
+ }
119
+ return {
120
+ exitCode: status.exit_code,
121
+ stderr: `diffpact [codex-notify]: ${status.status.toUpperCase()} (exit ${status.exit_code}) — ${status.reason}`
122
+ };
123
+ }
124
+
125
+ function extractBalancedJsonVerdict(text )
126
+
127
+
128
+
129
+ {
130
+ for (let start = 0; start < text.length; start++) {
131
+ if (text[start] !== '{') continue;
132
+ let depth = 0;
133
+ let inStr = false;
134
+ let esc = false;
135
+ for (let end = start; end < text.length; end++) {
136
+ const ch = text[end] ;
137
+ if (inStr) {
138
+ if (esc) esc = false;
139
+ else if (ch === '\\') esc = true;
140
+ else if (ch === '"') inStr = false;
141
+ continue;
142
+ }
143
+ if (ch === '"') inStr = true;
144
+ else if (ch === '{') depth++;
145
+ else if (ch === '}') {
146
+ depth--;
147
+ if (depth === 0) {
148
+ const candidate = text.slice(start, end + 1);
149
+ if (candidate.includes('"verdict"')) {
150
+ try {
151
+ const parsed = JSON.parse(candidate) ;
152
+ if (parsed.verdict === 'approve' || parsed.verdict === 'reject') {
153
+ return {
154
+ verdict: parsed.verdict,
155
+ summary: typeof parsed.summary === 'string' ? parsed.summary : 'Codex review completed',
156
+ findings: Array.isArray(parsed.findings) ? parsed.findings.map(String) : []
157
+ };
158
+ }
159
+ } catch {
160
+ // continue scanning
161
+ }
162
+ }
163
+ break;
164
+ }
165
+ }
166
+ }
167
+ }
168
+ return null;
169
+ }
170
+
171
+ /**
172
+ * Parses `codex exec --json` JSONL output to extract the true `thread_id`
173
+ * and structured review verdict (`{ verdict: "approve"|"reject", summary, findings }`).
174
+ */
175
+ export function parseCodexJsonlReview(jsonlOutput )
176
+
177
+
178
+
179
+
180
+ {
181
+ let threadId ;
182
+ const candidateTexts = [];
183
+
184
+ for (const line of jsonlOutput.split(/\r?\n/)) {
185
+ const trimmed = line.trim();
186
+ if (!trimmed.startsWith('{')) continue;
187
+ try {
188
+ const ev = JSON.parse(trimmed) ;
189
+ if (ev.type === 'thread.started' && typeof ev.thread_id === 'string') {
190
+ threadId = ev.thread_id;
191
+ }
192
+ if (typeof ev['thread-id'] === 'string' && !threadId) {
193
+ threadId = ev['thread-id'] ;
194
+ }
195
+ if (ev.type === 'item.completed' && typeof ev.item === 'object' && ev.item !== null) {
196
+ const item = ev.item ;
197
+ if (typeof item.text === 'string') {
198
+ candidateTexts.push(item.text);
199
+ }
200
+ if (Array.isArray(item.content)) {
201
+ for (const part of item.content) {
202
+ if (typeof part === 'object' && part !== null && typeof (part ).text === 'string') {
203
+ candidateTexts.push((part ).text );
204
+ }
205
+ }
206
+ }
207
+ }
208
+ if (typeof ev.verdict === 'string' && (ev.verdict === 'approve' || ev.verdict === 'reject')) {
209
+ return {
210
+ threadId,
211
+ verdict: ev.verdict,
212
+ summary: typeof ev.summary === 'string' ? ev.summary : 'Codex review completed',
213
+ findings: Array.isArray(ev.findings) ? ev.findings.map(String) : []
214
+ };
215
+ }
216
+ } catch {
217
+ // ignore non-JSON lines
218
+ }
219
+ }
220
+
221
+ for (let i = candidateTexts.length - 1; i >= 0; i--) {
222
+ const found = extractBalancedJsonVerdict(candidateTexts[i] );
223
+ if (found) {
224
+ return {
225
+ threadId,
226
+ ...found
227
+ };
228
+ }
229
+ }
230
+
231
+ return { threadId };
232
+ }
233
+
234
+ /**
235
+ * Executes a wrapped Codex read-only reviewer command, verifies the worktree remained untouched,
236
+ * extracts the Codex `thread_id` to guarantee session independence, and records `review.json`.
237
+ */
238
+ export function runWrappedCodexReview(options
239
+
240
+
241
+
242
+
243
+
244
+
245
+ ) {
246
+ const cwd = options.cwd ?? process.cwd();
247
+ const contractAbs = path.resolve(cwd, options.contractPath);
248
+ if (!fs.existsSync(contractAbs)) {
249
+ return { exitCode: EXIT_INCOMPLETE, error: `Missing contract "${contractAbs}"` };
250
+ }
251
+ let contract;
252
+ try {
253
+ contract = validateContract(JSON.parse(fs.readFileSync(contractAbs, 'utf8')));
254
+ } catch (err) {
255
+ return { exitCode: EXIT_INCOMPLETE, error: (err ).message };
256
+ }
257
+
258
+ const repoRoot = resolveRepoRoot(cwd);
259
+ const headBefore = resolveHeadSha(repoRoot);
260
+
261
+ const [bin, ...args] = options.commandArgs;
262
+ if (!bin) {
263
+ return { exitCode: EXIT_INCOMPLETE, error: 'Missing codex reviewer command' };
264
+ }
265
+
266
+ const proc = spawnSync(bin, args, {
267
+ cwd: repoRoot,
268
+ encoding: 'utf8',
269
+ maxBuffer: 32 * 1024 * 1024
270
+ });
271
+
272
+ if (proc.status !== 0) {
273
+ return {
274
+ exitCode: EXIT_VIOLATION,
275
+ error: `Codex reviewer process failed (exit ${proc.status ?? 1}): ${proc.stderr || proc.stdout}`
276
+ };
277
+ }
278
+
279
+ const headAfter = resolveHeadSha(repoRoot);
280
+ const snapAfter = collectRepoChanges(repoRoot, contract.starting_sha, headAfter);
281
+ if (headAfter !== headBefore || !snapAfter.workingTreeClean) {
282
+ return {
283
+ exitCode: EXIT_VIOLATION,
284
+ error: 'Read-only Codex reviewer mutated HEAD or left dirty working tree files'
285
+ };
286
+ }
287
+
288
+ const parsed = parseCodexJsonlReview(proc.stdout);
289
+ if (!parsed.threadId || !parsed.verdict) {
290
+ return {
291
+ exitCode: EXIT_INCOMPLETE,
292
+ error: 'Codex JSONL stream did not contain both thread_id and structured verdict ("approve"|"reject")'
293
+ };
294
+ }
295
+
296
+ const revResult = runReview({
297
+ contractPath: contractAbs,
298
+ cwd: repoRoot,
299
+ reviewer: {
300
+ agent_id: options.reviewerAgentId,
301
+ session_id: parsed.threadId,
302
+ harness: 'codex'
303
+ },
304
+ verdict: parsed.verdict,
305
+ summary: parsed.summary ?? 'Codex review',
306
+ findings: parsed.findings ?? [],
307
+ inspectedRawDiff: options.inspectedRawDiff ?? true,
308
+ attestationMode: 'wrapper-verified',
309
+ evidenceLineageId: options.evidenceLineageId
310
+ });
311
+
312
+ return {
313
+ exitCode: revResult.exitCode,
314
+ error: revResult.error,
315
+ reviewSha256: revResult.review?.review_sha256
316
+ };
317
+ }
318
+
319
+ export function generateCodexConfig(contractPath = '.diffpact/contract.json') {
320
+ const cmd = `diffpact --contract ${contractPath} hook codex`;
321
+ return JSON.stringify(
322
+ {
323
+ hooks: {
324
+ PreToolUse: [
325
+ {
326
+ matcher: 'Bash|apply_patch',
327
+ hooks: [
328
+ {
329
+ type: 'command',
330
+ command: cmd,
331
+ statusMessage: 'Checking diffpact task boundaries...'
332
+ }
333
+ ]
334
+ }
335
+ ],
336
+ PostToolUse: [
337
+ {
338
+ matcher: 'Bash|apply_patch',
339
+ hooks: [{ type: 'command', command: cmd }]
340
+ }
341
+ ],
342
+ Stop: [{ hooks: [{ type: 'command', command: cmd }] }]
343
+ }
344
+ },
345
+ null,
346
+ 2
347
+ );
348
+ }