harness-everything 0.56.0 → 0.57.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 (44) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/CHANGELOG.md +23 -0
  4. package/benchmarks/results/live-host/claude-2026-11-21-ledger-lesson/README.md +33 -0
  5. package/benchmarks/results/live-host/claude-2026-11-21-ledger-lesson/trace.jsonl +13 -0
  6. package/ci/fixtures/394-claude-ledger-lesson/post-tool-use-failure.json +13 -0
  7. package/ci/fixtures/394-claude-ledger-lesson/pre-tool-use.json +10 -0
  8. package/ci/fixtures/394-codex-ledger-lesson/post-tool-use-failure.json +17 -0
  9. package/ci/fixtures/394-codex-ledger-lesson/post-tool-use-success.json +17 -0
  10. package/ci/fixtures/394-codex-ledger-lesson/post-tool-use-unknown.json +15 -0
  11. package/ci/fixtures/394-codex-ledger-lesson/pre-tool-use.json +12 -0
  12. package/ci/fixtures/394-ledger-match/commitlint-empty-subject.txt +5 -0
  13. package/ci/fixtures/394-ledger-match/commitlint-subject-case.txt +5 -0
  14. package/ci/fixtures/394-ledger-match/provisional-candidates.json +20 -0
  15. package/ci/fixtures/394-ledger-match/quoted-match-record.md +25 -0
  16. package/ci/fixtures/468-dispatch/runner.js +30 -4
  17. package/ci/mechanism-394-claude-ledger-lesson.test.js +176 -0
  18. package/ci/mechanism-394-codex-ledger-lesson.test.js +203 -0
  19. package/ci/mechanism-394-ledger-match.test.js +507 -0
  20. package/ci/mechanism-394-opencode-ledger-lesson.test.js +232 -0
  21. package/ci/mechanism-468-dispatch-cli.test.js +143 -5
  22. package/ci/mechanism-errors-sync-root.test.js +86 -4
  23. package/ci/mechanism-report-writer.test.js +13 -1
  24. package/docs/adr/ROUTE-001-error-lesson-delivery.md +52 -49
  25. package/docs/error-handling/details/c8-dispatch-cli.md +8 -4
  26. package/docs/governed-index.md +1 -1
  27. package/docs/platform-capabilities.md +4 -0
  28. package/hooks/hooks.json +22 -0
  29. package/hooks/scripts/codex-ledger-lesson.js +82 -0
  30. package/hooks/scripts/ledger-lesson.js +94 -0
  31. package/hooks/scripts/lib/ledger-match.js +452 -0
  32. package/opencode-plugin/index.mjs +113 -4
  33. package/opencode-plugin/plugin.json +1 -1
  34. package/package.json +1 -1
  35. package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
  36. package/plugins/harness-everything/hooks/hooks.json +24 -0
  37. package/plugins/harness-everything/hooks/scripts/codex-ledger-lesson.js +82 -0
  38. package/plugins/harness-everything/hooks/scripts/ledger-lesson.js +94 -0
  39. package/plugins/harness-everything/hooks/scripts/lib/ledger-match.js +452 -0
  40. package/plugins/harness-everything/plugin.json +1 -1
  41. package/sbom.cdx.json +7 -7
  42. package/scripts/dispatch.js +31 -7
  43. package/scripts/errors-sync.js +63 -2
  44. package/scripts/report-writer.js +4 -2
