harness-everything 1.0.0 → 1.1.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 (39) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/CHANGELOG.md +21 -0
  4. package/ci/mechanism-394-ledger-match.test.js +324 -3
  5. package/ci/mechanism-496-claude-capture.test.js +342 -0
  6. package/ci/mechanism-496-codex-capture.test.js +508 -0
  7. package/ci/mechanism-496-local-error-cli-edges.test.js +234 -0
  8. package/ci/mechanism-496-local-error-cli.test.js +517 -0
  9. package/ci/mechanism-496-local-error-store.test.js +731 -0
  10. package/ci/mechanism-496-opencode-capture.test.js +483 -0
  11. package/ci/mechanism-496-review-fixes.test.js +278 -0
  12. package/ci/mechanism-516-agy-post-tool-exit.test.js +472 -0
  13. package/ci/mechanism-516-agy-stop-revision.test.js +215 -0
  14. package/hooks/scripts/agy-post-tool.js +79 -16
  15. package/hooks/scripts/agy-stop.js +63 -10
  16. package/hooks/scripts/codex-ledger-lesson.js +103 -27
  17. package/hooks/scripts/ledger-lesson.js +94 -23
  18. package/hooks/scripts/lib/ledger-match.js +169 -21
  19. package/hooks/scripts/lib/local-error-source.js +127 -0
  20. package/hooks/scripts/lib/local-errors.js +597 -0
  21. package/hooks/scripts/lib/observations.js +1 -1
  22. package/hooks/scripts/state-persist.js +7 -1
  23. package/opencode-plugin/index.mjs +86 -1
  24. package/opencode-plugin/plugin.json +1 -1
  25. package/package.json +2 -1
  26. package/plugins/harness-everything/.antigravity-plugin/plugin.json +1 -1
  27. package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
  28. package/plugins/harness-everything/hooks/scripts/agy-post-tool.js +79 -16
  29. package/plugins/harness-everything/hooks/scripts/agy-stop.js +63 -10
  30. package/plugins/harness-everything/hooks/scripts/codex-ledger-lesson.js +103 -27
  31. package/plugins/harness-everything/hooks/scripts/ledger-lesson.js +94 -23
  32. package/plugins/harness-everything/hooks/scripts/lib/ledger-match.js +169 -21
  33. package/plugins/harness-everything/hooks/scripts/lib/local-error-source.js +127 -0
  34. package/plugins/harness-everything/hooks/scripts/lib/local-errors.js +597 -0
  35. package/plugins/harness-everything/hooks/scripts/lib/observations.js +1 -1
  36. package/plugins/harness-everything/hooks/scripts/state-persist.js +7 -1
  37. package/plugins/harness-everything/plugin.json +1 -1
  38. package/sbom.cdx.json +7 -7
  39. package/scripts/errors-local.js +357 -0
