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,731 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const assert = require('node:assert');
5
+ const fs = require('node:fs');
6
+ const os = require('node:os');
7
+ const path = require('node:path');
8
+ const { spawnSync, execFileSync } = require('node:child_process');
9
+
10
+ const ROOT = path.resolve(__dirname, '..');
11
+ const EXPORTER = path.join(ROOT, 'scripts', 'system-one-observations-export.js');
12
+ const observations = require(path.join(ROOT, 'hooks', 'scripts', 'lib', 'observations.js'));
13
+ const { matchLedgerLessons, validateMatch } = require(path.join(ROOT, 'hooks', 'scripts', 'lib', 'ledger-match.js'));
14
+ const localErrors = require(path.join(ROOT, 'hooks', 'scripts', 'lib', 'local-errors.js'));
15
+
16
+ let failures = 0;
17
+ function test(name, fn) {
18
+ try {
19
+ fn();
20
+ console.log(` PASS ${name}`);
21
+ } catch (error) {
22
+ failures += 1;
23
+ console.error(` FAIL ${name}\n ${error.stack.split('\n').slice(0, 4).join('\n ')}`);
24
+ }
25
+ }
26
+
27
+ function canonicalDir(dir) {
28
+ return fs.realpathSync.native ? fs.realpathSync.native(dir) : fs.realpathSync(dir);
29
+ }
30
+
31
+ function makeSandbox() {
32
+ const dir = canonicalDir(fs.mkdtempSync(path.join(os.tmpdir(), 'local-err-')));
33
+ const home = path.join(dir, 'home');
34
+ const store = path.join(dir, 'observations');
35
+ const stateHome = path.join(dir, 'state-home');
36
+ const repoA = path.join(dir, 'repo-a');
37
+ const repoB = path.join(dir, 'repo-b');
38
+ fs.mkdirSync(home, { recursive: true });
39
+ fs.mkdirSync(store, { recursive: true });
40
+ fs.mkdirSync(stateHome, { recursive: true });
41
+ fs.mkdirSync(repoA, { recursive: true });
42
+ fs.mkdirSync(repoB, { recursive: true });
43
+ execFileSync('git', ['init', '-q', repoA]);
44
+ execFileSync('git', ['init', '-q', repoB]);
45
+ const env = {
46
+ ...process.env,
47
+ HOME: home,
48
+ USERPROFILE: home,
49
+ HARNESS_OBSERVATIONS_DIR: store,
50
+ HARNESS_STATE_HOME: stateHome,
51
+ };
52
+ delete env.HARNESS_OBSERVATIONS;
53
+ delete env.HARNESS_SYSTEM_ONE_MODE;
54
+ delete env.HARNESS_WORKSPACE_ROOT;
55
+ delete env.CLAUDE_PROJECT_DIR;
56
+ delete env.CODEX_PROJECT_DIR;
57
+ return { dir, home, store, stateHome, repoA, repoB, env };
58
+ }
59
+
60
+ test('observations.js exposes shared lock and atomic write primitives', () => {
61
+ assert.strictEqual(typeof observations.withLock, 'function');
62
+ assert.strictEqual(typeof observations.writeJsonAtomic, 'function');
63
+ });
64
+
65
+ test('append occurrence and read back with full schema fields', () => {
66
+ const s = makeSandbox();
67
+ const res = localErrors.appendOccurrence({
68
+ workspaceRoot: s.repoA,
69
+ host: 'claude',
70
+ sessionKey: 'sess-raw-1',
71
+ toolUseId: 'tool-use-1',
72
+ command: 'git commit -m "feat: Bad Subject"',
73
+ exitCode: 1,
74
+ output: '⧗ input: feat: Bad Subject\n✖ subject must be lower-case [subject-case]\n✖ found 1 problems, 0 warnings',
75
+ matchedLedgerIds: ['E-0003', 'E-0003'],
76
+ }, { env: s.env });
77
+
78
+ assert.strictEqual(res.status, 'appended');
79
+ assert.ok(res.record);
80
+ assert.strictEqual(res.record.schemaVersion, 1);
81
+ assert.strictEqual(res.record.kind, 'occurrence');
82
+ assert.strictEqual(res.record.source, 'tool-failure');
83
+ assert.strictEqual(res.record.host, 'claude');
84
+ assert.strictEqual(res.record.destination, 'unknown');
85
+ assert.strictEqual(res.record.commandClass, 'git');
86
+ assert.strictEqual(res.record.exitCode, 1);
87
+ assert.deepStrictEqual(res.record.matchedLedgerIds, ['E-0003']);
88
+ assert.strictEqual(res.record.signature, 'v1-git-commitlint-subject-case');
89
+ assert.ok(!/^E-/i.test(res.record.provisionalId), 'provisionalId must stay outside E- namespace');
90
+ assert.ok(/^[a-z0-9][a-z0-9_-]{0,63}$/.test(res.record.provisionalId), 'provisionalId must satisfy matcher identifier');
91
+ assert.notStrictEqual(res.record.sessionKey, 'sess-raw-1', 'sessionKey must be opaque');
92
+ assert.notStrictEqual(res.record.toolUseId, 'tool-use-1', 'toolUseId must be opaque');
93
+
94
+ const listed = localErrors.listRecords({ env: s.env, workspaceRoot: s.repoA, kind: 'occurrence' });
95
+ assert.strictEqual(listed.length, 1);
96
+ assert.deepStrictEqual(listed[0], res.record);
97
+ assert.strictEqual(localErrors.listRecords({ env: s.env, workspaceRoot: s.repoB }).length, 0,
98
+ 'records are partitioned by canonical workspaceKey');
99
+ });
100
+
101
+ test('idempotent retry with same host/workspace/session/toolUseId vs distinct failures', () => {
102
+ const s = makeSandbox();
103
+ const base = {
104
+ workspaceRoot: s.repoA,
105
+ host: 'codex',
106
+ sessionKey: 'sess-idem',
107
+ toolUseId: 'tu-1',
108
+ command: 'npm test',
109
+ exitCode: 1,
110
+ output: 'npm ERR! Test failed. See above for more details.\nnpm ERR! code 1',
111
+ };
112
+ const first = localErrors.appendOccurrence(base, { env: s.env });
113
+ const retry = localErrors.appendOccurrence(base, { env: s.env });
114
+ assert.strictEqual(first.status, 'appended');
115
+ assert.strictEqual(retry.status, 'duplicate');
116
+ assert.strictEqual(retry.record.provisionalId, first.record.provisionalId);
117
+
118
+ const distinct = localErrors.appendOccurrence({ ...base, toolUseId: 'tu-2' }, { env: s.env });
119
+ assert.strictEqual(distinct.status, 'appended');
120
+ assert.strictEqual(distinct.record.signature, first.record.signature);
121
+ assert.notStrictEqual(distinct.record.provisionalId, first.record.provisionalId);
122
+
123
+ const noToolUse1 = localErrors.appendOccurrence({ ...base, toolUseId: null }, { env: s.env });
124
+ const noToolUse2 = localErrors.appendOccurrence({ ...base, toolUseId: null }, { env: s.env });
125
+ assert.strictEqual(noToolUse1.status, 'appended');
126
+ assert.strictEqual(noToolUse2.status, 'appended');
127
+ assert.notStrictEqual(noToolUse1.record.provisionalId, noToolUse2.record.provisionalId);
128
+
129
+ const listed = localErrors.listRecords({ env: s.env, workspaceRoot: s.repoA });
130
+ assert.strictEqual(listed.length, 4);
131
+ });
132
+
133
+ test('redacts email, home paths, and token-like strings before persistence and before signature', () => {
134
+ const s = makeSandbox();
135
+ const secretA = 'ghp_1234567890abcdefghijklmnopqrstuv';
136
+ const secretB = 'ghp_zyxwvutsrqponmlkjihgfedcba987654';
137
+ const bearerA = 'Bearer sk-proj-aaaaaaaaaaaaaaaaaaaaaaaaaaaa';
138
+ const bearerB = 'Bearer sk-proj-bbbbbbbbbbbbbbbbbbbbbbbbbbbb';
139
+ const outputA = `Fatal custom crash for alice@example.com at /Users/alice/work/app.js with ${secretA} and ${bearerA} and api_key=topsecret123`;
140
+ const outputB = `Fatal custom crash for bob@other.org at /home/bob/work/app.js with ${secretB} and ${bearerB} and api_key=different999`;
141
+
142
+ const sigA = localErrors.normalizeSignature({ command: 'node run.js', output: outputA });
143
+ const sigB = localErrors.normalizeSignature({ command: 'node run.js', output: outputB });
144
+ assert.strictEqual(sigA, sigB, 'redaction must happen before signature derivation');
145
+
146
+ const res = localErrors.appendOccurrence({
147
+ workspaceRoot: s.repoA,
148
+ host: 'claude',
149
+ command: 'node run.js --token super-secret-arg',
150
+ exitCode: 1,
151
+ output: outputA,
152
+ }, { env: s.env });
153
+ assert.strictEqual(res.status, 'appended');
154
+
155
+ const rawIndex = fs.readFileSync(path.join(s.store, 'errors-index.json'), 'utf8');
156
+ for (const leaked of ['alice@example.com', '/Users/alice', secretA, 'sk-proj-aaaa', 'topsecret123', 'super-secret-arg']) {
157
+ assert.ok(!rawIndex.includes(leaked), `persisted store must not retain ${leaked}`);
158
+ }
159
+ assert.ok(res.record.outputExcerpt.includes('<email>'));
160
+ assert.ok(res.record.outputExcerpt.includes('<home>'));
161
+ assert.ok(res.record.outputExcerpt.includes('<redacted>'));
162
+ });
163
+
164
+ test('excerpt cap is 2 KiB with short positive control preserved', () => {
165
+ const s = makeSandbox();
166
+ const shortOut = 'short error line';
167
+ const shortRes = localErrors.appendOccurrence({
168
+ workspaceRoot: s.repoA,
169
+ host: 'claude',
170
+ command: 'ls /nope',
171
+ exitCode: 2,
172
+ output: shortOut,
173
+ }, { env: s.env });
174
+ assert.strictEqual(shortRes.record.outputExcerpt, shortOut);
175
+
176
+ const bigOut = 'x'.repeat(5000) + 'TAIL_MARKER';
177
+ const bigRes = localErrors.appendOccurrence({
178
+ workspaceRoot: s.repoA,
179
+ host: 'claude',
180
+ command: 'ls /nope',
181
+ exitCode: 2,
182
+ output: bigOut,
183
+ }, { env: s.env });
184
+ assert.ok(Buffer.byteLength(bigRes.record.outputExcerpt, 'utf8') <= 2048, 'excerpt must not exceed 2 KiB');
185
+ assert.ok(bigRes.record.outputExcerpt.endsWith('TAIL_MARKER'), 'tailBytes preserves the tail of the failure output');
186
+ });
187
+
188
+ test('per-workspace and total retention/size bounds are enforced', () => {
189
+ const s = makeSandbox();
190
+ const limits = { maxRecordsPerWorkspace: 2, maxTotalRecords: 3 };
191
+
192
+ for (let i = 1; i <= 3; i += 1) {
193
+ const r = localErrors.appendOccurrence({
194
+ workspaceRoot: s.repoA,
195
+ host: 'claude',
196
+ command: 'npm test',
197
+ exitCode: 1,
198
+ output: `npm ERR! code 1 failure ${i}`,
199
+ }, { env: s.env, limits });
200
+ assert.strictEqual(r.status, 'appended');
201
+ }
202
+ const inA = localErrors.listRecords({ env: s.env, workspaceRoot: s.repoA });
203
+ assert.strictEqual(inA.length, 2, 'per-workspace cap keeps at most 2 records');
204
+ assert.ok(inA[0].outputExcerpt.includes('failure 2') && inA[1].outputExcerpt.includes('failure 3'),
205
+ 'oldest occurrence evicted first');
206
+
207
+ for (let i = 1; i <= 2; i += 1) {
208
+ const r = localErrors.appendOccurrence({
209
+ workspaceRoot: s.repoB,
210
+ host: 'claude',
211
+ command: 'npm test',
212
+ exitCode: 1,
213
+ output: `npm ERR! code 1 repoB ${i}`,
214
+ }, { env: s.env, limits });
215
+ assert.strictEqual(r.status, 'appended');
216
+ }
217
+ const all = localErrors.listRecords({ env: s.env });
218
+ assert.strictEqual(all.length, 3, 'total cap keeps at most 3 records across workspaces');
219
+ });
220
+
221
+ test('lock contention returns fail-open without throwing and leaves index untouched', () => {
222
+ const s = makeSandbox();
223
+ const lockFile = path.join(s.store, '.index.lock');
224
+ fs.writeFileSync(lockFile, 'held-by-test');
225
+
226
+ const blocked = localErrors.appendOccurrence({
227
+ workspaceRoot: s.repoA,
228
+ host: 'claude',
229
+ command: 'npm test',
230
+ exitCode: 1,
231
+ output: 'npm ERR! code 1',
232
+ }, { env: s.env, lockTimeoutMs: 25 });
233
+ assert.strictEqual(blocked.status, 'lock-timeout');
234
+ assert.strictEqual(fs.existsSync(path.join(s.store, 'errors-index.json')), false,
235
+ 'timed out write must not create or mutate errors-index.json');
236
+
237
+ fs.unlinkSync(lockFile);
238
+ const unblocked = localErrors.appendOccurrence({
239
+ workspaceRoot: s.repoA,
240
+ host: 'claude',
241
+ command: 'npm test',
242
+ exitCode: 1,
243
+ output: 'npm ERR! code 1',
244
+ }, { env: s.env, lockTimeoutMs: 50 });
245
+ assert.strictEqual(unblocked.status, 'appended');
246
+ });
247
+
248
+ test('local error records stay absent from turn index and System One export path', () => {
249
+ const s = makeSandbox();
250
+ // Seed one valid turn observation in observations-index.json.
251
+ const turnText = { prompt: 'fix a unit test', previous: '' };
252
+ const contentSha256 = observations.sha(JSON.stringify(turnText));
253
+ const turnRecord = {
254
+ id: 'turn-obs-1',
255
+ source: 'observation',
256
+ status: 'active',
257
+ observedAt: new Date().toISOString(),
258
+ validUntil: new Date(Date.now() + 86400000).toISOString(),
259
+ contentSha256,
260
+ host: 'claude',
261
+ turn: 1,
262
+ writer: { sessionId: 'sess-turn-1' },
263
+ scope: { taskTerms: ['fix'], requirementTerms: [], roles: [] },
264
+ promptBytes: 15,
265
+ router: null,
266
+ behavior: observations.emptyBehavior(),
267
+ selfReport: { v: 1, validity: 'actionable', tier: 'tier2', intents: ['fix'], workflow: 'iterative-single', skills: [] },
268
+ selfReportReason: null,
269
+ };
270
+ assert.strictEqual(observations.appendRecord(s.store, turnRecord, turnText), true);
271
+
272
+ // Append local error occurrence and provisional lesson into the same store root.
273
+ const errRes = localErrors.appendOccurrence({
274
+ workspaceRoot: s.repoA,
275
+ host: 'claude',
276
+ command: 'git commit -m "feat: Bad"',
277
+ exitCode: 1,
278
+ output: '✖ subject must be lower-case [subject-case]',
279
+ }, { env: s.env });
280
+ assert.strictEqual(errRes.status, 'appended');
281
+
282
+ const turnIndex = observations.readJson(path.join(s.store, 'observations-index.json'), null);
283
+ assert.strictEqual(turnIndex.records.length, 1);
284
+ assert.strictEqual(turnIndex.records[0].id, 'turn-obs-1');
285
+
286
+ const outDir = path.join(s.dir, 'export-out');
287
+ const exported = spawnSync(process.execPath, [EXPORTER, '--store', s.store, '--out', outDir, '--self-report-only'], {
288
+ env: s.env, encoding: 'utf8', timeout: 10000,
289
+ });
290
+ assert.strictEqual(exported.status, 0, `exporter failed: ${exported.stderr}`);
291
+ const report = JSON.parse(fs.readFileSync(path.join(outDir, 'export-report.json'), 'utf8'));
292
+ assert.strictEqual(report.records, 1);
293
+ assert.strictEqual(report.exported, 1);
294
+ const prompts = fs.readFileSync(path.join(outDir, 'prompts-observed.jsonl'), 'utf8');
295
+ assert.ok(!prompts.includes(errRes.record.provisionalId));
296
+ assert.ok(!prompts.includes('subject-case'));
297
+ });
298
+
299
+ test('provisional lesson validates match, rejects invalid match and E- namespace, and projects into ledger-match', () => {
300
+ assert.strictEqual(typeof validateMatch, 'function', 'ledger-match.js must export validateMatch');
301
+ assert.strictEqual(localErrors.validateMatch, validateMatch,
302
+ 'local-errors.js must import validateMatch from ledger-match.js rather than copying it');
303
+ const s = makeSandbox();
304
+ const validMatch = {
305
+ actions: [{ tool: 'shell', executable: 'git', subcommand: 'commit' }],
306
+ failures: [{ tool: 'shell', executable: 'git', subcommand: 'commit', diagnostics: ['subject-case'] }],
307
+ };
308
+
309
+ assert.throws(() => localErrors.addProvisionalLesson({
310
+ workspaceRoot: s.repoA,
311
+ signature: 'v1-git-commitlint-subject-case',
312
+ match: { invalidKey: [] },
313
+ lesson: 'Keep commit subjects lower-case.',
314
+ }, { env: s.env }), /invalid match/i);
315
+
316
+ assert.throws(() => localErrors.addProvisionalLesson({
317
+ workspaceRoot: s.repoA,
318
+ signature: 'v1-git-commitlint-subject-case',
319
+ match: { failures: [{ tool: 'shell', executable: 'git', subcommand: 'commit', diagnostics: ['dup', 'dup'] }] },
320
+ lesson: 'Keep commit subjects lower-case.',
321
+ }, { env: s.env }), /invalid diagnostics/i);
322
+
323
+ assert.throws(() => localErrors.addProvisionalLesson({
324
+ workspaceRoot: s.repoA,
325
+ provisionalId: 'E-0099',
326
+ signature: 'v1-git-commitlint-subject-case',
327
+ match: validMatch,
328
+ lesson: 'Keep commit subjects lower-case.',
329
+ }, { env: s.env }), /provisionalId/i);
330
+
331
+ assert.throws(() => localErrors.addProvisionalLesson({
332
+ workspaceRoot: s.repoA,
333
+ signature: 'v1-git-commitlint-subject-case',
334
+ match: validMatch,
335
+ lesson: 'Keep commit subjects lower-case.',
336
+ issueUrl: 'http://insecure.example.com/1',
337
+ }, { env: s.env }), /issueUrl/i);
338
+
339
+ const added = localErrors.addProvisionalLesson({
340
+ workspaceRoot: s.repoA,
341
+ destination: 'project',
342
+ signature: 'v1-git-commitlint-subject-case',
343
+ match: validMatch,
344
+ cue: 'Commit rejected by commitlint.',
345
+ lesson: 'Use lowercase subjects; contact alice@example.com with ghp_1234567890abcdefghijklmnopqrstuv.',
346
+ issueUrl: 'https://github.com/dyphn1/Harness-everything/issues/496',
347
+ promotionId: 'E-0003',
348
+ }, { env: s.env });
349
+ assert.strictEqual(added.status, 'appended');
350
+ assert.strictEqual(added.record.kind, 'provisional-lesson');
351
+ assert.strictEqual(added.record.destination, 'project');
352
+ assert.strictEqual(added.record.promotionId, 'E-0003');
353
+ assert.ok(!/^E-/i.test(added.record.provisionalId));
354
+ assert.ok(!added.record.lesson.includes('alice@example.com'));
355
+ assert.ok(!added.record.lesson.includes('ghp_1234567890'));
356
+
357
+ const lessons = localErrors.listRecords({ env: s.env, workspaceRoot: s.repoA, kind: 'provisional-lesson' });
358
+ assert.strictEqual(lessons.length, 1);
359
+
360
+ // Verify C2-style projection is accepted end-to-end by ledger-match.js.
361
+ const stateDir = path.join(s.dir, 'match-state');
362
+ const matched = matchLedgerLessons({
363
+ workspaceRoot: s.repoA,
364
+ workspaceIdentity: lessons[0].workspaceKey,
365
+ sessionIdentity: 'sess-proj-1',
366
+ stateDir,
367
+ event: {
368
+ phase: 'action',
369
+ tool: 'shell',
370
+ command: 'git commit -m "chore: test"',
371
+ outcome: { failed: 'unknown' },
372
+ },
373
+ provisionalSource: () => lessons.map(item => ({
374
+ identity: item.provisionalId,
375
+ signature: item.signature,
376
+ promotionId: item.promotionId,
377
+ match: item.match,
378
+ cue: item.cue,
379
+ lesson: item.lesson,
380
+ })),
381
+ });
382
+ assert.ok(matched && matched.ids.includes(lessons[0].provisionalId),
383
+ 'projected provisional lesson must be accepted and matched by ledger-match.js');
384
+ });
385
+
386
+ test('real failure signature fixtures are stable across volatile details and divergent classes differ', () => {
387
+ const commitlint1 = localErrors.normalizeSignature({
388
+ command: 'git commit -m "feat: Add Store"',
389
+ output: '⧗ input: feat: Add Store\n✖ subject must be lower-case [subject-case]\n✖ found 1 problems, 0 warnings',
390
+ });
391
+ const commitlint2 = localErrors.normalizeSignature({
392
+ command: 'git commit -m "fix: Another Uppercase Header"',
393
+ output: '⧗ input: fix: Another Uppercase Header\n✖ subject must be lower-case [subject-case]\n✖ found 2 problems, 1 warnings',
394
+ });
395
+ assert.strictEqual(commitlint1, commitlint2);
396
+
397
+ const npm1 = localErrors.normalizeSignature({
398
+ command: 'npm test',
399
+ output: 'npm ERR! Test failed. See above for more details.\nnpm ERR! code 1\nnpm ERR! path /Users/alice/repo-1\nnpm ERR! A complete log of this run can be found in: /Users/alice/.npm/_logs/2026-11-24T01_00_00_000Z-debug-0.log',
400
+ });
401
+ const npm2 = localErrors.normalizeSignature({
402
+ command: 'npm run test:consistency',
403
+ output: 'npm ERR! code 1\nnpm ERR! path /home/bob/repo-2\nnpm ERR! command failed\nnpm ERR! A complete log of this run can be found in: /home/bob/.npm/_logs/2026-11-25T23_59_59_999Z-debug-0.log',
404
+ });
405
+ assert.strictEqual(npm1, npm2);
406
+
407
+ const eperm1 = localErrors.normalizeSignature({
408
+ command: 'node scripts/workflow.js',
409
+ output: "Error: EPERM: operation not permitted, open '/Users/alice/.agents/harness-everything/workspaces/a-111/state/file.json'\n at Object.openSync (node:fs:561:18)",
410
+ });
411
+ const eperm2 = localErrors.normalizeSignature({
412
+ command: 'node scripts/other.js',
413
+ output: "Error: EPERM: operation not permitted, mkdir '/home/bob/.agents/harness-everything/workspaces/b-222/state'\n at Object.mkdirSync (node:fs:1009:26)",
414
+ });
415
+ assert.strictEqual(eperm1, eperm2);
416
+
417
+ const gitNff1 = localErrors.normalizeSignature({
418
+ command: 'git push origin main',
419
+ output: "To github.com:org/repo-a.git\n ! [rejected] main -> main (non-fast-forward)\nerror: failed to push some refs to 'github.com:org/repo-a.git'\nhint: Updates were rejected because the tip of your current branch is behind",
420
+ });
421
+ const gitNff2 = localErrors.normalizeSignature({
422
+ command: 'git push upstream feat/abc',
423
+ output: "To github.com:other/repo-b.git\n ! [rejected] feat/abc -> feat/abc (non-fast-forward)\nerror: failed to push some refs to 'github.com:other/repo-b.git'",
424
+ });
425
+ assert.strictEqual(gitNff1, gitNff2);
426
+
427
+ const unique = new Set([commitlint1, npm1, eperm1, gitNff1]);
428
+ assert.strictEqual(unique.size, 4, 'divergent failure classes must produce distinct signatures');
429
+ for (const sig of unique) {
430
+ assert.ok(/^v1-[a-z0-9][a-z0-9_-]{0,60}$/.test(sig), `signature ${sig} must be versioned and matcher-safe`);
431
+ }
432
+
433
+ // E-0027 control: multi-family output produces an order-independent composite signature distinct from single-family.
434
+ const multiA = localErrors.normalizeSignature({
435
+ command: 'npm test',
436
+ output: 'npm ERR! code 1\nError: EPERM: operation not permitted, open /tmp/a',
437
+ });
438
+ const multiB = localErrors.normalizeSignature({
439
+ command: 'npm test',
440
+ output: 'Error: EPERM: operation not permitted, open /tmp/b\nnpm ERR! code 1',
441
+ });
442
+ assert.strictEqual(multiA, multiB, 'multi-family signature must be order-independent');
443
+ assert.notStrictEqual(multiA, npm1, 'multi-family output must not collapse to first single-family match');
444
+ });
445
+
446
+ test('D1b row 1: issueUrl with userinfo is rejected and leaves index bytes unchanged', () => {
447
+ const s = makeSandbox();
448
+ const validMatch = {
449
+ actions: [{ tool: 'shell', executable: 'git', subcommand: 'commit' }],
450
+ };
451
+ const seed = localErrors.addProvisionalLesson({
452
+ workspaceRoot: s.repoA,
453
+ destination: 'project',
454
+ signature: 'v1-git-seed-row1',
455
+ match: validMatch,
456
+ lesson: 'Seed lesson before negative check.',
457
+ issueUrl: 'https://github.com/o/r/issues/1',
458
+ }, { env: s.env });
459
+ assert.strictEqual(seed.status, 'appended');
460
+
461
+ const indexPath = path.join(s.store, 'errors-index.json');
462
+ const before = fs.readFileSync(indexPath);
463
+
464
+ for (const badUrl of [
465
+ 'https://user:pass@github.com/o/r/issues/1',
466
+ 'https://tokenonly@github.com/o/r/issues/1',
467
+ 'https://:secret@github.com/o/r/issues/1',
468
+ ]) {
469
+ assert.throws(() => localErrors.addProvisionalLesson({
470
+ workspaceRoot: s.repoA,
471
+ destination: 'project',
472
+ signature: 'v1-git-userinfo-bad',
473
+ match: validMatch,
474
+ lesson: 'Should not persist.',
475
+ issueUrl: badUrl,
476
+ }, { env: s.env }), /issueUrl/i, `expected rejection for ${badUrl}`);
477
+ }
478
+
479
+ const after = fs.readFileSync(indexPath);
480
+ assert.strictEqual(Buffer.compare(before, after), 0, 'index bytes must be unchanged after userinfo rejection');
481
+ });
482
+
483
+ test('D1b row 2: issueUrl with secret-like query param or token-shaped value is rejected and leaves index unchanged', () => {
484
+ const s = makeSandbox();
485
+ const validMatch = {
486
+ actions: [{ tool: 'shell', executable: 'git', subcommand: 'commit' }],
487
+ };
488
+ const seed = localErrors.addProvisionalLesson({
489
+ workspaceRoot: s.repoA,
490
+ destination: 'project',
491
+ signature: 'v1-git-seed-row2',
492
+ match: validMatch,
493
+ lesson: 'Seed lesson before query check.',
494
+ issueUrl: 'https://github.com/o/r/issues/1',
495
+ }, { env: s.env });
496
+ assert.strictEqual(seed.status, 'appended');
497
+
498
+ const indexPath = path.join(s.store, 'errors-index.json');
499
+ const before = fs.readFileSync(indexPath);
500
+
501
+ for (const badUrl of [
502
+ 'https://github.com/o/r/issues/1?token=secret123',
503
+ 'https://github.com/o/r/issues/1?api_key=abc123',
504
+ 'https://github.com/o/r/issues/1?secret=xyz789',
505
+ 'https://github.com/o/r/issues/1?password=hunter2',
506
+ 'https://github.com/o/r/issues/1?sig=deadbeef01',
507
+ 'https://github.com/o/r/issues/1?ref=ghp_1234567890abcdefghijklmnopqrstuv',
508
+ 'https://github.com/o/r/issues/1?v=eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.abc1234567890',
509
+ ]) {
510
+ assert.throws(() => localErrors.addProvisionalLesson({
511
+ workspaceRoot: s.repoA,
512
+ destination: 'project',
513
+ signature: 'v1-git-query-bad',
514
+ match: validMatch,
515
+ lesson: 'Should not persist.',
516
+ issueUrl: badUrl,
517
+ }, { env: s.env }), /issueUrl/i, `expected rejection for ${badUrl}`);
518
+ }
519
+
520
+ const after = fs.readFileSync(indexPath);
521
+ assert.strictEqual(Buffer.compare(before, after), 0, 'index bytes must be unchanged after secret query rejection');
522
+ });
523
+
524
+ test('D1b row 3: plain HTTPS issue and issue comment links are accepted and read back', () => {
525
+ const s = makeSandbox();
526
+ const validMatch = {
527
+ actions: [{ tool: 'shell', executable: 'git', subcommand: 'commit' }],
528
+ };
529
+ const plainUrl = 'https://github.com/o/r/issues/1';
530
+ const commentUrl = 'https://github.com/o/r/issues/1#issuecomment-123';
531
+
532
+ const r1 = localErrors.addProvisionalLesson({
533
+ workspaceRoot: s.repoA,
534
+ destination: 'project',
535
+ signature: 'v1-git-plain-issue',
536
+ match: validMatch,
537
+ lesson: 'Plain issue link lesson.',
538
+ issueUrl: plainUrl,
539
+ }, { env: s.env });
540
+ const r2 = localErrors.addProvisionalLesson({
541
+ workspaceRoot: s.repoA,
542
+ destination: 'project',
543
+ signature: 'v1-git-comment-issue',
544
+ match: validMatch,
545
+ lesson: 'Comment link lesson.',
546
+ issueUrl: commentUrl,
547
+ }, { env: s.env });
548
+
549
+ assert.strictEqual(r1.status, 'appended');
550
+ assert.strictEqual(r2.status, 'appended');
551
+
552
+ const listed = localErrors.listRecords({ env: s.env, workspaceRoot: s.repoA, kind: 'provisional-lesson' });
553
+ const urls = listed.map(r => r.issueUrl);
554
+ assert.ok(urls.includes(plainUrl), 'plain issue URL must be read back');
555
+ assert.ok(urls.includes(commentUrl), 'issue comment URL must be read back');
556
+ });
557
+
558
+ test('D1b row 4: writers reject supplied workspaceKey without resolvable workspace context and do not write', () => {
559
+ const s = makeSandbox();
560
+ const validMatch = {
561
+ actions: [{ tool: 'shell', executable: 'git', subcommand: 'commit' }],
562
+ };
563
+ const indexPath = path.join(s.store, 'errors-index.json');
564
+
565
+ for (const suppliedKey of ['/Users/alice/secret-repo', 'repo-a-1234567890ab']) {
566
+ const occ = localErrors.appendOccurrence({
567
+ workspaceKey: suppliedKey,
568
+ host: 'claude',
569
+ command: 'npm test',
570
+ exitCode: 1,
571
+ output: 'npm ERR! code 1',
572
+ }, { env: s.env });
573
+ assert.strictEqual(occ.status, 'invalid', `appendOccurrence must fail-open reject unbound key ${suppliedKey}`);
574
+ assert.strictEqual(occ.record, null);
575
+
576
+ assert.throws(() => localErrors.addProvisionalLesson({
577
+ workspaceKey: suppliedKey,
578
+ destination: 'project',
579
+ signature: 'v1-git-unbound-key',
580
+ match: validMatch,
581
+ lesson: 'Should not persist without workspace context.',
582
+ }, { env: s.env }), /workspace/i, `addProvisionalLesson must reject unbound key ${suppliedKey}`);
583
+ }
584
+
585
+ assert.strictEqual(fs.existsSync(indexPath), false, 'no index file may be written on unbound workspaceKey');
586
+ });
587
+
588
+ test('D1b row 5: writers reject disagreeing workspaceKey and accept matching canonical key', () => {
589
+ const s = makeSandbox();
590
+ const validMatch = {
591
+ actions: [{ tool: 'shell', executable: 'git', subcommand: 'commit' }],
592
+ };
593
+ const canonicalA = localErrors.resolveWorkspaceKey({ workspaceRoot: s.repoA }, { env: s.env });
594
+ const canonicalB = localErrors.resolveWorkspaceKey({ workspaceRoot: s.repoB }, { env: s.env });
595
+ assert.notStrictEqual(canonicalA, canonicalB);
596
+
597
+ // Matching canonical key is accepted for both writers.
598
+ const okOcc = localErrors.appendOccurrence({
599
+ workspaceRoot: s.repoA,
600
+ workspaceKey: canonicalA,
601
+ host: 'claude',
602
+ command: 'npm test',
603
+ exitCode: 1,
604
+ output: 'npm ERR! code 1',
605
+ }, { env: s.env });
606
+ assert.strictEqual(okOcc.status, 'appended');
607
+ assert.strictEqual(okOcc.record.workspaceKey, canonicalA);
608
+
609
+ const okLesson = localErrors.addProvisionalLesson({
610
+ workspaceRoot: s.repoA,
611
+ workspaceKey: canonicalA,
612
+ destination: 'project',
613
+ signature: 'v1-git-match-key',
614
+ match: validMatch,
615
+ lesson: 'Matching canonical key accepted.',
616
+ }, { env: s.env });
617
+ assert.strictEqual(okLesson.status, 'appended');
618
+ assert.strictEqual(okLesson.record.workspaceKey, canonicalA);
619
+
620
+ const indexPath = path.join(s.store, 'errors-index.json');
621
+ const before = fs.readFileSync(indexPath);
622
+
623
+ // Disagreeing key is rejected for both writers, index bytes unchanged.
624
+ for (const wrongKey of [canonicalB, '/Users/alice/forged-path']) {
625
+ const badOcc = localErrors.appendOccurrence({
626
+ workspaceRoot: s.repoA,
627
+ workspaceKey: wrongKey,
628
+ host: 'claude',
629
+ command: 'npm test',
630
+ exitCode: 1,
631
+ output: 'npm ERR! code 1',
632
+ }, { env: s.env });
633
+ assert.strictEqual(badOcc.status, 'invalid');
634
+ assert.strictEqual(badOcc.record, null);
635
+
636
+ assert.throws(() => localErrors.addProvisionalLesson({
637
+ workspaceRoot: s.repoA,
638
+ workspaceKey: wrongKey,
639
+ destination: 'project',
640
+ signature: 'v1-git-mismatch-key',
641
+ match: validMatch,
642
+ lesson: 'Should not persist.',
643
+ }, { env: s.env }), /workspace/i);
644
+ }
645
+
646
+ const after = fs.readFileSync(indexPath);
647
+ assert.strictEqual(Buffer.compare(before, after), 0, 'index bytes must be unchanged after disagreeing workspaceKey');
648
+ });
649
+
650
+ test('D1b row 6: workspace-scoped reads and matcher-supplied bounded reader lookup work without granting write identity', () => {
651
+ const s = makeSandbox();
652
+ const validMatch = {
653
+ actions: [{ tool: 'shell', executable: 'git', subcommand: 'commit' }],
654
+ };
655
+ const addedA = localErrors.addProvisionalLesson({
656
+ workspaceRoot: s.repoA,
657
+ destination: 'project',
658
+ signature: 'v1-git-read-a',
659
+ match: validMatch,
660
+ lesson: 'Lesson for repo A.',
661
+ }, { env: s.env });
662
+ const addedB = localErrors.addProvisionalLesson({
663
+ workspaceRoot: s.repoB,
664
+ destination: 'project',
665
+ signature: 'v1-git-read-b',
666
+ match: validMatch,
667
+ lesson: 'Lesson for repo B.',
668
+ }, { env: s.env });
669
+ assert.strictEqual(addedA.status, 'appended');
670
+ assert.strictEqual(addedB.status, 'appended');
671
+
672
+ const keyA = addedA.record.workspaceKey;
673
+ const keyB = addedB.record.workspaceKey;
674
+
675
+ // Normal workspace-scoped read works.
676
+ const byRoot = localErrors.listRecords({ env: s.env, workspaceRoot: s.repoA });
677
+ assert.strictEqual(byRoot.length, 1);
678
+ assert.strictEqual(byRoot[0].signature, 'v1-git-read-a');
679
+
680
+ // Matcher-supplied key works for bounded read lookup.
681
+ const byKey = localErrors.listRecords({ env: s.env, workspaceKey: keyA });
682
+ assert.strictEqual(byKey.length, 1);
683
+ assert.strictEqual(byKey[0].signature, 'v1-git-read-a');
684
+
685
+ // Disagreeing root + key on read returns empty.
686
+ assert.deepStrictEqual(localErrors.listRecords({ env: s.env, workspaceRoot: s.repoA, workspaceKey: keyB }), []);
687
+
688
+ // Oversized or control-char key on read is rejected (returns empty).
689
+ assert.deepStrictEqual(localErrors.listRecords({ env: s.env, workspaceKey: 'a'.repeat(300) }), []);
690
+ assert.deepStrictEqual(localErrors.listRecords({ env: s.env, workspaceKey: `${keyA}\n` }), []);
691
+
692
+ // End-to-end matcher callback uses workspaceIdentity for read lookup only.
693
+ const stateDir = path.join(s.dir, 'match-state-row6');
694
+ const matched = matchLedgerLessons({
695
+ workspaceRoot: s.repoA,
696
+ workspaceIdentity: keyA,
697
+ sessionIdentity: 'sess-row6',
698
+ stateDir,
699
+ event: {
700
+ phase: 'action',
701
+ tool: 'shell',
702
+ command: 'git commit -m "chore: test"',
703
+ outcome: { failed: 'unknown' },
704
+ },
705
+ provisionalSource: (wsIdentity) => localErrors.listRecords({
706
+ env: s.env,
707
+ workspaceKey: wsIdentity,
708
+ kind: 'provisional-lesson',
709
+ }).map(item => ({
710
+ identity: item.provisionalId,
711
+ signature: item.signature,
712
+ match: item.match,
713
+ lesson: item.lesson,
714
+ })),
715
+ });
716
+ assert.ok(matched && matched.ids.includes(addedA.record.provisionalId));
717
+
718
+ // Same matcher-supplied key cannot establish write identity on its own.
719
+ const rejectedWrite = localErrors.appendOccurrence({
720
+ workspaceKey: keyA,
721
+ host: 'claude',
722
+ command: 'npm test',
723
+ exitCode: 1,
724
+ output: 'npm ERR! code 1',
725
+ }, { env: s.env });
726
+ assert.strictEqual(rejectedWrite.status, 'invalid');
727
+ assert.strictEqual(localErrors.listRecords({ env: s.env, workspaceKey: keyA }).length, 1);
728
+ });
729
+
730
+ console.log(failures ? `\n${failures} failure(s)` : '\nAll local-error-store checks passed.');
731
+ process.exit(failures ? 1 : 0);