harness-everything 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/CHANGELOG.md +21 -0
  4. package/ci/mechanism-394-ledger-match.test.js +324 -3
  5. package/ci/mechanism-496-claude-capture.test.js +342 -0
  6. package/ci/mechanism-496-codex-capture.test.js +508 -0
  7. package/ci/mechanism-496-local-error-cli-edges.test.js +234 -0
  8. package/ci/mechanism-496-local-error-cli.test.js +517 -0
  9. package/ci/mechanism-496-local-error-store.test.js +731 -0
  10. package/ci/mechanism-496-opencode-capture.test.js +483 -0
  11. package/ci/mechanism-496-review-fixes.test.js +278 -0
  12. package/ci/mechanism-516-agy-post-tool-exit.test.js +472 -0
  13. package/ci/mechanism-516-agy-stop-revision.test.js +215 -0
  14. package/hooks/scripts/agy-post-tool.js +79 -16
  15. package/hooks/scripts/agy-stop.js +63 -10
  16. package/hooks/scripts/codex-ledger-lesson.js +103 -27
  17. package/hooks/scripts/ledger-lesson.js +94 -23
  18. package/hooks/scripts/lib/ledger-match.js +169 -21
  19. package/hooks/scripts/lib/local-error-source.js +127 -0
  20. package/hooks/scripts/lib/local-errors.js +597 -0
  21. package/hooks/scripts/lib/observations.js +1 -1
  22. package/hooks/scripts/state-persist.js +7 -1
  23. package/opencode-plugin/index.mjs +86 -1
  24. package/opencode-plugin/plugin.json +1 -1
  25. package/package.json +2 -1
  26. package/plugins/harness-everything/.antigravity-plugin/plugin.json +1 -1
  27. package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
  28. package/plugins/harness-everything/hooks/scripts/agy-post-tool.js +79 -16
  29. package/plugins/harness-everything/hooks/scripts/agy-stop.js +63 -10
  30. package/plugins/harness-everything/hooks/scripts/codex-ledger-lesson.js +103 -27
  31. package/plugins/harness-everything/hooks/scripts/ledger-lesson.js +94 -23
  32. package/plugins/harness-everything/hooks/scripts/lib/ledger-match.js +169 -21
  33. package/plugins/harness-everything/hooks/scripts/lib/local-error-source.js +127 -0
  34. package/plugins/harness-everything/hooks/scripts/lib/local-errors.js +597 -0
  35. package/plugins/harness-everything/hooks/scripts/lib/observations.js +1 -1
  36. package/plugins/harness-everything/hooks/scripts/state-persist.js +7 -1
  37. package/plugins/harness-everything/plugin.json +1 -1
  38. package/sbom.cdx.json +7 -7
  39. package/scripts/errors-local.js +357 -0