@@ -0,0 +1,215 @@
1
+ 'use strict';
2
+
3
+ const assert = require('assert');
4
+ const fs = require('fs');
5
+ const os = require('os');
6
+ const path = require('path');
7
+ const { spawnSync } = require('child_process');
8
+
9
+ const ROOT = path.resolve(__dirname, '..');
10
+ const PACKAGED_SCRIPTS = path.join(ROOT, 'plugins', 'harness-everything', 'hooks', 'scripts');
11
+ const TEMP_ROOT = fs.mkdtempSync(path.join(os.tmpdir(), 'harness-516-agy-stop-'));
12
+ const STATE_HOME = path.join(TEMP_ROOT, 'state-home');
13
+ const NO_GIT_PATH = path.join(TEMP_ROOT, 'no-git');
14
+ const originalStateHome = process.env.HARNESS_STATE_HOME;
15
+ fs.mkdirSync(STATE_HOME, { recursive: true });
16
+ fs.mkdirSync(NO_GIT_PATH, { recursive: true });
17
+ process.env.HARNESS_STATE_HOME = STATE_HOME;
18
+
19
+ const { getSessionDir } = require(path.join(PACKAGED_SCRIPTS, 'lib', 'harness-state'));
20
+ const realpath = fs.realpathSync.native || fs.realpathSync;
21
+
22
+ function run(script, payload, args = [], extraEnv = {}) {
23
+ const childEnv = { ...process.env, HARNESS_STATE_HOME: STATE_HOME, ...extraEnv };
24
+ delete childEnv.HARNESS_REQUIRE_VERIFICATION;
25
+ delete childEnv.HARNESS_DOC_RECONCILIATION_PILOT;
26
+ delete childEnv.HARNESS_WORKSPACE_ROOT;
27
+ const result = spawnSync(process.execPath, [path.join(PACKAGED_SCRIPTS, script), ...args], {
28
+ input: JSON.stringify(payload),
29
+ encoding: 'utf8',
30
+ env: childEnv,
31
+ timeout: 20000
32
+ });
33
+ assert.ifError(result.error);
34
+ assert.strictEqual(result.status, 0, `${script} failed: ${result.stderr}`);
35
+ return result.stdout.trim() ? JSON.parse(result.stdout.trim()) : null;
36
+ }
37
+
38
+ function git(root, args) {
39
+ const result = spawnSync('git', args, { cwd: root, encoding: 'utf8', timeout: 20000 });
40
+ assert.ifError(result.error);
41
+ assert.strictEqual(result.status, 0, `git ${args.join(' ')} failed: ${result.stderr}`);
42
+ return result.stdout.trim();
43
+ }
44
+
45
+ function makeWorkspace(name, withGit = true) {
46
+ const root = path.join(TEMP_ROOT, name);
47
+ fs.mkdirSync(root, { recursive: true });
48
+ if (withGit) {
49
+ git(root, ['init']);
50
+ git(root, ['config', 'user.name', 'Harness test']);
51
+ git(root, ['config', 'user.email', 'harness@example.test']);
52
+ fs.writeFileSync(path.join(root, 'tracked.txt'), 'baseline\n');
53
+ git(root, ['add', 'tracked.txt']);
54
+ git(root, ['commit', '-m', 'test baseline']);
55
+ }
56
+ return realpath(root);
57
+ }
58
+
59
+ function postTool(root, sessionId, toolCall, fields = {}) {
60
+ return run('agy-post-tool.js', {
61
+ conversationId: sessionId,
62
+ workspacePaths: [root],
63
+ toolCall,
64
+ ...fields
65
+ });
66
+ }
67
+
68
+ function writeFile(root, sessionId, target, content) {
69
+ fs.writeFileSync(target, content, 'utf8');
70
+ postTool(root, sessionId, { name: 'write_file', args: { Path: target, Content: content } });
71
+ }
72
+
73
+ function handoffPath(root, sessionId) {
74
+ return path.join(getSessionDir(root, sessionId), 'handoff-state.json');
75
+ }
76
+
77
+ function readHandoff(root, sessionId) {
78
+ return JSON.parse(fs.readFileSync(handoffPath(root, sessionId), 'utf8'));
79
+ }
80
+
81
+ function runUnknownCommand(root, sessionId, command = 'harness_unrecognized_command') {
82
+ const before = readHandoff(root, sessionId).lastEditAt || 0;
83
+ while (Date.now() <= before) {}
84
+ postTool(root, sessionId, {
85
+ name: 'run_command',
86
+ args: { CommandLine: command, Cwd: root }
87
+ });
88
+ const after = readHandoff(root, sessionId).lastEditAt || 0;
89
+ assert.ok(after > before, 'unrecognized run_command must preserve the existing AGY shell edit signal');
90
+ return after;
91
+ }
92
+
93
+ function stop(root, sessionId, extraEnv = {}) {
94
+ return run('agy-stop.js', {
95
+ conversationId: sessionId,
96
+ workspacePaths: [root],
97
+ terminationReason: 'NO_TOOL_CALL'
98
+ }, [], extraEnv);
99
+ }
100
+
101
+ function expectAllow(root, sessionId, message, extraEnv = {}) {
102
+ assert.deepStrictEqual(stop(root, sessionId, extraEnv), { decision: 'allow' }, message);
103
+ }
104
+
105
+ try {
106
+ const repo = makeWorkspace('git-workspace');
107
+ const session = 'p516-main';
108
+ const tracked = path.join(repo, 'tracked.txt');
109
+ assert.strictEqual(git(repo, ['status', '--porcelain']), '', 'the Git fixture starts clean');
110
+
111
+ // A direct in-workspace edit earns one continuation; shell timestamp churn
112
+ // during the same unresolved revision must not earn another.
113
+ writeFile(repo, session, tracked, 'direct edit\n');
114
+ assert.notStrictEqual(git(repo, ['status', '--porcelain']), '', 'the direct edit makes the Git fixture dirty');
115
+ assert.strictEqual(stop(repo, session).decision, 'continue', 'the first unresolved edit gets one continuation');
116
+ for (let i = 0; i < 3; i++) {
117
+ runUnknownCommand(repo, session);
118
+ expectAllow(repo, session, `shell timestamp churn ${i + 1} must not spend a second continuation`);
119
+ }
120
+
121
+ // A reason change from missing verification to a tool failure stays within
122
+ // the same revision and uses the already-spent continuation.
123
+ postTool(repo, session, {
124
+ name: 'run_command',
125
+ args: { CommandLine: 'harness_unrecognized_failure', Cwd: repo }
126
+ }, { error: 'command failed' });
127
+ expectAllow(repo, session, 'a failure reason transition in the same revision must not rearm the allowance');
128
+
129
+ // A proven verification resolves the episode. A later failure in the same
130
+ // content revision starts a fresh unresolved episode and gets one allowance.
131
+ postTool(repo, session, {
132
+ name: 'run_command',
133
+ args: { CommandLine: 'npm test', Cwd: repo }
134
+ }, { toolResponse: { exitCode: 0 } });
135
+ expectAllow(repo, session, 'proven verification resolves the prior episode');
136
+ postTool(repo, session, {
137
+ name: 'run_command',
138
+ args: { CommandLine: 'npm test', Cwd: repo }
139
+ }, { error: 'new failure after resolution' });
140
+ assert.strictEqual(stop(repo, session).decision, 'continue', 'a new unresolved episode after verification gets one continuation');
141
+ expectAllow(repo, session, 'the new episode is still bounded to one continuation');
142
+
143
+ // A real tracked-content edit made by a shell reopens one continuation even
144
+ // though state-persist also changes lastEditAt for the unrecognized command.
145
+ fs.writeFileSync(tracked, 'shell changed tracked bytes\n');
146
+ runUnknownCommand(repo, session);
147
+ assert.strictEqual(stop(repo, session).decision, 'continue', 'new tracked bytes rearm one continuation');
148
+ expectAllow(repo, session, 'the tracked-content revision is bounded to one continuation');
149
+
150
+ // Non-ignored untracked bytes are part of the same content identity. Staging
151
+ // and committing those exact bytes must not rearm the allowance.
152
+ const untracked = path.join(repo, 'shell-generated.txt');
153
+ fs.writeFileSync(untracked, 'untracked shell bytes\n');
154
+ runUnknownCommand(repo, session);
155
+ assert.strictEqual(stop(repo, session).decision, 'continue', 'new non-ignored untracked bytes rearm one continuation');
156
+ git(repo, ['add', 'tracked.txt', 'shell-generated.txt']);
157
+ git(repo, ['commit', '-m', 'record shell output']);
158
+ assert.strictEqual(git(repo, ['status', '--porcelain']), '', 'the Git fixture returns to clean after commit');
159
+ runUnknownCommand(repo, session, 'git add tracked.txt && git commit -m record');
160
+ expectAllow(repo, session, 'staging or committing the same bytes must not rearm the allowance');
161
+
162
+ // A missed content probe during a reason transition must preserve the last
163
+ // known digest so a real edit without a direct-write event still rearms once.
164
+ const probeMiss = makeWorkspace('probe-miss-workspace');
165
+ const probeMissSession = 'p516-probe-miss';
166
+ const probeMissTracked = path.join(probeMiss, 'tracked.txt');
167
+ writeFile(probeMiss, probeMissSession, probeMissTracked, 'direct edit\n');
168
+ assert.strictEqual(stop(probeMiss, probeMissSession).decision, 'continue', 'the probe-miss fixture spends its first allowance with a valid digest');
169
+ postTool(probeMiss, probeMissSession, {
170
+ name: 'run_command',
171
+ args: { CommandLine: 'harness_unrecognized_failure', Cwd: probeMiss }
172
+ }, { error: 'reason transition during probe miss' });
173
+ expectAllow(probeMiss, probeMissSession, 'a reason transition during a missed Git probe stays within the spent allowance', { PATH: NO_GIT_PATH });
174
+ fs.writeFileSync(probeMissTracked, 'new bytes without direct-write event\n');
175
+ assert.strictEqual(stop(probeMiss, probeMissSession).decision, 'continue', 'recovered Git detects changed bytes after the probe miss and rearms exactly once');
176
+ expectAllow(probeMiss, probeMissSession, 'the recovered content revision is still bounded to one continuation');
177
+
178
+ // The same reason transition on unchanged bytes remains allowed after Git returns.
179
+ const unchangedProbe = makeWorkspace('unchanged-probe-workspace');
180
+ const unchangedSession = 'p516-unchanged-probe';
181
+ writeFile(unchangedProbe, unchangedSession, path.join(unchangedProbe, 'tracked.txt'), 'direct edit\n');
182
+ assert.strictEqual(stop(unchangedProbe, unchangedSession).decision, 'continue', 'the unchanged-byte control spends one allowance with a valid digest');
183
+ postTool(unchangedProbe, unchangedSession, {
184
+ name: 'run_command',
185
+ args: { CommandLine: 'harness_unrecognized_failure', Cwd: unchangedProbe }
186
+ }, { error: 'same reason transition during probe miss' });
187
+ expectAllow(unchangedProbe, unchangedSession, 'the unchanged-byte reason transition is allowed while Git is unavailable', { PATH: NO_GIT_PATH });
188
+ expectAllow(unchangedProbe, unchangedSession, 'unchanged bytes remain allowed after Git returns');
189
+ expectAllow(unchangedProbe, unchangedSession, 'unchanged bytes do not gain verification credit or a new allowance');
190
+
191
+ // Non-Git workspaces fall back to the stable direct revision/session budget.
192
+ const plain = makeWorkspace('non-git-workspace', false);
193
+ const plainSession = 'p516-non-git';
194
+ writeFile(plain, plainSession, path.join(plain, 'edited.txt'), 'edit\n');
195
+ assert.strictEqual(stop(plain, plainSession).decision, 'continue', 'non-Git pending edit gets one continuation');
196
+ for (let i = 0; i < 2; i++) {
197
+ runUnknownCommand(plain, plainSession);
198
+ expectAllow(plain, plainSession, 'a failed workspace fingerprint probe must still be bounded');
199
+ }
200
+
201
+ // If the marker cannot be written safely, Stop must fail open rather than
202
+ // return continue without a durable cap.
203
+ const markerRoot = makeWorkspace('marker-failure-workspace', false);
204
+ const markerSession = 'p516-marker-failure';
205
+ writeFile(markerRoot, markerSession, path.join(markerRoot, 'edited.txt'), 'edit\n');
206
+ const stopStatePath = path.join(getSessionDir(markerRoot, markerSession), 'agy-stop-state.json');
207
+ fs.mkdirSync(stopStatePath);
208
+ expectAllow(markerRoot, markerSession, 'a marker write failure must allow stop');
209
+
210
+ console.log('AGY Stop revision allowance verified through packaged hooks.');
211
+ } finally {
212
+ if (originalStateHome === undefined) delete process.env.HARNESS_STATE_HOME;
213
+ else process.env.HARNESS_STATE_HOME = originalStateHome;
214
+ fs.rmSync(TEMP_ROOT, { recursive: true, force: true });
215
+ }
@@ -25,6 +25,66 @@ const FILE_MUTATION_TOOLS = new Set([
25
25
  'multi_replace_file_content'
26
26
  ]);
