harness-everything 1.1.1 → 1.2.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 (27) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/CHANGELOG.md +18 -0
  4. package/benchmarks/results/live-host/multi-host-2026-11-25-496-capture/README.md +32 -0
  5. package/benchmarks/results/live-host/multi-host-2026-11-25-496-capture/claude-records.json +1 -0
  6. package/benchmarks/results/live-host/multi-host-2026-11-25-496-capture/codex-hook-trace.txt +24 -0
  7. package/benchmarks/results/live-host/multi-host-2026-11-25-496-capture/opencode-records.json +1 -0
  8. package/benchmarks/results/live-host/multi-host-2026-11-25-496-capture/probe.sh +16 -0
  9. package/ci/mechanism-496-local-error-store.test.js +188 -5
  10. package/ci/mechanism-498-local-store-promote.test.js +402 -0
  11. package/ci/mechanism-498-local-store-scan.test.js +582 -0
  12. package/error-ledger-bootstrap/SKILL.md +1 -1
  13. package/error-ledger-bootstrap/references/workflow.md +15 -1
  14. package/error-ledger-bootstrap/scripts/promote.js +145 -9
  15. package/error-ledger-bootstrap/scripts/scan.js +394 -3
  16. package/hooks/scripts/lib/local-errors.js +24 -7
  17. package/opencode-plugin/plugin.json +1 -1
  18. package/package.json +1 -1
  19. package/plugins/harness-everything/.antigravity-plugin/plugin.json +1 -1
  20. package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
  21. package/plugins/harness-everything/hooks/scripts/lib/local-errors.js +24 -7
  22. package/plugins/harness-everything/plugin.json +1 -1
  23. package/plugins/harness-everything/skills/error-ledger-bootstrap/SKILL.md +1 -1
  24. package/plugins/harness-everything/skills/error-ledger-bootstrap/references/workflow.md +15 -1
  25. package/plugins/harness-everything/skills/error-ledger-bootstrap/scripts/promote.js +145 -9
  26. package/plugins/harness-everything/skills/error-ledger-bootstrap/scripts/scan.js +394 -3
  27. package/sbom.cdx.json +7 -7
