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
@@ -108,6 +108,18 @@
108
108
  "statusMessage": "Recording local Harness skill telemetry"
109
109
  }
110
110
  ]
111
+ },
112
+ {
113
+ "matcher": "Bash",
114
+ "hooks": [
115
+ {
116
+ "type": "command",
117
+ "command": "node \"${PLUGIN_ROOT}/hooks/scripts/codex-ledger-lesson.js\"",
118
+ "commandWindows": "node \"${PLUGIN_ROOT}\\hooks\\scripts\\codex-ledger-lesson.js\"",
119
+ "timeout": 10,
120
+ "statusMessage": "Checking relevant workspace lessons"
121
+ }
122
+ ]
111
123
  }
112
124
  ],
113
125
  "PermissionRequest": [
@@ -213,6 +225,18 @@
213
225
  "statusMessage": "Recording a local System One turn observation"
214
226
  }
215
227
  ]
228
+ },
229
+ {
230
+ "matcher": "Bash",
231
+ "hooks": [
232
+ {
233
+ "type": "command",
234
+ "command": "node \"${PLUGIN_ROOT}/hooks/scripts/codex-ledger-lesson.js\"",
235
+ "commandWindows": "node \"${PLUGIN_ROOT}\\hooks\\scripts\\codex-ledger-lesson.js\"",
236
+ "timeout": 10,
237
+ "statusMessage": "Checking relevant workspace lessons"
238
+ }
239
+ ]
216
240
  }
217
241
  ],