@@ -0,0 +1,452 @@
1
+ 'use strict';
2
+
3
+ const crypto = require('node:crypto');
4
+ const fs = require('node:fs');
5
+ const path = require('node:path');
6
+
7
+ const LIMITS = Object.freeze({
8
+ indexBytes: 512 * 1024,
9
+ indexRows: 512,
10
+ recordBytes: 32 * 1024,
11
+ candidates: 32,
12
+ sourceBytes: 64 * 1024,
13
+ candidateText: 4096,
14
+ command: 8192,
15
+ output: 32 * 1024,
16
+ reminders: 2,
17
+ reminderChars: 1500
18
+ });
19
+ const INVITATION = 'Consider a fresh look, and zoom out if warranted.';
20
+ const PROVISIONAL_LABEL = 'Provisional local lesson (unreviewed)';
21
+ const LEDGER_RELATIVE = path.join('.agents', 'harness-everything', 'errors');
22
+ const FILE_PATTERN = /^\.agents\/harness-everything\/errors\/(E-\d{4,})-[a-z0-9-]+\.md$/;
23
+ const IDENTIFIER_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/;
24
+ const RECORD_ID_PATTERN = /^E-\d{4,}$/;
25
+ const PENDING_HANDOFFS = new WeakMap();
26
+
27
+ function isObject(value) {
28
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
29
+ }
30
+
31
+ function hasOnlyKeys(value, allowed) {
32
+ return Object.keys(value).every(key => allowed.includes(key));
33
+ }
34
+
35
+ function validIdentifier(value) {
36
+ return typeof value === 'string' && IDENTIFIER_PATTERN.test(value);
37
+ }
38
+
39
+ function validateRuleList(value, failure) {
40
+ if (!Array.isArray(value) || value.length < 1 || value.length > 8) throw new Error('invalid rule list');
41
+ const keys = failure ? ['tool', 'executable', 'subcommand', 'diagnostics'] : ['tool', 'executable', 'subcommand'];
42
+ return value.map(rule => {
43
+ if (!isObject(rule) || !hasOnlyKeys(rule, keys) || rule.tool !== 'shell' ||
44
+ !validIdentifier(rule.executable) || !validIdentifier(rule.subcommand)) throw new Error('invalid rule');
45
+ const result = { tool: 'shell', executable: rule.executable, subcommand: rule.subcommand };
46
+ if (failure) {
47
+ if (!Array.isArray(rule.diagnostics) || rule.diagnostics.length < 1 || rule.diagnostics.length > 16 ||
48
+ !rule.diagnostics.every(validIdentifier) || new Set(rule.diagnostics).size !== rule.diagnostics.length) {
49
+ throw new Error('invalid diagnostics');
50
+ }
51
+ result.diagnostics = [...rule.diagnostics];
52
+ }
53
+ return result;
54
+ });
55
+ }
56
+
57
+ function validateMatch(match) {
58
+ if (!isObject(match) || !hasOnlyKeys(match, ['actions', 'failures']) ||
59
+ (!Object.hasOwn(match, 'actions') && !Object.hasOwn(match, 'failures'))) throw new Error('invalid match');
60
+ const result = {};
61
+ if (Object.hasOwn(match, 'actions')) result.actions = validateRuleList(match.actions, false);
62
+ if (Object.hasOwn(match, 'failures')) result.failures = validateRuleList(match.failures, true);
63
+ return result;
64
+ }
65
+
66
+ function frontmatter(text) {
67
+ const found = text.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/);
68
+ if (!found) throw new Error('missing frontmatter');
69
+ return found[1];
70
+ }
71
+
72
+ function section(text, name) {
73
+ const lines = text.split(/\r?\n/);
74
+ const heading = lines.findIndex(line => new RegExp(`^## ${name}[ \\t]*$`).test(line));
75
+ if (heading < 0) throw new Error(`missing ${name}`);
76
+ let end = lines.length;
77
+ for (let index = heading + 1; index < lines.length; index += 1) {
78
+ if (/^#{1,2}\s/.test(lines[index])) { end = index; break; }
79
+ }
80
+ const body = lines.slice(heading + 1, end);
81
+ while (body.length && !body[0].trim()) body.shift();
82
+ while (body.length && !body[body.length - 1].trim()) body.pop();
83
+ const result = body.join('\n');
84
+ if (!result) throw new Error(`empty ${name}`);
85
+ return result;
86
+ }
87
+
88
+ function isWithin(root, candidate) {
89
+ const relative = path.relative(root, candidate);
90
+ return relative === '' || (!path.isAbsolute(relative) && relative !== '..' && !relative.startsWith(`..${path.sep}`));
91
+ }
92
+
93
+ function canonicalWorkspace(root) {
94
+ if (typeof root !== 'string' || !path.isAbsolute(root)) throw new Error('invalid workspace root');
95
+ const real = fs.realpathSync.native(root);
96
+ if (!fs.statSync(real).isDirectory()) throw new Error('workspace root is not a directory');
97
+ return real;
98
+ }
99
+
100
+ function validIndexRow(row) {
101
+ if (!isObject(row) || !hasOnlyKeys(row, [
102
+ 'id', 'signature', 'class', 'title', 'scope', 'status', 'sites', 'violates',
103
+ 'mechanism_ref', 'episodes', 'rounds', 'file', 'match', 'matchBinding'
104
+ ]) ||
105
+ !RECORD_ID_PATTERN.test(row.id) || !validIdentifier(row.signature) ||
106
+ typeof row.file !== 'string') throw new Error('invalid index row');
107
+ const file = FILE_PATTERN.exec(row.file);
108
+ if (!file || file[1] !== row.id) throw new Error('invalid record path');
109
+ const match = Object.hasOwn(row, 'match') ? validateMatch(row.match) : null;
110
+ if (match ? (typeof row.matchBinding !== 'string' || !/^[a-f0-9]{64}$/.test(row.matchBinding))
111
+ : Object.hasOwn(row, 'matchBinding')) throw new Error('invalid match binding');
112
+ return {
113
+ id: row.id,
114
+ signature: row.signature,
115
+ file: row.file,
116
+ match,
117
+ ...(match ? { matchBinding: row.matchBinding } : {})
118
+ };
119
+ }
120
+
121
+ function matchBinding(frontmatterText, row) {
122
+ return crypto.createHash('sha256').update(JSON.stringify([
123
+ frontmatterText.replace(/\r\n?/g, '\n'), row.id, row.signature, row.file, row.match
124
+ ])).digest('hex');
125
+ }
126
+
127
+ function readIndex(root) {
128
+ const ledgerPath = path.join(root, LEDGER_RELATIVE);
129
+ const ledger = fs.realpathSync.native(ledgerPath);
130
+ if (!isWithin(root, ledger) || !fs.statSync(ledger).isDirectory()) throw new Error('ledger escaped workspace');
131
+ const index = fs.realpathSync.native(path.join(ledger, 'index.jsonl'));
132
+ if (!isWithin(ledger, index) || !fs.statSync(index).isFile()) throw new Error('index escaped ledger');
133
+ const stat = fs.statSync(index);
134
+ if (stat.size > LIMITS.indexBytes) throw new Error('oversized index');
135
+ const content = fs.readFileSync(index, 'utf8');
136
+ const lines = content.split(/\r?\n/);
137
+ if (lines.at(-1) === '') lines.pop();
138
+ if (lines.length > LIMITS.indexRows || lines.some(line => !line.trim())) throw new Error('invalid index rows');
139
+ return { ledger, rows: lines.map(line => validIndexRow(JSON.parse(line))) };
140
+ }
141
+
142
+ function readRecord(ledger, row) {
143
+ const fullPath = path.join(ledger, path.posix.basename(row.file));
144
+ const real = fs.realpathSync.native(fullPath);
145
+ if (!isWithin(ledger, real) || !fs.statSync(real).isFile()) throw new Error('record escaped ledger');
146
+ const stat = fs.statSync(real);
147
+ if (stat.size > LIMITS.recordBytes) throw new Error('oversized record');
148
+ const text = fs.readFileSync(real, 'utf8');
149
+ if (matchBinding(frontmatter(text), row) !== row.matchBinding) throw new Error('stale indexed match binding');
150
+ return {
151
+ id: row.id,
152
+ signature: row.signature,
153
+ identity: `signature:${row.signature}`,
154
+ match: row.match,
155
+ cue: section(text, 'Cue'),
156
+ lesson: section(text, 'Lesson'),
157
+ source: 'repo'
158
+ };
159
+ }
160
+
161
+ // shortcut: only direct commands and listed Git prefixes are parsed; add wrapper support if a carrier needs it.
162
+ function words(command) {
163
+ if (typeof command !== 'string' || command.length > LIMITS.command || /[\r\n\0]/.test(command)) return null;
164
+ const tokens = [];
165
+ let value = '';
166
+ let quote = null;
167
+ let active = false;
168
+ for (let index = 0; index < command.length; index += 1) {
169
+ const char = command[index];
170
+ if (quote) {
171
+ if (char === quote) quote = null;
172
+ else if (char === '\\' && quote === '"' && index + 1 < command.length) value += command[++index];
173
+ else value += char;
174
+ active = true;
175
+ continue;
176
+ }
177
+ if (char === '"' || char === "'") { quote = char; active = true; continue; }
178
+ if (char === '\\' && index + 1 < command.length) { value += command[++index]; active = true; continue; }
179
+ if (';&|<>'.includes(char)) return null;
180
+ if (/\s/.test(char)) {
181
+ if (active) { tokens.push(value); value = ''; active = false; }
182
+ continue;
183
+ }
184
+ value += char;
185
+ active = true;
186
+ }
187
+ if (quote) return null;
188
+ if (active) tokens.push(value);
189
+ return tokens;
190
+ }
191
+
192
+ function normalizeShellCommand(command) {
193
+ try {
194
+ const tokens = words(command);
195
+ if (!tokens || tokens.length < 2) return null;
196
+ const executable = tokens[0].replaceAll('\\', '/').split('/').at(-1).toLowerCase().replace(/\.exe$/, '');
197
+ if (!validIdentifier(executable)) return null;
198
+ let index = 1;
199
+ if (executable === 'git') {
200
+ while (tokens[index]?.startsWith('-')) {
201
+ const option = tokens[index++];
202
+ if (option === '-C') {
203
+ if (!tokens[index++]) return null;
204
+ } else if (option === '-c') {
205
+ const setting = tokens[index++];
206
+ const equals = setting?.indexOf('=');
207
+ if (!setting || equals < 1 || equals === setting.length - 1) return null;
208
+ } else if (option === '--no-pager' || option === '-P') {
209
+ continue;
210
+ } else if (option.startsWith('--git-dir=')) {
211
+ if (option.length === '--git-dir='.length) return null;
212
+ } else if (option.startsWith('--work-tree=')) {
213
+ if (option.length === '--work-tree='.length) return null;
214
+ } else {
215
+ return null;
216
+ }
217
+ }
218
+ }
219
+ if (!validIdentifier(tokens[index])) return null;
220
+ return { tool: 'shell', executable, subcommand: tokens[index] };
221
+ } catch (_) {
222
+ return null;
223
+ }
224
+ }
225
+
226
+ function normalizeGitCommitCommand(command) {
227
+ const invocation = normalizeShellCommand(command);
228
+ return invocation?.executable === 'git' && invocation.subcommand === 'commit' ? invocation : null;
229
+ }
230
+
231
+ function normalizeEvent(event) {
232
+ if (!isObject(event) || !['action', 'failure'].includes(event.phase) || event.tool !== 'shell' ||
233
+ !isObject(event.outcome) || ![true, false, 'unknown'].includes(event.outcome.failed) ||
234
+ (event.outcome.output !== undefined && typeof event.outcome.output !== 'string') ||
235
+ (event.phase === 'failure' && event.outcome.output && event.outcome.output.length > LIMITS.output)) return null;
236
+ const invocation = normalizeShellCommand(event.command);
237
+ return invocation ? { phase: event.phase, tool: 'shell', command: event.command, outcome: event.outcome, invocation } : null;
238
+ }
239
+
240
+ function ruleMatches(rule, invocation) {
241
+ return rule.tool === invocation.tool && rule.executable === invocation.executable && rule.subcommand === invocation.subcommand;
242
+ }
243
+
244
+ function hasDiagnostic(output, diagnostics) {
245
+ const accepted = new Set(diagnostics);
246
+ return output.split(/\r?\n/).some(line => {
247
+ const found = line.match(/^\s*✖\s+[^[]+\[([a-z0-9][a-z0-9_-]{0,63})\]\s*$/);
248
+ return found && accepted.has(found[1]);
249
+ });
250
+ }
251
+
252
+ function eventMatches(match, event) {
253
+ if (!match) return false;
254
+ if (event.phase === 'action') return Boolean(match.actions?.some(rule => ruleMatches(rule, event.invocation)));
255
+ return event.outcome.failed === true && typeof event.outcome.output === 'string' &&
256
+ Boolean(match.failures?.some(rule => rule.tool === event.invocation.tool &&
257
+ rule.executable === event.invocation.executable && rule.subcommand === event.invocation.subcommand &&
258
+ hasDiagnostic(event.outcome.output, rule.diagnostics)));
259
+ }
260
+
261
+ function validProvisionalCandidate(candidate) {
262
+ const allowed = ['identity', 'signature', 'promotionId', 'match', 'cue', 'lesson'];
263
+ if (!isObject(candidate) || !hasOnlyKeys(candidate, allowed) || !validIdentifier(candidate.identity) ||
264
+ (candidate.signature !== undefined && !validIdentifier(candidate.signature)) ||
265
+ (candidate.promotionId !== undefined && !RECORD_ID_PATTERN.test(candidate.promotionId)) ||
266
+ typeof candidate.lesson !== 'string' || !candidate.lesson.trim() || candidate.lesson.length > LIMITS.candidateText ||
267
+ (candidate.cue !== undefined && (typeof candidate.cue !== 'string' || candidate.cue.length > LIMITS.candidateText))) {
268
+ throw new Error('invalid provisional candidate');
269
+ }
270
+ return {
271
+ id: candidate.identity,
272
+ identity: candidate.signature ? `signature:${candidate.signature}` : `identity:${candidate.identity}`,
273
+ signature: candidate.signature || null,
274
+ promotionId: candidate.promotionId || null,
275
+ match: validateMatch(candidate.match),
276
+ cue: candidate.cue || '',
277
+ lesson: candidate.lesson,
278
+ source: 'provisional'
279
+ };
280
+ }
281
+
282
+ function readProvisional(source, workspaceIdentity) {
283
+ if (source === undefined) return [];
284
+ if (typeof source !== 'function') throw new Error('invalid provisional source');
285
+ const values = source(workspaceIdentity, {
286
+ maxCandidates: LIMITS.candidates,
287
+ maxBytes: LIMITS.sourceBytes,
288
+ maxTextChars: LIMITS.candidateText
289
+ });
290
+ if (!Array.isArray(values) || values.length > LIMITS.candidates) throw new Error('oversized provisional source');
291
+ const result = values.map(validProvisionalCandidate);
292
+ if (Buffer.byteLength(JSON.stringify(result), 'utf8') > LIMITS.sourceBytes) throw new Error('oversized provisional source');
293
+ return result;
294
+ }
295
+
296
+ function matchedRepoCandidates(root, event) {
297
+ try {
298
+ const { ledger, rows } = readIndex(root);
299
+ const candidates = [];
300
+ for (const row of rows) {
301
+ if (row.match && eventMatches(row.match, event)) {
302
+ candidates.push(readRecord(ledger, row));
303
+ if (candidates.length > LIMITS.candidates) throw new Error('too many repo candidates');
304
+ }
305
+ }
306
+ return candidates;
307
+ } catch (_) {
308
+ return [];
309
+ }
310
+ }
311
+
312
+ function matchedProvisionalCandidates(source, workspaceIdentity, event) {
313
+ try {
314
+ return readProvisional(source, workspaceIdentity)
315
+ .filter(candidate => eventMatches(candidate.match, event));
316
+ } catch (_) {
317
+ return [];
318
+ }
319
+ }
320
+
321
+ function collapseCandidates(repo, provisional) {
322
+ const compare = (left, right) => left < right ? -1 : left > right ? 1 : 0;
323
+ const orderedRepo = [...repo].sort((a, b) => compare(a.signature, b.signature) || compare(a.id, b.id));
324
+ const orderedProvisional = [...provisional].sort((a, b) =>
325
+ compare(a.signature || a.id, b.signature || b.id) || compare(a.id, b.id));
326
+ const result = [];
327
+ const aliases = new Map();
328
+ const add = candidate => {
329
+ const keys = [`id:${candidate.id}`];
330
+ if (candidate.signature) keys.push(`signature:${candidate.signature}`);
331
+ if (candidate.promotionId) keys.push(`id:${candidate.promotionId}`);
332
+ if (keys.some(key => aliases.has(key))) return;
333
+ const identity = candidate.signature ? `signature:${candidate.signature}` : candidate.identity;
334
+ candidate.lessonIdentity = identity;
335
+ result.push(candidate);
336
+ for (const key of keys) aliases.set(key, identity);
337
+ };
338
+ orderedRepo.forEach(add);
339
+ orderedProvisional.forEach(add);
340
+ return result;
341
+ }
342
+
343
+ function ensureStateDir(stateDir) {
344
+ if (typeof stateDir !== 'string' || !path.isAbsolute(stateDir)) return null;
345
+ try {
346
+ fs.mkdirSync(stateDir, { recursive: true, mode: 0o700 });
347
+ const real = fs.realpathSync.native(stateDir);
348
+ return fs.statSync(real).isDirectory() ? real : null;
349
+ } catch (_) {
350
+ return null;
351
+ }
352
+ }
353
+
354
+ function claim(stateDir, input, candidate, phase) {
355
+ const key = crypto.createHash('sha256').update(JSON.stringify([
356
+ input.workspaceIdentity, input.sessionIdentity, candidate.lessonIdentity, phase
357
+ ])).digest('hex');
358
+ const file = path.join(stateDir, `ledger-match-${key}.claim`);
359
+ const token = crypto.randomBytes(16).toString('hex');
360
+ try {
361
+ const fd = fs.openSync(file, 'wx', 0o600);
362
+ try {
363
+ fs.writeFileSync(fd, token, 'utf8');
364
+ fs.closeSync(fd);
365
+ return { status: 'claimed', file, token };
366
+ } catch (error) {
367
+ try { fs.closeSync(fd); } catch (_) {}
368
+ try { fs.unlinkSync(file); } catch (_) {}
369
+ return { status: 'unavailable' };
370
+ }
371
+ } catch (error) {
372
+ return { status: error.code === 'EEXIST' ? 'exists' : 'unavailable' };
373
+ }
374
+ }
375
+
376
+ function block(candidate) {
377
+ return candidate.source === 'repo'
378
+ ? `Cue:\n${candidate.cue}\nLesson:\n${candidate.lesson}`
379
+ : `${PROVISIONAL_LABEL}\n${candidate.lesson}`;
380
+ }
381
+
382
+ function charCount(text) {
383
+ return Array.from(text).length;
384
+ }
385
+
386
+ function matchLedgerLessons(input) {
387
+ try {
388
+ if (!isObject(input) || typeof input.workspaceIdentity !== 'string' || !input.workspaceIdentity.trim() ||
389
+ input.workspaceIdentity.length > 256 || /[\0\r\n]/.test(input.workspaceIdentity) ||
390
+ typeof input.sessionIdentity !== 'string' || !input.sessionIdentity.trim() ||
391
+ input.sessionIdentity.length > 256 || /[\0\r\n]/.test(input.sessionIdentity)) return null;
392
+ const root = canonicalWorkspace(input.workspaceRoot);
393
+ const event = normalizeEvent(input.event);
394
+ if (!event) return null;
395
+ let repo = matchedRepoCandidates(root, event);
396
+ let provisional = matchedProvisionalCandidates(input.provisionalSource, input.workspaceIdentity, event);
397
+ const candidates = collapseCandidates(repo, provisional);
398
+ if (!candidates.length) return null;
399
+ const state = ensureStateDir(input.stateDir);
400
+ if (!state) return null;
401
+
402
+ const selected = [];
403
+ const claims = [];
404
+ for (const candidate of candidates) {
405
+ if (selected.length >= LIMITS.reminders) break;
406
+ const prospective = [...selected.map(item => block(item)), block(candidate)].join('\n\n') + `\n\n${INVITATION}`;
407
+ if (charCount(prospective) > LIMITS.reminderChars) continue;
408
+ const claimed = claim(state, input, candidate, event.phase);
409
+ if (claimed.status === 'exists') continue;
410
+ if (claimed.status !== 'claimed') {
411
+ for (const prior of claims) releaseClaim(prior);
412
+ return null;
413
+ }
414
+ claims.push(claimed);
415
+ selected.push(candidate);
416
+ }
417
+ if (!selected.length) return null;
418
+ const result = {
419
+ text: `${selected.map(block).join('\n\n')}\n\n${INVITATION}`,
420
+ ids: selected.map(candidate => candidate.id)
421
+ };
422
+ PENDING_HANDOFFS.set(result, claims);
423
+ return result;
424
+ } catch (_) {
425
+ return null;
426
+ }
427
+ }
428
+
429
+ function releaseClaim(claimed) {
430
+ try {
431
+ if (fs.readFileSync(claimed.file, 'utf8') !== claimed.token) return true;
432
+ } catch (error) {
433
+ if (error.code === 'ENOENT') return true;
434
+ return false;
435
+ }
436
+ try { fs.unlinkSync(claimed.file); return true; } catch (_) { return false; }
437
+ }
438
+
439
+ // Carriers release a reservation only when the returned context handoff is dropped.
440
+ function releaseLedgerMatch(result) {
441
+ const claims = result && PENDING_HANDOFFS.get(result);
442
+ if (!claims) return false;
443
+ const remaining = claims.filter(claimed => !releaseClaim(claimed));
444
+ if (remaining.length) {
445
+ PENDING_HANDOFFS.set(result, remaining);
446
+ return false;
447
+ }
448
+ PENDING_HANDOFFS.delete(result);
449
+ return true;
450
+ }
451
+
452
+ module.exports = { matchLedgerLessons, normalizeGitCommitCommand, releaseLedgerMatch };
@@ -58,7 +58,11 @@ const HARNESS_ROOT = findHarnessRoot()
58
58
  const STOP_GATE_FILE = join(HARNESS_ROOT || resolve(PLUGIN_DIRECTORY, ".."), "hooks", "scripts", "workflow-stop-gate.js")
59
59
  const OBSERVATIONS_FILE = HARNESS_ROOT && join(HARNESS_ROOT, "hooks", "scripts", "lib", "observations.js")
60
60
  const ROUTER_FILE = HARNESS_ROOT && join(HARNESS_ROOT, "harness-everything", "scripts", "kernel-router.js")
61
+ const LEDGER_MATCHER_FILE = HARNESS_ROOT && join(HARNESS_ROOT, "hooks", "scripts", "lib", "ledger-match.js")
62
+ const HARNESS_STATE_FILE = HARNESS_ROOT && join(HARNESS_ROOT, "hooks", "scripts", "lib", "harness-state.js")
61
63
  let observationsApi
64
+ let ledgerMatcherApi
65
+ let harnessStateApi
62
66
 
63
67
  function systemOneObservations() {
64
68
  if (!OBSERVATIONS_FILE) return null
@@ -68,6 +72,48 @@ function systemOneObservations() {
68
72
  return observationsApi
69
73
  }
70
74
 
75
+ function ledgerMatcher() {
76
+ if (!LEDGER_MATCHER_FILE || !HARNESS_STATE_FILE) return null
77
+ try {
78
+ ledgerMatcherApi ||= requireFromPlugin(LEDGER_MATCHER_FILE)
79
+ harnessStateApi ||= requireFromPlugin(HARNESS_STATE_FILE)
80
+ if (typeof ledgerMatcherApi.matchLedgerLessons !== "function"
81
+ || typeof ledgerMatcherApi.releaseLedgerMatch !== "function"
82
+ || typeof harnessStateApi.resolveWorkspaceIdentity !== "function"
83
+ || typeof harnessStateApi.getSessionDir !== "function") return null
84
+ return { matcher: ledgerMatcherApi, state: harnessStateApi }
85
+ } catch { return null }
86
+ }
87
+
88
+ function queueLedgerLesson(pending, workspace, sessionID, event) {
89
+ try {
90
+ if (typeof workspace !== "string" || !workspace || typeof sessionID !== "string" || !sessionID) return
91
+ const api = ledgerMatcher()
92
+ if (!api) return
93
+ const context = { workspace_root: workspace, session_id: sessionID, host_id: "opencode" }
94
+ const identity = api.state.resolveWorkspaceIdentity(context)
95
+ if (!identity?.workspaceRoot || !identity.workspaceKey || identity.sessionId !== sessionID) return
96
+ if (identity.workspaceKey !== getWorkspaceKey(workspace)) return
97
+ const result = api.matcher.matchLedgerLessons({
98
+ workspaceRoot: identity.workspaceRoot,
99
+ workspaceIdentity: identity.workspaceKey,
100
+ sessionIdentity: sessionID,
101
+ stateDir: api.state.getSessionDir(identity.workspaceRoot, sessionID, context),
102
+ event,
103
+ })
104
+ if (!result) return
105
+ const lessons = pending.get(sessionID) || []
106
+ lessons.push({ workspace: identity.workspaceRoot, phase: event.phase, result })
107
+ pending.set(sessionID, lessons)
108
+ } catch { /* ledger context is fail-open */ }
109
+ }
110
+
111
+ function releaseLedgerLessons(lessons) {
112
+ const api = ledgerMatcher()
113
+ if (!api) return lessons
114
+ return lessons.filter(lesson => !api.matcher.releaseLedgerMatch(lesson.result))
115
+ }
116
+
71
117
  // OpenCode's host process is a compiled Bun binary, so process.execPath is the
72
118
  // opencode executable. That binary cannot run a Node .js script - it treats the
73
119
  // script path as a project directory (ENOTDIR) - so a non-Node host must run
@@ -1000,6 +1046,8 @@ export default {
1000
1046
  const promptRoutes = new Map()
1001
1047
  const sessionBindings = new Map()
1002
1048
  const sessionOwners = new Map()
1049
+ const pendingLedgerLessons = new Map()
1050
+ const ledgerReleaseRetry = new Set()
1003
1051
  const invalidatedSessions = new Set()
1004
1052
  const enforcementByWorkspace = new Map()
1005
1053
  const pendingEvents = new Set()
@@ -1009,6 +1057,22 @@ export default {
1009
1057
  pending.then(() => pendingEvents.delete(pending), () => pendingEvents.delete(pending))
1010
1058
  return pending
1011
1059
  }
1060
+ const retryLedgerReleases = () => {
1061
+ for (const lesson of ledgerReleaseRetry) {
1062
+ if (releaseLedgerLessons([lesson]).length === 0) ledgerReleaseRetry.delete(lesson)
1063
+ }
1064
+ }
1065
+ const releaseSessionLedger = sessionID => {
1066
+ const lessons = pendingLedgerLessons.get(sessionID) || []
1067
+ pendingLedgerLessons.delete(sessionID)
1068
+ for (const lesson of releaseLedgerLessons(lessons)) ledgerReleaseRetry.add(lesson)
1069
+ retryLedgerReleases()
1070
+ }
1071
+ const releaseAllLedger = () => {
1072
+ for (const sessionID of pendingLedgerLessons.keys()) releaseSessionLedger(sessionID)
1073
+ retryLedgerReleases()
1074
+ }
1075
+ events.signal.addEventListener("abort", releaseAllLedger, { once: true })
1012
1076
  let unresolvedIdentityCount = 0
1013
1077
  const routerUnavailableCounts = new Map()
1014
1078
 
@@ -1112,6 +1176,24 @@ export default {
1112
1176
  if (events.signal.aborted || invalidatedSessions.has(sessionID) || promptRoutes.get(sessionID) !== prompt) return null
1113
1177
  return bindSessionWorkspace(sessionID, identity.workspace, hooks)
1114
1178
  }
1179
+ const deliverLedgerLessons = event => {
1180
+ const sessionID = event?.sessionID
1181
+ if (typeof sessionID !== "string" || !sessionID || (event.kind && event.kind !== "primary")) return
1182
+ const lessons = pendingLedgerLessons.get(sessionID)
1183
+ if (!lessons?.length) return
1184
+ const workspace = sessionBindings.get(sessionID)?.workspace
1185
+ if (!Array.isArray(event.system) || invalidatedSessions.has(sessionID) || !workspace
1186
+ || lessons.some(lesson => getWorkspaceKey(lesson.workspace) !== getWorkspaceKey(workspace))) {
1187
+ releaseSessionLedger(sessionID)
1188
+ return
1189
+ }
1190
+ try {
1191
+ event.system.push(...lessons.map(lesson => ({ type: "text", text: lesson.result.text })))
1192
+ pendingLedgerLessons.delete(sessionID)
1193
+ } catch {
1194
+ releaseSessionLedger(sessionID)
1195
+ }
1196
+ }
1115
1197
 
1116
1198
  await ctx.session.hook("prompt", event => {
1117
1199
  if (events.signal.aborted) return
@@ -1165,8 +1247,9 @@ export default {
1165
1247
  await ctx.session.hook("context", event => {
1166
1248
  if (events.signal.aborted) return
1167
1249
  const output = promptRoutes.get(event?.sessionID)?.routerOutput
1168
- if (!output || (event.kind && event.kind !== "primary") || !Array.isArray(event.system)) return
1169
- if (!event.system.some(part => part && part.text === output)) event.system.push({ type: "text", text: output })
1250
+ if (output && (!event.kind || event.kind === "primary") && Array.isArray(event.system)
1251
+ && !event.system.some(part => part && part.text === output)) event.system.push({ type: "text", text: output })
1252
+ deliverLedgerLessons(event)
1170
1253
  })
1171
1254
 
1172
1255
  await ctx.tool.hook("execute.before", event => {
@@ -1174,7 +1257,14 @@ export default {
1174
1257
  return trackPending(async () => {
1175
1258
  if (events.signal.aborted) return
1176
1259
  const binding = await bindingForSession(event?.sessionID)
1177
- if (events.signal.aborted || !binding?.workspace || !binding.hooks) return
1260
+ if (events.signal.aborted || !binding?.workspace) return
1261
+ retryLedgerReleases()
1262
+ if (event.tool === "bash" && typeof event.input?.command === "string") {
1263
+ queueLedgerLesson(pendingLedgerLessons, binding.workspace, event.sessionID, {
1264
+ phase: "action", tool: "shell", command: event.input.command, outcome: { failed: "unknown" },
1265
+ })
1266
+ }
1267
+ if (!binding.hooks) return
1178
1268
  return binding.hooks["tool.execute.before"](toolEventInput(event), { args: event.input })
1179
1269
  })
1180
1270
  })
@@ -1185,6 +1275,21 @@ export default {
1185
1275
  const prompt = promptRoutes.get(event?.sessionID)
1186
1276
  const binding = await bindingForSession(event?.sessionID)
1187
1277
  if (events.signal.aborted || !binding?.workspace) return
1278
+ retryLedgerReleases()
1279
+ const errorOutput = event.status === "error"
1280
+ ? typeof event.error === "string" ? event.error
1281
+ : typeof event.error?.message === "string" ? event.error.message : undefined
1282
+ : undefined
1283
+ const resultFailed = event.status === "completed"
1284
+ && Number.isFinite(event.result?.metadata?.exit) && event.result.metadata.exit !== 0
1285
+ const resultOutput = resultFailed && typeof event.result?.output === "string" ? event.result.output : undefined
1286
+ const failureOutput = errorOutput ?? resultOutput
1287
+ if (event.tool === "bash" && failureOutput !== undefined && typeof event.input?.command === "string") {
1288
+ queueLedgerLesson(pendingLedgerLessons, binding.workspace, event.sessionID, {
1289
+ phase: "failure", tool: "shell", command: event.input.command,
1290
+ outcome: { failed: true, output: failureOutput },
1291
+ })
1292
+ }
1188
1293
  if (prompt?.status === "resolved" && prompt.workspace) observeOpenCodeTool(event, prompt.workspace)
1189
1294
  if (!binding.hooks) return
1190
1295
  return binding.hooks["tool.execute.after"](toolEventInput(event), {
@@ -1209,9 +1314,13 @@ export default {
1209
1314
  const turnEnded = raw.type === "session.idle" || raw.type === "session.execution.succeeded"
1210
1315
  const lifecycleEvent = ["session.idle", "session.created", "session.deleted"].includes(raw.type)
1211
1316
  if ((!turnEnded && !lifecycleEvent) || typeof sessionID !== "string" || !sessionID) continue
1317
+ retryLedgerReleases()
1212
1318
  if (raw.type === "session.deleted") invalidatedSessions.add(sessionID)
1213
1319
  else if (raw.type === "session.created") invalidatedSessions.delete(sessionID)
1214
- if (raw.type === "session.created" || raw.type === "session.deleted") promptRoutes.delete(sessionID)
1320
+ if (raw.type === "session.created" || raw.type === "session.deleted") {
1321
+ releaseSessionLedger(sessionID)
1322
+ promptRoutes.delete(sessionID)
1323
+ }
1215
1324
  const prompt = promptRoutes.get(sessionID)
1216
1325
  if (turnEnded && prompt?.status === "resolved") {
1217
1326
  trackPending(() => observeOpenCodeCompletion(sessionID, ctx, promptRoutes, events.signal))
@@ -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.56.0",
4
+ "version": "0.57.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": "0.56.0",
3
+ "version": "0.57.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": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "harness-everything",
3
- "version": "0.56.0",
3
+ "version": "0.57.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",