@@ -0,0 +1,582 @@
1
+ 'use strict';
2
+
3
+ const assert = require('node:assert/strict');
4
+ const childProcess = require('node:child_process');
5
+ const crypto = require('node:crypto');
6
+ const fs = require('node:fs');
7
+ const os = require('node:os');
8
+ const path = require('node:path');
9
+ const localErrors = require('../hooks/scripts/lib/local-errors');
10
+
11
+ const ROOT = path.resolve(__dirname, '..');
12
+ const SCANNER = path.join(ROOT, 'error-ledger-bootstrap', 'scripts', 'scan.js');
13
+ const PACKAGED_SCANNER = path.join(ROOT, 'plugins', 'harness-everything', 'skills', 'error-ledger-bootstrap', 'scripts', 'scan.js');
14
+ const ERRORS_SYNC = path.join(ROOT, 'scripts', 'errors-sync.js');
15
+ const TMP = fs.realpathSync.native(fs.mkdtempSync(path.join(os.tmpdir(), 'harness-498-local-store-')));
16
+ const STORE = path.join(TMP, 'store');
17
+ const HOME = path.join(TMP, 'home');
18
+ const NOW = '2026-11-25T12:34:56.000Z';
19
+ const PRIVATE_VALUES = [
20
+ 'PRIVATE_EXCERPT_SENTINEL', 'PRIVATE_CUE_SENTINEL', 'PRIVATE_LESSON_SENTINEL',
21
+ 'PRIVATE_URL_SENTINEL', 'PRIVATE_PATH_SENTINEL', 'PRIVATE_SESSION_SENTINEL',
22
+ 'PRIVATE_TOOL_USE_SENTINEL', 'PRIVATE_READER_ROW_SENTINEL', 'sharedrawid',
23
+ 'readerprivateid', 'distinct-lesson-id', 'surviving-lesson-id'
24
+ ];
25
+ const ACTIONS = {
26
+ commit: { actions: [{ tool: 'shell', executable: 'git', subcommand: 'commit' }] },
27
+ push: { actions: [{ tool: 'shell', executable: 'git', subcommand: 'push' }] },
28
+ pull: { actions: [{ tool: 'shell', executable: 'git', subcommand: 'pull' }] }
29
+ };
30
+
31
+ fs.mkdirSync(HOME, { recursive: true });
32
+ const WRITER_ENV = isolatedEnv({ HARNESS_OBSERVATIONS_DIR: STORE, HOME, USERPROFILE: HOME });
33
+
34
+ function isolatedEnv(overrides = {}) {
35
+ const env = { ...process.env, ...overrides };
36
+ for (const key of ['HARNESS_WORKSPACE_ROOT', 'CLAUDE_PROJECT_DIR', 'CODEX_PROJECT_DIR']) delete env[key];
37
+ return env;
38
+ }
39
+
40
+ function runNode(script, args, env = {}) {
41
+ const childEnv = isolatedEnv();
42
+ Object.assign(childEnv, env);
43
+ const result = childProcess.spawnSync(process.execPath, [script, ...args], {
44
+ encoding: 'utf8',
45
+ env: childEnv,
46
+ stdio: ['ignore', 'pipe', 'pipe']
47
+ });
48
+ assert.ifError(result.error);
49
+ return result;
50
+ }
51
+
52
+ function git(repo, args, env = {}) {
53
+ const result = childProcess.spawnSync('git', ['-C', repo, ...args], {
54
+ encoding: 'utf8',
55
+ env: isolatedEnv({
56
+ GIT_CONFIG_NOSYSTEM: '1',
57
+ GIT_AUTHOR_NAME: 'Local Store Fixture',
58
+ GIT_AUTHOR_EMAIL: 'fixture@example.invalid',
59
+ GIT_COMMITTER_NAME: 'Local Store Fixture',
60
+ GIT_COMMITTER_EMAIL: 'fixture@example.invalid',
61
+ GIT_AUTHOR_DATE: NOW,
62
+ GIT_COMMITTER_DATE: NOW,
63
+ ...env
64
+ }),
65
+ stdio: ['ignore', 'pipe', 'pipe']
66
+ });
67
+ assert.ifError(result.error);
68
+ assert.strictEqual(result.status, 0, `git ${args.join(' ')} failed: ${result.stderr}`);
69
+ return result.stdout.trim();
70
+ }
71
+
72
+ function write(file, text) {
73
+ fs.mkdirSync(path.dirname(file), { recursive: true });
74
+ fs.writeFileSync(file, text);
75
+ }
76
+
77
+ function makeRepo(name) {
78
+ const repo = path.join(TMP, name);
79
+ fs.mkdirSync(repo, { recursive: true });
80
+ git(repo, ['init', '-q']);
81
+ write(path.join(repo, 'README.md'), '# Fixture\n');
82
+ git(repo, ['add', '-A']);
83
+ git(repo, ['commit', '-q', '-m', 'chore: initialize fixture']);
84
+ return repo;
85
+ }
86
+
87
+ function addLedgerRecord(repo, id, signature, match) {
88
+ const errors = path.join(repo, '.agents', 'harness-everything', 'errors');
89
+ const file = path.join(errors, `${id}-${signature}.md`);
90
+ const matchText = match ? `match:\n${Object.entries(match).map(([phase, rules]) =>
91
+ ` ${phase}:\n${rules.map(rule => ` - tool: ${rule.tool}\n executable: ${rule.executable}\n subcommand: ${rule.subcommand}${rule.diagnostics ? `\n diagnostics: [${rule.diagnostics.join(', ')}]` : ''}`).join('\n')}`).join('\n')}\n` : '';
92
+ write(file, [
93
+ '---', `id: ${id}`, `signature: ${signature}`, 'class: fixture', 'title: Fixture rule',
94
+ 'scope: in', 'status: lesson', 'sites: []', 'violates: Fixture', matchText.trimEnd(),
95
+ 'episodes: []', '---', '', '## Cue', '', 'Fixture cue.', '', '## Lesson', '', 'Fixture lesson.', ''
96
+ ].filter(Boolean).join('\n'));
97
+ }
98
+
99
+ function finalizeLedger(repo) {
100
+ const result = runNode(ERRORS_SYNC, ['--root', repo]);
101
+ assert.strictEqual(result.status, 0, `errors-sync failed: ${result.stderr}`);
102
+ git(repo, ['add', '-A']);
103
+ git(repo, ['commit', '-q', '-m', 'chore: prepare destination ledger']);
104
+ }
105
+
106
+ function addLesson(workspaceRoot, signature, destination, match = ACTIONS.push, id = 'sharedrawid') {
107
+ const result = localErrors.addProvisionalLesson({
108
+ workspaceRoot,
109
+ destination,
110
+ provisionalId: id,
111
+ signature,
112
+ match,
113
+ lesson: `PRIVATE_LESSON_SENTINEL for ${signature} at /private/PRIVATE_PATH_SENTINEL`,
114
+ cue: 'PRIVATE_CUE_SENTINEL',
115
+ issueUrl: 'https://private.example/PRIVATE_URL_SENTINEL'
116
+ }, { env: WRITER_ENV });
117
+ assert.ok(['appended', 'duplicate'].includes(result.status), `could not create real provisional fixture: ${result.status}`);
118
+ return result.record;
119
+ }
120
+
121
+ function addOccurrence(workspaceRoot, signature, destination, index) {
122
+ const result = localErrors.appendOccurrence({
123
+ workspaceRoot,
124
+ destination,
125
+ signature,
126
+ commandClass: 'test',
127
+ exitCode: 1,
128
+ sessionKey: `PRIVATE_SESSION_SENTINEL-${index}`,
129
+ toolUseId: `PRIVATE_TOOL_USE_SENTINEL-${index}`,
130
+ output: 'PRIVATE_EXCERPT_SENTINEL'
131
+ }, { env: WRITER_ENV });
132
+ assert.strictEqual(result.status, 'appended', `could not create real occurrence fixture: ${result.status}`);
133
+ return result.record;
134
+ }
135
+
136
+ function fileHash(file) {
137
+ try { return crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex'); }
138
+ catch (error) { if (error.code === 'ENOENT') return 'missing'; throw error; }
139
+ }
140
+
141
+ function treeHash(directory) {
142
+ if (!fs.existsSync(directory)) return 'missing';
143
+ const entries = [];
144
+ function visit(current) {
145
+ for (const name of fs.readdirSync(current).sort()) {
146
+ const file = path.join(current, name);
147
+ const stat = fs.lstatSync(file);
148
+ if (stat.isSymbolicLink()) entries.push([path.relative(directory, file), 'symlink']);
149
+ else if (stat.isDirectory()) visit(file);
150
+ else entries.push([path.relative(directory, file), fileHash(file)]);
151
+ }
152
+ }
153
+ visit(directory);
154
+ return crypto.createHash('sha256').update(JSON.stringify(entries)).digest('hex');
155
+ }
156
+
157
+ function scan(repo, destination, storeRoot = STORE, envOverrides = {}) {
158
+ const out = path.join(TMP, `reports-${crypto.randomBytes(5).toString('hex')}`);
159
+ fs.mkdirSync(out);
160
+ const storeFile = path.join(storeRoot, localErrors.INDEX_FILE);
161
+ const ledgerDir = path.join(repo, '.agents', 'harness-everything', 'errors');
162
+ const beforeStore = treeHash(storeRoot);
163
+ const beforeLedger = treeHash(ledgerDir);
164
+ const result = runNode(SCANNER, [
165
+ '--root', repo, '--no-memory', '--source', 'local-store', '--destination', destination,
166
+ '--out', out, '--json'
167
+ ], { HARNESS_OBSERVATIONS_DIR: storeRoot, HOME, USERPROFILE: HOME, ...envOverrides });
168
+ assert.strictEqual(result.status, 0,
169
+ `scanner exit ${result.status}; stderr: ${result.stderr.trim()}; stdout: ${result.stdout.trim()}`);
170
+ assert.strictEqual(result.stderr.trim(), '', 'successful scans do not write stderr');
171
+ const envelope = JSON.parse(result.stdout);
172
+ assert.strictEqual(envelope.ok, true, 'scanner JSON envelope reports success');
173
+ assert.strictEqual(treeHash(storeRoot), beforeStore, 'scan leaves the shared local store bytes unchanged');
174
+ assert.strictEqual(treeHash(ledgerDir), beforeLedger, 'scan leaves destination ledger bytes unchanged');
175
+ const report = JSON.parse(fs.readFileSync(envelope.reportJson, 'utf8'));
176
+ const markdown = fs.readFileSync(envelope.reportMd, 'utf8');
177
+ return { report, markdown, envelope, storeFile };
178
+ }
179
+
180
+ function localSource(report) {
181
+ return report.sources.find(source => source.type === 'local-store');
182
+ }
183
+
184
+ function localCandidates(report) {
185
+ return report.candidates.filter(candidate => candidate.sources.some(source => source.type === 'local-store'));
186
+ }
187
+
188
+ function bySignature(report, signature) {
189
+ return localCandidates(report).find(candidate => candidate.signature === signature);
190
+ }
191
+
192
+ function sourceRefs(candidate) {
193
+ return candidate.sources.filter(source => source.type === 'local-store').map(source => source.ref).sort();
194
+ }
195
+
196
+ function assertPrivate(report, markdown) {
197
+ const output = `${JSON.stringify(report)}\n${markdown}`;
198
+ for (const value of PRIVATE_VALUES) assert.ok(!output.includes(value), `private local value escaped: ${value}`);
199
+ }
200
+
201
+ function incompleteReaderSource() {
202
+ return [
203
+ "'use strict';",
204
+ "const fs = require('node:fs');",
205
+ "const path = require('node:path');",
206
+ "function called(name) { fs.appendFileSync(process.env.READER_CALL_LOG, name + '\\n'); }",
207
+ 'const reader = {',
208
+ ' SCHEMA_VERSION: 1,',
209
+ " INDEX_FILE: 'errors-index.json',",
210
+ " INDEX_KIND: 'local-error-store',",
211
+ " DESTINATIONS: ['harness', 'project', 'unknown'],",
212
+ " COMMAND_CLASSES: ['git', 'gh', 'test', 'build', 'package', 'shell'],",
213
+ ' LIMITS: { maxIndexBytes: 2 * 1024 * 1024, maxExcerptBytes: 2048, maxLessonChars: 4096, maxCueChars: 4096, maxMatchedLedgerIds: 16 },',
214
+ ' resolveWorkspaceKey(input) { called(\'resolveWorkspaceKey\'); return input.workspaceRoot; },',
215
+ " getStorePath() { called('getStorePath'); return { file: path.join(process.env.HARNESS_OBSERVATIONS_DIR, 'errors-index.json') }; },",
216
+ " listRecords() { called('listRecords'); return JSON.parse(fs.readFileSync(process.env.READER_FIXTURE_ROWS, 'utf8')); },",
217
+ ' validateMatch(match) { called(\'validateMatch\'); return match; }',
218
+ '};',
219
+ 'delete reader.DESTINATIONS;',
220
+ 'module.exports = reader;'
221
+ ].join('\n');
222
+ }
223
+
224
+ const legacy = makeRepo('legacy-target');
225
+ const legacyOut = path.join(TMP, 'legacy-reports');
226
+ fs.mkdirSync(legacyOut);
227
+ const freezeTime = path.join(TMP, 'freeze-time.js');
228
+ write(freezeTime, [
229
+ "const NativeDate = Date;",
230
+ "class FrozenDate extends NativeDate { constructor(...args) { super(...(args.length ? args : ['2026-11-25T12:34:56.000Z'])); } static now() { return NativeDate.parse('2026-11-25T12:34:56.000Z'); } }",
231
+ 'global.Date = FrozenDate;'
232
+ ].join('\n'));
233
+ const legacyRun = childProcess.spawnSync(process.execPath, [
234
+ '--require', freezeTime, SCANNER, '--root', legacy, '--no-memory', '--out', legacyOut, '--json'
235
+ ], { encoding: 'utf8', env: isolatedEnv({ HOME, USERPROFILE: HOME }), stdio: ['ignore', 'pipe', 'pipe'] });
236
+ assert.ifError(legacyRun.error);
237
+ assert.strictEqual(legacyRun.status, 0, `legacy control scan failed: ${legacyRun.stderr}`);
238
+ const legacyEnvelope = JSON.parse(legacyRun.stdout);
239
+ const legacyJsonBytes = fs.readFileSync(legacyEnvelope.reportJson, 'utf8');
240
+ const legacyMarkdownBytes = fs.readFileSync(legacyEnvelope.reportMd, 'utf8');
241
+ assert.strictEqual(legacyJsonBytes, JSON.stringify({
242
+ schemaVersion: 1,
243
+ root: 'legacy-target',
244
+ generatedAt: NOW,
245
+ options: { hideLedger: false, noMemory: true, memory: [], instructions: [], homeOverridden: false },
246
+ sources: [
247
+ { type: 'git', origin: 'history', status: 'used' },
248
+ { type: 'doc', origin: 'history', status: 'missing', reason: 'no repeated Markdown or docs paths found' },
249
+ { type: 'tracker', origin: 'offline', status: 'missing', reason: 'no --tracker file provided' },
250
+ { type: 'memory', origin: 'auto', status: 'disabled', verified: false, reason: 'disabled by --no-memory' },
251
+ { type: 'instruction', origin: 'repository', status: 'disabled', reason: 'disabled by --no-memory' },
252
+ { type: 'instruction', origin: 'global-explicit', status: 'disabled', reason: 'disabled by --no-memory' }
253
+ ],
254
+ candidates: []
255
+ }, null, 2) + '\n', 'no-source JSON report remains byte-identical to the legacy contract');
256
+ assert.strictEqual(legacyMarkdownBytes, [
257
+ '# Error ledger candidate report', '', '- Schema version: 1', '- Root: `legacy-target`', `- Generated: ${NOW}`,
258
+ '- Candidates: 0', '', '## Options', '', '- hideLedger: false', '- noMemory: true', '- memory: none',
259
+ '- instructions: none', '- homeOverridden: false', '', '## Sources', '',
260
+ '- `git` (history) — **used** — history',
261
+ '- `doc` (history) — **missing** — history — no repeated Markdown or docs paths found',
262
+ '- `tracker` (offline) — **missing** — offline — no --tracker file provided',
263
+ '- `memory` (auto) — **disabled** — auto — disabled by --no-memory — verified: false',
264
+ '- `instruction` (repository) — **disabled** — repository — disabled by --no-memory',
265
+ '- `instruction` (global-explicit) — **disabled** — global-explicit — disabled by --no-memory',
266
+ '', '## Candidates', '', ''
267
+ ].join('\n'), 'no-source Markdown report remains byte-identical to the legacy contract');
268
+
269
+ const workspaceA = makeRepo('workspace-a');
270
+ const workspaceB = makeRepo('workspace-b');
271
+ const workspaceCollision = makeRepo('workspace-collision');
272
+ addLedgerRecord(workspaceA, 'E-0001', 'duplicate-lesson', null);
273
+ addLedgerRecord(workspaceA, 'E-0002', 'existing-rule', ACTIONS.push);
274
+ addLedgerRecord(workspaceA, 'E-0003', 'ambiguous-lesson', null);
275
+ addLedgerRecord(workspaceA, 'E-0004', 'other-ambiguous', ACTIONS.pull);
276
+ finalizeLedger(workspaceA);
277
+ fs.mkdirSync(path.join(workspaceB, '.agents', 'harness-everything', 'errors'), { recursive: true });
278
+ finalizeLedger(workspaceB);
279
+ fs.mkdirSync(path.join(workspaceCollision, '.agents', 'harness-everything', 'errors'), { recursive: true });
280
+ finalizeLedger(workspaceCollision);
281
+
282
+ const sharedA = addLesson(workspaceA, 'shared-lesson', 'harness', ACTIONS.commit, 'sharedrawid');
283
+ const sharedB = addLesson(workspaceB, 'shared-lesson', 'harness', ACTIONS.commit, 'sharedrawid');
284
+ assert.strictEqual(sharedA.provisionalId, sharedB.provisionalId, 'positive control: both real writers accepted the same raw provisional ID');
285
+ addLesson(workspaceA, 'duplicate-lesson', 'harness', ACTIONS.commit, 'lesson-duplicate');
286
+ addLesson(workspaceA, 'rule-lesson', 'harness', ACTIONS.push, 'lesson-rule');
287
+ addLesson(workspaceA, 'ambiguous-lesson', 'harness', ACTIONS.pull, 'lesson-ambiguous');
288
+ addLesson(workspaceA, 'covered-lesson', 'harness', ACTIONS.commit, 'lesson-covered');
289
+ addLesson(workspaceA, 'project-lesson', 'project', ACTIONS.commit, 'lesson-project');
290
+ addLesson(workspaceA, 'unknown-lesson', 'unknown', ACTIONS.commit, 'lesson-unknown');
291
+ addLesson(workspaceB, 'workspace-b-only', 'harness', ACTIONS.commit, 'lesson-b-only');
292
+ addOccurrence(workspaceA, 'occurrence-class', 'harness', 1);
293
+ addOccurrence(workspaceA, 'occurrence-class', 'harness', 2);
294
+ addOccurrence(workspaceA, 'covered-lesson', 'harness', 3);
295
+ addOccurrence(workspaceA, 'project-occurrence', 'project', 4);
296
+ addOccurrence(workspaceA, 'unknown-occurrence', 'unknown', 5);
297
+ addOccurrence(workspaceB, 'workspace-b-occurrence', 'harness', 6);
298
+ const collisionOccurrence = addOccurrence(workspaceCollision, 'collision-occurrence', 'harness', 7);
299
+ const collisionRawId = collisionOccurrence.provisionalId;
300
+ PRIVATE_VALUES.push(collisionRawId);
301
+ const collisionLesson = addLesson(
302
+ workspaceCollision, 'collision-lesson', 'project', ACTIONS.commit, `${collisionRawId}-lesson`
303
+ );
304
+ addLesson(workspaceB, 'collision-id-other-workspace', 'harness', ACTIONS.commit, collisionRawId);
305
+ const collisionFixtureFile = path.join(STORE, localErrors.INDEX_FILE);
306
+ const collisionFixtureIndex = JSON.parse(fs.readFileSync(collisionFixtureFile, 'utf8'));
307
+ const collisionFixtureLesson = collisionFixtureIndex.records.find(record =>
308
+ record.kind === 'provisional-lesson' &&
309
+ record.workspaceKey === collisionLesson.workspaceKey &&
310
+ record.provisionalId === collisionLesson.provisionalId
311
+ );
312
+ assert.ok(collisionFixtureLesson, 'positive control: the lesson exists before creating a legacy collision');
313
+ collisionFixtureLesson.provisionalId = collisionRawId;
314
+ fs.writeFileSync(collisionFixtureFile, `${JSON.stringify(collisionFixtureIndex)}\n`);
315
+ const distinctLesson = addLesson(workspaceCollision, 'distinct-lesson-signature', 'harness', ACTIONS.commit, 'distinct-lesson-id');
316
+ const distinctOccurrence = addOccurrence(workspaceCollision, 'distinct-occurrence-signature', 'harness', 8);
317
+ PRIVATE_VALUES.push(distinctOccurrence.provisionalId);
318
+ const survivingLesson = addLesson(workspaceCollision, 'surviving-lesson', 'harness', ACTIONS.commit, 'surviving-lesson-id');
319
+
320
+ const baselineStore = fs.readFileSync(path.join(STORE, localErrors.INDEX_FILE));
321
+ const firstA = scan(workspaceA, 'harness');
322
+ const statusA = localSource(firstA.report);
323
+ assert.ok(statusA, 'opt-in reports local-store status');
324
+ assert.strictEqual(statusA.status, 'used');
325
+ assert.strictEqual(statusA.destination, 'harness');
326
+ assert.match(statusA.workspaceRef, /^w-local-[a-f0-9]{64}$/);
327
+ assert.strictEqual(statusA.counts.destinationMismatch, 2);
328
+ assert.strictEqual(statusA.counts.unknownDestination, 2);
329
+ assert.strictEqual(statusA.counts.malformed, 0);
330
+ assert.strictEqual(localCandidates(firstA.report).length, 6, 'one lead per lesson plus one clustered uncovered occurrence signature');
331
+ assert.strictEqual(bySignature(firstA.report, 'occurrence-class').sources.filter(source => source.type === 'local-store').length, 2,
332
+ 'occurrences with the same signature form one lead with both opaque refs');
333
+ assert.strictEqual(bySignature(firstA.report, 'covered-lesson').sources.filter(source => source.kind === 'occurrence').length, 0,
334
+ 'an occurrence cluster covered by a lesson is suppressed');
335
+ assert.ok(!bySignature(firstA.report, 'project-lesson'));
336
+ assert.ok(!bySignature(firstA.report, 'unknown-lesson'));
337
+ assert.ok(!bySignature(firstA.report, 'project-occurrence'));
338
+ assert.ok(!bySignature(firstA.report, 'unknown-occurrence'));
339
+ assert.strictEqual(bySignature(firstA.report, 'shared-lesson').local.evidenceReadiness, 'needs-evidence');
340
+ assert.strictEqual(bySignature(firstA.report, 'shared-lesson').local.dedupe.status, 'none');
341
+ assert.strictEqual(bySignature(firstA.report, 'shared-lesson').local.dedupe.newClassEligible, true);
342
+ assert.deepStrictEqual(bySignature(firstA.report, 'duplicate-lesson').local.dedupe,
343
+ { status: 'existing', classIds: ['E-0001'], matchedBy: ['signature'], newClassEligible: false });
344
+ assert.deepStrictEqual(bySignature(firstA.report, 'rule-lesson').local.dedupe,
345
+ { status: 'existing', classIds: ['E-0002'], matchedBy: ['whole-rule'], newClassEligible: false });
346
+ assert.deepStrictEqual(bySignature(firstA.report, 'ambiguous-lesson').local.dedupe,
347
+ { status: 'ambiguous', classIds: ['E-0003', 'E-0004'], matchedBy: ['signature', 'whole-rule'], newClassEligible: false });
348
+ assertPrivate(firstA.report, firstA.markdown);
349
+ assert.ok(!JSON.stringify(firstA.report).includes(sharedA.workspaceKey), 'raw workspace keys stay private');
350
+ assert.ok(firstA.markdown.includes('needs-evidence'), 'Markdown carries evidence readiness');
351
+ assert.ok(firstA.markdown.includes('ambiguous'), 'Markdown carries exact dedupe outcome');
352
+
353
+ const secondA = scan(workspaceA, 'harness');
354
+ assert.deepStrictEqual(sourceRefs(bySignature(secondA.report, 'shared-lesson')),
355
+ sourceRefs(bySignature(firstA.report, 'shared-lesson')), 'repeat scan preserves the record ref');
356
+ const scanB = scan(workspaceB, 'harness');
357
+ assert.strictEqual(localCandidates(scanB.report).length, 4, 'workspace B sees its same-ID row independently from workspace C');
358
+ assert.strictEqual(sourceRefs(bySignature(scanB.report, 'shared-lesson')).length, 1);
359
+ assert.notDeepStrictEqual(sourceRefs(bySignature(scanB.report, 'shared-lesson')),
360
+ sourceRefs(bySignature(firstA.report, 'shared-lesson')), 'same raw provisional ID has a different ref in another workspace');
361
+ assert.ok(!bySignature(scanB.report, 'duplicate-lesson'));
362
+ assert.ok(bySignature(scanB.report, 'workspace-b-only'));
363
+ assert.ok(bySignature(scanB.report, 'collision-id-other-workspace'), 'a matching raw ID in another workspace remains isolated');
364
+
365
+ const projectScan = scan(workspaceA, 'project');
366
+ assert.strictEqual(localSource(projectScan.report).destination, 'project');
367
+ assert.ok(bySignature(projectScan.report, 'project-lesson'));
368
+ assert.ok(bySignature(projectScan.report, 'project-occurrence'));
369
+ assert.strictEqual(localCandidates(projectScan.report).length, 2, 'project destination includes only project records');
370
+
371
+ const missingStore = path.join(TMP, 'missing-store');
372
+ const missing = scan(workspaceA, 'harness', missingStore);
373
+ assert.strictEqual(localSource(missing.report).status, 'missing');
374
+ assert.strictEqual(localSource(missing.report).reason, 'index-missing');
375
+ assert.strictEqual(localCandidates(missing.report).length, 0);
376
+
377
+ const emptyStore = path.join(TMP, 'empty-store');
378
+ fs.mkdirSync(emptyStore);
379
+ write(path.join(emptyStore, localErrors.INDEX_FILE), `${JSON.stringify({
380
+ schemaVersion: localErrors.SCHEMA_VERSION, kind: localErrors.INDEX_KIND, records: []
381
+ })}\n`);
382
+ const empty = scan(workspaceA, 'harness', emptyStore);
383
+ assert.strictEqual(localSource(empty.report).status, 'unverified');
384
+ assert.strictEqual(localSource(empty.report).reason, 'empty-reader-result');
385
+
386
+ const rawStoreFile = path.join(STORE, localErrors.INDEX_FILE);
387
+ const validStoreBytes = fs.readFileSync(rawStoreFile);
388
+ try {
389
+ fs.writeFileSync(rawStoreFile, '{invalid json');
390
+ const corruptBytes = fs.readFileSync(rawStoreFile);
391
+ const corrupt = scan(workspaceA, 'harness');
392
+ assert.strictEqual(localSource(corrupt.report).status, 'unverified');
393
+ assert.strictEqual(localSource(corrupt.report).reason, 'store-corrupt');
394
+ assert.deepStrictEqual(fs.readFileSync(rawStoreFile), corruptBytes, 'corrupt store fixture bytes remain unchanged by scan');
395
+ } finally { fs.writeFileSync(rawStoreFile, validStoreBytes); }
396
+
397
+ const unreadableStore = path.join(TMP, 'unreadable-store');
398
+ fs.mkdirSync(unreadableStore);
399
+ fs.mkdirSync(path.join(unreadableStore, localErrors.INDEX_FILE));
400
+ const unreadable = scan(workspaceA, 'harness', unreadableStore);
401
+ assert.strictEqual(localSource(unreadable.report).status, 'unverified');
402
+ assert.strictEqual(localSource(unreadable.report).reason, 'store-unreadable');
403
+
404
+ const beforeMalformed = fs.readFileSync(rawStoreFile);
405
+ try {
406
+ const index = JSON.parse(beforeMalformed.toString('utf8'));
407
+ const row = index.records.find(record => record.workspaceKey === sharedA.workspaceKey && record.kind === 'provisional-lesson');
408
+ assert.ok(row, 'positive control: fixture contains a real writer-generated row');
409
+ row.destination = 'not-a-destination';
410
+ fs.writeFileSync(rawStoreFile, `${JSON.stringify(index)}\n`);
411
+ const malformedBytes = fs.readFileSync(rawStoreFile);
412
+ const malformed = scan(workspaceA, 'harness');
413
+ assert.strictEqual(localSource(malformed.report).status, 'unverified');
414
+ assert.strictEqual(localSource(malformed.report).counts.malformed, 1);
415
+ assert.ok(!JSON.stringify(malformed.report).includes('not-a-destination'));
416
+ assert.deepStrictEqual(fs.readFileSync(rawStoreFile), malformedBytes, 'malformed store bytes remain unchanged by scan');
417
+ } finally { fs.writeFileSync(rawStoreFile, beforeMalformed); }
418
+
419
+ const mismatch = scan(workspaceA, 'harness', STORE, { HARNESS_WORKSPACE_ROOT: workspaceB });
420
+ assert.strictEqual(localSource(mismatch.report).status, 'unverified');
421
+ assert.strictEqual(localSource(mismatch.report).reason, 'workspace-binding-mismatch');
422
+ assert.strictEqual(localCandidates(mismatch.report).length, 0);
423
+
424
+ const ledgerIndex = path.join(workspaceA, '.agents', 'harness-everything', 'errors', 'index.jsonl');
425
+ const validLedgerBytes = fs.readFileSync(ledgerIndex);
426
+ try {
427
+ fs.rmSync(ledgerIndex);
428
+ fs.mkdirSync(ledgerIndex);
429
+ const unreadableLedger = scan(workspaceA, 'harness');
430
+ assert.strictEqual(localSource(unreadableLedger.report).ledgerStatus, 'unverified');
431
+ assert.strictEqual(localSource(unreadableLedger.report).ledgerReason, 'ledger-unreadable');
432
+ assert.strictEqual(bySignature(unreadableLedger.report, 'shared-lesson').local.dedupe.status, 'unverified');
433
+ assert.strictEqual(bySignature(unreadableLedger.report, 'shared-lesson').local.dedupe.newClassEligible, false);
434
+ } finally {
435
+ fs.rmSync(ledgerIndex, { recursive: true, force: true });
436
+ fs.writeFileSync(ledgerIndex, validLedgerBytes);
437
+ }
438
+
439
+ function failedArgs(args, diagnostic) {
440
+ const result = runNode(SCANNER, ['--root', workspaceA, '--no-memory', ...args, '--json'], {
441
+ HARNESS_OBSERVATIONS_DIR: STORE, HOME, USERPROFILE: HOME
442
+ });
443
+ assert.strictEqual(result.status, 2, `expected CLI argument failure for ${args.join(' ')}`);
444
+ assert.match(result.stderr.trim(), diagnostic);
445
+ }
446
+ failedArgs(['--source', 'other', '--destination', 'harness'], /unknown source/);
447
+ failedArgs(['--source', 'local-store', '--source', 'local-store', '--destination', 'harness'], /duplicate option: --source/);
448
+ failedArgs(['--source', 'local-store'], /--destination is required/);
449
+ failedArgs(['--source', 'local-store', '--destination', 'unknown'], /invalid --destination/);
450
+ failedArgs(['--destination', 'harness'], /--destination requires --source local-store/);
451
+
452
+ const packagedOut = path.join(TMP, 'packaged-reports');
453
+ fs.mkdirSync(packagedOut);
454
+ const packaged = runNode(PACKAGED_SCANNER, [
455
+ '--root', workspaceA, '--no-memory', '--source', 'local-store', '--destination', 'harness',
456
+ '--out', packagedOut, '--json'
457
+ ], { HARNESS_OBSERVATIONS_DIR: STORE, HOME, USERPROFILE: HOME });
458
+ assert.strictEqual(packaged.status, 0, `packaged scan must fail safe when the store contract is absent: ${packaged.stderr}`);
459
+ const packagedEnvelope = JSON.parse(packaged.stdout);
460
+ const packagedReport = JSON.parse(fs.readFileSync(packagedEnvelope.reportJson, 'utf8'));
461
+ assert.strictEqual(localSource(packagedReport).status, 'unavailable');
462
+ assert.strictEqual(localSource(packagedReport).reason, 'reader-unavailable');
463
+ assert.strictEqual(localCandidates(packagedReport).length, 0);
464
+
465
+ function verifyProvisionalCollision() {
466
+ const originalBytes = fs.readFileSync(rawStoreFile);
467
+ const index = JSON.parse(originalBytes.toString('utf8'));
468
+ const collisionRows = index.records.filter(record =>
469
+ record.workspaceKey === collisionLesson.workspaceKey && record.provisionalId === collisionRawId);
470
+ assert.deepStrictEqual(collisionRows.map(record => record.kind).sort(), ['occurrence', 'provisional-lesson']);
471
+ try {
472
+ for (const records of [index.records, [...index.records].reverse()]) {
473
+ fs.writeFileSync(rawStoreFile, `${JSON.stringify({ ...index, records })}\n`);
474
+ const { report, markdown } = scan(workspaceCollision, 'harness');
475
+ const source = localSource(report);
476
+ assert.deepStrictEqual({
477
+ status: source.status,
478
+ reason: source.reason,
479
+ malformed: source.counts.malformed,
480
+ workspaceRecords: source.counts.workspaceRecords,
481
+ destinationMismatch: source.counts.destinationMismatch,
482
+ candidates: localCandidates(report).map(candidate => candidate.signature).sort()
483
+ }, {
484
+ status: 'unverified',
485
+ reason: 'provisional-id-collision',
486
+ malformed: 2,
487
+ workspaceRecords: 3,
488
+ destinationMismatch: 0,
489
+ candidates: ['distinct-lesson-signature', 'distinct-occurrence-signature', 'surviving-lesson']
490
+ }, 'both cross-kind rows are excluded while unrelated and distinct-ID leads survive');
491
+ assert.notStrictEqual(distinctLesson.provisionalId, distinctOccurrence.provisionalId);
492
+ assert.strictEqual(sourceRefs(bySignature(report, 'distinct-lesson-signature')).length, 1);
493
+ assert.strictEqual(sourceRefs(bySignature(report, 'distinct-occurrence-signature')).length, 1);
494
+ assert.notDeepStrictEqual(
495
+ sourceRefs(bySignature(report, 'distinct-lesson-signature')),
496
+ sourceRefs(bySignature(report, 'distinct-occurrence-signature')),
497
+ 'distinct IDs retain distinct opaque refs');
498
+ assert.ok(bySignature(report, 'surviving-lesson'), 'an unrelated lead survives');
499
+ assert.ok(!bySignature(report, 'collision-lesson'));
500
+ assert.ok(!bySignature(report, 'collision-occurrence'));
501
+ assertPrivate(report, markdown);
502
+ }
503
+ } finally { fs.writeFileSync(rawStoreFile, originalBytes); }
504
+ }
505
+
506
+ function verifyIncompleteReaderContract() {
507
+ const fixtureRoot = path.join(TMP, 'incomplete-reader');
508
+ const fixtureScanner = path.join(fixtureRoot, 'error-ledger-bootstrap', 'scripts', 'scan.js');
509
+ write(fixtureScanner, fs.readFileSync(SCANNER, 'utf8'));
510
+ write(path.join(fixtureRoot, 'hooks', 'scripts', 'lib', 'local-errors.js'), incompleteReaderSource());
511
+
512
+ const readerRowsFile = path.join(TMP, 'incomplete-reader-rows.json');
513
+ write(readerRowsFile, JSON.stringify([{
514
+ schemaVersion: localErrors.SCHEMA_VERSION,
515
+ kind: 'occurrence',
516
+ workspaceKey: workspaceA,
517
+ provisionalId: 'readerprivateid',
518
+ destination: 'harness',
519
+ signature: 'reader-contract-control',
520
+ createdAt: NOW,
521
+ source: 'tool-failure',
522
+ host: 'unknown',
523
+ commandClass: 'test',
524
+ exitCode: 1,
525
+ sessionKey: null,
526
+ toolUseId: null,
527
+ outputExcerpt: 'PRIVATE_READER_ROW_SENTINEL',
528
+ matchedLedgerIds: []
529
+ }]));
530
+ const readerCallLog = path.join(TMP, 'incomplete-reader-calls.txt');
531
+ const out = path.join(TMP, 'incomplete-reader-reports');
532
+ fs.mkdirSync(out);
533
+ const ledgerDir = path.join(workspaceA, '.agents', 'harness-everything', 'errors');
534
+ const beforeStore = treeHash(STORE);
535
+ const beforeLedger = treeHash(ledgerDir);
536
+ const result = runNode(fixtureScanner, [
537
+ '--root', workspaceA, '--no-memory', '--source', 'local-store', '--destination', 'harness',
538
+ '--out', out, '--json'
539
+ ], {
540
+ HARNESS_OBSERVATIONS_DIR: STORE,
541
+ READER_CALL_LOG: readerCallLog,
542
+ READER_FIXTURE_ROWS: readerRowsFile,
543
+ HOME,
544
+ USERPROFILE: HOME
545
+ });
546
+ assert.strictEqual(result.status, 0,
547
+ `incomplete reader should produce a safe report; exit ${result.status}; stderr: ${result.stderr.trim()}; stdout: ${result.stdout.trim()}`);
548
+ assert.strictEqual(result.stderr.trim(), '');
549
+ const envelope = JSON.parse(result.stdout);
550
+ const report = JSON.parse(fs.readFileSync(envelope.reportJson, 'utf8'));
551
+ const markdown = fs.readFileSync(envelope.reportMd, 'utf8');
552
+ assert.strictEqual(localSource(report).status, 'unavailable');
553
+ assert.strictEqual(localSource(report).reason, 'reader-contract-incomplete');
554
+ assert.strictEqual(localCandidates(report).length, 0);
555
+ assert.ok(!fs.existsSync(readerCallLog), 'incomplete reader is rejected before any reader function is called');
556
+ const otherSources = new Set(report.sources.filter(source => source.type !== 'local-store').map(source => source.type));
557
+ for (const type of ['git', 'doc', 'tracker', 'memory', 'instruction']) {
558
+ assert.ok(otherSources.has(type), `non-local source ${type} remains in the report`);
559
+ }
560
+ assertPrivate(report, markdown);
561
+ assert.strictEqual(treeHash(STORE), beforeStore, 'incomplete reader scan leaves store bytes unchanged');
562
+ assert.strictEqual(treeHash(ledgerDir), beforeLedger, 'incomplete reader scan leaves ledger bytes unchanged');
563
+ }
564
+
565
+ const acceptanceFailures = [];
566
+ function runAcceptanceCase(name, test) {
567
+ try { test(); }
568
+ catch (error) { acceptanceFailures.push(`${name}: ${error.message}`); }
569
+ }
570
+ runAcceptanceCase('F1 cross-kind collision', verifyProvisionalCollision);
571
+ runAcceptanceCase('F2 incomplete reader', verifyIncompleteReaderContract);
572
+ if (acceptanceFailures.length) {
573
+ process.stderr.write(`Scanner acceptance failures:\n${acceptanceFailures.join('\n')}\n`);
574
+ process.exitCode = 1;
575
+ }
576
+
577
+ assert.deepStrictEqual(fs.readFileSync(rawStoreFile), baselineStore, 'the fixture store is restored byte-for-byte');
578
+ if (!acceptanceFailures.length) {
579
+ console.log('Local-store scanner CLI verified: legacy bytes, workspace isolation, collision handling, reader contract, redaction, statuses, dedupe, and packaged fallback.');
580
+ }
581
+
582
+ try { fs.rmSync(TMP, { recursive: true, force: true }); } catch (_) { /* temporary fixture cleanup */ }
@@ -4,7 +4,7 @@ description: "Bootstrap a local error ledger for an existing repository by inven
4
4
  license: Apache-2.0
5
5
  metadata:
6
6
  author: Miya Daniel
7
- version: 0.55.0
7
+ version: 1.2.0
8
8
  ---
9
9
 
10
10
  # Error Ledger Bootstrap
@@ -14,6 +14,18 @@ Bug/regression/flake labels or `fix`/`bug` title prefixes qualify; reports keep
14
14
  - `--hide-ledger` excludes existing error-ledger files from the scan.
15
15
  - `--home <dir>` changes the local home used to resolve automatic memory.
16
16
 
17
+ ## Optional local error store
18
+
19
+ Local observations are opt-in: `--source local-store --destination harness|project`. With no `--source` option, the scanner keeps the legacy report bytes and source set. `--destination` is required with this source and accepts only `harness` or `project`; it is the operator's declaration for the canonical Git `--root`.
20
+
21
+ The scanner derives the workspace key from that root, calls the supported reader as `listRecords({ workspaceRoot, workspaceKey })`, and accepts only returned rows carrying that key. A bound host workspace that disagrees fails closed. The report binds the resolved destination to an opaque `workspaceRef`; each record ref is `p-local-<sha256>` over the workspace key and validated stored provisional ID. Raw provisional IDs are never reported. If the reader contract is absent (including the packaged Skills-only copy), the scan succeeds with source status `unavailable` and reason `reader-unavailable`.
22
+
23
+ The `local-store` source status is `used`, `missing`, `unverified`, or `unavailable`. Missing indexes use `index-missing`; unreadable or corrupt input uses a sanitized reason such as `store-unreadable`, `store-corrupt`, or `store-unsupported`. An empty reader result is `unverified` (`empty-reader-result`) because the reader returns an empty array for both an empty workspace and several read failures. Invalid rows are skipped and counted as `malformed`; they are never quoted. The report separately counts valid rows assigned to another destination and rows whose destination is `unknown`.
24
+
25
+ Each valid destination-matched provisional lesson yields one neutral local lead. Occurrences are grouped by exact signature and suppressed when a selected lesson covers that signature. JSON and Markdown contain only opaque refs, validated destination/kind/command-class metadata, signatures, counts, and dedupe/evidence results. They never include excerpts, cues, lesson text, issue URLs, paths, session IDs, or tool-use IDs. Keep the reports local; the local store and destination ledger are read-only during scan.
26
+
27
+ Each lead's `local` object includes `evidenceReadiness: needs-evidence`, `occurrenceCount`, and `dedupe`. The dedupe object contains `status` (`none`, `existing`, `ambiguous`, or `unverified`), sorted `classIds`, sorted `matchedBy` values (`signature` and/or `whole-rule`), and `newClassEligible`. The scanner checks only the selected destination's `index.jsonl`: a unique exact signature or exact whole-rule match (validated with the existing matcher validator) reports `existing` and its E-ID; matches to multiple E-IDs report `ambiguous`; an unreadable index reports `unverified`; otherwise the status is `none`. Only `none` sets `newClassEligible: true`, and that means only that exact dedupe found no existing class. The local lead still needs independently corroborated Git or documentation evidence and fresh item approval before promotion. Fuzzy matches remain for local classification.
28
+
17
29
  Treat memory and instructions as private input. A local report may include opaque source IDs, a neutral generated title or a short summary the operator reviewed locally, and only site paths verified to exist in the target repository. Keep raw source text, excerpts, private filenames and paths, credentials, and personal identifiers out of both report formats. The scanner emits reports outside the target repository: by default, into a private temporary directory; `--out <dir>` must also resolve outside the target, including through symlinks. Keep both reports local, including for company repositories.
18
30
 
19
31
  ## Classify candidates locally
@@ -26,6 +38,8 @@ Obtain explicit owner approval for each candidate. Bind the approval to the exac
26
38
 
27
39
  The top-level approval JSON has `schemaVersion: 1`, a 20-character hexadecimal `candidateId`, a 64-character hexadecimal `reportSha256` of the exact report bytes, an absolute canonical `targetRoot` matching `--target`, a non-empty `approvedBy`, and a parseable `approvedAt` timestamp. Its `record` object has a kebab-case `signature`; non-empty `class`, `title`, `violates`, and `sourcesNote`; `scope` of `in`, `out`, or `unresolved`; `status` of `open`, `lesson`, or `mechanism`; and `sites`, an array of existing target-repository files named by relative paths without absolute paths or `.` or `..` components. Do not put absolute paths in `approvedBy`, `approvedAt`, or the record text fields. The approved candidate must occur exactly once in the report, and the selected and approved site files must exist in the target.
28
40
 
41
+ For a candidate with a `local-store` source, also include top-level `destination: harness` or `destination: project` in the approval. Promotion requires one `used` workspace binding whose opaque ref resolves to canonical `--target` through the trusted Harness checkout's local-store reader; every candidate ref must still resolve to a row for that workspace and destination. The report's exact-dedupe result must be eligible, and the candidate must carry a verified Git or documentation commit source that exists in the target repository on that same candidate. Promotion rechecks exact signature and whole-rule dedupe against the current destination ledger while holding the promotion lock. Missing, unknown, mismatched, stale, or unreadable local bindings fail closed before ledger changes. Legacy reports without a local-store source keep their existing approval shape. A stored issue URL is only a local lead and never satisfies the durable-source requirement.
42
+
29
43
  Use this complete example as the approval file structure, replacing the sample candidate ID and digest with the exact report values, `targetRoot` with the target's absolute canonical path, and the approver, timestamp, and reviewed record content with the owner's approval:
30
44
 
31
45
  ```json
@@ -59,7 +73,7 @@ mkdir -p "<target repo>/.agents/harness-everything/errors"
59
73
 
60
74
  Promotion refuses when the directory is absent. No index file is needed beforehand; successful promotion updates the index through the sync command below.
61
75
 
62
- Before promotion, resolve a trusted local Harness checkout containing `scripts/errors-sync.js` and verify its Node dependencies are installed. The current sync script requires `js-yaml`; a read-only preflight is:
76
+ Before promotion, resolve a trusted local Harness checkout containing `scripts/errors-sync.js` and verify its Node dependencies are installed. Local-store candidates also require `hooks/scripts/lib/local-errors.js` in that checkout. The current sync script requires `js-yaml`; a read-only preflight is:
63
77
 
64
78
  ```sh
65
79
  test -f "<Harness checkout>/scripts/errors-sync.js"