harness-everything 0.56.1 → 0.57.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/CHANGELOG.md +22 -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/mechanism-394-claude-ledger-lesson.test.js +176 -0
  17. package/ci/mechanism-394-codex-ledger-lesson.test.js +203 -0
  18. package/ci/mechanism-394-ledger-match.test.js +521 -0
  19. package/ci/mechanism-394-opencode-ledger-lesson.test.js +232 -0
  20. package/ci/mechanism-errors-sync-root.test.js +86 -4
  21. package/docs/adr/ROUTE-001-error-lesson-delivery.md +52 -49
  22. package/docs/governed-index.md +1 -1
  23. package/docs/platform-capabilities.md +4 -0
  24. package/hooks/hooks.json +22 -0
  25. package/hooks/scripts/codex-ledger-lesson.js +82 -0
  26. package/hooks/scripts/ledger-lesson.js +94 -0
  27. package/hooks/scripts/lib/ledger-match.js +452 -0
  28. package/opencode-plugin/index.mjs +113 -4
  29. package/opencode-plugin/plugin.json +1 -1
  30. package/package.json +1 -1
  31. package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
  32. package/plugins/harness-everything/hooks/hooks.json +24 -0
  33. package/plugins/harness-everything/hooks/scripts/codex-ledger-lesson.js +82 -0
  34. package/plugins/harness-everything/hooks/scripts/ledger-lesson.js +94 -0
  35. package/plugins/harness-everything/hooks/scripts/lib/ledger-match.js +452 -0
  36. package/plugins/harness-everything/plugin.json +1 -1
  37. package/sbom.cdx.json +7 -7
  38. package/scripts/errors-sync.js +63 -2
