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
@@ -195,19 +195,141 @@ function harnessTool(harnessInput) {
195
195
  catch (error) {
196
196
  problem(`Harness checkout cannot resolve js-yaml; install its Node dependencies and retry with that checkout (${error.message})`);
197
197
  }
198
- return script;
198
+ return { root, syncScript: script };
199
199
  }
200
200
 
201
- function durableSources(candidate) {
201
+ function localStoreTool(harnessRoot) {
202
+ const file = path.join(harnessRoot, 'hooks', 'scripts', 'lib', 'local-errors.js');
203
+ try {
204
+ const store = require(file);
205
+ if (typeof store.resolveWorkspaceKey !== 'function' || typeof store.listRecords !== 'function' ||
206
+ typeof store.validateMatch !== 'function') throw new Error('local-store reader contract is incomplete');
207
+ return store;
208
+ } catch (_) {
209
+ problem('local-store promotion requires hooks/scripts/lib/local-errors.js in the trusted Harness checkout');
210
+ }
211
+ }
212
+
213
+ function workspaceRef(workspaceKey) {
214
+ return `w-local-${hash(workspaceKey)}`;
215
+ }
216
+
217
+ function localStoreRef(workspaceKey, provisionalId) {
218
+ return `p-local-${hash(JSON.stringify([workspaceKey, provisionalId]))}`;
219
+ }
220
+
221
+ function validateLocalLead(report, candidate, approval, targetRoot, harnessRoot) {
222
+ const localSources = Array.isArray(candidate.sources)
223
+ ? candidate.sources.filter(source => source && source.type === 'local-store') : [];
224
+ if (!localSources.length) return null;
225
+
226
+ const bindings = Array.isArray(report.sources)
227
+ ? report.sources.filter(source => source && source.type === 'local-store') : [];
228
+ if (bindings.length !== 1 || bindings[0].origin !== 'workspace' || bindings[0].status !== 'used') {
229
+ problem('local-store report must contain one used workspace binding');
230
+ }
231
+ const binding = bindings[0];
232
+ if (binding.destination === 'unknown' || !['harness', 'project'].includes(binding.destination) ||
233
+ !['harness', 'project'].includes(approval.destination)) {
234
+ problem('local-store promotion requires a known harness or project destination');
235
+ }
236
+ if (binding.destination !== approval.destination ||
237
+ localSources.some(source => source.destination !== binding.destination)) {
238
+ problem('approved destination does not match the local-store report destination');
239
+ }
240
+ if (candidate.local?.evidenceReadiness !== 'needs-evidence' ||
241
+ candidate.local?.dedupe?.status !== 'none' || candidate.local?.dedupe?.newClassEligible !== true ||
242
+ !Array.isArray(candidate.local?.dedupe?.classIds) || candidate.local.dedupe.classIds.length !== 0) {
243
+ problem('local-store candidate is not eligible under its scanned exact-dedupe result');
244
+ }
245
+
246
+ const store = localStoreTool(harnessRoot);
247
+ let workspaceKey;
248
+ try { workspaceKey = store.resolveWorkspaceKey({ workspaceRoot: targetRoot }); }
249
+ catch (_) { problem('cannot resolve the local-store workspace for the canonical --target'); }
250
+ if (!/^w-local-[a-f0-9]{64}$/.test(binding.workspaceRef || '') || binding.workspaceRef !== workspaceRef(workspaceKey)) {
251
+ problem('local-store report workspace binding does not match the canonical --target');
252
+ }
253
+
254
+ let records;
255
+ try { records = store.listRecords({ workspaceRoot: targetRoot, workspaceKey }); }
256
+ catch (_) { problem('cannot read local-store records for the canonical --target'); }
257
+ const seen = new Set();
258
+ const matchedRecords = [];
259
+ for (const source of localSources) {
260
+ if (typeof source.ref !== 'string' || !/^p-local-[a-f0-9]{64}$/.test(source.ref) ||
261
+ source.signature !== candidate.signature || seen.has(source.ref)) {
262
+ problem('local-store candidate contains an invalid or duplicate opaque reference');
263
+ }
264
+ seen.add(source.ref);
265
+ const matches = records.filter(record => localStoreRef(workspaceKey, record.provisionalId) === source.ref);
266
+ if (matches.length !== 1 || matches[0].workspaceKey !== workspaceKey ||
267
+ matches[0].destination !== binding.destination || matches[0].signature !== candidate.signature ||
268
+ matches[0].kind !== source.kind) {
269
+ problem('local-store candidate reference is unavailable or does not match its report binding');
270
+ }
271
+ matchedRecords.push(matches[0]);
272
+ }
273
+ return { store, records: matchedRecords };
274
+ }
275
+
276
+ function hasTargetCommit(targetRoot, sha) {
277
+ const result = childProcess.spawnSync('git', ['-C', targetRoot, 'cat-file', '-e', `${sha}^{commit}`], {
278
+ env: { ...process.env, GIT_CONFIG_NOSYSTEM: '1' },
279
+ stdio: 'ignore'
280
+ });
281
+ return !result.error && result.status === 0;
282
+ }
283
+
284
+ function durableSources(candidate, targetRoot, verifyTarget = false) {
202
285
  const sources = new Set();
203
286
  for (const source of Array.isArray(candidate.sources) ? candidate.sources : []) {
204
- if (source && ['git', 'doc'].includes(source.type) && typeof source.sha === 'string' && COMMIT.test(source.sha)) {
287
+ if (source && ['git', 'doc'].includes(source.type) && typeof source.sha === 'string' &&
288
+ COMMIT.test(source.sha) && (!verifyTarget || hasTargetCommit(targetRoot, source.sha))) {
205
289
  sources.add(`commit ${source.sha.toLowerCase()}`);
206
290
  }
207
291
  }
208
292
  return [...sources].sort();
209
293
  }
210
294
 
295
+ function canonicalMatch(match, store) {
296
+ const validated = store.validateMatch(match);
297
+ const normalized = {};
298
+ for (const phase of ['actions', 'failures']) {
299
+ if (!validated[phase]) continue;
300
+ normalized[phase] = validated[phase].map(rule => ({
301
+ ...rule,
302
+ ...(rule.diagnostics ? { diagnostics: [...rule.diagnostics].sort() } : {})
303
+ })).sort((left, right) => JSON.stringify(left).localeCompare(JSON.stringify(right)));
304
+ }
305
+ return JSON.stringify(normalized);
306
+ }
307
+
308
+ function assertFreshDedupe(context) {
309
+ let rendered;
310
+ try {
311
+ const sync = require(context.syncScript);
312
+ if (typeof sync.render !== 'function') throw new Error('trusted errors-sync does not expose its renderer');
313
+ rendered = sync.render(context.targetRoot);
314
+ } catch (_) {
315
+ problem('destination ledger cannot be read safely for exact dedupe');
316
+ }
317
+ const current = indexState(context.index);
318
+ if (!current.bytes || current.bytes.toString('utf8') !== rendered) {
319
+ problem('destination ledger index is stale or unavailable; refresh it and rescan before promotion');
320
+ }
321
+
322
+ const signatures = new Set([context.candidate.signature, context.approval.record.signature]);
323
+ const rules = new Set(context.localLead.records.filter(record => record.match)
324
+ .map(record => canonicalMatch(record.match, context.localLead.store)));
325
+ const rows = rendered.split(/\r?\n/).filter(Boolean).map(line => JSON.parse(line));
326
+ for (const row of rows) {
327
+ if (signatures.has(row.signature) || (row.match && rules.has(canonicalMatch(row.match, context.localLead.store)))) {
328
+ problem('destination ledger contains an exact duplicate class; rescan and obtain fresh approval');
329
+ }
330
+ }
331
+ }
332
+
211
333
  function assertApprovalUnused(errorsDir, approvalHash) {
212
334
  for (const name of fs.readdirSync(errorsDir)) {
213
335
  if (!RECORD_NAME.test(name)) continue;
@@ -224,10 +346,10 @@ function yaml(value) {
224
346
  return JSON.stringify(value);
225
347
  }
226
348
 
227
- function recordText(approval, candidate, id, reportHash, approvalHash) {
349
+ function recordText(approval, candidate, id, reportHash, approvalHash, targetRoot, verifyTarget) {
228
350
  const record = approval.record;
229
351
  const sources = [...new Set([
230
- ...durableSources(candidate),
352
+ ...durableSources(candidate, targetRoot, verifyTarget),
231
353
  ...record.sites.map(site => `repo/${site.replace(/\\/g, '/')}`)
232
354
  ])].sort();
233
355
  return [
@@ -338,9 +460,18 @@ function preflight(options) {
338
460
  if (!samePath(targetRoot, approval.targetRoot)) problem('approval targetRoot does not match the resolved --target');
339
461
  validateSites(candidate.sites, targetRoot, 'selected report candidate sites');
340
462
  validateSites(approval.record.sites, targetRoot, 'approved record sites');
341
- if (!durableSources(candidate).length) problem('selected report candidate has no durable source evidence');
463
+ const hasLocalSource = Array.isArray(candidate.sources) &&
464
+ candidate.sources.some(source => source && source.type === 'local-store');
465
+ let harness = hasLocalSource ? harnessTool(options.harness) : null;
466
+ const localLead = hasLocalSource
467
+ ? validateLocalLead(report, candidate, approval, targetRoot, harness.root) : null;
468
+ if (!durableSources(candidate, targetRoot, Boolean(localLead)).length) {
469
+ problem(localLead
470
+ ? 'selected report candidate has no verified durable source evidence in the target repository'
471
+ : 'selected report candidate has no durable source evidence');
472
+ }
473
+ if (!harness) harness = harnessTool(options.harness);
342
474
  const { errorsDir, index } = directoryInfo(targetRoot);
343
- const syncScript = harnessTool(options.harness);
344
475
  const lockPath = path.join(errorsDir, LOCK);
345
476
  try {
346
477
  fs.lstatSync(lockPath);
@@ -354,7 +485,10 @@ function preflight(options) {
354
485
  const next = nextId(errorsDir, index);
355
486
  const destination = checkDestination(errorsDir, next.id, approval.record.signature, lockPath);
356
487
  assertApprovalUnused(errorsDir, approvalHash);
357
- return { approval, candidate, targetRoot, errorsDir, index, syncScript, lockPath, destination, reportHash, approvalHash };
488
+ return {
489
+ approval, candidate, targetRoot, errorsDir, index, syncScript: harness.syncScript,
490
+ localLead, lockPath, destination, reportHash, approvalHash
491
+ };
358
492
  }
359
493
 
360
494
  function runSync(script, targetRoot, check) {
@@ -519,10 +653,12 @@ function promote(context) {
519
653
 
520
654
  beforeNames = fs.readdirSync(context.errorsDir).filter(name => name !== LOCK).sort();
521
655
  saved = savedIndex(context.index);
656
+ if (context.localLead) assertFreshDedupe(context);
522
657
  assertApprovalUnused(context.errorsDir, context.approvalHash);
523
658
  const next = nextId(context.errorsDir, context.index);
524
659
  destination = checkDestination(context.errorsDir, next.id, context.approval.record.signature, context.lockPath);
525
- const text = recordText(context.approval, context.candidate, next.id, context.reportHash, context.approvalHash);
660
+ const text = recordText(context.approval, context.candidate, next.id, context.reportHash, context.approvalHash,
661
+ context.targetRoot, Boolean(context.localLead));
526
662
  let recordFd;
527
663
  try {
528
664
  recordFd = fs.openSync(destination.destination, 'wx', 0o644);
@@ -7,10 +7,14 @@ const fs = require('node:fs');
7
7
  const os = require('node:os');
8
8
  const path = require('node:path');
9
9
 
10
- const USAGE = 'usage: node scan.js --root <repo> [--out <dir>] [--no-memory] [--memory <path>]... [--instructions <path>]... [--tracker <file.json>]... [--hide-ledger] [--home <dir>] [--json]';
10
+ const USAGE = 'usage: node scan.js --root <repo> [--out <dir>] [--no-memory] [--memory <path>]... [--instructions <path>]... [--tracker <file.json>]... [--source local-store --destination harness|project] [--hide-ledger] [--home <dir>] [--json]';
11
11
  const HASH = /^[0-9a-f]{40}$/i;
12
- const SOURCE_STATUSES = new Set(['used', 'missing', 'disabled', 'unverified']);
12
+ const SOURCE_STATUSES = new Set(['used', 'missing', 'disabled', 'unverified', 'unavailable']);
13
13
  const GIT_MAX_BUFFER = 32 * 1024 * 1024;
14
+ const LEDGER_INDEX_MAX_BYTES = 512 * 1024;
15
+ const LOCAL_IDENTIFIER = /^[a-z0-9][a-z0-9_-]{0,63}$/;
16
+ const PROVISIONAL_ID = /^[a-z0-9][a-z0-9_-]{0,63}$/;
17
+ const RECORD_ID = /^E-\d{4,}$/;
14
18
 
15
19
  function failure(message, exitCode = 2) {
16
20
  const error = new Error(message);
@@ -21,7 +25,7 @@ function failure(message, exitCode = 2) {
21
25
  function parseArgs(args) {
22
26
  const options = { memory: [], instructions: [], tracker: [], noMemory: false, hideLedger: false, json: false };
23
27
  const seen = new Set();
24
- const values = new Set(['--root', '--out', '--home', '--memory', '--instructions', '--tracker']);
28
+ const values = new Set(['--root', '--out', '--home', '--memory', '--instructions', '--tracker', '--source', '--destination']);
25
29
  for (let i = 0; i < args.length; i++) {
26
30
  const arg = args[i];
27
31
  if (arg === '--no-memory' || arg === '--hide-ledger' || arg === '--json') {
@@ -44,6 +48,12 @@ function parseArgs(args) {
44
48
  options[arg.slice(2)] = value;
45
49
  }
46
50
  if (!options.root) failure(`--root is required; ${USAGE}`);
51
+ if (options.source !== undefined && options.source !== 'local-store') failure(`unknown source: ${options.source}`);
52
+ if (options.source === 'local-store' && !options.destination) failure('--destination is required for --source local-store');
53
+ if (options.destination !== undefined && options.source !== 'local-store') failure('--destination requires --source local-store');
54
+ if (options.destination !== undefined && !['harness', 'project'].includes(options.destination)) {
55
+ failure(`invalid --destination: ${options.destination}`);
56
+ }
47
57
  return options;
48
58
  }
49
59
 
@@ -444,6 +454,369 @@ function collectSources(options, root, home, files, historyCandidates) {
444
454
  return { sources, candidates };
445
455
  }
446
456
 
457
+ function localStoreRef(workspaceKey, provisionalId) {
458
+ const key = JSON.stringify([workspaceKey, provisionalId]);
459
+ return `p-local-${crypto.createHash('sha256').update(key).digest('hex')}`;
460
+ }
461
+
462
+ function workspaceRef(workspaceKey) {
463
+ return `w-local-${crypto.createHash('sha256').update(workspaceKey).digest('hex')}`;
464
+ }
465
+
466
+ function validLocalRecord(record, workspaceKey, store) {
467
+ if (!record || typeof record !== 'object' || Array.isArray(record) ||
468
+ record.schemaVersion !== store.SCHEMA_VERSION ||
469
+ !['occurrence', 'provisional-lesson'].includes(record.kind) ||
470
+ record.workspaceKey !== workspaceKey ||
471
+ typeof record.provisionalId !== 'string' || !PROVISIONAL_ID.test(record.provisionalId) || /^E-/i.test(record.provisionalId) ||
472
+ !store.DESTINATIONS.includes(record.destination) ||
473
+ typeof record.signature !== 'string' || !LOCAL_IDENTIFIER.test(record.signature) ||
474
+ typeof record.createdAt !== 'string' || !Number.isFinite(Date.parse(record.createdAt))) return false;
475
+ if (record.kind === 'occurrence') {
476
+ return record.source === 'tool-failure' && ['claude', 'codex', 'opencode', 'unknown'].includes(record.host) &&
477
+ store.COMMAND_CLASSES.includes(record.commandClass) &&
478
+ (record.exitCode === null || Number.isSafeInteger(record.exitCode)) &&
479
+ (record.sessionKey === null || /^[a-f0-9]{24}$/.test(record.sessionKey)) &&
480
+ (record.toolUseId === null || /^[a-f0-9]{24}$/.test(record.toolUseId)) &&
481
+ typeof record.outputExcerpt === 'string' && Buffer.byteLength(record.outputExcerpt, 'utf8') <= store.LIMITS.maxExcerptBytes &&
482
+ Array.isArray(record.matchedLedgerIds) && record.matchedLedgerIds.length <= store.LIMITS.maxMatchedLedgerIds &&
483
+ record.matchedLedgerIds.every(id => typeof id === 'string' && (RECORD_ID.test(id) || LOCAL_IDENTIFIER.test(id)));
484
+ }
485
+ try {
486
+ store.validateMatch(record.match);
487
+ } catch (_) { return false; }
488
+ return typeof record.lesson === 'string' && record.lesson.trim().length > 0 &&
489
+ Buffer.byteLength(record.lesson, 'utf8') <= store.LIMITS.maxLessonChars &&
490
+ (record.cue === undefined || (typeof record.cue === 'string' && Buffer.byteLength(record.cue, 'utf8') <= store.LIMITS.maxCueChars)) &&
491
+ (record.issueUrl === null || typeof record.issueUrl === 'string') &&
492
+ (record.promotionId === null || (typeof record.promotionId === 'string' && RECORD_ID.test(record.promotionId)));
493
+ }
494
+
495
+ function validLocalStoreReader(store) {
496
+ try {
497
+ if (!store || typeof store !== 'object' || Array.isArray(store)) return false;
498
+ const destinations = store.DESTINATIONS;
499
+ const commandClasses = store.COMMAND_CLASSES;
500
+ const limits = store.LIMITS;
501
+ const validEnum = (values, required) => Array.isArray(values) &&
502
+ required.every(value => values.includes(value)) &&
503
+ values.every((value, index) => typeof value === 'string' && value.length > 0 && values.indexOf(value) === index);
504
+ return Number.isSafeInteger(store.SCHEMA_VERSION) && store.SCHEMA_VERSION > 0 &&
505
+ typeof store.INDEX_FILE === 'string' && /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(store.INDEX_FILE) &&
506
+ typeof store.INDEX_KIND === 'string' && store.INDEX_KIND.length > 0 &&
507
+ validEnum(destinations, ['harness', 'project', 'unknown']) &&
508
+ validEnum(commandClasses, ['git', 'gh', 'test', 'build', 'package', 'shell']) &&
509
+ limits !== null && typeof limits === 'object' && !Array.isArray(limits) &&
510
+ ['maxIndexBytes', 'maxExcerptBytes', 'maxMatchedLedgerIds', 'maxLessonChars', 'maxCueChars']
511
+ .every(name => Number.isSafeInteger(limits[name]) && limits[name] > 0) &&
512
+ ['getStorePath', 'resolveWorkspaceKey', 'listRecords', 'validateMatch']
513
+ .every(name => typeof store[name] === 'function');
514
+ } catch (_) { return false; }
515
+ }
516
+
517
+ function inspectLocalStore(file, store) {
518
+ let stat;
519
+ try { stat = fs.lstatSync(file); }
520
+ catch (cause) {
521
+ return cause.code === 'ENOENT'
522
+ ? { status: 'missing', reason: 'index-missing' }
523
+ : { status: 'unverified', reason: 'store-unreadable' };
524
+ }
525
+ if (stat.isSymbolicLink() || !stat.isFile()) return { status: 'unverified', reason: 'store-unreadable' };
526
+ if (stat.size > store.LIMITS.maxIndexBytes) return { status: 'unverified', reason: 'store-corrupt' };
527
+ let envelope;
528
+ try {
529
+ const bytes = fs.readFileSync(file);
530
+ if (bytes.length > store.LIMITS.maxIndexBytes) return { status: 'unverified', reason: 'store-corrupt' };
531
+ envelope = JSON.parse(bytes.toString('utf8'));
532
+ } catch (_) { return { status: 'unverified', reason: 'store-corrupt' }; }
533
+ if (!envelope || typeof envelope !== 'object' || Array.isArray(envelope) || !Array.isArray(envelope.records)) {
534
+ return { status: 'unverified', reason: 'store-corrupt' };
535
+ }
536
+ if (envelope.schemaVersion !== store.SCHEMA_VERSION || envelope.kind !== store.INDEX_KIND) {
537
+ return { status: 'unverified', reason: 'store-unsupported' };
538
+ }
539
+ return { status: 'used', rowCount: envelope.records.length };
540
+ }
541
+
542
+ function inspectDestinationLedger(root, store) {
543
+ const errors = path.join(root, '.agents', 'harness-everything', 'errors');
544
+ let errorsStat;
545
+ try { errorsStat = fs.lstatSync(errors); }
546
+ catch (cause) {
547
+ return cause.code === 'ENOENT'
548
+ ? { status: 'unverified', reason: 'ledger-missing', rows: [] }
549
+ : { status: 'unverified', reason: 'ledger-unreadable', rows: [] };
550
+ }
551
+ if (errorsStat.isSymbolicLink() || !errorsStat.isDirectory()) return { status: 'unverified', reason: 'ledger-unreadable', rows: [] };
552
+ let realErrors;
553
+ try { realErrors = canonical(errors); }
554
+ catch (_) { return { status: 'unverified', reason: 'ledger-unreadable', rows: [] }; }
555
+ if (!isWithin(root, realErrors)) return { status: 'unverified', reason: 'ledger-unreadable', rows: [] };
556
+
557
+ const file = path.join(realErrors, 'index.jsonl');
558
+ let stat;
559
+ try { stat = fs.lstatSync(file); }
560
+ catch (cause) {
561
+ return cause.code === 'ENOENT'
562
+ ? { status: 'unverified', reason: 'ledger-missing', rows: [] }
563
+ : { status: 'unverified', reason: 'ledger-unreadable', rows: [] };
564
+ }
565
+ if (stat.isSymbolicLink() || !stat.isFile()) return { status: 'unverified', reason: 'ledger-unreadable', rows: [] };
566
+ if (stat.size > LEDGER_INDEX_MAX_BYTES) return { status: 'unverified', reason: 'ledger-corrupt', rows: [] };
567
+
568
+ let text;
569
+ try {
570
+ text = fs.readFileSync(file, 'utf8');
571
+ if (Buffer.byteLength(text, 'utf8') > LEDGER_INDEX_MAX_BYTES) return { status: 'unverified', reason: 'ledger-corrupt', rows: [] };
572
+ } catch (_) { return { status: 'unverified', reason: 'ledger-unreadable', rows: [] }; }
573
+
574
+ const lines = text.split(/\r?\n/);
575
+ if (lines.at(-1) === '') lines.pop();
576
+ if (lines.length > 512 || lines.some(line => !line.trim())) return { status: 'unverified', reason: 'ledger-corrupt', rows: [] };
577
+ const rows = [];
578
+ const ids = new Set();
579
+ try {
580
+ for (const line of lines) {
581
+ const row = JSON.parse(line);
582
+ if (!row || typeof row !== 'object' || Array.isArray(row) ||
583
+ typeof row.id !== 'string' || !RECORD_ID.test(row.id) || ids.has(row.id) ||
584
+ typeof row.signature !== 'string' || !LOCAL_IDENTIFIER.test(row.signature) ||
585
+ typeof row.file !== 'string' || !new RegExp(`^\\.agents/harness-everything/errors/${row.id}-[a-z0-9-]+\\.md$`).test(row.file)) {
586
+ throw new Error('invalid index row');
587
+ }
588
+ let match = null;
589
+ if (Object.hasOwn(row, 'match')) {
590
+ match = store.validateMatch(row.match);
591
+ if (typeof row.matchBinding !== 'string' || !/^[a-f0-9]{64}$/.test(row.matchBinding)) throw new Error('invalid match binding');
592
+ } else if (Object.hasOwn(row, 'matchBinding')) throw new Error('invalid match binding');
593
+ ids.add(row.id);
594
+ rows.push({ id: row.id, signature: row.signature, match });
595
+ }
596
+ } catch (_) { return { status: 'unverified', reason: 'ledger-corrupt', rows: [] }; }
597
+ return { status: 'verified', rows };
598
+ }
599
+
600
+ function canonicalMatch(match, store) {
601
+ const validated = store.validateMatch(match);
602
+ const normalized = {};
603
+ for (const phase of ['actions', 'failures']) {
604
+ if (!validated[phase]) continue;
605
+ normalized[phase] = validated[phase].map(rule => ({
606
+ ...rule,
607
+ ...(rule.diagnostics ? { diagnostics: [...rule.diagnostics].sort() } : {})
608
+ })).sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b)));
609
+ }
610
+ return JSON.stringify(normalized);
611
+ }
612
+
613
+ function destinationDedupe(signature, match, ledger, store) {
614
+ if (ledger.status !== 'verified') {
615
+ return { status: 'unverified', classIds: [], matchedBy: [], newClassEligible: false };
616
+ }
617
+ const matches = new Map();
618
+ const localMatch = match ? canonicalMatch(match, store) : null;
619
+ for (const row of ledger.rows) {
620
+ const methods = [];
621
+ if (row.signature === signature) methods.push('signature');
622
+ if (localMatch && row.match && canonicalMatch(row.match, store) === localMatch) methods.push('whole-rule');
623
+ if (methods.length) matches.set(row.id, new Set([...(matches.get(row.id) || []), ...methods]));
624
+ }
625
+ const classIds = [...matches.keys()].sort();
626
+ const matchedBy = [...new Set([...matches.values()].flatMap(methods => [...methods]))].sort();
627
+ return {
628
+ status: classIds.length > 1 ? 'ambiguous' : classIds.length === 1 ? 'existing' : 'none',
629
+ classIds,
630
+ matchedBy,
631
+ newClassEligible: classIds.length === 0
632
+ };
633
+ }
634
+
635
+ function localCandidate(title, signature, records, match, ledger, store, destination) {
636
+ const candidate = makeCandidate({
637
+ title,
638
+ signature,
639
+ sites: [],
640
+ sources: records.map(record => ({
641
+ type: 'local-store',
642
+ kind: record.kind,
643
+ ref: localStoreRef(record.workspaceKey, record.provisionalId),
644
+ destination,
645
+ signature: record.signature,
646
+ ...(record.kind === 'occurrence' ? { commandClass: record.commandClass } : {})
647
+ }))
648
+ });
649
+ candidate.local = {
650
+ evidenceReadiness: 'needs-evidence',
651
+ occurrenceCount: records.filter(record => record.kind === 'occurrence').length,
652
+ dedupe: destinationDedupe(signature, match, ledger, store)
653
+ };
654
+ return candidate;
655
+ }
656
+
657
+ function collectLocalStore(options, root) {
658
+ const fallbackWorkspaceRef = workspaceRef(root);
659
+ const emptyCounts = { workspaceRecords: 0, lessons: 0, occurrences: 0, candidates: 0, destinationMismatch: 0, unknownDestination: 0, malformed: 0, suppressedOccurrences: 0 };
660
+ let store;
661
+ try { store = require(path.join(__dirname, '..', '..', 'hooks', 'scripts', 'lib', 'local-errors.js')); }
662
+ catch (_) {
663
+ const ledger = { status: 'unverified', reason: 'ledger-not-checked' };
664
+ return {
665
+ source: sourceStatus('local-store', 'workspace', 'unavailable', {
666
+ reason: 'reader-unavailable', workspaceRef: fallbackWorkspaceRef, destination: options.destination,
667
+ ledgerStatus: ledger.status, ledgerReason: ledger.reason,
668
+ counts: { workspaceRecords: 0, lessons: 0, occurrences: 0, candidates: 0, destinationMismatch: 0, unknownDestination: 0, malformed: 0, suppressedOccurrences: 0 }
669
+ }),
670
+ candidates: []
671
+ };
672
+ }
673
+ if (!validLocalStoreReader(store)) {
674
+ return {
675
+ source: sourceStatus('local-store', 'workspace', 'unavailable', {
676
+ reason: 'reader-contract-incomplete', workspaceRef: fallbackWorkspaceRef, destination: options.destination,
677
+ ledgerStatus: 'unverified', ledgerReason: 'ledger-not-checked', counts: emptyCounts
678
+ }),
679
+ candidates: []
680
+ };
681
+ }
682
+
683
+ let workspaceKey;
684
+ try { workspaceKey = store.resolveWorkspaceKey({ workspaceRoot: root }); }
685
+ catch (_) {
686
+ return {
687
+ source: sourceStatus('local-store', 'workspace', 'unverified', {
688
+ reason: 'workspace-unavailable', workspaceRef: fallbackWorkspaceRef, destination: options.destination,
689
+ ledgerStatus: 'unverified', ledgerReason: 'ledger-not-checked',
690
+ counts: emptyCounts
691
+ }),
692
+ candidates: []
693
+ };
694
+ }
695
+ const ref = workspaceRef(workspaceKey);
696
+ const hostBinding = ['HARNESS_WORKSPACE_ROOT', 'CLAUDE_PROJECT_DIR', 'CODEX_PROJECT_DIR']
697
+ .some(name => typeof process.env[name] === 'string' && process.env[name].trim());
698
+ if (hostBinding) {
699
+ let hostKey;
700
+ try { hostKey = store.resolveWorkspaceKey({}, { env: process.env }); }
701
+ catch (_) {
702
+ return {
703
+ source: sourceStatus('local-store', 'workspace', 'unverified', {
704
+ reason: 'workspace-binding-unavailable', workspaceRef: ref, destination: options.destination,
705
+ ledgerStatus: 'unverified', ledgerReason: 'ledger-not-checked',
706
+ counts: emptyCounts
707
+ }),
708
+ candidates: []
709
+ };
710
+ }
711
+ if (hostKey !== workspaceKey) {
712
+ return {
713
+ source: sourceStatus('local-store', 'workspace', 'unverified', {
714
+ reason: 'workspace-binding-mismatch', workspaceRef: ref, destination: options.destination,
715
+ ledgerStatus: 'unverified', ledgerReason: 'ledger-not-checked',
716
+ counts: emptyCounts
717
+ }),
718
+ candidates: []
719
+ };
720
+ }
721
+ }
722
+
723
+ let storePath;
724
+ try { storePath = store.getStorePath().file; }
725
+ catch (_) {
726
+ return {
727
+ source: sourceStatus('local-store', 'workspace', 'unverified', {
728
+ reason: 'store-unreadable', workspaceRef: ref, destination: options.destination,
729
+ ledgerStatus: 'unverified', ledgerReason: 'ledger-not-checked',
730
+ counts: emptyCounts
731
+ }),
732
+ candidates: []
733
+ };
734
+ }
735
+ const diagnostic = inspectLocalStore(storePath, store);
736
+ const ledger = inspectDestinationLedger(root, store);
737
+ if (diagnostic.status !== 'used') {
738
+ return {
739
+ source: sourceStatus('local-store', 'workspace', diagnostic.status, {
740
+ reason: diagnostic.reason, workspaceRef: ref, destination: options.destination,
741
+ ledgerStatus: ledger.status, ...(ledger.reason ? { ledgerReason: ledger.reason } : {}), counts: emptyCounts
742
+ }),
743
+ candidates: []
744
+ };
745
+ }
746
+
747
+ let records;
748
+ try {
749
+ records = store.listRecords({ workspaceRoot: root, workspaceKey });
750
+ } catch (_) {
751
+ return {
752
+ source: sourceStatus('local-store', 'workspace', 'unverified', {
753
+ reason: 'reader-failed', workspaceRef: ref, destination: options.destination,
754
+ ledgerStatus: ledger.status, ...(ledger.reason ? { ledgerReason: ledger.reason } : {}), counts: emptyCounts
755
+ }),
756
+ candidates: []
757
+ };
758
+ }
759
+ const scoped = Array.isArray(records) ? records.filter(record => record && record.workspaceKey === workspaceKey) : [];
760
+ let malformed = Array.isArray(records) ? 0 : 1;
761
+ const valid = [];
762
+ const seen = new Set();
763
+ for (const record of scoped) {
764
+ const key = `${record.kind}:${record.provisionalId}`;
765
+ if (!validLocalRecord(record, workspaceKey, store) || seen.has(key)) {
766
+ malformed += 1;
767
+ continue;
768
+ }
769
+ seen.add(key);
770
+ valid.push(record);
771
+ }
772
+ const idKinds = new Map();
773
+ for (const record of valid) {
774
+ const kinds = idKinds.get(record.provisionalId) || new Set();
775
+ kinds.add(record.kind);
776
+ idKinds.set(record.provisionalId, kinds);
777
+ }
778
+ const collisions = new Set([...idKinds].filter(([, kinds]) => kinds.size > 1).map(([id]) => id));
779
+ const unambiguous = valid.filter(record => {
780
+ if (!collisions.has(record.provisionalId)) return true;
781
+ malformed += 1;
782
+ return false;
783
+ });
784
+ const counts = { ...emptyCounts, workspaceRecords: unambiguous.length, malformed };
785
+ const selected = [];
786
+ for (const record of unambiguous) {
787
+ if (record.destination === 'unknown') { counts.unknownDestination += 1; continue; }
788
+ if (record.destination !== options.destination) { counts.destinationMismatch += 1; continue; }
789
+ selected.push(record);
790
+ if (record.kind === 'provisional-lesson') counts.lessons += 1;
791
+ else counts.occurrences += 1;
792
+ }
793
+ const lessons = selected.filter(record => record.kind === 'provisional-lesson');
794
+ const covered = new Set(lessons.map(record => record.signature));
795
+ const candidates = lessons.map(record => localCandidate(
796
+ 'Local provisional lesson', record.signature, [record], record.match, ledger, store, options.destination
797
+ ));
798
+ const occurrences = new Map();
799
+ for (const record of selected.filter(record => record.kind === 'occurrence')) {
800
+ if (covered.has(record.signature)) { counts.suppressedOccurrences += 1; continue; }
801
+ const group = occurrences.get(record.signature) || [];
802
+ group.push(record);
803
+ occurrences.set(record.signature, group);
804
+ }
805
+ for (const [signature, group] of occurrences) {
806
+ candidates.push(localCandidate('Local tool-failure lead', signature, group, null, ledger, store, options.destination));
807
+ }
808
+ counts.candidates = candidates.length;
809
+ const status = malformed || scoped.length === 0 ? 'unverified' : 'used';
810
+ const reason = collisions.size ? 'provisional-id-collision' : malformed ? 'malformed-records' : scoped.length === 0 ? 'empty-reader-result' : undefined;
811
+ return {
812
+ source: sourceStatus('local-store', 'workspace', status, {
813
+ ...(reason ? { reason } : {}), workspaceRef: ref, destination: options.destination,
814
+ ledgerStatus: ledger.status, ...(ledger.reason ? { ledgerReason: ledger.reason } : {}), counts
815
+ }),
816
+ candidates
817
+ };
818
+ }
819
+
447
820
  function addAttachments(candidates, files, root, hideLedger) {
448
821
  const testFiles = files.filter(file => {
449
822
  const base = path.posix.basename(file);
@@ -498,10 +871,23 @@ function markdownReport(report) {
498
871
  for (const source of report.sources) {
499
872
  const label = source.ref || (source.refs && source.refs.join(', ')) || source.origin;
500
873
  lines.push(`- \`${source.type}\` (${source.origin}) — **${source.status}** — ${label}${source.reason ? ` — ${source.reason}` : ''}${source.verified === undefined ? '' : ` — verified: ${source.verified}`}${source.verificationRef ? ` — verification: ${source.verificationRef}` : ''}`);
874
+ if (source.type === 'local-store') {
875
+ lines.push(` - Workspace ref: \`${source.workspaceRef}\``, ` - Destination: \`${source.destination}\``,
876
+ ` - Records: ${source.counts.workspaceRecords}; lessons: ${source.counts.lessons}; occurrences: ${source.counts.occurrences}; candidates: ${source.counts.candidates}`,
877
+ ` - Destination mismatches: ${source.counts.destinationMismatch}; unknown destinations: ${source.counts.unknownDestination}; malformed: ${source.counts.malformed}; suppressed occurrences: ${source.counts.suppressedOccurrences}`,
878
+ ` - Destination ledger dedupe: **${source.ledgerStatus}**${source.ledgerReason ? ` — ${source.ledgerReason}` : ''}`);
879
+ }
501
880
  }
502
881
  lines.push('', '## Candidates', '');
503
882
  for (const item of report.candidates) {
504
883
  lines.push(`### ${item.title}`, '', `- ID: \`${item.id}\``, `- Kind: \`${item.kind}\``, `- Domain: \`${item.domain}\``, `- Signature: \`${item.signature}\``, `- Status: **${item.status}**`, `- Sites: ${item.sites.length ? item.sites.map(site => `\`${site}\``).join(', ') : 'none'}`, '- Sources:');
884
+ if (item.local) {
885
+ lines.push(`- Evidence readiness: **${item.local.evidenceReadiness}**`,
886
+ `- Occurrence count: ${item.local.occurrenceCount}`,
887
+ `- Destination dedupe: **${item.local.dedupe.status}**${item.local.dedupe.classIds.length ? ` — ${item.local.dedupe.classIds.map(id => `\`${id}\``).join(', ')}` : ''}`,
888
+ `- Exact match signals: ${item.local.dedupe.matchedBy.length ? item.local.dedupe.matchedBy.join(', ') : 'none'}`,
889
+ `- New-class dedupe eligible: ${item.local.dedupe.newClassEligible}`);
890
+ }
505
891
  for (const source of item.sources) {
506
892
  lines.push(` - \`${source.type}\` ${source.ref || source.path || source.sha}${source.path && source.sha ? ` — ${source.sha}` : ''}${source.subject ? ` — ${source.subject}` : ''}`);
507
893
  }
@@ -597,6 +983,11 @@ function scan(options) {
597
983
  const historyCandidates = parseHistory(root, options.hideLedger);
598
984
  const files = repoFiles(root);
599
985
  const selected = collectSources(options, root, home, files, historyCandidates);
986
+ if (options.source === 'local-store') {
987
+ const local = collectLocalStore(options, root);
988
+ selected.sources.push(local.source);
989
+ selected.candidates.push(...local.candidates);
990
+ }
600
991
  const candidates = [...new Map([...historyCandidates, ...selected.candidates].map(item => [item.id, item])).values()];
601
992
  addAttachments(candidates, files, root, options.hideLedger);
602
993
  for (const item of candidates) {