27
27
 
28
+ const FAILED_STATUSES = new Set([
29
+ 'failed',
30
+ 'fail',
31
+ 'error',
32
+ 'errored',
33
+ 'timed_out',
34
+ 'timeout',
35
+ 'cancelled',
36
+ 'canceled',
37
+ 'aborted'
38
+ ]);
39
+
40
+ function normalizeErrorText(rawError) {
41
+ if (typeof rawError === 'string') return rawError.trim();
42
+ if (rawError === null || rawError === undefined || rawError === false) return '';
43
+ if (typeof rawError === 'object') {
44
+ if (Array.isArray(rawError) && rawError.length === 0) return '';
45
+ if (!Array.isArray(rawError) && Object.keys(rawError).length === 0) return '';
46
+ }
47
+ const serialized = JSON.stringify(rawError);
48
+ return typeof serialized === 'string' ? serialized.trim() : '';
49
+ }
50
+
51
+ function hasExplicitFailureFlag(obj) {
52
+ return obj.isError === true
53
+ || obj.is_error === true
54
+ || obj.success === false
55
+ || obj.ok === false
56
+ || obj.interrupted === true;
57
+ }
58
+
59
+ function classifyStructuredOutcome(safePayload, responseObj, error) {
60
+ const rawExitCodes = [
61
+ safePayload.exitCode,
62
+ safePayload.exit_code,
63
+ responseObj.exitCode,
64
+ responseObj.exit_code
65
+ ].filter(Number.isInteger);
66
+ const nonzeroCode = rawExitCodes.find(code => code !== 0);
67
+ const exitCode = nonzeroCode ?? rawExitCodes[0];
68
+
69
+ const statuses = [safePayload.status, responseObj.status]
70
+ .filter(value => typeof value === 'string' && value.trim())
71
+ .map(value => value.trim().toLowerCase());
72
+
73
+ // Structured host errors, failure flags, and nonzero exit codes win over any
74
+ // zero or generic metadata fields. Text-only stdout/output markers are never parsed here
75
+ // because retained AGY captures do not distinguish host metadata from stdout.
76
+ const isFailed = Boolean(error && error.trim())
77
+ || (exitCode !== undefined && exitCode !== 0)
78
+ || hasExplicitFailureFlag(safePayload)
79
+ || hasExplicitFailureFlag(responseObj)
80
+ || statuses.some(status => FAILED_STATUSES.has(status));
81
+
82
+ return {
83
+ isFailed,
84
+ exitCode: isFailed ? (exitCode !== undefined && exitCode !== 0 ? exitCode : undefined) : exitCode
85
+ };
86
+ }
87
+
28
88
  function mapAgyPayloadToStatePersist(payload) {
29
89
  const safePayload = payload && typeof payload === 'object' ? payload : {};
30
90
  const sessionId = getAgySessionId(safePayload);
@@ -56,21 +116,22 @@ function mapAgyPayloadToStatePersist(payload) {
56
116
  toolInput = { ...args, file_path: filePath };
57
117
  }
58
118
 
59
- const toolResponse = safePayload.toolResponse || safePayload.tool_response || safePayload.result || {};
60
- const rawError = safePayload.error || toolResponse.error || '';
61
- const error = typeof rawError === 'string' ? rawError : (rawError ? JSON.stringify(rawError) : '');
62
- const stdout = toolResponse.stdout || (typeof safePayload.output === 'string' ? safePayload.output : '') || '';
63
- const stderr = toolResponse.stderr || (typeof error === 'string' ? error : '') || '';
64
-
65
- const rawExitCodes = [
66
- safePayload.exitCode,
67
- safePayload.exit_code,
68
- toolResponse.exitCode,
69
- toolResponse.exit_code
70
- ].filter(Number.isInteger);
71
- const exitCode = rawExitCodes.find(code => code !== 0) ?? rawExitCodes[0];
119
+ const rawResponse = safePayload.toolResponse || safePayload.tool_response || safePayload.result;
120
+ const responseObj = (rawResponse && typeof rawResponse === 'object' && !Array.isArray(rawResponse))
121
+ ? rawResponse
122
+ : {};
123
+ const error = normalizeErrorText(safePayload.error) || normalizeErrorText(responseObj.error);
124
+ const stdout = (typeof responseObj.stdout === 'string' && responseObj.stdout)
125
+ || (typeof safePayload.stdout === 'string' && safePayload.stdout)
126
+ || (typeof safePayload.output === 'string' && safePayload.output)
127
+ || (typeof rawResponse === 'string' && rawResponse)
128
+ || '';
129
+ const stderr = (typeof responseObj.stderr === 'string' && responseObj.stderr)
130
+ || (typeof safePayload.stderr === 'string' && safePayload.stderr)
131
+ || error
132
+ || '';
72
133
 
73
- const isFailed = Boolean(error && error.trim()) || (exitCode !== undefined && exitCode !== 0);
134
+ const { isFailed, exitCode } = classifyStructuredOutcome(safePayload, responseObj, error);
74
135
 
75
136
  return {
76
137
  hook_event_name: isFailed ? 'PostToolUseFailure' : 'PostToolUse',
@@ -89,7 +150,9 @@ function mapAgyPayloadToStatePersist(payload) {
89
150
  stderr,
90
151
  ...(exitCode !== undefined ? { exitCode } : {})
91
152
  },
92
- error: isFailed ? (error || stderr || `Command exited with code ${exitCode}`) : '',
153
+ error: isFailed
154
+ ? (error || stderr || (exitCode !== undefined ? `Command exited with code ${exitCode}` : 'Tool execution failed'))
155
+ : '',
93
156
  ...(exitCode !== undefined ? { exitCode } : {})
94
157
  };
95
158
  }