@@ -0,0 +1,232 @@
1
+ 'use strict';
2
+
3
+ const assert = require('node:assert/strict');
4
+ const fs = require('node:fs');
5
+ const os = require('node:os');
6
+ const path = require('node:path');
7
+ const { spawnSync } = require('node:child_process');
8
+ const { pathToFileURL } = require('node:url');
9
+ const { test } = require('node:test');
10
+
11
+ const ROOT = path.resolve(__dirname, '..');
12
+ const PLUGIN = path.join(ROOT, 'opencode-plugin', 'index.mjs');
13
+ const LEDGER = path.join(ROOT, '.agents', 'harness-everything', 'errors');
14
+ const ERRORS_SYNC = path.join(ROOT, 'scripts', 'errors-sync.js');
15
+ const COMMITLINT = fs.readFileSync(path.join(__dirname, 'fixtures/394-ledger-match/commitlint-subject-case.txt'), 'utf8');
16
+ const OLD_ENV = Object.fromEntries(['HOME', 'USERPROFILE', 'HARNESS_STATE_HOME', 'HARNESS_TELEMETRY', 'HARNESS_SYSTEM_ONE_MODE']
17
+ .map(key => [key, process.env[key]]));
18
+ const TMP = fs.mkdtempSync(path.join(os.tmpdir(), 'mechanism-394-opencode-ledger-'));
19
+
20
+ function isOutside(root, target) {
21
+ const relative = path.relative(root, target);
22
+ return relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative);
23
+ }
24
+
25
+ function addLedger(workspace) {
26
+ const target = path.join(workspace, '.agents', 'harness-everything', 'errors');
27
+ fs.cpSync(LEDGER, target, { recursive: true });
28
+ const generated = spawnSync(process.execPath, [ERRORS_SYNC, '--root', workspace], { cwd: ROOT, encoding: 'utf8' });
29
+ assert.equal(generated.status, 0, generated.stderr);
30
+ }
31
+
32
+ function packagePlugin() {
33
+ const installed = path.join(TMP, 'opencode-install');
34
+ const pluginDir = path.join(installed, 'plugins');
35
+ fs.mkdirSync(pluginDir, { recursive: true });
36
+ fs.copyFileSync(PLUGIN, path.join(pluginDir, 'harness-enforcement.mjs'));
37
+ for (const relative of [
38
+ 'harness-everything/scripts/kernel-router.js',
39
+ 'hooks/scripts/lib/observations.js',
40
+ 'hooks/scripts/lib/ledger-match.js',
41
+ 'hooks/scripts/lib/harness-state.js',
42
+ 'scripts/lib/workspace.js',
43
+ ]) {
44
+ const destination = path.join(installed, relative);
45
+ fs.mkdirSync(path.dirname(destination), { recursive: true });
46
+ fs.copyFileSync(path.join(ROOT, relative), destination);
47
+ }
48
+ fs.cpSync(path.join(ROOT, 'hooks/scripts/lib/platforms'), path.join(installed, 'hooks/scripts/lib/platforms'), { recursive: true });
49
+ return path.join(pluginDir, 'harness-enforcement.mjs');
50
+ }
51
+
52
+ function createV2Context(sessionWorkspaces, pluginFile = PLUGIN) {
53
+ const toolHooks = new Map();
54
+ const sessionHooks = new Map();
55
+ const eventQueue = [];
56
+ let eventWaiter;
57
+ let currentEvent;
58
+ const ctx = {
59
+ location: { directory: ROOT },
60
+ tool: { hook: async (name, callback) => { toolHooks.set(name, callback); return { dispose: async () => {} }; } },
61
+ session: {
62
+ get: async ({ sessionID }) => ({ id: sessionID, location: { directory: sessionWorkspaces[sessionID] } }),
63
+ hook: async (name, callback) => { sessionHooks.set(name, callback); return { dispose: async () => {} }; },
64
+ prompt: async () => ({}),
65
+ context: async () => [],
66
+ },
67
+ event: {
68
+ subscribe: ({ signal }) => ({
69
+ [Symbol.asyncIterator]() {
70
+ return {
71
+ next: () => {
72
+ currentEvent?.resolve();
73
+ currentEvent = null;
74
+ if (eventQueue.length) {
75
+ currentEvent = eventQueue.shift();
76
+ return Promise.resolve({ value: currentEvent.event, done: false });
77
+ }
78
+ if (signal.aborted) return Promise.resolve({ done: true });
79
+ return new Promise(resolve => {
80
+ eventWaiter = resolve;
81
+ signal.addEventListener('abort', () => resolve({ done: true }), { once: true });
82
+ });
83
+ },
84
+ };
85
+ },
86
+ }),
87
+ },
88
+ };
89
+ return import(pathToFileURL(pluginFile).href).then(async mod => ({
90
+ toolHooks,
91
+ sessionHooks,
92
+ pushEvent: event => new Promise(resolve => {
93
+ const item = { event, resolve };
94
+ if (eventWaiter) {
95
+ currentEvent = item;
96
+ eventWaiter({ value: event, done: false });
97
+ eventWaiter = null;
98
+ } else eventQueue.push(item);
99
+ }),
100
+ dispose: await mod.default.setup(ctx),
101
+ }));
102
+ }
103
+
104
+ async function toolCall(harness, sessionID, id, status = 'completed', output = 'ok', exit = 0) {
105
+ const command = 'git commit -m "docs(errors): Bad Case"';
106
+ const before = { tool: 'bash', sessionID, agent: 'build', messageID: `message-${id}`, id, input: { command } };
107
+ const beforeSnapshot = structuredClone(before);
108
+ assert.equal(await harness.toolHooks.get('execute.before')(before), undefined);
109
+ assert.deepEqual(before, beforeSnapshot, 'execute.before does not change the tool request');
110
+
111
+ const after = {
112
+ ...before,
113
+ status,
114
+ ...(status === 'error'
115
+ ? { error: { name: 'ToolError', message: output } }
116
+ : { result: { output, metadata: { exit } } }),
117
+ };
118
+ const afterSnapshot = structuredClone(after);
119
+ assert.equal(await harness.toolHooks.get('execute.after')(after), undefined);
120
+ assert.deepEqual(after, afterSnapshot, 'execute.after does not change the host tool result');
121
+ }
122
+
123
+ async function context(harness, sessionID, base = 'base system') {
124
+ const event = { sessionID, kind: 'primary', system: [{ type: 'text', text: base }] };
125
+ await harness.sessionHooks.get('context')(event);
126
+ return event.system.map(part => part.text || '').join('\n');
127
+ }
128
+
129
+ test.after(() => {
130
+ for (const [key, value] of Object.entries(OLD_ENV)) {
131
+ if (value === undefined) delete process.env[key];
132
+ else process.env[key] = value;
133
+ }
134
+ fs.rmSync(TMP, { recursive: true, force: true });
135
+ });
136
+
137
+ test('OpenCode V2 carries real ledger matches through the source and packaged context hooks', async () => {
138
+ assert.ok(isOutside(ROOT, TMP), 'fixture state must stay outside the repository');
139
+ const home = path.join(TMP, 'home');
140
+ const workspace = path.join(TMP, 'workspace');
141
+ const otherWorkspace = path.join(TMP, 'other-workspace');
142
+ const emptyWorkspace = path.join(TMP, 'empty-workspace');
143
+ fs.mkdirSync(home, { recursive: true });
144
+ fs.mkdirSync(workspace, { recursive: true });
145
+ fs.mkdirSync(otherWorkspace, { recursive: true });
146
+ fs.mkdirSync(emptyWorkspace, { recursive: true });
147
+ addLedger(workspace);
148
+ addLedger(otherWorkspace);
149
+ process.env.HOME = home;
150
+ process.env.USERPROFILE = home;
151
+ process.env.HARNESS_STATE_HOME = path.join(TMP, 'harness-state');
152
+ process.env.HARNESS_TELEMETRY = 'off';
153
+ delete process.env.HARNESS_SYSTEM_ONE_MODE;
154
+
155
+ const sessionWorkspaces = {
156
+ same: workspace,
157
+ other: workspace,
158
+ separateWorkspace: otherWorkspace,
159
+ noLedger: emptyWorkspace,
160
+ disposal: workspace,
161
+ sessionCleanup: workspace,
162
+ };
163
+ const harness = await createV2Context(sessionWorkspaces);
164
+ const command = 'git -C x commit -m "docs(errors): Bad Case"';
165
+ try {
166
+ assert.ok(harness.toolHooks.has('execute.before') && harness.toolHooks.has('execute.after'));
167
+ assert.ok(harness.sessionHooks.has('context'));
168
+ assert.equal(harness.toolHooks.size, 2, 'the carrier registers no permission hook or additional tool gate');
169
+
170
+ const before = { tool: 'bash', sessionID: 'same', agent: 'build', messageID: 'message-same', id: 'same-action', input: { command } };
171
+ const beforeSnapshot = structuredClone(before);
172
+ assert.equal(await harness.toolHooks.get('execute.before')(before), undefined);
173
+ assert.deepEqual(before, beforeSnapshot);
174
+
175
+ const failure = {
176
+ ...before,
177
+ status: 'error',
178
+ error: { name: 'ToolError', message: COMMITLINT },
179
+ };
180
+ const failureSnapshot = structuredClone(failure);
181
+ assert.equal(await harness.toolHooks.get('execute.after')(failure), undefined);
182
+ assert.deepEqual(failure, failureSnapshot, 'the failed shell result remains untouched');
183
+
184
+ const wrongSessionSystem = [{ type: 'text', text: 'base system' }];
185
+ await harness.sessionHooks.get('context')({ sessionID: 'other', kind: 'primary', system: wrongSessionSystem });
186
+ assert.deepEqual(wrongSessionSystem, [{ type: 'text', text: 'base system' }], 'a pending lesson stays bound to its session');
187
+
188
+ const delivered = await context(harness, 'same');
189
+ assert.equal((delivered.match(/Cue:\n/g) || []).length, 2,
190
+ 'action selection runs in execute.before and failure selection in execute.after; both arrive at the next model request');
191
+ assert.match(delivered, /subject-case/);
192
+ assert.equal(await context(harness, 'same'), 'base system', 'a delivered phase is not replayed on another context build');
193
+
194
+ await toolCall(harness, 'other', 'other-action', 'completed', COMMITLINT, 0);
195
+ assert.equal((await context(harness, 'other')).match(/Cue:\n/g)?.length, 1,
196
+ 'diagnostic text with a zero exit remains action-only in a second session');
197
+
198
+ await toolCall(harness, 'separateWorkspace', 'workspace-action', 'completed', COMMITLINT, 1);
199
+ assert.equal((await context(harness, 'separateWorkspace')).match(/Cue:\n/g)?.length, 2,
200
+ 'a completed tool result with nonzero metadata.exit and captured diagnostics selects failure too');
201
+
202
+ await toolCall(harness, 'noLedger', 'no-ledger-action');
203
+ assert.equal(await context(harness, 'noLedger'), 'base system', 'an unrelated workspace without a ledger is silent');
204
+
205
+ await toolCall(harness, 'sessionCleanup', 'session-cleanup-action');
206
+ const state = require(path.join(ROOT, 'hooks/scripts/lib/harness-state.js'));
207
+ const sessionState = state.getSessionDir(workspace, 'sessionCleanup', { workspace_root: workspace, session_id: 'sessionCleanup', host_id: 'opencode' });
208
+ const claims = fs.readdirSync(sessionState).filter(file => file.endsWith('.claim'));
209
+ assert.equal(claims.length, 1);
210
+ await harness.pushEvent({ type: 'session.deleted', sessionID: 'sessionCleanup' });
211
+ assert.ok(claims.every(file => !fs.existsSync(path.join(sessionState, file))),
212
+ 'session invalidation releases an undelivered matcher reservation');
213
+
214
+ await harness.toolHooks.get('execute.before')({
215
+ tool: 'bash', sessionID: 'disposal', agent: 'build', messageID: 'message-disposal', id: 'pending-action', input: { command },
216
+ });
217
+ } finally {
218
+ await harness.dispose();
219
+ }
220
+
221
+ const packaged = await createV2Context(sessionWorkspaces, packagePlugin());
222
+ try {
223
+ await packaged.toolHooks.get('execute.before')({
224
+ tool: 'bash', sessionID: 'disposal', agent: 'build', messageID: 'message-disposal-2', id: 'pending-action-2', input: { command },
225
+ });
226
+ const packagedDelivery = await context(packaged, 'disposal');
227
+ assert.match(packagedDelivery, /subject-case/,
228
+ 'disposing the prior carrier releases an undelivered claim, and the packaged loader resolves the shared matcher');
229
+ } finally {
230
+ await packaged.dispose();
231
+ }
232
+ });
@@ -57,6 +57,87 @@ function seedLedger(name) {
57
57
  return { root, dir, index: path.join(dir, 'index.jsonl'), record: path.join(dir, 'E-0001-root-test.md') };
58
58
  }
