harness-everything 0.54.0 → 0.54.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.
Files changed (45) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/CHANGELOG.md +8 -0
  4. package/ci/action-gate.test.js +1 -1
  5. package/ci/mechanism-2at-fable-execution-phases.test.js +38 -0
  6. package/ci/mechanism-codex-hook-results.test.js +145 -0
  7. package/ci/openai-plugin-runtime.test.js +2 -1
  8. package/ci/prompt-contract-regressions.test.js +6 -2
  9. package/docs/platform-capabilities.md +17 -0
  10. package/fable-mode/SKILL.md +5 -5
  11. package/fable-mode/execution-guardrails/SKILL.md +1 -1
  12. package/fable-mode/fable-haiku/SKILL.md +1 -1
  13. package/fable-mode/fable-opus/SKILL.md +1 -1
  14. package/fable-mode/fable-sonnet/SKILL.md +1 -1
  15. package/fable-mode/references/execution-phases.md +26 -4
  16. package/hooks/scripts/action-gate.js +5 -0
  17. package/hooks/scripts/codex-action-gate-post.js +3 -12
  18. package/hooks/scripts/contract-test.js +17 -7
  19. package/hooks/scripts/lib/codex-tool-outcome.js +28 -0
  20. package/hooks/scripts/rule-of-3-tracker.js +11 -4
  21. package/hooks/scripts/state-persist.js +15 -9
  22. package/hooks/scripts/subagent-scope-guard.js +32 -25
  23. package/hooks/scripts/subagent-start.js +1 -1
  24. package/hooks/scripts/subagent-stop.js +14 -3
  25. package/opencode-plugin/plugin.json +1 -1
  26. package/package.json +1 -1
  27. package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
  28. package/plugins/harness-everything/hooks/hooks.json +6 -6
  29. package/plugins/harness-everything/hooks/scripts/action-gate.js +5 -0
  30. package/plugins/harness-everything/hooks/scripts/codex-action-gate-post.js +3 -12
  31. package/plugins/harness-everything/hooks/scripts/contract-test.js +17 -7
  32. package/plugins/harness-everything/hooks/scripts/lib/codex-tool-outcome.js +28 -0
  33. package/plugins/harness-everything/hooks/scripts/rule-of-3-tracker.js +11 -4
  34. package/plugins/harness-everything/hooks/scripts/state-persist.js +15 -9
  35. package/plugins/harness-everything/hooks/scripts/subagent-scope-guard.js +32 -25
  36. package/plugins/harness-everything/hooks/scripts/subagent-start.js +1 -1
  37. package/plugins/harness-everything/hooks/scripts/subagent-stop.js +14 -3
  38. package/plugins/harness-everything/plugin.json +1 -1
  39. package/plugins/harness-everything/skills/fable-mode/SKILL.md +5 -5
  40. package/plugins/harness-everything/skills/fable-mode/execution-guardrails/SKILL.md +1 -1
  41. package/plugins/harness-everything/skills/fable-mode/fable-haiku/SKILL.md +1 -1
  42. package/plugins/harness-everything/skills/fable-mode/fable-opus/SKILL.md +1 -1
  43. package/plugins/harness-everything/skills/fable-mode/fable-sonnet/SKILL.md +1 -1
  44. package/plugins/harness-everything/skills/fable-mode/references/execution-phases.md +26 -4
  45. package/sbom.cdx.json +7 -7
@@ -4,6 +4,8 @@ const path = require('path');
4
4
  const { getWorkspaceRoot, getSessionDir } = require('./lib/harness-state');
5
5
  const { cwdOf, classifyShell, isVerificationShell, directMutationInWorkspace } = require('./lib/workflow-isolation');
6
6
  const { observeTool } = require('./lib/telemetry');
7
+ const { readCodexToolOutcome } = require('./lib/codex-tool-outcome');
8
+ const codex = process.argv.includes('--codex');
7
9
 