@@ -121,4 +184,4 @@ if (require.main === module) {
121
184
  });
122
185
  }
123
186
 
124
- module.exports = { main, mapAgyPayloadToStatePersist };
187
+ module.exports = { main, mapAgyPayloadToStatePersist, classifyStructuredOutcome };
@@ -26,6 +26,7 @@ const {
26
26
  normalizeAgyStatePayload
27
27
  } = require('./lib/agy-adapter-core');
28
28
  const { getWorkspaceRoot, getSessionDir } = require('./lib/harness-state');
29
+ const { workspaceFingerprint } = require('./lib/workflow-isolation');
29
30
 
30
31
  const STOP_STATE_FILE = 'agy-stop-state.json';
31
32
 
@@ -40,16 +41,58 @@ function readStopState(filePath) {
40
41
  }
41
42
 
42
43
  function writeStopState(filePath, state) {
44
+ let temp;
43
45
  try {
44
46
  fs.mkdirSync(path.dirname(filePath), { recursive: true });
45
- const temp = `${filePath}.${process.pid}.${Date.now()}.tmp`;
47
+ temp = `${filePath}.${process.pid}.${Date.now()}.tmp`;
46
48
  fs.writeFileSync(temp, JSON.stringify(state, null, 2) + '\n', 'utf8');
47
49
  fs.renameSync(temp, filePath);
50
+ return true;
48
51
  } catch (_) {
49
- // Best-effort marker write; never fail stop evaluation on state IO.
52
+ if (temp) { try { fs.unlinkSync(temp); } catch (_) {} }
53
+ return false;
50
54
  }
51
55
  }