218
242
  "SubagentStart": [
@@ -0,0 +1,82 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const path = require('node:path');
5
+ const { getWorkspaceRoot, getSessionDir, getSessionId, resolveWorkspaceIdentity } = require('./lib/harness-state');
6
+ const { readCodexToolOutcome } = require('./lib/codex-tool-outcome');
7
+ const { matchLedgerLessons, releaseLedgerMatch } = require('./lib/ledger-match');
8
+
9
+ const MAX_INPUT_BYTES = 128 * 1024;
10
+
11
+ function eventFor(payload) {
12
+ if (payload?.tool_name !== 'Bash' || typeof payload?.tool_input?.command !== 'string') return null;
13
+ const command = payload.tool_input.command;
14
+ if (payload.hook_event_name === 'PreToolUse') {
15
+ return { phase: 'action', tool: 'shell', command, outcome: { failed: 'unknown' } };
16
+ }
17
+ if (payload.hook_event_name !== 'PostToolUse') return null;
18
+
19
+ const result = readCodexToolOutcome(payload);
20
+ const failed = result.outcome === 'failure' ? true : result.outcome === 'success' ? false : 'unknown';
21
+ const outcome = { failed };
22
+ if (failed === true) outcome.output = [result.stderr, result.stdout].filter(Boolean).join('\n');
23
+ return { phase: 'failure', tool: 'shell', command, outcome };
24
+ }
25
+
26
+ function deliver(payload) {
27
+ if (typeof payload?.cwd !== 'string' || !payload.cwd.trim()) return;
28
+ const event = eventFor(payload);
29
+ const sessionIdentity = getSessionId(payload);
30
+ if (!event || !sessionIdentity) return;
31
+
32
+ const workspaceRoot = getWorkspaceRoot(payload);
33
+ const identity = resolveWorkspaceIdentity(payload);
34
+ if (!workspaceRoot || !identity?.workspaceKey) return;
35
+ const stateDir = path.join(getSessionDir(workspaceRoot, sessionIdentity, payload), 'ledger-lessons');
36
+ const result = matchLedgerLessons({
37
+ workspaceRoot,
38
+ workspaceIdentity: identity.workspaceKey,
39
+ sessionIdentity,
40
+ stateDir,
41
+ event,
42
+ });
43
+ if (!result) return;
44
+
45
+ try {
46
+ const output = JSON.stringify({
47
+ hookSpecificOutput: {
48
+ hookEventName: payload.hook_event_name,
49
+ additionalContext: result.text,
50
+ },
51
+ });
52
+ process.stdout.write(output, error => {
53
+ if (error) releaseLedgerMatch(result);
54
+ });
55
+ } catch (_) {
56
+ releaseLedgerMatch(result);
57
+ }
58
+ }
59
+
60
+ function run() {
61
+ let input = '';
62
+ let bytes = 0;
63
+ let oversized = false;
64
+ process.stdin.setEncoding('utf8');
65
+ process.stdin.on('data', chunk => {
66
+ if (oversized) return;
67
+ bytes += Buffer.byteLength(chunk, 'utf8');
68
+ if (bytes > MAX_INPUT_BYTES) {
69
+ input = '';
70
+ oversized = true;
71
+ return;
72
+ }
73
+ input += chunk;
74
+ });
75
+ process.stdin.on('end', () => {
76
+ if (oversized) return;
77
+ try { deliver(JSON.parse(input || '{}')); } catch (_) { /* Fail open without changing tool flow. */ }
78
+ });
79
+ process.stdin.on('error', () => {});
80
+ }
81
+
82
+ if (require.main === module) run();
@@ -0,0 +1,94 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const path = require('node:path');
5
+
6
+ const MAX_INPUT_BYTES = 64 * 1024;
7
+ let state;
8
+ let matcher;
9
+ try {
10
+ state = require('./lib/harness-state');
11
+ matcher = require('./lib/ledger-match');
12
+ } catch (_) {
13
+ // Missing runtime pieces leave the host hook fail-open and silent.
14
+ }
15
+
16
+ let pending = null;
17
+ function releasePending() {
18
+ if (!pending) return;
19
+ try { matcher?.releaseLedgerMatch(pending); } catch (_) { /* fail open */ }
20
+ pending = null;
21
+ }
22
+
23
+ process.stdout.on('error', releasePending);
24
+
25
+ function handle(payload) {
26
+ try {
27
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload) || !state || !matcher) return;
28
+ const hookEventName = payload.hook_event_name;
29
+ const phase = hookEventName === 'PreToolUse' ? 'action'
30
+ : hookEventName === 'PostToolUseFailure' ? 'failure' : null;
31
+ if (!phase || payload.tool_name !== 'Bash') return;
32
+ if (typeof payload.cwd !== 'string' || !path.isAbsolute(payload.cwd)) return;
33
+
34
+ const sessionIdentity = state.getSessionId(payload);
35
+ const command = typeof payload.tool_input_command === 'string' ? payload.tool_input_command
36
+ : typeof payload.tool_input?.command === 'string' ? payload.tool_input.command : null;
37
+ if (!sessionIdentity || !command) return;
38
+
39
+ const workspace = state.resolveWorkspaceIdentity(payload);
40
+ if (!workspace.workspaceRoot || !workspace.workspaceKey) return;
41
+ const sessionDir = state.getSessionDir(workspace.workspaceRoot, sessionIdentity, payload);
42
+ const result = matcher.matchLedgerLessons({
43
+ workspaceRoot: workspace.workspaceRoot,
44
+ workspaceIdentity: workspace.workspaceKey,
45
+ sessionIdentity,
46
+ stateDir: path.join(sessionDir, 'ledger-lessons'),
47
+ event: {
48
+ phase,
49
+ tool: 'shell',
50
+ command,
51
+ outcome: phase === 'failure'
52
+ ? { failed: true, ...(typeof payload.error === 'string' ? { output: payload.error } : {}) }
53
+ : { failed: 'unknown' }
54
+ }
55
+ });
56
+ if (!result) return;
57
+
58
+ pending = result;
59
+ process.stdout.write(`${JSON.stringify({
60
+ hookSpecificOutput: { hookEventName, additionalContext: result.text }
61
+ })}\n`, error => {
62
+ if (error) releasePending();
63
+ else pending = null;
64
+ });
65
+ } catch (_) {
66
+ releasePending();
67
+ }
68
+ }
69
+
70
+ let input = '';
71
+ let inputBytes = 0;
72
+ let oversized = false;
73
+ let finished = false;
74
+
75
+ function finish() {
76
+ if (finished) return;
77
+ finished = true;
78
+ if (oversized) return;
79
+ try { handle(JSON.parse(input)); } catch (_) { /* malformed payloads are silent */ }
80
+ }
81
+
82
+ process.stdin.setEncoding('utf8');
83
+ process.stdin.on('data', chunk => {
84
+ if (oversized) return;
85
+ inputBytes += Buffer.byteLength(chunk, 'utf8');
86
+ if (inputBytes > MAX_INPUT_BYTES) {
87
+ oversized = true;
88
+ input = '';
89
+ return;
90
+ }
91
+ input += chunk;
92
+ });
93
+ process.stdin.on('end', finish);
94
+ process.stdin.on('error', finish);
@@ -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 };
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
3
3
  "name": "harness-everything",
4
- "version": "0.56.0",
4
+ "version": "0.57.0",
5
5
  "description": "Invariant-first engineering harness for routing, verification, and failure recovery while preserving agent autonomy.",
6
6
  "author": {
7
7
  "name": "Miya Daniel",