@@ -0,0 +1,483 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const assert = require('node:assert/strict');
5
+ const { spawnSync } = require('node:child_process');
6
+ const fs = require('node:fs');
7
+ const os = require('node:os');
8
+ const path = require('node:path');
9
+ const test = require('node:test');
10
+ const { createV2Driver } = require('./lib/opencode-v2-driver');
11
+
12
+ const ROOT = path.resolve(__dirname, '..');
13
+ const PLUGIN = path.join(ROOT, 'opencode-plugin', 'index.mjs');
14
+ const ERRORS_SYNC = path.join(ROOT, 'scripts', 'errors-sync.js');
15
+ const ERRORS_LOCAL = path.join(ROOT, 'scripts', 'errors-local.js');
16
+ const LEDGER = path.join(ROOT, '.agents', 'harness-everything', 'errors');
17
+ const E3_FILE = fs.readdirSync(LEDGER).find(file => /^E-0003-[a-z0-9-]+\.md$/.test(file));
18
+ const COMMITLINT_OUTPUT = fs.readFileSync(
19
+ path.join(__dirname, 'fixtures/394-ledger-match/commitlint-subject-case.txt'),
20
+ 'utf8'
21
+ );
22
+
23
+ const ENV_KEYS = [
24
+ 'HOME', 'USERPROFILE', 'HARNESS_STATE_HOME', 'HARNESS_OBSERVATIONS_DIR',
25
+ 'HARNESS_OBSERVATIONS', 'HARNESS_TELEMETRY', 'HARNESS_SYSTEM_ONE_MODE',
26
+ 'CLAUDE_PROJECT_DIR', 'CODEX_PROJECT_DIR', 'HARNESS_WORKSPACE_ROOT', 'FABLE_WORKSPACE_ROOT',
27
+ ];
28
+ const OLD_ENV = Object.fromEntries(ENV_KEYS.map(key => [key, process.env[key]]));
29
+
30
+ // E-0011: canonicalize temp root with realpathSync.native to expand Windows 8.3 short paths.
31
+ const TMP = fs.realpathSync.native(fs.mkdtempSync(path.join(os.tmpdir(), '496-opencode-capture-')));
32
+ let serial = 0;
33
+
34
+ function isOutside(root, target) {
35
+ const rel = path.relative(root, target);
36
+ return rel === '..' || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel);
37
+ }
38
+
39
+ test.after(() => {
40
+ for (const [key, value] of Object.entries(OLD_ENV)) {
41
+ if (value === undefined) delete process.env[key];
42
+ else process.env[key] = value;
43
+ }
44
+ fs.rmSync(TMP, { recursive: true, force: true });
45
+ });
46
+
47
+ function newCaseWorkspace(name, { withLedger = true } = {}) {
48
+ const caseDir = path.join(TMP, `${name}-${++serial}`);
49
+ const workspaceRoot = path.join(caseDir, 'workspace');
50
+ const homeDir = path.join(caseDir, 'home');
51
+ const stateHome = path.join(caseDir, 'state-home');
52
+ const obsDir = path.join(caseDir, 'observations');
53
+ fs.mkdirSync(workspaceRoot, { recursive: true });
54
+ fs.mkdirSync(homeDir, { recursive: true });
55
+ fs.mkdirSync(stateHome, { recursive: true });
56
+ if (withLedger) {
57
+ const ledgerDir = path.join(workspaceRoot, '.agents', 'harness-everything', 'errors');
58
+ fs.mkdirSync(ledgerDir, { recursive: true });
59
+ fs.copyFileSync(path.join(LEDGER, E3_FILE), path.join(ledgerDir, E3_FILE));
60
+ const synced = spawnSync(process.execPath, [ERRORS_SYNC, '--root', workspaceRoot], {
61
+ cwd: ROOT,
62
+ encoding: 'utf8',
63
+ });
64
+ assert.equal(synced.status, 0, synced.stderr || 'errors-sync should succeed');
65
+ }
66
+ const env = {
67
+ ...process.env,
68
+ HOME: homeDir,
69
+ USERPROFILE: homeDir,
70
+ HARNESS_STATE_HOME: stateHome,
71
+ HARNESS_OBSERVATIONS_DIR: obsDir,
72
+ HARNESS_OBSERVATIONS: 'off',
73
+ HARNESS_TELEMETRY: 'off',
74
+ };
75
+ delete env.HARNESS_SYSTEM_ONE_MODE;
76
+ delete env.CLAUDE_PROJECT_DIR;
77
+ delete env.CODEX_PROJECT_DIR;
78
+ delete env.HARNESS_WORKSPACE_ROOT;
79
+ delete env.FABLE_WORKSPACE_ROOT;
80
+ return { caseDir, workspaceRoot, homeDir, stateHome, obsDir, env };
81
+ }
82
+
83
+ function applyCaseEnv(ctx) {
84
+ process.env.HOME = ctx.homeDir;
85
+ process.env.USERPROFILE = ctx.homeDir;
86
+ process.env.HARNESS_STATE_HOME = ctx.stateHome;
87
+ process.env.HARNESS_OBSERVATIONS_DIR = ctx.obsDir;
88
+ process.env.HARNESS_OBSERVATIONS = 'off';
89
+ process.env.HARNESS_TELEMETRY = 'off';
90
+ delete process.env.HARNESS_SYSTEM_ONE_MODE;
91
+ delete process.env.CLAUDE_PROJECT_DIR;
92
+ delete process.env.CODEX_PROJECT_DIR;
93
+ delete process.env.HARNESS_WORKSPACE_ROOT;
94
+ delete process.env.FABLE_WORKSPACE_ROOT;
95
+ }
96
+
97
+ function runCli(args, cwd, env) {
98
+ return spawnSync(process.execPath, [ERRORS_LOCAL, ...args], {
99
+ cwd,
100
+ env,
101
+ encoding: 'utf8',
102
+ });
103
+ }
104
+
105
+ function listRecords(workspaceRoot, env, extraArgs = []) {
106
+ const res = runCli(['list', '--json', ...extraArgs], workspaceRoot, env);
107
+ assert.equal(res.status, 0, res.stderr || 'errors-local list should exit 0');
108
+ return JSON.parse(res.stdout);
109
+ }
110
+
111
+ function packagePlugin(name, { includeLocalErrors = true } = {}) {
112
+ const installed = path.join(TMP, `packaged-${name}-${++serial}`);
113
+ const pluginDir = path.join(installed, 'plugins');
114
+ fs.mkdirSync(pluginDir, { recursive: true });
115
+ fs.copyFileSync(PLUGIN, path.join(pluginDir, 'harness-enforcement.mjs'));
116
+ const files = [
117
+ 'harness-everything/scripts/kernel-router.js',
118
+ 'hooks/scripts/lib/observations.js',
119
+ 'hooks/scripts/lib/ledger-match.js',
120
+ 'hooks/scripts/lib/harness-state.js',
121
+ 'scripts/lib/workspace.js',
122
+ ...(includeLocalErrors
123
+ ? [
124
+ 'hooks/scripts/lib/local-errors.js',
125
+ 'hooks/scripts/lib/local-error-source.js',
126
+ ]
127
+ : []),
128
+ ];
129
+ for (const rel of files) {
130
+ const destination = path.join(installed, rel);
131
+ fs.mkdirSync(path.dirname(destination), { recursive: true });
132
+ fs.copyFileSync(path.join(ROOT, rel), destination);
133
+ }
134
+ fs.cpSync(
135
+ path.join(ROOT, 'hooks/scripts/lib/platforms'),
136
+ path.join(installed, 'hooks/scripts/lib/platforms'),
137
+ { recursive: true }
138
+ );
139
+ return path.join(pluginDir, 'harness-enforcement.mjs');
140
+ }
141
+
142
+ async function readContext(driver, sessionID, base = 'base system') {
143
+ const event = { sessionID, kind: 'primary', system: [{ type: 'text', text: base }] };
144
+ await driver.sessionHook('context')(event);
145
+ return event.system.map(part => part.text || '').join('\n');
146
+ }
147
+
148
+ async function runWithDriver(ctx, fn, { plugin } = {}) {
149
+ const driver = await createV2Driver({
150
+ workspace: ctx.workspaceRoot,
151
+ ...(plugin ? { plugin } : {}),
152
+ });
153
+ applyCaseEnv(ctx);
154
+ try {
155
+ return await fn(driver);
156
+ } finally {
157
+ await driver.teardown();
158
+ }
159
+ }
160
+
161
+ test('Row 1: confirmed failure captures one redacted occurrence with matchedLedgerIds (error status and nonzero metadata.exit)', async () => {
162
+ assert.ok(isOutside(ROOT, TMP), 'fixture state must stay outside the repository');
163
+
164
+ // Case 1a: status === 'error' on bash tool
165
+ const ctxA = newCaseWorkspace('confirmed-error');
166
+ const secretPath = path.join(ctxA.homeDir, 'private-project', 'secret.txt');
167
+ const errorWithHome = `${COMMITLINT_OUTPUT}\nsee ${secretPath}\n`;
168
+ await runWithDriver(ctxA, async driver => {
169
+ const after = {
170
+ tool: 'bash',
171
+ sessionID: 'sess-e2e-a',
172
+ agent: 'build',
173
+ messageID: 'msg-a',
174
+ id: 'call-e2e-a',
175
+ input: { command: 'git commit -m "Bad Subject"' },
176
+ status: 'error',
177
+ error: { name: 'ToolError', message: errorWithHome },
178
+ };
179
+ const snapshot = structuredClone(after);
180
+ assert.equal(await driver.toolHook('execute.after')(after), undefined);
181
+ assert.deepEqual(after, snapshot, 'execute.after must not mutate the host tool event');
182
+
183
+ const delivered = await readContext(driver, 'sess-e2e-a');
184
+ assert.match(delivered, /Check the subject line against both rules/);
185
+ });
186
+
187
+ const recordsA = listRecords(ctxA.workspaceRoot, ctxA.env);
188
+ assert.equal(recordsA.length, 1, 'exactly one occurrence row captured');
189
+ const rowA = recordsA[0];
190
+ assert.equal(rowA.kind, 'occurrence');
191
+ assert.equal(rowA.host, 'opencode');
192
+ assert.equal(rowA.destination, 'unknown');
193
+ assert.equal(rowA.commandClass, 'git');
194
+ assert.equal(rowA.exitCode, null);
195
+ assert.ok(rowA.sessionKey && !rowA.sessionKey.includes('sess-e2e-a'), 'sessionKey is opaque');
196
+ assert.ok(rowA.toolUseId && !rowA.toolUseId.includes('call-e2e-a'), 'toolUseId is opaque');
197
+ assert.ok(rowA.outputExcerpt.includes('<home>'), 'home path is redacted in outputExcerpt');
198
+ assert.ok(!rowA.outputExcerpt.includes(ctxA.homeDir), 'raw home path is not stored in outputExcerpt');
199
+ assert.ok(rowA.matchedLedgerIds.includes('E-0003'), `matchedLedgerIds should include E-0003, got ${JSON.stringify(rowA.matchedLedgerIds)}`);
200
+
201
+ // Case 1b: live OpenCode 2.1.4 shell shape (status === 'completed', finite nonzero metadata.exit)
202
+ const ctxB = newCaseWorkspace('confirmed-nonzero-exit');
203
+ const secretPathB = path.join(ctxB.homeDir, 'private-project', 'secret.txt');
204
+ const outputWithHome = `${COMMITLINT_OUTPUT}\nsee ${secretPathB}\n`;
205
+ await runWithDriver(ctxB, async driver => {
206
+ const after = {
207
+ tool: 'shell',
208
+ sessionID: 'sess-e2e-b',
209
+ agent: 'build',
210
+ messageID: 'msg-b',
211
+ id: 'call-e2e-b',
212
+ input: { command: 'git -C x commit -m "docs(errors): Bad Case"', workdir: ctxB.workspaceRoot },
213
+ status: 'completed',
214
+ result: {
215
+ output: { exit: 1, truncated: false, output: outputWithHome, status: 'completed' },
216
+ content: [{ type: 'text', text: outputWithHome }],
217
+ metadata: { status: 'completed', truncated: false, exit: 1 },
218
+ },
219
+ };
220
+ const snapshot = structuredClone(after);
221
+ assert.equal(await driver.toolHook('execute.after')(after), undefined);
222
+ assert.deepEqual(after, snapshot, 'execute.after must not mutate live shell tool result');
223
+ });
224
+
225
+ const recordsB = listRecords(ctxB.workspaceRoot, ctxB.env);
226
+ assert.equal(recordsB.length, 1, 'nonzero metadata.exit captures one occurrence row');
227
+ assert.equal(recordsB[0].host, 'opencode');
228
+ assert.equal(recordsB[0].exitCode, 1);
229
+ assert.equal(recordsB[0].commandClass, 'git');
230
+ assert.ok(recordsB[0].outputExcerpt.includes('<home>'));
231
+ assert.ok(!recordsB[0].outputExcerpt.includes(ctxB.homeDir));
232
+ assert.ok(recordsB[0].matchedLedgerIds.includes('E-0003'));
233
+ });
234
+
235
+ test('Row 2: CLI-added provisional lesson is injected on next action event (labelled provisional, no counts)', async () => {
236
+ const ctx = newCaseWorkspace('provisional-action', { withLedger: false });
237
+ const lessonText = 'Run npm run build before npm test in this project';
238
+
239
+ const addRes = runCli(
240
+ [
241
+ 'add',
242
+ '--executable', 'npm',
243
+ '--subcommand', 'test',
244
+ '--lesson', lessonText,
245
+ '--destination', 'project',
246
+ ],
247
+ ctx.workspaceRoot,
248
+ ctx.env
249
+ );
250
+ assert.equal(addRes.status, 0, addRes.stderr || 'errors-local add exits 0');
251
+
252
+ await runWithDriver(ctx, async driver => {
253
+ const before = {
254
+ tool: 'bash',
255
+ sessionID: 'sess-prov',
256
+ agent: 'build',
257
+ messageID: 'msg-prov',
258
+ id: 'call-prov',
259
+ input: { command: 'npm test' },
260
+ };
261
+ const snapshot = structuredClone(before);
262
+ assert.equal(await driver.toolHook('execute.before')(before), undefined);
263
+ assert.deepEqual(before, snapshot, 'execute.before must not mutate the tool request');
264
+
265
+ const delivered = await readContext(driver, 'sess-prov');
266
+ assert.ok(delivered.includes(lessonText), 'injected context contains provisional lesson text');
267
+ assert.match(delivered, /provisional/i, 'injected context labels lesson as provisional');
268
+ assert.doesNotMatch(delivered, /\b\d+\s*(?:times?|occurrences?|count|failures?)\b/i, 'no counts injected in lesson text');
269
+ });
270
+
271
+ // Action event must not capture an occurrence row.
272
+ assert.equal(listRecords(ctx.workspaceRoot, ctx.env, ['--kind', 'occurrence']).length, 0);
273
+ });
274
+
275
+ test('Row 3: unknown/zero outcomes and masked-failure exception do not capture; confirmed failure with no output still captures', async () => {
276
+ const ctx = newCaseWorkspace('outcomes');
277
+
278
+ await runWithDriver(ctx, async driver => {
279
+ // Action event -> no row
280
+ await driver.toolHook('execute.before')({
281
+ tool: 'bash',
282
+ sessionID: 'sess-outcomes',
283
+ agent: 'build',
284
+ messageID: 'msg-1',
285
+ id: 'call-before',
286
+ input: { command: 'git commit -m "Bad Subject"' },
287
+ });
288
+
289
+ // Zero exit -> no row
290
+ await driver.toolHook('execute.after')({
291
+ tool: 'bash',
292
+ sessionID: 'sess-outcomes',
293
+ agent: 'build',
294
+ messageID: 'msg-2',
295
+ id: 'call-zero',
296
+ input: { command: 'git commit -m "Bad Subject"' },
297
+ status: 'completed',
298
+ result: { output: COMMITLINT_OUTPUT, metadata: { exit: 0 } },
299
+ });
300
+
301
+ // Masked-failure compound command with exit 0 -> reminder still fires, but NO capture row
302
+ await driver.toolHook('execute.after')({
303
+ tool: 'bash',
304
+ sessionID: 'sess-masked',
305
+ agent: 'build',
306
+ messageID: 'msg-3',
307
+ id: 'call-masked',
308
+ input: { command: 'git commit -m "Bad Subject"; echo "$?"' },
309
+ status: 'completed',
310
+ result: { output: COMMITLINT_OUTPUT, metadata: { exit: 0 } },
311
+ });
312
+ const maskedContext = await readContext(driver, 'sess-masked');
313
+ assert.match(maskedContext, /subject-case/, 'masked-failure reminder behavior stays intact');
314
+
315
+ // Unknown exit (metadata.exit absent) -> no row
316
+ await driver.toolHook('execute.after')({
317
+ tool: 'bash',
318
+ sessionID: 'sess-outcomes',
319
+ agent: 'build',
320
+ messageID: 'msg-4',
321
+ id: 'call-unknown',
322
+ input: { command: 'git commit -m "Bad Subject"' },
323
+ status: 'completed',
324
+ result: { output: COMMITLINT_OUTPUT, metadata: {} },
325
+ });
326
+
327
+ // Non-shell tool error -> no row
328
+ await driver.toolHook('execute.after')({
329
+ tool: 'write',
330
+ sessionID: 'sess-outcomes',
331
+ agent: 'build',
332
+ messageID: 'msg-5',
333
+ id: 'call-write-err',
334
+ input: { command: 'git commit -m "Bad Subject"' },
335
+ status: 'error',
336
+ error: { name: 'ToolError', message: 'disk full' },
337
+ });
338
+
339
+ assert.equal(listRecords(ctx.workspaceRoot, ctx.env).length, 0,
340
+ 'none of the negative controls created an occurrence row');
341
+
342
+ // Positive control 1: status === 'error' with no output at all -> 1 row
343
+ await driver.toolHook('execute.after')({
344
+ tool: 'bash',
345
+ sessionID: 'sess-outcomes',
346
+ agent: 'build',
347
+ messageID: 'msg-6',
348
+ id: 'call-err-no-output',
349
+ input: { command: 'npm test' },
350
+ status: 'error',
351
+ });
352
+ const afterErrNoOut = listRecords(ctx.workspaceRoot, ctx.env);
353
+ assert.equal(afterErrNoOut.length, 1, 'status=error with no output captures 1 row');
354
+ assert.equal(afterErrNoOut[0].exitCode, null);
355
+ assert.equal(afterErrNoOut[0].outputExcerpt, '');
356
+ assert.equal(afterErrNoOut[0].commandClass, 'test');
357
+
358
+ // Positive control 2: status === 'completed' with finite nonzero metadata.exit and no output -> 2nd row
359
+ await driver.toolHook('execute.after')({
360
+ tool: 'shell',
361
+ sessionID: 'sess-outcomes',
362
+ agent: 'build',
363
+ messageID: 'msg-7',
364
+ id: 'call-exit-no-output',
365
+ input: { command: 'npm run build' },
366
+ status: 'completed',
367
+ result: { metadata: { exit: 2 } },
368
+ });
369
+ const afterExitNoOut = listRecords(ctx.workspaceRoot, ctx.env);
370
+ assert.equal(afterExitNoOut.length, 2, 'nonzero metadata.exit with no output captures 2nd row');
371
+ assert.equal(afterExitNoOut[1].exitCode, 2);
372
+ assert.equal(afterExitNoOut[1].outputExcerpt, '');
373
+ assert.equal(afterExitNoOut[1].commandClass, 'build');
374
+ });
375
+ });
376
+
377
+ test('Row 4: unwritable store or missing modules leave injected context identical and do not throw', async () => {
378
+ const normalCtx = newCaseWorkspace('failopen-normal');
379
+ const blockedCtx = newCaseWorkspace('failopen-unwritable');
380
+ // Regular file at HARNESS_OBSERVATIONS_DIR causes store writes to fail on POSIX and Windows.
381
+ fs.writeFileSync(blockedCtx.obsDir, 'not-a-directory', 'utf8');
382
+
383
+ const eventFor = () => ({
384
+ tool: 'bash',
385
+ sessionID: 'sess-failopen',
386
+ agent: 'build',
387
+ messageID: 'msg-failopen',
388
+ id: 'call-failopen',
389
+ input: { command: 'git commit -m "Bad Subject"' },
390
+ status: 'error',
391
+ error: { name: 'ToolError', message: COMMITLINT_OUTPUT },
392
+ });
393
+
394
+ const normalContext = await runWithDriver(normalCtx, async driver => {
395
+ await driver.toolHook('execute.after')(eventFor());
396
+ return readContext(driver, 'sess-failopen');
397
+ });
398
+ const blockedContext = await runWithDriver(blockedCtx, async driver => {
399
+ await driver.toolHook('execute.after')(eventFor());
400
+ return readContext(driver, 'sess-failopen');
401
+ });
402
+
403
+ assert.match(normalContext, /Check the subject line against both rules/);
404
+ assert.equal(blockedContext, normalContext, 'unwritable store leaves injected context identical');
405
+ assert.equal(listRecords(normalCtx.workspaceRoot, normalCtx.env).length, 1, 'positive control captured 1 row');
406
+ assert.equal(listRecords(blockedCtx.workspaceRoot, blockedCtx.env).length, 0, 'blocked store captured 0 rows');
407
+
408
+ // Missing local-errors.js / local-error-source.js in a packaged plugin -> identical context, no throw.
409
+ const missingCtx = newCaseWorkspace('failopen-missing-mod');
410
+ const missingPlugin = packagePlugin('missing-local-errors', { includeLocalErrors: false });
411
+ const missingContext = await runWithDriver(missingCtx, async driver => {
412
+ await driver.toolHook('execute.after')(eventFor());
413
+ return readContext(driver, 'sess-failopen');
414
+ }, { plugin: missingPlugin });
415
+
416
+ assert.equal(missingContext, normalContext, 'missing local-error modules leave injected context identical');
417
+ assert.equal(listRecords(missingCtx.workspaceRoot, missingCtx.env).length, 0);
418
+
419
+ // Packaged plugin WITH local-errors.js / local-error-source.js -> captures AND delivers provisional lesson.
420
+ const packagedCtx = newCaseWorkspace('packaged-full');
421
+ const fullPlugin = packagePlugin('full-local-errors', { includeLocalErrors: true });
422
+ const addRes = runCli(
423
+ ['add', '--executable', 'npm', '--subcommand', 'test', '--lesson', 'Packaged provisional lesson', '--destination', 'project'],
424
+ packagedCtx.workspaceRoot,
425
+ packagedCtx.env
426
+ );
427
+ assert.equal(addRes.status, 0, addRes.stderr);
428
+
429
+ await runWithDriver(packagedCtx, async driver => {
430
+ await driver.toolHook('execute.before')({
431
+ tool: 'bash',
432
+ sessionID: 'sess-pkg',
433
+ agent: 'build',
434
+ messageID: 'msg-pkg-1',
435
+ id: 'call-pkg-1',
436
+ input: { command: 'npm test' },
437
+ });
438
+ const pkgActionCtx = await readContext(driver, 'sess-pkg');
439
+ assert.match(pkgActionCtx, /Packaged provisional lesson/);
440
+ assert.match(pkgActionCtx, /provisional/i);
441
+
442
+ await driver.toolHook('execute.after')(eventFor());
443
+ }, { plugin: fullPlugin });
444
+
445
+ const pkgOccurrences = listRecords(packagedCtx.workspaceRoot, packagedCtx.env, ['--kind', 'occurrence']);
446
+ assert.equal(pkgOccurrences.length, 1, 'packaged plugin captures occurrence');
447
+ assert.ok(pkgOccurrences[0].matchedLedgerIds.includes('E-0003'));
448
+ });
449
+
450
+ test('Row 5: same call id is idempotent; distinct call ids create two rows both with matchedLedgerIds', async () => {
451
+ const ctx = newCaseWorkspace('idempotency');
452
+
453
+ await runWithDriver(ctx, async driver => {
454
+ const baseEvent = {
455
+ tool: 'bash',
456
+ sessionID: 'sess-idem',
457
+ agent: 'build',
458
+ messageID: 'msg-idem',
459
+ input: { command: 'git commit -m "Bad Subject"' },
460
+ status: 'error',
461
+ error: { name: 'ToolError', message: COMMITLINT_OUTPUT },
462
+ };
463
+
464
+ // First failure: delivers lesson and captures 1 row.
465
+ await driver.toolHook('execute.after')({ ...baseEvent, id: 'call-same' });
466
+ const firstCtx = await readContext(driver, 'sess-idem');
467
+ assert.match(firstCtx, /Check the subject line against both rules/);
468
+
469
+ // Duplicate call id: delivery silent, still 1 row.
470
+ await driver.toolHook('execute.after')({ ...baseEvent, id: 'call-same' });
471
+ assert.equal(await readContext(driver, 'sess-idem'), 'base system', 'duplicate failure delivery is silent');
472
+ assert.equal(listRecords(ctx.workspaceRoot, ctx.env).length, 1, 'same call id is idempotent (1 row)');
473
+
474
+ // Distinct call id: delivery still silent (session already claimed), but 2nd row captured with matchedLedgerIds.
475
+ await driver.toolHook('execute.after')({ ...baseEvent, id: 'call-distinct' });
476
+ assert.equal(await readContext(driver, 'sess-idem'), 'base system', 'second distinct failure delivery is silent');
477
+
478
+ const records = listRecords(ctx.workspaceRoot, ctx.env);
479
+ assert.equal(records.length, 2, 'distinct call id creates a second row');
480
+ assert.ok(records[0].matchedLedgerIds.includes('E-0003'));
481
+ assert.ok(records[1].matchedLedgerIds.includes('E-0003'), 'second silent failure still records matchedLedgerIds');
482
+ });
483
+ });