52
56
 
57
+ function clearStopState(filePath) {
58
+ try { fs.unlinkSync(filePath); } catch (_) {}
59
+ }
60
+
61
+ function pendingRevision(handoff, root, sessionId) {
62
+ const directRevision = Number.isSafeInteger(handoff && handoff.agyDirectMutationRevision)
63
+ ? handoff.agyDirectMutationRevision
64
+ : null;
65
+ let contentFingerprint = null;
66
+ try { contentFingerprint = workspaceFingerprint(root, { maxPaths: 5000 }); } catch (_) {}
67
+ return {
68
+ revision: directRevision === null ? `session:${sessionId || 'default'}` : `direct:${directRevision}`,
69
+ directRevision,
70
+ contentFingerprint
71
+ };
72
+ }
73
+
74
+ function samePendingRevision(saved, current) {
75
+ if (!saved) return false;
76
+ if (!saved.lastContinuedRevision) {
77
+ // Older markers have no stable revision. Keep their session allowance
78
+ // when handoff state is legacy too; the prior content baseline is unknown.
79
+ return current.directRevision === null && Boolean(saved.lastContinuedFingerprint);
80
+ }
81
+ if (saved.lastContinuedRevision !== current.revision) return false;
82
+ return !current.contentFingerprint || !saved.lastContinuedContentFingerprint
83
+ || saved.lastContinuedContentFingerprint === current.contentFingerprint;
84
+ }
85
+
86
+ function stopMarker(revision, reason) {
87
+ return {
88
+ lastContinuedRevision: revision.revision,
89
+ lastContinuedContentFingerprint: revision.contentFingerprint,
90
+ lastContinuedFingerprint: `${revision.revision}${revision.contentFingerprint ? `|workspace:${revision.contentFingerprint}` : ''}`,
91
+ lastContinuedReason: reason,
92
+ updatedAt: new Date().toISOString()
93
+ };
94
+ }
95
+
53
96
  const ABNORMAL_TERMINATION_REASONS = new Set([
54
97
  'USER_CANCELED',
55
98
  'CANCELED',
@@ -103,17 +146,14 @@ function evaluateStop(payload) {
103
146
  let pending = null;
104
147
  if (isFailed) {
105
148
  pending = {
106
- fingerprint: `failed:${handoff.timestamp || ''}:${handoff.tool || ''}:${handoff.exitCode ?? ''}`,
107
149
  reason: 'Harness Verify-Before-Claim: pending tool failure must be resolved before claiming completion.'
108
150
  };
109
151
  } else if (lastEditAt > 0 && lastVerifyAt < lastEditAt) {
110
152
  pending = {
111
- fingerprint: `edit:${lastEditAt}`,
112
153
  reason: 'Harness Verify-Before-Claim: unverified edits exist in session. Run relevant test/build/lint verification before claiming completion.'
113
154
  };
114
155
  } else if (process.env.HARNESS_REQUIRE_VERIFICATION === '1' && (!lastVerifyAt || lastVerifyAt < lastEditAt)) {
115
156
  pending = {
116
- fingerprint: `strict:${lastVerifyAt}`,
117
157
  reason: 'Harness Verify-Before-Claim: objective test verification is required before claiming completion.'
118
158
  };
119
159
  }
@@ -121,19 +161,32 @@ function evaluateStop(payload) {
121
161
  if (pending) {
122
162
  const stopStateFile = path.join(sessionDir, STOP_STATE_FILE);
123
163
  const saved = readStopState(stopStateFile);
124
- if (saved && saved.lastContinuedFingerprint === pending.fingerprint) {
164
+ const revision = pendingRevision(handoff, root, sessionId);
165
+ if (samePendingRevision(saved, revision)) {
166
+ if (saved.lastContinuedReason !== pending.reason
167
+ || saved.lastContinuedRevision !== revision.revision
168
+ || (!saved.lastContinuedContentFingerprint && revision.contentFingerprint)) {
169
+ const marker = stopMarker(revision, pending.reason);
170
+ // A missed probe can refresh diagnostics, but cannot erase the last content baseline.
171
+ if (!revision.contentFingerprint && saved.lastContinuedContentFingerprint) {
172
+ marker.lastContinuedContentFingerprint = saved.lastContinuedContentFingerprint;
173
+ marker.lastContinuedFingerprint = saved.lastContinuedFingerprint;
174
+ }
175
+ writeStopState(stopStateFile, {
176
+ ...saved,
177
+ ...marker
178
+ });
179
+ }
125
180
  return { decision: 'allow' };
126
181
  }
127
- writeStopState(stopStateFile, {
128
- lastContinuedFingerprint: pending.fingerprint,
129
- updatedAt: new Date().toISOString()
130
- });
182
+ if (!writeStopState(stopStateFile, stopMarker(revision, pending.reason))) return { decision: 'allow' };
131
183
  return {
132
184
  decision: 'continue',
133
185
  reason: pending.reason
134
186
  };
135
187
  }
136
188
 
189
+ clearStopState(path.join(sessionDir, STOP_STATE_FILE));
137
190
  return { decision: 'allow' };
138
191
  }
139
192
 
@@ -4,58 +4,134 @@
4
4
  const path = require('node:path');
5
5
  const { getWorkspaceRoot, getSessionDir, getSessionId, resolveWorkspaceIdentity } = require('./lib/harness-state');
6
6
  const { readCodexToolOutcome } = require('./lib/codex-tool-outcome');
7
- const { matchLedgerLessons, releaseLedgerMatch } = require('./lib/ledger-match');
7
+ const { matchLedgerLessons, peekRepoMatches, releaseLedgerMatch } = require('./lib/ledger-match');
8
+
9
+ let localErrorSource;
10
+ try {
11
+ localErrorSource = require('./lib/local-error-source');
12
+ } catch (_) {
13
+ // Missing provisional source leaves the host hook fail-open.
14
+ }
15
+ let localErrors;
16
+ try {
17
+ localErrors = require('./lib/local-errors');
18
+ } catch (_) {
19
+ // Missing local error store leaves capture fail-open and silent.
20
+ }
8
21
 
9
22
  const MAX_INPUT_BYTES = 128 * 1024;
10
23
 
11
- function eventFor(payload) {
24
+ function buildInvocation(payload) {
12
25
  if (payload?.tool_name !== 'Bash' || typeof payload?.tool_input?.command !== 'string') return null;
13
26
  const command = payload.tool_input.command;
14
27
  if (payload.hook_event_name === 'PreToolUse') {
15
- return { phase: 'action', tool: 'shell', command, outcome: { failed: 'unknown' } };
28
+ return {
29
+ event: { phase: 'action', tool: 'shell', command, outcome: { failed: 'unknown' } },
30
+ toolOutcome: null,
31
+ };
16
32
  }
17
33
  if (payload.hook_event_name !== 'PostToolUse') return null;
18
34
 
19
- const result = readCodexToolOutcome(payload);
20
- const failed = result.outcome === 'failure' ? true : result.outcome === 'success' ? false : 'unknown';
35
+ const toolOutcome = readCodexToolOutcome(payload);
36
+ const failed = toolOutcome.outcome === 'failure' ? true : toolOutcome.outcome === 'success' ? false : 'unknown';
21
37
  const outcome = { failed };
22
38
  // Exact ledger diagnostics can identify a masked failure only when the host
23
39
  // provides a structured exit outcome. Opaque text-only responses stay unknown.
24
- if (result.outcome !== 'unknown') outcome.output = [result.stderr, result.stdout].filter(Boolean).join('\n');
25
- return { phase: 'failure', tool: 'shell', command, outcome };
40
+ if (toolOutcome.outcome !== 'unknown') {
41
+ outcome.output = [toolOutcome.stderr, toolOutcome.stdout].filter(Boolean).join('\n');
42
+ }
43
+ return {
44
+ event: { phase: 'failure', tool: 'shell', command, outcome },
45
+ toolOutcome,
46
+ };
47
+ }
48
+
49
+ function extractToolUseId(payload) {
50
+ for (const candidate of [payload?.tool_use_id, payload?.toolUseId, payload?.call_id, payload?.callId]) {
51
+ if (typeof candidate === 'string' && candidate.trim()) return candidate.trim();
52
+ }
53
+ return null;
54
+ }
55
+
56
+ function captureFailure(payload, workspaceRoot, sessionIdentity, event, toolOutcome) {
57
+ if (!localErrors || typeof localErrors.appendOccurrence !== 'function') return;
58
+ try {
59
+ const matchedLedgerIds = typeof peekRepoMatches === 'function'
60
+ ? peekRepoMatches({ workspaceRoot, event })
61
+ : [];
62
+ const toolUseId = extractToolUseId(payload);
63
+ localErrors.appendOccurrence({
64
+ workspaceRoot,
65
+ host: 'codex',
66
+ sessionKey: sessionIdentity,
67
+ ...(toolUseId ? { toolUseId } : {}),
68
+ command: event.command,
69
+ exitCode: Number.isInteger(toolOutcome.exitCode) ? toolOutcome.exitCode : null,
70
+ output: typeof event.outcome?.output === 'string' ? event.outcome.output : '',
71
+ matchedLedgerIds,
72
+ destination: 'unknown',
73
+ }, { env: process.env });
74
+ } catch (_) {
75
+ // Capture is write-only, silent, and fail-open.
76
+ }
26
77
  }
27
78
 
28
79
  function deliver(payload) {
29
80
  if (typeof payload?.cwd !== 'string' || !payload.cwd.trim()) return;
30
- const event = eventFor(payload);
81
+ const invocation = buildInvocation(payload);
31
82
  const sessionIdentity = getSessionId(payload);
32
- if (!event || !sessionIdentity) return;
83
+ if (!invocation || !sessionIdentity) return;
33
84
 
85
+ const { event, toolOutcome } = invocation;
34
86
  const workspaceRoot = getWorkspaceRoot(payload);
35
87
  const identity = resolveWorkspaceIdentity(payload);
36
88
  if (!workspaceRoot || !identity?.workspaceKey) return;
37
- const stateDir = path.join(getSessionDir(workspaceRoot, sessionIdentity, payload), 'ledger-lessons');
38
- const result = matchLedgerLessons({
39
- workspaceRoot,
40
- workspaceIdentity: identity.workspaceKey,
41
- sessionIdentity,
42
- stateDir,
43
- event,
44
- });
45
- if (!result) return;
46
89
 
90
+ let provisionalSource;
91
+ if (localErrorSource && typeof localErrorSource.createProvisionalSource === 'function') {
92
+ try {
93
+ provisionalSource = localErrorSource.createProvisionalSource({
94
+ env: process.env,
95
+ workspaceRoot,
96
+ });
97
+ } catch (_) {
98
+ provisionalSource = undefined;
99
+ }
100
+ }
101
+
102
+ let result = null;
47
103
  try {
48
- const output = JSON.stringify({
49
- hookSpecificOutput: {
50
- hookEventName: payload.hook_event_name,
51
- additionalContext: result.text,
52
- },
53
- });
54
- process.stdout.write(output, error => {
55
- if (error) releaseLedgerMatch(result);
104
+ const stateDir = path.join(getSessionDir(workspaceRoot, sessionIdentity, payload), 'ledger-lessons');
105
+ result = matchLedgerLessons({
106
+ workspaceRoot,
107
+ workspaceIdentity: identity.workspaceKey,
108
+ sessionIdentity,
109
+ stateDir,
110
+ event,
111
+ ...(provisionalSource ? { provisionalSource } : {}),
56
112
  });
57
113
  } catch (_) {
58
- releaseLedgerMatch(result);
114
+ result = null;
115
+ }
116
+
117
+ if (result) {
118
+ try {
119
+ const output = JSON.stringify({
120
+ hookSpecificOutput: {
121
+ hookEventName: payload.hook_event_name,
122
+ additionalContext: result.text,
123
+ },
124
+ });
125
+ process.stdout.write(output, error => {
126
+ if (error) releaseLedgerMatch(result);
127
+ });
128
+ } catch (_) {
129
+ releaseLedgerMatch(result);
130
+ }
131
+ }
132
+
133
+ if (payload.hook_event_name === 'PostToolUse' && toolOutcome?.outcome === 'failure') {
134
+ captureFailure(payload, workspaceRoot, sessionIdentity, event, toolOutcome);
59
135
  }
60
136
  }
61
137