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
@@ -60,9 +60,13 @@ const OBSERVATIONS_FILE = HARNESS_ROOT && join(HARNESS_ROOT, "hooks", "scripts",
60
60
  const ROUTER_FILE = HARNESS_ROOT && join(HARNESS_ROOT, "harness-everything", "scripts", "kernel-router.js")
61
61
  const LEDGER_MATCHER_FILE = HARNESS_ROOT && join(HARNESS_ROOT, "hooks", "scripts", "lib", "ledger-match.js")
62
62
  const HARNESS_STATE_FILE = HARNESS_ROOT && join(HARNESS_ROOT, "hooks", "scripts", "lib", "harness-state.js")
63
+ const LOCAL_ERRORS_FILE = HARNESS_ROOT && join(HARNESS_ROOT, "hooks", "scripts", "lib", "local-errors.js")
64
+ const LOCAL_ERROR_SOURCE_FILE = HARNESS_ROOT && join(HARNESS_ROOT, "hooks", "scripts", "lib", "local-error-source.js")
63
65
  let observationsApi
64
66
  let ledgerMatcherApi
65
67
  let harnessStateApi
68
+ let localErrorsApi
69
+ let localErrorSourceApi
66
70
 
67
71
  function systemOneObservations() {
68
72
  if (!OBSERVATIONS_FILE) return null
@@ -72,6 +76,22 @@ function systemOneObservations() {
72
76
  return observationsApi
73
77
  }
74
78
 
79
+ function localErrors() {
80
+ if (!LOCAL_ERRORS_FILE) return null
81
+ if (!localErrorsApi) {
82
+ try { localErrorsApi = requireFromPlugin(LOCAL_ERRORS_FILE) } catch { return null }
83
+ }
84
+ return typeof localErrorsApi?.appendOccurrence === "function" ? localErrorsApi : null
85
+ }
86
+
87
+ function localErrorSource() {
88
+ if (!LOCAL_ERROR_SOURCE_FILE) return null
89
+ if (!localErrorSourceApi) {
90
+ try { localErrorSourceApi = requireFromPlugin(LOCAL_ERROR_SOURCE_FILE) } catch { return null }
91
+ }
92
+ return typeof localErrorSourceApi?.createProvisionalSource === "function" ? localErrorSourceApi : null
93
+ }
94
+
75
95
  function ledgerMatcher() {
76
96
  if (!LEDGER_MATCHER_FILE || !HARNESS_STATE_FILE) return null
77
97
  try {
@@ -94,12 +114,25 @@ function queueLedgerLesson(pending, workspace, sessionID, event) {
94
114
  const identity = api.state.resolveWorkspaceIdentity(context)
95
115
  if (!identity?.workspaceRoot || !identity.workspaceKey || identity.sessionId !== sessionID) return
96
116
  if (identity.workspaceKey !== getWorkspaceKey(workspace)) return
117
+ let provisionalSource
118
+ const sourceApi = localErrorSource()
119
+ if (sourceApi) {
120
+ try {
121
+ provisionalSource = sourceApi.createProvisionalSource({
122
+ env: process.env,
123
+ workspaceRoot: identity.workspaceRoot,
124
+ })
125
+ } catch {
126
+ provisionalSource = undefined
127
+ }
128
+ }
97
129
  const result = api.matcher.matchLedgerLessons({
98
130
  workspaceRoot: identity.workspaceRoot,
99
131
  workspaceIdentity: identity.workspaceKey,
100
132
  sessionIdentity: sessionID,
101
133
  stateDir: api.state.getSessionDir(identity.workspaceRoot, sessionID, context),
102
134
  event,
135
+ ...(provisionalSource ? { provisionalSource } : {}),
103
136
  })
104
137
  if (!result) return
105
138
  const lessons = pending.get(sessionID) || []
@@ -108,6 +141,52 @@ function queueLedgerLesson(pending, workspace, sessionID, event) {
108
141
  } catch { /* ledger context is fail-open */ }
109
142
  }
110
143
 
144
+ function captureOpenCodeFailure(workspace, sessionID, event, command, failureOutput, exitCode) {
145
+ try {
146
+ if (typeof workspace !== "string" || !workspace || typeof sessionID !== "string" || !sessionID) return
147
+ const store = localErrors()
148
+ if (!store) return
149
+ const api = ledgerMatcher()
150
+ let workspaceRoot = workspace
151
+ if (api) {
152
+ const context = { workspace_root: workspace, session_id: sessionID, host_id: "opencode" }
153
+ const identity = api.state.resolveWorkspaceIdentity(context)
154
+ if (!identity?.workspaceRoot || !identity.workspaceKey || identity.sessionId !== sessionID) return
155
+ if (identity.workspaceKey !== getWorkspaceKey(workspace)) return
156
+ workspaceRoot = identity.workspaceRoot
157
+ }
158
+ let matchedLedgerIds = []
159
+ if (typeof api?.matcher?.peekRepoMatches === "function") {
160
+ try {
161
+ matchedLedgerIds = api.matcher.peekRepoMatches({
162
+ workspaceRoot,
163
+ event: {
164
+ phase: "failure",
165
+ tool: "shell",
166
+ command,
167
+ outcome: { failed: true, ...(typeof failureOutput === "string" ? { output: failureOutput } : {}) },
168
+ },
169
+ })
170
+ } catch {
171
+ matchedLedgerIds = []
172
+ }
173
+ }
174
+ const callId = [event?.id, event?.callID, event?.callId, event?.toolCallID, event?.toolCallId]
175
+ .find(value => typeof value === "string" && value.trim())
176
+ store.appendOccurrence({
177
+ workspaceRoot,
178
+ host: "opencode",
179
+ sessionKey: sessionID,
180
+ ...(callId ? { toolUseId: callId } : {}),
181
+ command,
182
+ exitCode: Number.isFinite(exitCode) ? exitCode : null,
183
+ output: typeof failureOutput === "string" ? failureOutput : "",
184
+ matchedLedgerIds,
185
+ destination: "unknown",
186
+ }, { env: process.env })
187
+ } catch { /* capture is write-only, silent, and fail-open */ }
188
+ }
189
+
111
190
  function releaseLedgerLessons(lessons) {
112
191
  const api = ledgerMatcher()
113
192
  if (!api) return lessons
@@ -1280,12 +1359,18 @@ export default {
1280
1359
  ? typeof event.error === "string" ? event.error
1281
1360
  : typeof event.error?.message === "string" ? event.error.message : undefined
1282
1361
  : undefined
1283
- const resultExit = event.status === "completed" && Number.isFinite(event.result?.metadata?.exit)
1362
+ const metadataExit = Number.isFinite(event.result?.metadata?.exit)
1284
1363
  ? event.result.metadata.exit : null
1364
+ const resultExit = event.status === "completed" && metadataExit !== null
1365
+ ? metadataExit : null
1285
1366
  const resultFailed = resultExit !== null && resultExit !== 0
1367
+ const confirmedFailure = event.status === "error" || (metadataExit !== null && metadataExit !== 0)
1286
1368
  const resultOutput = typeof event.result?.output === "string" ? event.result.output
1287
1369
  : typeof event.result?.output?.output === "string" ? event.result.output.output : undefined
1288
1370
  const failureOutput = errorOutput ?? resultOutput
1371
+ if ((event.tool === "bash" || event.tool === "shell") && confirmedFailure && typeof event.input?.command === "string") {
1372
+ captureOpenCodeFailure(binding.workspace, event.sessionID, event, event.input.command, failureOutput, metadataExit)
1373
+ }
1289
1374
  if ((event.tool === "bash" || event.tool === "shell") && failureOutput !== undefined && typeof event.input?.command === "string") {
1290
1375
  queueLedgerLesson(pendingLedgerLessons, binding.workspace, event.sessionID, {
1291
1376
  phase: "failure", tool: "shell", command: event.input.command,
@@ -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": "1.0.0",
4
+ "version": "1.1.0",
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": "1.0.0",
3
+ "version": "1.1.0",
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": {
@@ -18,6 +18,7 @@
18
18
  "repo:contract": "node scripts/repository-contract.js",
19
19
  "docs:sync": "node scripts/sync-current-docs.js",
20
20
  "errors:sync": "node scripts/errors-sync.js",
21
+ "errors:local": "node scripts/errors-local.js",
21
22
  "report": "node scripts/report-writer.js",
22
23
  "dispatch": "node scripts/dispatch.js",
23
24
  "test:repo-contract": "node ci/repository-contract.test.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "harness-everything",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
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",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "harness-everything",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
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",
@@ -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