59
59
 
60
+ const ACTION_RULE = { tool: 'shell', executable: 'git', subcommand: 'commit' };
61
+
62
+ function recordWithMatch(match) {
63
+ const metadata = { id: 'E-0003', signature: 'schema-test', class: 'test', scope: 'in', status: 'lesson', match };
64
+ return `---\n${JSON.stringify(metadata)}\n---\nA schema fixture.\n`;
65
+ }
66
+
67
+ let invalidMatchNumber = 0;
68
+ function assertInvalidMatch(label, match) {
69
+ const root = path.join(temp, `invalid match ${++invalidMatchNumber}`);
70
+ const dir = path.join(root, '.agents', 'harness-everything', 'errors');
71
+ const record = 'E-0003-schema-test.md';
72
+ fs.mkdirSync(dir, { recursive: true });
73
+ fs.writeFileSync(path.join(dir, record), recordWithMatch(match));
74
+
75
+ const result = invoke(['--root', root]);
76
+ assert.notEqual(result.status, 0, `${label}: errors:sync rejects malformed match data`);
77
+ assert.ok(result.stderr.includes(record), `${label}: errors:sync names the malformed record: ${result.stderr}`);
78
+ assert.equal(fs.existsSync(path.join(dir, 'index.jsonl')), false, `${label}: malformed data does not publish an index`);
79
+ }
80
+
81
+ function assertMatchSchema() {
82
+ const rows = render().trimEnd().split('\n').map(JSON.parse);
83
+ const e3 = rows.find(row => row.id === 'E-0003');
84
+ assert.deepEqual(e3.match, {
85
+ actions: [ACTION_RULE],
86
+ failures: [{ ...ACTION_RULE, diagnostics: ['subject-case', 'header-max-length', 'type-empty', 'subject-empty'] }],
87
+ }, 'the real E-0003 row carries both match rule lists');
88
+ const e3Text = fs.readFileSync(path.join(ROOT, e3.file), 'utf8');
89
+ const rawFrontmatter = /^---\r?\n([\s\S]*?)\r?\n---/.exec(e3Text)[1].replace(/\r\n?/g, '\n');
90
+ const expectedBinding = crypto.createHash('sha256').update(JSON.stringify([
91
+ rawFrontmatter, e3.id, e3.signature, e3.file, e3.match
92
+ ])).digest('hex');
93
+ assert.equal(e3.matchBinding, expectedBinding, 'the binding hashes normalized raw frontmatter and the generated rule row');
94
+ assert.equal(Object.hasOwn(rows.find(row => row.id === 'E-0001'), 'match'), false,
95
+ 'records without match keep the field absent');
96
+
97
+ const boundaryRoot = path.join(temp, 'match boundary repo');
98
+ const boundaryDir = path.join(boundaryRoot, '.agents', 'harness-everything', 'errors');
99
+ fs.mkdirSync(boundaryDir, { recursive: true });
100
+ const boundaryMatch = {
101
+ actions: Array.from({ length: 8 }, (_, i) => ({
102
+ tool: 'shell', executable: i === 0 ? 'a'.repeat(64) : 'git', subcommand: i === 0 ? 'c' : `cmd${i}`,
103
+ })),
104
+ failures: Array.from({ length: 8 }, (_, i) => ({
105
+ ...ACTION_RULE,
106
+ subcommand: `cmd${i}`,
107
+ diagnostics: i === 0 ? Array.from({ length: 16 }, (_, j) => `diag-${j}`) : ['x'],
108
+ })),
109
+ };
110
+ fs.writeFileSync(path.join(boundaryDir, 'E-0003-schema-test.md'), recordWithMatch(boundaryMatch));
111
+ assert.deepEqual(JSON.parse(render(boundaryRoot).trim()).match, boundaryMatch,
112
+ 'schema accepts the 1/64-character, 8-rule, and 16-diagnostic boundaries');
113
+
114
+ const failure = (overrides = {}) => ({ ...ACTION_RULE, ...overrides });
115
+ const malformed = [
116
+ ['match mapping', null],
117
+ ['match has a supported field', { actions: [ACTION_RULE], unknown: [] }],
118
+ ['match contains actions or failures', {}],
119
+ ['actions is an array', { actions: ACTION_RULE }],
120
+ ['actions has at least one rule', { actions: [] }],
121
+ ['actions has at most eight rules', { actions: Array(9).fill(ACTION_RULE) }],
122
+ ['action rule is a mapping', { actions: ['git'] }],
123
+ ['action rule has exact keys', { actions: [failure({ extra: true })] }],
124
+ ['action tool is shell', { actions: [failure({ tool: 'git' })] }],
125
+ ['executable is lowercase', { actions: [failure({ executable: 'Git' })] }],
126
+ ['subcommand is a literal id', { actions: [failure({ subcommand: 'commit --amend' })] }],
127
+ ['literal id is at most 64 characters', { actions: [failure({ executable: 'a'.repeat(65) })] }],
128
+ ['failures is an array', { failures: ACTION_RULE }],
129
+ ['failures has at least one rule', { failures: [] }],
130
+ ['failures has at most eight rules', { failures: Array(9).fill({ ...ACTION_RULE, diagnostics: ['subject-case'] }) }],
131
+ ['failure rule has exact keys', { failures: [{ ...ACTION_RULE, diagnostics: ['subject-case'], extra: true }] }],
132
+ ['failure rule requires diagnostics', { failures: [ACTION_RULE] }],
133
+ ['diagnostics has 1 to 16 values', { failures: [{ ...ACTION_RULE, diagnostics: [] }] }],
134
+ ['diagnostics has at most 16 values', { failures: [{ ...ACTION_RULE, diagnostics: Array(17).fill('x') }] }],
135
+ ['diagnostics are unique', { failures: [{ ...ACTION_RULE, diagnostics: ['type-empty', 'type-empty'] }] }],
136
+ ['diagnostics are lowercase literal ids', { failures: [{ ...ACTION_RULE, diagnostics: ['Subject-Case'] }] }],
137
+ ];
138
+ for (const [label, match] of malformed) assertInvalidMatch(label, match);
139
+ }
140
+
60
141
  function assertUnsafeRefused(target, unchanged, tempDirs) {
61
142
  const before = unchanged.map(snapshot);
62
143
  const harnessBefore = fs.readFileSync(HARNESS_INDEX);
@@ -75,9 +156,10 @@ function assertUnsafeRefused(target, unchanged, tempDirs) {
75
156
 
76
157
  try {
77
158
  const harnessIndexDigest = digest(HARNESS_INDEX);
78
- const harnessIndex = fs.readFileSync(HARNESS_INDEX, 'utf8');
79
- assert.equal(invoke(['--check']).status, 0, 'the no-root Harness check is the regression control');
80
- assert.equal(render(), harnessIndex, 'render() defaults to the current Harness root');
159
+ assertMatchSchema();
160
+ const generatedControl = seedLedger('generated check control');
161
+ assert.equal(invoke(['--check', '--root', generatedControl.root]).status, 0,
162
+ 'errors-sync --check validates a generated temporary ledger');
81
163
  assert.ok(targetRoot.includes(' '), 'the target root must contain a space');
82
164
  assert.equal(isWithin(ROOT, targetRoot), false, 'the temporary target must stay outside the Harness root');
83
165
 
@@ -116,7 +198,7 @@ try {
116
198
  fs.copyFileSync(SCRIPT, isolatedScript);
117
199
  const isolatedInvoke = args => invokeScript(isolatedScript, args, isolatedDefault.root, {
118
200
  ...process.env,
119
- NODE_PATH: [path.join(ROOT, 'node_modules'), process.env.NODE_PATH].filter(Boolean).join(path.delimiter),
201
+ NODE_PATH: [...require.resolve.paths('js-yaml'), process.env.NODE_PATH].filter(Boolean).join(path.delimiter),
120
202
  });
121
203
  assert.equal(isolatedInvoke(['--check']).status, 0, 'no-root check uses its isolated default ledger');
122
204
  fs.writeFileSync(isolatedDefault.index, 'deliberately stale default ledger\n');
@@ -1,12 +1,14 @@
1
1
  ---
2
2
  id: ROUTE-001
3
- status: proposed
3
+ status: superseded
4
4
  ---
5
5
 
6
6
  # ROUTE-001 — Error lesson delivery into active-step context
7
7
 
8
- **This is a design ADR for a mechanism that is not shipped.** Nothing in this repository is modified
9
- by this document; the follow-up implementation it defines does not exist yet. This ADR does **not** claim:
8
+ > **Superseded (2026-11-21).** The E-0002 delivery design below is no longer the governing design. Owner decision [#394 comment 7062351415](https://github.com/dyphn1/Harness-everything/issues/394#issuecomment-7062351415) supersedes it; E-0002 is now owned by the C4 report writer shipped in [#462](https://github.com/dyphn1/Harness-everything/pull/462), and the Rule-of-3 breaker it carved out around was retired in [#494](https://github.com/dyphn1/Harness-everything/pull/494). Obsolete design is struck through; the enduring policy and historical evidence remain unstruck.
9
+
10
+ ~~**This is a design ADR for a mechanism that is not shipped.** Nothing in this repository is modified
11
+ by this document; the follow-up implementation it defines does not exist yet.~~ This ADR does **not** claim:
10
12
 
11
13
  - that error handling improved, or that any behavior changed (no paired evidence exists);
12
14
  - that the chosen error class is closed or its recurrence prevented;
@@ -19,7 +21,7 @@ by this document; the follow-up implementation it defines does not exist yet. Th
19
21
 
20
22
  ## Decision
21
23
 
22
- - **Chosen error class: `E-0002` (`report-protocol` — reports ending without a plain column-zero
24
+ - ~~**Chosen error class: `E-0002` (`report-protocol` — reports ending without a plain column-zero
23
25
  terminal `STATUS` line).** The generated ledger index has no rank field; E-0002 is not the most
24
26
  frequent class (E-0009 has 7 episodes, E-0002 and E-0003 have 5 each — counts freshly verified by
25
27
  `node scripts/errors-sync.js --check` at this SHA). E-0002 is chosen because it fits #402's stated
@@ -28,7 +30,7 @@ by this document; the follow-up implementation it defines does not exist yet. Th
28
30
  `425-review2-label-after-status` (2026-11-11) occurred *after* the lesson existed, in packets that did
29
31
  not state the terminal-line condition. Sources:
30
32
  [#402 comment 6785928296](https://github.com/dyphn1/Harness-everything/issues/402#issuecomment-6785928296);
31
- `.agents/harness-everything/errors/E-0002-report-missing-terminal-status.md`.
33
+ `.agents/harness-everything/errors/E-0002-report-missing-terminal-status.md`.~~
32
34
  - **The existing ledger lesson (carried verbatim, not restated):** every report ends with one plain
33
35
  column-zero `STATUS: DONE` or `STATUS: BLOCKED: <reason>` line; when a host rule also requires a
34
36
  trailing line, the packet must state which line is terminal. The E-0002 record file is the content
@@ -44,14 +46,16 @@ by this document; the follow-up implementation it defines does not exist yet. Th
44
46
  | `SONE` | System One domain; this decision does not change System One provider or routing internals |
45
47
  | `DIST` | Distribution domain; this decision changes no packaging or distribution behavior |
46
48
 
47
- - **Delivery channel: prompt context at `UserPromptSubmit`, through the existing `additionalContext`
49
+ - ~~**Delivery channel: prompt context at `UserPromptSubmit`, through the existing `additionalContext`
48
50
  seam (owner ruling A7.1).** No new hook file, no second router. On Claude Code the router already runs
49
51
  at `UserPromptSubmit` (`hooks/hooks.json`, id `harness:pre:kernel-router`); on Codex,
50
52
  `hooks/scripts/codex-user-prompt.js` pipes the whole hook payload to the router and wraps its stdout as
51
53
  JSON `hookSpecificOutput.additionalContext` (`plugins/harness-everything/hooks/hooks.json`), because
52
54
  Codex adds prompt-time context to the model only from that JSON field
53
55
  ([system-one-observations.md](../system-one-observations.md#hosts)). The lesson rides in the context the
54
- seam already sends; the hook stays a **context carrier, not a decision maker** (A2).
56
+ seam already sends;~~ the hook stays a **context carrier, not a decision maker** (A2).
57
+
58
+ ### Mermaid flow (superseded, historical)
55
59
 
56
60
  ```mermaid
57
61
  flowchart LR
@@ -64,7 +68,7 @@ flowchart LR
64
68
  W --> O["Observation: the report file's raw<br/>final line is column-zero STATUS —<br/>or it is not"]
65
69
  ```
66
70
 
67
- - **Relevance: an explicit report-required signal selects the E-0002 record only (owner ruling A7.2).**
71
+ - ~~**Relevance: an explicit report-required signal selects the E-0002 record only (owner ruling A7.2).**
68
72
  The signal is defined concretely:
69
73
  - *Source:* the prompt text of the `UserPromptSubmit` payload — `payload.prompt`, which the router
70
74
  already reads (`harness-everything/scripts/kernel-router.js`: `const prompt = promptArg ||
@@ -84,19 +88,18 @@ flowchart LR
84
88
  (`activeExecutionFor` → `activeStepSnapshot`) — defined only when a retained workflow with a loaded
85
89
  obligation set exists, so it covers a subset of report work through a second selection surface; and
86
90
  agent-side grep of the index at task start — no code change but depends on agent discipline, the
87
- failure mode the ledger README already records.
88
-
91
+ failure mode the ledger README already records.~~
89
92
  - **Label vs STATUS (owner ruling A7.4), stated as decided:**
90
93
  - A report **file** ends with its raw column-zero `STATUS:` line and carries no harness-label; the
91
94
  **turn's** final message summarises or links the report and ends with the hidden harness-label line
92
95
  (`docs/routing.md` § Turn label line).
93
- - When the report *is* the turn's final message, the rule is a **report-turn exception to
96
+ - ~~When the report *is* the turn's final message, the rule is a **report-turn exception to
94
97
  label-last**. That exception is owned by `AGENTS.md` (applicability) and `docs/routing.md` (label
95
- contract); making it is a follow-up change, **not made here** — those files are not edited by this ADR.
98
+ contract); making it is a follow-up change, **not made here** — those files are not edited by this ADR.~~
96
99
  - E-0002's recorded episodes (including the label-after-status ones) stay as history; a
97
100
  provenance-carrying correction of the lesson text is **#359's** follow-up. This ADR does not rewrite
98
101
  the ledger record.
99
- - **Success / failure observation, in three layers that are never merged into one PASS:**
102
+ - **Success / failure observation, in three layers that are never merged into one PASS:** *(historical E-0002 example)*
100
103
 
101
104
  | Layer | What is recorded | What is not claimed |
102
105
  | --- | --- | --- |
@@ -108,25 +111,25 @@ flowchart LR
108
111
  nonconformant. Neither is recorded as a single PASS.
109
112
  - Any later behavior-improvement claim requires paired baseline/treatment evidence; this ADR's
110
113
  observation contract does not provide it.
111
- - **Smallest follow-up implementation acceptance (design only; nothing is implemented here):** one seam
114
+ - ~~**Smallest follow-up implementation acceptance (design only; nothing is implemented here):** one seam
112
115
  (the `UserPromptSubmit` context assembly above), one minimal change (signal match ⇒ read
113
116
  `.agents/harness-everything/errors/E-0002-report-missing-terminal-status.md` § Lesson and append it
114
- verbatim to the existing context), with these controls:
117
+ verbatim to the existing context), with these controls:~~
115
118
 
116
- | Control | Expected result | Evidence layer the check gives |
119
+ | ~~Control~~ | ~~Expected result~~ | ~~Evidence layer the check gives~~ |
117
120
  | --- | --- | --- |
118
- | No marker in the prompt | No injection; context identical to today | Deterministic mechanism test |
119
- | Marker present, record readable | The exact E-0002 lesson text delivered in context | Deterministic mechanism test, then one real-host task for receipt |
120
- | Marker present, record unreadable or source stale | Delivery unavailable; tools stay usable; no fallback to the whole ledger | Deterministic mechanism test |
121
- | Report produced | Final line conformant or not, recorded per the observation table | One real-host task (one-run outcome) |
121
+ | ~~No marker in the prompt~~ | ~~No injection; context identical to today~~ | ~~Deterministic mechanism test~~ |
122
+ | ~~Marker present, record readable~~ | ~~The exact E-0002 lesson text delivered in context~~ | ~~Deterministic mechanism test, then one real-host task for receipt~~ |
123
+ | ~~Marker present, record unreadable or source stale~~ | ~~Delivery unavailable; tools stay usable; no fallback to the whole ledger~~ | ~~Deterministic mechanism test~~ |
124
+ | ~~Report produced~~ | ~~Final line conformant or not, recorded per the observation table~~ | ~~One real-host task (one-run outcome)~~ |
122
125
 
123
126
  - Explicitly forbidden: no fallback to the whole ledger, no fabricated receipt, no automatic rewrite of
124
127
  the report, no error counter, no fixed recurrence threshold, no reflection tokens, no forced report,
125
128
  no mutation lock, no automatic escalation or reset ritual (A2).
126
- - Host evidence boundary: only the host seam chosen here (`UserPromptSubmit` context on Claude Code and
129
+ - ~~Host evidence boundary: only the host seam chosen here (`UserPromptSubmit` context on Claude Code and
127
130
  Codex) is covered by future checks. Other hosts and other lifecycle events are unverified; a file
128
- existing in a package proves no host loaded it ([platform-capabilities.md](../platform-capabilities.md)).
129
- - **Rule-of-3 boundary (owner ruling A7.5), stated exactly:** this cycle's lesson delivery adds, extends,
131
+ existing in a package proves no host loaded it ([platform-capabilities.md](../platform-capabilities.md)).~~
132
+ - ~~**Rule-of-3 boundary (owner ruling A7.5), stated exactly:** this cycle's lesson delivery adds, extends,
130
133
  calls or depends on **no counter, lock or forced reflection**; the existing Rule-of-3 breaker
131
134
  (`hooks/scripts/rule-of-3.js` `isTripped`/`blockForReflection`, `hooks/scripts/rule-of-3-tracker.js`,
132
135
  `hooks/scripts/reset-circuit-breaker.js`, [docs/enforcement-locks.md](../enforcement-locks.md)) is not
@@ -138,7 +141,7 @@ flowchart LR
138
141
  own separate Rule-of-3 breaker (`opencode-plugin/index.mjs` — an independent counter, required
139
142
  reflection, block on the covered edit tools), which this delivery neither uses nor modifies and which
140
143
  this ADR does not claim conforms to A2. The OpenCode sources are reading-list evidence only: they do not
141
- mean OpenCode was run and do not extend the hosts the lesson injection supports.
144
+ mean OpenCode was run and do not extend the hosts the lesson injection supports.~~
142
145
  - **Non-goals (from A2 and the ownership boundary):** the hook stays a context carrier, not a decision
143
146
  maker; this ADR does not duplicate #359 (Error Ledger), #394 (ledger context injection and
144
147
  agent-initiated zoom-out) or #141 (candidate creation/evaluation); candidate creation/evaluation
@@ -150,7 +153,7 @@ flowchart LR
150
153
 
151
154
  - **The problem:** agent mistakes recur even when a lesson is already recorded in the ledger — the
152
155
  recording-to-application gap [#402 comment 6785928296](https://github.com/dyphn1/Harness-everything/issues/402#issuecomment-6785928296).
153
- - **What exists today (each verified in this repository):**
156
+ - **What exists ~~today~~ (each verified in this repository):**
154
157
  - the ledger and generated index (`.agents/harness-everything/errors/README.md`, `index.jsonl`,
155
158
  `E-*.md`) with a lookup convention (grep by write-set or signature); a convention, not a gate;
156
159
  - hook context seams that carry *policy and routing* context but do not retrieve ledger records:
@@ -164,22 +167,22 @@ flowchart LR
164
167
  `self-evolve/scripts/lesson-candidate.js`);
165
168
  - zoom-out and self-evolve skills as agent-initiated reflection/evaluation paths (`zoom-out/SKILL.md`,
166
169
  `self-evolve/SKILL.md`).
167
- - No ledger-aware delivery seam exists today.
168
- - **What zoom-out carries today (correction):** when an agent enters a repair-loop reflection, the
170
+ - ~~No ledger-aware delivery seam exists today.~~
171
+ - ~~**What zoom-out carries today (correction):** when an agent enters a repair-loop reflection, the
169
172
  carried material is the acceptance anchor, links to the previous comparable report, prior finding IDs
170
173
  and dispositions, the fix made since, and round counts per class in the error ledger
171
174
  (`zoom-out/references/circuit-breaker.md`). It does **not** carry the static ledger lesson text; no
172
- current seam delivers the E-0002 record.
175
+ current seam delivers the E-0002 record.~~
173
176
  - **Ownership boundary:** #359 owns the Error Ledger; #394 owns ledger context injection and
174
177
  agent-initiated zoom-out; #141 owns candidate creation/evaluation
175
178
  ([#402 comment 6785928296](https://github.com/dyphn1/Harness-everything/issues/402#issuecomment-6785928296)).
176
- **Unverified:** current tracker state of #394 (no #394-specific implementation found on local `main`).
179
+ ~~**Unverified:** current tracker state of #394 (no #394-specific implementation found on local `main`).~~
177
180
 
178
181
  ## Evidence
179
182
 
180
183
  - **E-0002 episode table** (counts freshly verified by `node scripts/errors-sync.js --check`, exit 0, at
181
184
  this SHA) drawn from `.agents/harness-everything/errors/E-0002-report-missing-terminal-status.md` and
182
- its index row:
185
+ its index row: *(historical)*
183
186
 
184
187
  | Episode | Date | Rounds | Closed |
185
188
  | --- | --- | --- | --- |
@@ -201,20 +204,20 @@ flowchart LR
201
204
  - **The rule conflict witness:** episode `412-review13-label-after-status` (a column-zero
202
205
  `STATUS: DONE` followed by a hidden harness-label line) as the concrete observation that motivates the
203
206
  label/STATUS decision above.
204
- - **Candidate-class context:** the index has 14 records; only E-0003 carries a non-null `mechanism_ref`
205
- (`.husky/commit-msg`). E-0002 has `mechanism_ref: null`.
207
+ - ~~**Candidate-class context:** the index has 14 records; only E-0003 carries a non-null `mechanism_ref`
208
+ (`.husky/commit-msg`). E-0002 has `mechanism_ref: null`.~~
206
209
 
207
210
  ## Open gates
208
211
 
209
- - **Owner acceptance of this ADR** (`status: proposed`); the follow-up implementation and its
210
- verification (deterministic mechanism tests, then one real-host task) are not started.
211
- - **`AGENTS.md` / `docs/routing.md` wording change** for the report-turn exception to label-last (A7.4)
212
- is a follow-up owned by those files; not made here.
213
- - **A provenance-carrying correction of the E-0002 lesson text** is a #359 follow-up.
214
- - **Whether A2 requires a separate change to the existing Rule-of-3 breaker** — separate item outside
215
- this ADR, unresolved for its owner (A7.5).
216
- - **#394 tracker state** is unverified against the tracker; no #394-specific implementation exists on
217
- local `main`.
212
+ - ~~**Owner acceptance of this ADR** (`status: proposed`); the follow-up implementation and its
213
+ verification (deterministic mechanism tests, then one real-host task) are not started.~~
214
+ - ~~**`AGENTS.md` / `docs/routing.md` wording change** for the report-turn exception to label-last (A7.4)
215
+ is a follow-up owned by those files; not made here.~~
216
+ - ~~**A provenance-carrying correction of the E-0002 lesson text** is a #359 follow-up.~~
217
+ - ~~**Whether A2 requires a separate change to the existing Rule-of-3 breaker** — separate item outside
218
+ this ADR, unresolved for its owner (A7.5).~~
219
+ - ~~**#394 tracker state** is unverified against the tracker; no #394-specific implementation exists on
220
+ local `main`.~~
218
221
 
219
222
  ## Reading list
220
223
 
@@ -285,21 +288,21 @@ Decision rests on. One line each.
285
288
  - **`AGENTS.md` rule 14 / `docs/routing.md` vs the E-0002 terminal rule:** the repository requires a
286
289
  trailing hidden harness-label line on every final message; the ledger lesson requires `STATUS:` to be
287
290
  the last line at column zero. Episode `412-review13-label-after-status` records the conflict. This ADR
288
- states the A7.4 decision and its report-turn exception, but the wording change in `AGENTS.md` and
289
- `docs/routing.md` is a follow-up; until it lands, the conflict stands as written.
290
- - **Existing generic Rule-of-3 lock vs A2:** `hooks/scripts/rule-of-3.js` and
291
+ states the A7.4 decision and its report-turn exception, ~~but the wording change in `AGENTS.md` and
292
+ `docs/routing.md` is a follow-up; until it lands, the conflict stands as written.~~
293
+ - ~~**Existing generic Rule-of-3 lock vs A2:** `hooks/scripts/rule-of-3.js` and
291
294
  [docs/enforcement-locks.md](../enforcement-locks.md) describe a generic three-failure mutation lock with
292
295
  a required reflection report; #402 prohibits exactly such mechanisms for ledger lesson handling. This
293
296
  ADR adds, extends, calls or depends on none of them and does not modify the breaker; whether A2 requires
294
297
  a separate change to the existing breaker stays unresolved for its owner. The OpenCode plugin's separate
295
298
  breaker (`opencode-plugin/index.mjs`, [opencode-plugin/README.md](../../opencode-plugin/README.md)) is
296
- likewise neither used nor modified by this delivery, and this ADR does not claim it conforms to A2.
299
+ likewise neither used nor modified by this delivery, and this ADR does not claim it conforms to A2.~~
297
300
  - **Ledger README lookup rule vs the owner's full-read standard:** the README says grep `index.jsonl` for
298
301
  the packet's write-set; the owner standard requires reading every record. Injecting one record does not
299
302
  change that operational standard for packets.
300
- - **#394 point-of-action proposals vs shipped code:** E-0002 and E-0003 propose point-of-action injection
301
- in #394, but no #394-specific implementation exists on local `main` (**unverified** against the tracker).
302
- - **Index freshness:** `scripts/errors-sync.js` is not wired into CI or hooks (its own source comment), so
303
- the index can be stale; this design never injects index content — the E-0002 record file is the content
303
+ - ~~**#394 point-of-action proposals vs shipped code:** E-0002 and E-0003 propose point-of-action injection
304
+ in #394, but no #394-specific implementation exists on local `main` (**unverified** against the tracker).~~
305
+ - **Index freshness:** ~~`scripts/errors-sync.js` is not wired into CI or hooks (its own source comment), so
306
+ the index can be stale;~~ this design never injects index content — the E-0002 record file is the content
304
307
  authority and the index is a locator. Counts cited in this ADR were verified by
305
308
  `node scripts/errors-sync.js --check` at this SHA.
@@ -13,7 +13,7 @@
13
13
  - `DOCS-007` — `docs/adr/DOCS-007-shared-doc-craft-derived-views.md` (role: adr; status: accepted)
14
14
  - `DOCS-008` — `docs/adr/DOCS-008-obligation-abstraction-bounded-consumer.md` (role: adr; status: accepted)
15
15
  - `EVID-001` — `docs/adr/EVID-001.md` (role: adr; status: proposed)
16
- - `ROUTE-001` — `docs/adr/ROUTE-001-error-lesson-delivery.md` (role: adr; status: proposed)
16
+ - `ROUTE-001` — `docs/adr/ROUTE-001-error-lesson-delivery.md` (role: adr; status: superseded)
17
17
 
18
18
  ## PRD revision chains
19
19
 
@@ -64,6 +64,10 @@ The registered `doc-check check --conflict-assessment` mode runs document lifecy
64
64
 
65
65
  Source and packaged plugin self-evolve entrypoints use installation-relative canonical workspace helpers and the same workspace/session state path. Missing helpers, unresolved identities, and unusable state paths fail explicitly; only absent candidate directories yield an empty list. The [resolver contract](../self-evolve/references/memory-resolution.md#workspace-helper-and-diagnostics) and source/package subprocess regressions establish deterministic mechanism coverage, not a live-host upgrade. Existing memory authorization remains required.
66
66
 
67
+ ### Error-ledger lesson injection (mechanism only, #394)
68
+
69
+ A shared matcher (`hooks/scripts/lib/ledger-match.js`) selects workspace ledger lessons whose `match` rules fit a direct `git commit` action (optionally after `-C`, `-c`, `--git-dir=`, `--work-tree=`, `--no-pager` or `-P`; compound and wrapped commands stay silent, #502) or its commitlint failure; rules are read from the generated index row and checked against the record's frontmatter binding, and the host carriers add the record's Cue and Lesson as model context: Claude Code `PreToolUse` and `PostToolUseFailure` (`hooks/scripts/ledger-lesson.js`), Codex `PreToolUse` and `PostToolUse` with outcome classification (`hooks/scripts/codex-ledger-lesson.js`, packaged and user-hook compatibility paths), and OpenCode V2 tool `execute.before/after` selection delivered through the next `context` hook, i.e. after the action. The OpenCode V1 adapter does not register `experimental.chat.system.transform` (`output.system`). V1 lesson delivery is `UNCHECKED`. Delivery is bounded, deduplicated per session and phase, fail-open, and never changes a tool result or permission. Deterministic mechanism tests cover all three carriers. [Claude Code live evidence](../benchmarks/results/live-host/claude-2026-11-21-ledger-lesson/README.md) (2.1.330, one run) shows both contexts in the model request that follows the commit, so the action lesson arrives after the first attempt. Codex and OpenCode live receipt remain `UNCHECKED`.
70
+
67
71
  ## Current capability summary
68
72
 
69
73
  | Platform surface | Standalone skills | Plugin support | Hooks/lifecycle | Project scope | Global scope | Current evidence boundary |
package/hooks/hooks.json CHANGED
@@ -123,6 +123,17 @@
123
123
  ],
124
124
  "description": "Record privacy-safe Harness skill load start telemetry",
125
125
  "id": "harness:pre:skill-telemetry"
126
+ },
127
+ {
128
+ "matcher": "Bash",
129
+ "hooks": [
130
+ {
131
+ "type": "command",
132
+ "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/scripts/ledger-lesson.js\""
133
+ }
134
+ ],
135
+ "description": "Inject a matched workspace ledger lesson as fail-open Bash context",
136
+ "id": "harness:pre:ledger-lesson"
126
137
  }
127
138
  ],
128
139
  "Stop": [
@@ -309,6 +320,17 @@
309
320
  ],
310
321
  "description": "Record a local, content-private System One turn observation (docs/system-one-observations.md); fail-open and silent",
311
322
  "id": "harness:obs:observation-posttoolusefailure"
323
+ },
324
+ {
325
+ "matcher": "Bash",
326
+ "hooks": [
327
+ {
328
+ "type": "command",
329
+ "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/scripts/ledger-lesson.js\""
330
+ }
331
+ ],
332
+ "description": "Inject a matched workspace ledger lesson after a failed Bash tool",
333
+ "id": "harness:post-failure:ledger-lesson"
312
334
  }
313
335
  ],
314
336
  "SubagentStart": [