8
10
  function isSuccessfulMetadataStep(command, cwd) {
9
11
  // A line break starts a second shell command, so it can never be metadata-only.
@@ -77,22 +79,26 @@ function processState(payload) {
77
79
  process.exit(0);
78
80
  }
79
81
  const toolResponse = payload.tool_response || {};
80
- const stdout = toolResponse.stdout ?? payload.stdout ?? '';
81
- const stderr = toolResponse.stderr ?? payload.stderr ?? payload.error ?? '';
82
+ const codexResult = codex ? readCodexToolOutcome(payload) : null;
83
+ const stdout = codexResult?.stdout ?? toolResponse.stdout ?? payload.stdout ?? '';
84
+ const stderr = codexResult?.stderr ?? toolResponse.stderr ?? payload.stderr ?? payload.error ?? '';
82
85
  const rawExitCode = toolResponse.exitCode ?? toolResponse.exit_code ?? payload.exitCode;
83
- const exitCode = typeof rawExitCode === 'number' ? rawExitCode : undefined;
86
+ const exitCode = codex ? codexResult.exitCode : typeof rawExitCode === 'number' ? rawExitCode : undefined;
84
87
  const stderrSignal = typeof stderr === 'string' && stderr.trim().length > 0;
85
88
  const hookEvent = captureEventName;
86
89
  const isSuccessEvent = hookEvent === 'PostToolUse';
87
- const isFailed = hookEvent === 'PostToolUseFailure' || (exitCode !== undefined && exitCode !== 0) || (!isSuccessEvent && exitCode === undefined && stderrSignal);
90
+ const isFailed = codex ? codexResult.outcome === 'failure' :
91
+ hookEvent === 'PostToolUseFailure' || (exitCode !== undefined && exitCode !== 0) ||
92
+ (!isSuccessEvent && exitCode === undefined && stderrSignal);
93
+ const verifiedSuccess = codex ? codexResult.outcome === 'success' : !isFailed && (isSuccessEvent || exitCode === 0);
88
94
  const toolName = payload.tool_name || payload.tool || 'command';
89
95
  let editAfterCapture = false;
90
96
  let stateOnlyCandidate = false;
91
97
  if (isFailed) {
92
- let output = (stderrSignal ? stderr : stdout) || payload.output || '';
98
+ let output = (stderrSignal ? stderr : stdout) || (typeof payload.output === 'string' ? payload.output : '');
93
99
  if (output.length > 500) output = '...' + output.slice(-500);
94
100
  state.status = 'failed'; state.timestamp = new Date().toISOString(); state.tool = toolName; state.exitCode = exitCode; state.errorSummary = output.trim();
95
- } else if (state.status === 'failed') {
101
+ } else if ((!codex || verifiedSuccess) && state.status === 'failed') {
96
102
  state.lastResolved = { tool: state.tool, timestamp: state.timestamp }; state.status = 'idle'; state.timestamp = new Date().toISOString(); delete state.exitCode; delete state.errorSummary;
97
103
  }
98
104
  const isDirectTool = toolName === 'Edit' || toolName === 'Write' || toolName === 'apply_patch';
@@ -106,13 +112,13 @@ function processState(payload) {
106
112
  stateOnlyCandidate = Boolean(docCheck && typeof payload.cwd === 'string' && payload.cwd
107
113
  && docCheck.isW6StateCommand(command, payload.cwd, root,
108
114
  { toolName, sessionId, agentId: payload.agent_id }));
109
- const metadataStep = !stateOnlyCandidate && !isFailed && (isSuccessEvent || exitCode === 0)
115
+ const metadataStep = !stateOnlyCandidate && verifiedSuccess
110
116
  && isSuccessfulMetadataStep(command, cwdOf(payload, root));
111
117
  if (!metadataStep && commandClass !== 'read-only' && commandClass !== 'worktree-setup') {
112
118
  if (stateOnlyCandidate) editAfterCapture = true;
113
119
  else state.lastEditAt = Date.now();
114
120
  }
115
- // Verification evidence needs a confirmed success: a PostToolUse event or an explicit zero exit.
121
+ // The host-specific outcome must confirm success before verification advances.
116
122
  // Pilot ON only: a registered, argv-validated doc-check that resolves to this install's own runtime is the document
117
123
  // verification evidence, and only at the shipped pin (R3-02). Any other path earns no verification evidence. OFF stays legacy.
118
124
  const installedCheck = docCheck && docCheck.registeredInstalledCheck(command, cwdOf(payload, root));
@@ -123,7 +129,7 @@ function processState(payload) {
123
129
  const verifies = stateOnlyCandidate ? false : docCheckCandidate
124
130
  ? Boolean(pinCheckable) && docCheck.fileDigest(installedCheck.installed) === docCheck.SHIPPED_DOC_CHECK_DIGEST
125
131
  : !(pilotEnabled && docCheck.trustRisk(command)) && isVerificationShell(command, { cwd: cwdOf(payload, root), root });
126
- if (!isFailed && (isSuccessEvent || exitCode === 0) && verifies) {
132
+ if (verifiedSuccess && verifies) {
127
133
  const verifiedAt = Date.now();
128
134
  const verifiedExitCode = exitCode ?? null;
129
135
  state.lastVerifyAt = verifiedAt;
@@ -8,7 +8,7 @@
8
8
  * newly changed paths as declared, ambiguous, or out-of-scope. Machine-
9
9
  * readable write sets may therefore clear expected changes without weakening
10
10
  * the conservative legacy path: when no stage contract exists, any new
11
- * change still exits 2 and requires explicit review.
11
+ * change still emits a reminder and requires explicit review.
12
12
  *
13
13
  * `writeSet: []` means read-only. Worker attribution is used when the host
14
14
  * exposes a worker/subagent id and the stage contract records the same id;
@@ -106,15 +106,13 @@ function classifyChanges(newlyChanged, declaredContracts, payload) {
106
106
  return { workerId: workerId || null, expected, ambiguous, outOfScope };
107
107
  }
108
108
 
109
- let inputData = '';
110
- process.stdin.on('data', chunk => { inputData += chunk; });
111
- process.stdin.on('end', () => {
109
+ function inspectScope(inputData, { info, warn }) {
112
110
  try {
113
111
  const payload = JSON.parse(inputData);
114
112
  const event = payload.hook_event_name;
115
113
  const toolName = payload.tool_name || payload.tool;
116
114
  const isSubagentEvent = event === 'SubagentStart' || event === 'SubagentStop';
117
- if (!isSubagentEvent && toolName !== 'Task' && toolName !== 'Agent') process.exit(0);
115
+ if (!isSubagentEvent && toolName !== 'Task' && toolName !== 'Agent') return;
118
116
 
119
117
  const root = getWorkspaceRoot(payload);
120
118
  const sessionId = getSessionId(payload);
@@ -134,17 +132,17 @@ process.stdin.on('end', () => {
134
132
  });
135
133
  }
136
134
  }
137
- process.exit(0);
135
+ return;
138
136
  }
139
137
 
140
138
  if (event === 'PostToolUse' || event === 'SubagentStop') {
141
139
  accountWorker(payload, event);
142
- if (!fs.existsSync(stateFile)) process.exit(0);
140
+ if (!fs.existsSync(stateFile)) return;
143
141
 
144
142
  let state;
145
- try { state = JSON.parse(fs.readFileSync(stateFile, 'utf8')); } catch (_) { process.exit(0); }
143
+ try { state = JSON.parse(fs.readFileSync(stateFile, 'utf8')); } catch (_) { return; }
146
144
  const current = gitStatus(root);
147
- if (current === null) process.exit(0);
145
+ if (current === null) return;
148
146
 
149
147
  const baselineLines = new Set(String(state.baseline || '').split('\n').filter(Boolean));
150
148
  const currentLines = current.split('\n').filter(Boolean);
@@ -161,20 +159,20 @@ process.stdin.on('end', () => {
161
159
  atomicWriteJson(path.join(sessionDir, 'subagent-scope-last.json'), audit);
162
160
 
163
161
  if (newlyChanged.length === 0) {
164
- console.log('[Subagent Scope Reminder] No new changed files detected during the subagent burst.');
162
+ info('[Subagent Scope Reminder] No new changed files detected during the subagent burst.');
165
163
  } else if (declaredContracts.length === 0) {
166
- console.error(`[Subagent Scope Reminder] ${newlyChanged.length} file(s) changed with no machine-readable writeSet contract:`);
167
- newlyChanged.forEach(line => console.error(` ${line}`));
168
- console.error('Semantic MUST: reconcile every changed path against the declared scope before trusting or committing this output.');
164
+ warn(`[Subagent Scope Reminder] ${newlyChanged.length} file(s) changed with no machine-readable writeSet contract:`);
165
+ newlyChanged.forEach(line => warn(` ${line}`));
166
+ warn('Semantic MUST: reconcile every changed path against the declared scope before trusting or committing this output.');
169
167
  } else {
170
168
  for (const entry of classified.expected) {
171
- console.log(`[Subagent Scope Reminder] in-scope ${entry.statusLine} -> ${entry.planId}/${entry.runId}/${entry.stageId}${entry.workerId ? ` worker=${entry.workerId}` : ''}`);
169
+ info(`[Subagent Scope Reminder] in-scope ${entry.statusLine} -> ${entry.planId}/${entry.runId}/${entry.stageId}${entry.workerId ? ` worker=${entry.workerId}` : ''}`);
172
170
  }
173
171
  for (const entry of classified.ambiguous) {
174
- console.error(`[Subagent Scope Reminder] ambiguous scope ${entry.statusLine}; matches ${entry.stages.map(stage => `${stage.runId}/${stage.stageId}`).join(', ')}`);
172
+ warn(`[Subagent Scope Reminder] ambiguous scope ${entry.statusLine}; matches ${entry.stages.map(stage => `${stage.runId}/${stage.stageId}`).join(', ')}`);
175
173
  }
176
174
  for (const entry of classified.outOfScope) {
177
- console.error(`[Subagent Scope Reminder] OUT-OF-SCOPE ${entry.statusLine}${entry.workerId ? ` worker=${entry.workerId}` : ''}; MUST reconcile/revert or explicitly re-authorize scope before accepting the result.`);
175
+ warn(`[Subagent Scope Reminder] OUT-OF-SCOPE ${entry.statusLine}${entry.workerId ? ` worker=${entry.workerId}` : ''}; MUST reconcile/revert or explicitly re-authorize scope before accepting the result.`);
178
176
  }
179
177
  }
180
178
 
@@ -188,24 +186,33 @@ process.stdin.on('end', () => {
188
186
  ? newlyChanged.length > 0
189
187
  : classified.ambiguous.length > 0 || classified.outOfScope.length > 0;
190
188
  if (violated) {
191
- console.error('Do not "git add -A"; stage files explicitly so unexpected paths stay visible.');
192
- process.exit(0);
189
+ warn('Do not "git add -A"; stage files explicitly so unexpected paths stay visible.');
193
190
  }
194
- process.exit(0);
195
191
  }
196
-
197
- process.exit(0);
198
192
  } catch (error) {
199
193
  if (error && error.code === 'HARNESS_WORKFLOW_BUDGET') {
200
- console.error(`[Subagent Scope Reminder] ${error.message}`);
201
- process.exit(0);
194
+ warn(`[Subagent Scope Reminder] ${error.message}`);
195
+ return;
202
196
  }
203
197
  // This is otherwise a post-execution visibility gate. Runtime errors fail open;
204
198
  // actionGate has a stricter fail-ask policy for side effects.
205
- process.exit(0);
199
+ return;
206
200
  }
207
- });
201
+ }
202
+
203
+ function run({ info = console.log, warn = console.error, complete = () => {} } = {}) {
204
+ let inputData = '';
205
+ process.stdin.setEncoding('utf8');
206
+ process.stdin.on('data', chunk => { inputData += chunk; });
207
+ process.stdin.on('end', () => {
208
+ inspectScope(inputData, { info, warn });
209
+ complete();
210
+ });
211
+ }
212
+
213
+ if (require.main === module) run();
208
214
 
209
215
  module.exports = {
210
216
  classifyChanges,
217
+ run,
211
218
  };
@@ -16,4 +16,4 @@ process.on('exit', () => {
16
16
  }) + '\n');
17
17
  });
18
18
 
19
- require('./subagent-scope-guard');
19
+ require('./subagent-scope-guard').run();
@@ -1,6 +1,17 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
3
 
4
- // The shared guard emits exit code 2 and stderr when a subagent changed files;
5
- // OpenAI/Codex treats that as a continuation signal for SubagentStop.
6
- require('./subagent-scope-guard');
4
+ const { run } = require('./subagent-scope-guard');
5
+
6
+ // Codex accepts warnings through systemMessage on SubagentStop. Keep the
7
+ // audit advisory and leave stdout empty when there is nothing to reconcile.
8
+ const warnings = [];
9
+ run({
10
+ info() {},
11
+ warn(message) { warnings.push(message); },
12
+ complete() {
13
+ if (warnings.length > 0) {
14
+ process.stdout.write(JSON.stringify({ systemMessage: warnings.join('\n') }) + '\n');
15
+ }
16
+ },
17
+ });
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "harness-enforcement",
3
3
  "description": "Repository inventory for the opencode enforcement plugin and its standalone helper",
4
- "version": "0.54.0",
4
+ "version": "0.54.1",
5
5
  "runtime": "index.mjs",
6
6
  "hooks": {
7
7
  "verify": "hooks/verify.js"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "harness-everything",
3
- "version": "0.54.0",
3
+ "version": "0.54.1",
4
4
  "description": "Harness OS: An Orchestrated Agent Operating System for AI-driven Development",
5
5
  "main": "harness-everything/scripts/bootstrap.js",
6
6
  "bin": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "harness-everything",
3
- "version": "0.54.0",
3
+ "version": "0.54.1",
4
4
  "description": "Invariant-first engineering harness for routing, verification, and failure recovery while preserving agent autonomy.",
5
5
  "author": {
6
6
  "name": "Miya Daniel",
@@ -143,15 +143,15 @@
143
143
  },
144
144
  {
145
145
  "type": "command",
146
- "command": "node \"${PLUGIN_ROOT}/hooks/scripts/rule-of-3-tracker.js\"",
147
- "commandWindows": "node \"${PLUGIN_ROOT}\\hooks\\scripts\\rule-of-3-tracker.js\"",
146
+ "command": "node \"${PLUGIN_ROOT}/hooks/scripts/rule-of-3-tracker.js\" --codex",
147
+ "commandWindows": "node \"${PLUGIN_ROOT}\\hooks\\scripts\\rule-of-3-tracker.js\" --codex",
148
148
  "timeout": 15,
149
149
  "statusMessage": "Recording Harness failure evidence"
150
150
  },
151
151
  {
152
152
  "type": "command",
153
- "command": "node \"${PLUGIN_ROOT}/hooks/scripts/state-persist.js\"",
154
- "commandWindows": "node \"${PLUGIN_ROOT}\\hooks\\scripts\\state-persist.js\"",
153
+ "command": "node \"${PLUGIN_ROOT}/hooks/scripts/state-persist.js\" --codex",
154
+ "commandWindows": "node \"${PLUGIN_ROOT}\\hooks\\scripts\\state-persist.js\" --codex",
155
155
  "timeout": 15,
156
156
  "statusMessage": "Saving Harness state and observed mutation"
157
157
  }
@@ -174,8 +174,8 @@
174
174
  "hooks": [
175
175
  {
176
176
  "type": "command",
177
- "command": "node \"${PLUGIN_ROOT}/hooks/scripts/contract-test.js\"",
178
- "commandWindows": "node \"${PLUGIN_ROOT}\\hooks\\scripts\\contract-test.js\"",
177
+ "command": "node \"${PLUGIN_ROOT}/hooks/scripts/contract-test.js\" --codex",
178
+ "commandWindows": "node \"${PLUGIN_ROOT}\\hooks\\scripts\\contract-test.js\" --codex",
179
179
  "timeout": 15,
180
180
  "statusMessage": "Checking Harness stage contract"
181
181
  }
@@ -547,6 +547,11 @@ function finalizeExecution(payload, outcome, options = {}) {
547
547
  record.disposition = 'integrity-violation';
548
548
  record.integrityViolation = 'executed-payload-hash-differs-from-approved-payload';
549
549
  } else {
550
+ // A replay without status cannot replace an already observed outcome.
551
+ const known = record.executionOutcome === 'success' || record.executionOutcome === 'failure';
552
+ if (record.disposition === 'executed' && known && outcome === 'unknown') {
553
+ return { kind: 'audit', exitCode: 0, record };
554
+ }
550
555
  record.disposition = 'executed';
551
556
  record.executionOutcome = outcome;
552
557
  }
@@ -3,19 +3,10 @@
3
3
 
4
4
  const { finalizeExecution } = require('./action-gate');
5
5
 
6
- function inferOutcome(payload) {
7
- const response = (payload && (payload.tool_response || payload.toolResponse)) || {};
8
- const rawExitCode = response.exitCode ?? response.exit_code ?? payload?.exitCode ?? payload?.exit_code;
9
- if (typeof rawExitCode === 'number') return rawExitCode === 0 ? 'success' : 'failure';
10
- if (response.success === false || response.ok === false) return 'failure';
6
+ const { readCodexToolOutcome } = require('./lib/codex-tool-outcome');
11
7
 
12
- const stderr = response.stderr ?? payload?.stderr ?? '';
13
- if (typeof stderr === 'string' && stderr.trim()) {
14
- if (/\b(error|fail|failed|failure|exception|fatal|panic|traceback|denied|refused|cannot|unable)\b/i.test(stderr)) {
15
- return 'failure';
16
- }
17
- }
18
- return 'success';
8
+ function inferOutcome(payload) {
9
+ return readCodexToolOutcome(payload).outcome;
19
10
  }
20
11
 
21
12
  function processPayload(payload) {
@@ -24,8 +24,14 @@ const {
24
24
  } = require('./lib/fable-contracts');
25
25
  const { loadWorkflow, matchingRun } = require('./lib/workflow-runtime');
26
26
  const { createLearningOpportunity } = require('./lib/learning-opportunity');
27
+ const { readCodexToolOutcome } = require('./lib/codex-tool-outcome');
28
+ const codex = process.argv.includes('--codex');
27
29
 
28
30
  function resultState(payload) {
31
+ if (codex) {
32
+ const { outcome, exitCode, stdout, stderr } = readCodexToolOutcome(payload);
33
+ return { outcome, exitCode, evidence: (stderr.trim() || stdout).slice(-1000).trim() };
34
+ }
29
35
  const toolResponse = payload.tool_response || payload.tool_result || {};
30
36
  const stdout = toolResponse.stdout ?? payload.stdout ?? '';
31
37
  const stderr = toolResponse.stderr ?? payload.stderr ?? '';
@@ -36,7 +42,7 @@ function resultState(payload) {
36
42
  (exitCode !== undefined && exitCode !== 0) ||
37
43
  (exitCode === undefined && stderrSignal);
38
44
  const evidence = ((stderrSignal ? stderr : stdout) || '').slice(-1000).trim();
39
- return { failed, exitCode, evidence };
45
+ return { outcome: failed ? 'failure' : 'success', exitCode, evidence };
40
46
  }
41
47
 
42
48
  function unresolvedBindings(contract) {
@@ -46,8 +52,9 @@ function unresolvedBindings(contract) {
46
52
  : !['loaded', 'not-needed'].includes(binding.status));
47
53
  }
48
54
 
49
- function updateRunContract(entry, payload, command, sessionId) {
50
- const { failed, exitCode, evidence } = resultState(payload);
55
+ function updateRunContract(entry, payload, command, sessionId, result) {
56
+ const { outcome, exitCode, evidence } = result;
57
+ const failed = outcome === 'failure';
51
58
  const unresolved = unresolvedBindings(entry.contract);
52
59
  const status = failed ? 'fail' : unresolved.length ? 'binding-unresolved' : 'pass';
53
60
  const observedAt = new Date().toISOString();
@@ -93,7 +100,7 @@ function activeFableStages(runRoot) {
93
100
  return [];
94
101
  }
95
102
 
96
- function resolveLegacyContract(stateRoot, command, payload) {
103
+ function resolveLegacyContract(stateRoot, command, result) {
97
104
  const contractsDir = path.join(stateRoot, 'contracts');
98
105
  let files = [];
99
106
  try { files = fs.readdirSync(contractsDir).filter(file => file.endsWith('.json')); } catch (_) { return null; }
@@ -106,7 +113,8 @@ function resolveLegacyContract(stateRoot, command, payload) {
106
113
  matches.push({ manifest, filePath });
107
114
  }
108
115
  if (matches.length !== 1) return matches.length > 1 ? { ambiguous: true } : null;
109
- const { failed, evidence } = resultState(payload);
116
+ const { outcome, evidence } = result;
117
+ const failed = outcome === 'failure';
110
118
  const match = matches[0];
111
119
  match.manifest.status = failed ? 'fail' : 'pass';
112
120
  match.manifest.evidence = evidence;
@@ -124,6 +132,8 @@ process.stdin.on('end', () => {
124
132
 
125
133
  const command = ((payload.tool_input && payload.tool_input.command) || '').trim();
126
134
  if (!command) process.exit(0);
135
+ const result = resultState(payload);
136
+ if (result.outcome === 'unknown') process.exit(0);
127
137
 
128
138
  const root = getWorkspaceRoot(payload);
129
139
  const stateRoot = getStateRoot(root, payload);
@@ -161,7 +171,7 @@ process.stdin.on('end', () => {
161
171
  }
162
172
  const previousStatus = entry.contract.status;
163
173
  const previousVerifiedAt = entry.contract.verifiedAt || entry.contract.updatedAt || null;
164
- const contract = updateRunContract(entry, payload, command, sessionId);
174
+ const contract = updateRunContract(entry, payload, command, sessionId, result);
165
175
  if (previousStatus === 'fail' && contract.status === 'pass') {
166
176
  try {
167
177
  createLearningOpportunity(payload, {
@@ -199,7 +209,7 @@ process.stdin.on('end', () => {
199
209
 
200
210
  // Temporary compatibility with pre-Phase-3 manifests. New orchestration
201
211
  // must use run-scoped contracts; legacy manifests have no plan/run link.
202
- const legacy = resolveLegacyContract(stateRoot, command, payload);
212
+ const legacy = resolveLegacyContract(stateRoot, command, result);
203
213
  if (legacy && legacy.ambiguous) {
204
214
  console.error(`[Contract Test] Ambiguous legacy stage contracts matched: ${command}`);
205
215
  process.exit(0);
@@ -0,0 +1,28 @@
1
+ 'use strict';
2
+
3
+ // Codex PostToolUse runs for both zero and nonzero exits. A string response
4
+ // can contain arbitrary command output and is never evidence of an exit code.
5
+ function readCodexToolOutcome(payload) {
6
+ const raw = payload?.tool_response ?? payload?.toolResponse;
7
+ const response = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};
8
+ const codes = [response.exitCode, response.exit_code, payload?.exitCode, payload?.exit_code]
9
+ .filter(Number.isInteger);
10
+ const exitCode = codes.find(code => code !== 0) ?? codes[0];
11
+ const stdout = typeof raw === 'string' ? raw : response.stdout ?? payload?.stdout;
12
+ const stderr = response.stderr ?? payload?.stderr;
13
+ const shell = ['Bash', 'PowerShell', 'exec_command'].includes(payload?.tool_name);
14
+ const failed = exitCode !== undefined && exitCode !== 0 ||
15
+ response.isError === true || response.is_error === true ||
16
+ response.success === false || response.ok === false;
17
+ const succeeded = exitCode === 0 || (!shell &&
18
+ (response.isError === false || response.is_error === false ||
19
+ response.success === true || response.ok === true));
20
+ return {
21
+ outcome: failed ? 'failure' : succeeded ? 'success' : 'unknown',
22
+ exitCode,
23
+ stdout: typeof stdout === 'string' ? stdout : '',
24
+ stderr: typeof stderr === 'string' ? stderr : '',
25
+ };
26
+ }
27
+
28
+ module.exports = { readCodexToolOutcome };
@@ -4,6 +4,8 @@ const path = require('path');
4
4
  const crypto = require('crypto');
5
5
  const { getWorkspaceRoot, getSessionDir } = require('./lib/harness-state');
6
6
  const { createLearningOpportunity } = require('./lib/learning-opportunity');
7
+ const { readCodexToolOutcome } = require('./lib/codex-tool-outcome');
8
+ const codex = process.argv.includes('--codex');
7
9
 
8
10
  // PostToolUse/PostToolUseFailure hooks in Claude Code receive their payload via stdin
9
11
  let inputData = '';
@@ -15,12 +17,14 @@ process.stdin.on('data', chunk => {
15
17
  process.stdin.on('end', () => {
16
18
  try {
17
19
  const payload = JSON.parse(inputData);
20
+ const codexResult = codex ? readCodexToolOutcome(payload) : null;
21
+ if (codexResult?.outcome === 'unknown') return;
18
22
  const hookEventName = payload.hook_event_name || payload.hookEventName || '';
19
23
  const isFailureEvent = hookEventName === 'PostToolUseFailure';
20
24
  const isSuccessEvent = hookEventName === 'PostToolUse';
21
25
  const toolResponse = payload.tool_response || {};
22
- const stdout = toolResponse.stdout ?? payload.stdout ?? '';
23
- const stderr = toolResponse.stderr ?? payload.stderr ?? '';
26
+ const stdout = codexResult?.stdout ?? toolResponse.stdout ?? payload.stdout ?? '';
27
+ const stderr = codexResult?.stderr ?? toolResponse.stderr ?? payload.stderr ?? '';
24
28
  const failureText = typeof payload.error === 'string' ? payload.error : '';
25
29
  const rawExitCode = toolResponse.exitCode ?? toolResponse.exit_code ?? payload.exitCode ?? payload.exit_code;
26
30
  const exitCode = typeof rawExitCode === 'number' ? rawExitCode : undefined;
@@ -33,11 +37,14 @@ process.stdin.on('end', () => {
33
37
  const explicitFailure = exitCode !== undefined && exitCode !== 0;
34
38
  const stderrSignal = typeof stderr === 'string' && stderr.trim().length > 0;
35
39
  const looksLikeError = /\b(error|fail|failed|failure|exception|fatal|panic|traceback|denied|refused|cannot|unable)\b/i.test(stderr);
36
- const isFailure = isFailureEvent || explicitFailure ||
40
+ const isFailure = codex ? codexResult.outcome === 'failure' : isFailureEvent || explicitFailure ||
37
41
  (!isSuccessEvent && exitCode === undefined && stderrSignal && looksLikeError);
38
- const errorText = isFailureEvent
42
+ const reportedError = isFailureEvent
39
43
  ? (failureText || (stderrSignal ? stderr : stdout) || '')
40
44
  : ((stderrSignal ? stderr : stdout) || failureText || '');
45
+ const errorText = reportedError || (codexResult?.outcome === 'failure'
46
+ ? (codexResult.exitCode === undefined ? 'Tool reported failure' : `Tool exited with code ${codexResult.exitCode}`)
47
+ : '');
41
48
 
42
49
  const root = getWorkspaceRoot(payload);
43
50
  const stateFile = path.join(getSessionDir(root, payload.session_id || payload.sessionId), 'rule-of-3-state.json');
@@ -4,6 +4,8 @@ const path = require('path');
4
4
  const { getWorkspaceRoot, getSessionDir } = require('./lib/harness-state');
5
5
  const { cwdOf, classifyShell, isVerificationShell, directMutationInWorkspace } = require('./lib/workflow-isolation');
6
6
  const { observeTool } = require('./lib/telemetry');
7
+ const { readCodexToolOutcome } = require('./lib/codex-tool-outcome');
8
+ const codex = process.argv.includes('--codex');
7
9
 
8
10
  function isSuccessfulMetadataStep(command, cwd) {
9
11
  // A line break starts a second shell command, so it can never be metadata-only.
@@ -77,22 +79,26 @@ function processState(payload) {
77
79
  process.exit(0);
78
80
  }
79
81
  const toolResponse = payload.tool_response || {};
80
- const stdout = toolResponse.stdout ?? payload.stdout ?? '';
81
- const stderr = toolResponse.stderr ?? payload.stderr ?? payload.error ?? '';
82
+ const codexResult = codex ? readCodexToolOutcome(payload) : null;
83
+ const stdout = codexResult?.stdout ?? toolResponse.stdout ?? payload.stdout ?? '';
84
+ const stderr = codexResult?.stderr ?? toolResponse.stderr ?? payload.stderr ?? payload.error ?? '';
82
85
  const rawExitCode = toolResponse.exitCode ?? toolResponse.exit_code ?? payload.exitCode;
83
- const exitCode = typeof rawExitCode === 'number' ? rawExitCode : undefined;
86
+ const exitCode = codex ? codexResult.exitCode : typeof rawExitCode === 'number' ? rawExitCode : undefined;
84
87
  const stderrSignal = typeof stderr === 'string' && stderr.trim().length > 0;
85
88
  const hookEvent = captureEventName;
86
89
  const isSuccessEvent = hookEvent === 'PostToolUse';
87
- const isFailed = hookEvent === 'PostToolUseFailure' || (exitCode !== undefined && exitCode !== 0) || (!isSuccessEvent && exitCode === undefined && stderrSignal);
90
+ const isFailed = codex ? codexResult.outcome === 'failure' :
91
+ hookEvent === 'PostToolUseFailure' || (exitCode !== undefined && exitCode !== 0) ||
92
+ (!isSuccessEvent && exitCode === undefined && stderrSignal);
93
+ const verifiedSuccess = codex ? codexResult.outcome === 'success' : !isFailed && (isSuccessEvent || exitCode === 0);
88
94
  const toolName = payload.tool_name || payload.tool || 'command';
89
95
  let editAfterCapture = false;
90
96
  let stateOnlyCandidate = false;
91
97
  if (isFailed) {
92
- let output = (stderrSignal ? stderr : stdout) || payload.output || '';
98
+ let output = (stderrSignal ? stderr : stdout) || (typeof payload.output === 'string' ? payload.output : '');
93
99
  if (output.length > 500) output = '...' + output.slice(-500);
94
100
  state.status = 'failed'; state.timestamp = new Date().toISOString(); state.tool = toolName; state.exitCode = exitCode; state.errorSummary = output.trim();
95
- } else if (state.status === 'failed') {
101
+ } else if ((!codex || verifiedSuccess) && state.status === 'failed') {
96
102
  state.lastResolved = { tool: state.tool, timestamp: state.timestamp }; state.status = 'idle'; state.timestamp = new Date().toISOString(); delete state.exitCode; delete state.errorSummary;
97
103
  }
98
104
  const isDirectTool = toolName === 'Edit' || toolName === 'Write' || toolName === 'apply_patch';
@@ -106,13 +112,13 @@ function processState(payload) {
106
112
  stateOnlyCandidate = Boolean(docCheck && typeof payload.cwd === 'string' && payload.cwd
107
113
  && docCheck.isW6StateCommand(command, payload.cwd, root,
108
114
  { toolName, sessionId, agentId: payload.agent_id }));
109
- const metadataStep = !stateOnlyCandidate && !isFailed && (isSuccessEvent || exitCode === 0)
115
+ const metadataStep = !stateOnlyCandidate && verifiedSuccess
110
116
  && isSuccessfulMetadataStep(command, cwdOf(payload, root));
111
117
  if (!metadataStep && commandClass !== 'read-only' && commandClass !== 'worktree-setup') {
112
118
  if (stateOnlyCandidate) editAfterCapture = true;
113
119
  else state.lastEditAt = Date.now();
114
120
  }
115
- // Verification evidence needs a confirmed success: a PostToolUse event or an explicit zero exit.
121
+ // The host-specific outcome must confirm success before verification advances.
116
122
  // Pilot ON only: a registered, argv-validated doc-check that resolves to this install's own runtime is the document
117
123
  // verification evidence, and only at the shipped pin (R3-02). Any other path earns no verification evidence. OFF stays legacy.
118
124
  const installedCheck = docCheck && docCheck.registeredInstalledCheck(command, cwdOf(payload, root));
@@ -123,7 +129,7 @@ function processState(payload) {
123
129
  const verifies = stateOnlyCandidate ? false : docCheckCandidate
124
130
  ? Boolean(pinCheckable) && docCheck.fileDigest(installedCheck.installed) === docCheck.SHIPPED_DOC_CHECK_DIGEST
125
131
  : !(pilotEnabled && docCheck.trustRisk(command)) && isVerificationShell(command, { cwd: cwdOf(payload, root), root });
126
- if (!isFailed && (isSuccessEvent || exitCode === 0) && verifies) {
132
+ if (verifiedSuccess && verifies) {
127
133
  const verifiedAt = Date.now();
128
134
  const verifiedExitCode = exitCode ?? null;
129
135
  state.lastVerifyAt = verifiedAt;