harness-everything 1.2.2 → 1.3.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 (31) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/CHANGELOG.md +23 -0
  4. package/ci/fixtures/468-dispatch/agy-quota-PROVENANCE.md +19 -0
  5. package/ci/fixtures/468-dispatch/agy-quota-direct-individual.stderr +2 -0
  6. package/ci/fixtures/468-dispatch/agy-quota-direct-third-party.stderr +2 -0
  7. package/ci/fixtures/468-dispatch/agy-quota-exec-individual.log +3 -0
  8. package/ci/mechanism-468-dispatch-cli.test.js +1496 -4
  9. package/ci/mechanism-548-bigint-identity.test.js +531 -0
  10. package/ci/mechanism-error-ledger-oracle.test.js +786 -3
  11. package/ci/mechanism-error-ledger-scan.test.js +981 -0
  12. package/ci/mechanism-report-writer.test.js +45 -0
  13. package/docs/error-handling/details/c8-dispatch-cli.md +109 -13
  14. package/error-ledger-bootstrap/SKILL.md +1 -1
  15. package/error-ledger-bootstrap/references/workflow.md +42 -7
  16. package/error-ledger-bootstrap/scripts/promote.js +8 -6
  17. package/error-ledger-bootstrap/scripts/scan.js +525 -12
  18. package/opencode-plugin/plugin.json +1 -1
  19. package/package.json +1 -1
  20. package/plugins/harness-everything/.antigravity-plugin/plugin.json +1 -1
  21. package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
  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 +42 -7
  25. package/plugins/harness-everything/skills/error-ledger-bootstrap/scripts/promote.js +8 -6
  26. package/plugins/harness-everything/skills/error-ledger-bootstrap/scripts/scan.js +525 -12
  27. package/sbom.cdx.json +7 -7
  28. package/scripts/dispatch.js +499 -87
  29. package/scripts/error-ledger-oracle.js +521 -27
  30. package/scripts/errors-sync.js +4 -3
  31. package/scripts/report-writer.js +4 -3
@@ -1,12 +1,31 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
3
 
4
+ const crypto = require('node:crypto');
4
5
  const fs = require('node:fs');
5
6
  const path = require('node:path');
6
7
  const yaml = require('js-yaml');
7
8
 
8
- const USAGE = 'usage: node scripts/error-ledger-oracle.js --report <scan-report.json> --ledger <errors dir> [--json] [--out <file>] [--platform <platform>]';
9
+ const USAGE = 'usage: node scripts/error-ledger-oracle.js --report <scan-report.json> --ledger <errors dir> [--labels <labels.json>] [--process-view] [--json] [--out <file>] [--platform <platform>]';
9
10
  const METRIC_NOTE = 'Path overlap is a proxy and may link distinct lessons. Both recall rates are path-linked proxies: recall (all) = linked records / all records; recall (comparable) = linked records / comparable records.';
11
+ const PROCESS_METRIC_NOTE = 'All process-view coverage rates are structural coverage proxies and may link distinct lessons. The conservative syntax-only site classifier is a proxy; unsupported or ambiguous site strings are treated as non-comparable for path overlap. Path-comparable coverage uses only path-comparable records as its denominator; overall coverage uses all records. Multi-record signature matches are disclosed as ambiguous and are not counted as resolved or as unique-link credit.';
12
+ const SHA256_HEX = /^[0-9a-f]{64}$/i;
13
+ const REPO_SHA_HEX = /^[0-9a-f]{40}$/i;
14
+ const LOCAL_IDENTIFIER = /^[a-z0-9][a-z0-9_-]{0,63}$/;
15
+ const GENERIC_SIGNATURES = new Set([
16
+ 'local-memory-lead',
17
+ 'local-instruction-lead',
18
+ 'local-tool-failure-lead',
19
+ 'local-provisional-lesson',
20
+ 'lesson',
21
+ 'unverified-lesson'
22
+ ]);
23
+ const LABEL_OUTCOMES = new Set([
24
+ 'true-positive-existing',
25
+ 'true-positive-new',
26
+ 'false-positive',
27
+ 'uncertain'
28
+ ]);
10
29
 
11
30
  function failure(message) {
12
31
  const error = new Error(message);
@@ -15,15 +34,16 @@ function failure(message) {
15
34
  }
16
35
 
17
36
  function parseArgs(args) {
18
- const options = { json: false, platform: process.platform };
19
- const values = new Set(['--report', '--ledger', '--out', '--platform']);
37
+ const options = { json: false, processView: false, platform: process.platform };
38
+ const values = new Set(['--report', '--ledger', '--labels', '--out', '--platform']);
20
39
  const seen = new Set();
21
40
  for (let i = 0; i < args.length; i++) {
22
41
  const arg = args[i];
23
- if (arg === '--json') {
42
+ if (arg === '--json' || arg === '--process-view') {
24
43
  if (seen.has(arg)) failure(`duplicate option: ${arg}`);
25
44
  seen.add(arg);
26
- options.json = true;
45
+ if (arg === '--json') options.json = true;
46
+ if (arg === '--process-view') options.processView = true;
27
47
  continue;
28
48
  }
29
49
  if (!values.has(arg)) failure(`unknown option: ${arg}`);
@@ -50,24 +70,83 @@ function normalizedSites(sites, platform) {
50
70
  return new Set(sites.map(site => normalizeSite(site, platform)).filter(Boolean));
51
71
  }
52
72
 
73
+ function normalizeProcessSite(value, platform) {
74
+ if (typeof value !== 'string') return null;
75
+ const raw = value.trim().replace(/\s+\(.*\)\s*$/, '').trim();
76
+ if (!raw) return null;
77
+ if (/^[a-z][a-z\d+.-]*:\/\//i.test(raw) || /^[a-z]:/i.test(raw) || /^[/\\]/.test(raw) || /^~(?:[/\\]|$)/.test(raw)) {
78
+ return null;
79
+ }
80
+ const slashed = raw.replace(/\\/g, '/');
81
+ if (slashed.includes('//') || /[*?[\]{}]/.test(slashed) || /[\x00-\x1f\x7f\t\r\n"'`<>|:;#=$!,]/.test(slashed)) {
82
+ return null;
83
+ }
84
+ const parts = slashed.split('/');
85
+ while (parts.length && parts[0] === '.') parts.shift();
86
+ if (parts.length > 1 && parts[parts.length - 1] === '') parts.pop();
87
+ if (!parts.length) return null;
88
+ for (const segment of parts) {
89
+ if (!segment || segment === '.' || segment === '..') return null;
90
+ if (/^\s|\s$|\s{2,}/.test(segment)) return null;
91
+ if (!/^[A-Za-z0-9._+@()-]+(?: [A-Za-z0-9._+@()-]+)*$/.test(segment)) return null;
92
+ }
93
+ const last = parts[parts.length - 1];
94
+ const hasSpace = parts.some(segment => segment.includes(' '));
95
+ const hasExtension = /^.+?\.[A-Za-z0-9]{1,12}$/.test(last) && !last.startsWith('.');
96
+ const isDotfile = parts.length === 1 && /^\.[A-Za-z0-9][A-Za-z0-9._-]*$/.test(last) && !hasSpace;
97
+ if (!hasExtension && !(parts.length >= 2 && !hasSpace) && !isDotfile) {
98
+ return null;
99
+ }
100
+ const normalized = parts.join('/');
101
+ return platform === 'win32' ? normalized.toLowerCase() : normalized;
102
+ }
103
+
104
+ function normalizedProcessSites(sites, platform) {
105
+ return new Set(sites.map(site => normalizeProcessSite(site, platform)).filter(Boolean));
106
+ }
107
+
108
+ function extractLocalStoreSignature(candidate) {
109
+ if (!Array.isArray(candidate.sources) || candidate.sources.length === 0) return null;
110
+ if (!candidate.sources.every(source => source && typeof source === 'object' && source.type === 'local-store')) {
111
+ return null;
112
+ }
113
+ if (typeof candidate.signature !== 'string' || !LOCAL_IDENTIFIER.test(candidate.signature)) {
114
+ return null;
115
+ }
116
+ if (GENERIC_SIGNATURES.has(candidate.signature)) return null;
117
+ if (!candidate.sources.every(source => source.signature === undefined || source.signature === candidate.signature)) {
118
+ return null;
119
+ }
120
+ return candidate.signature;
121
+ }
122
+
53
123
  function readReport(file, platform) {
124
+ let rawBytes;
54
125
  let report;
55
126
  try {
56
- report = JSON.parse(fs.readFileSync(file, 'utf8'));
127
+ rawBytes = fs.readFileSync(file);
128
+ report = JSON.parse(rawBytes.toString('utf8'));
57
129
  } catch (error) {
58
130
  failure(`could not read scan report: ${error.message}`);
59
131
  }
132
+ const reportSha256 = crypto.createHash('sha256').update(rawBytes).digest('hex');
60
133
  if (!report || !Array.isArray(report.candidates)) failure('scan report must contain a candidates array');
61
134
  const ids = new Set();
62
- return report.candidates.map((candidate, index) => {
135
+ const candidates = report.candidates.map((candidate, index) => {
63
136
  if (!candidate || typeof candidate.id !== 'string' || !candidate.id || !Array.isArray(candidate.sites) ||
64
137
  !candidate.sites.every(site => typeof site === 'string')) {
65
138
  failure(`scan report candidate ${index + 1} must have a string id and sites array`);
66
139
  }
67
140
  if (ids.has(candidate.id)) failure(`duplicate candidate id: ${candidate.id}`);
68
141
  ids.add(candidate.id);
69
- return { id: candidate.id, sites: normalizedSites(candidate.sites, platform) };
142
+ return {
143
+ id: candidate.id,
144
+ sites: normalizedSites(candidate.sites, platform),
145
+ processSites: normalizedProcessSites(candidate.sites, platform),
146
+ localStoreSignature: extractLocalStoreSignature(candidate)
147
+ };
70
148
  });
149
+ return { candidates, reportSha256 };
71
150
  }
72
151
 
73
152
  function readLedger(dir, platform) {
@@ -101,7 +180,12 @@ function readLedger(dir, platform) {
101
180
  }
102
181
  if (ids.has(metadata.id)) failure(`duplicate ledger id: ${metadata.id}`);
103
182
  ids.add(metadata.id);
104
- return { id: metadata.id, sites: normalizedSites(metadata.sites, platform) };
183
+ return {
184
+ id: metadata.id,
185
+ sites: normalizedSites(metadata.sites, platform),
186
+ processSites: normalizedProcessSites(metadata.sites, platform),
187
+ signature: typeof metadata.signature === 'string' && metadata.signature.trim() ? metadata.signature.trim() : null
188
+ };
105
189
  });
106
190
  }
107
191
 
@@ -173,10 +257,330 @@ function compare(records, candidates) {
173
257
  };
174
258
  }
175
259
 
176
- function isWithin(root, candidate) {
177
- const relative = path.relative(root, candidate);
178
- const comparable = process.platform === 'win32' ? relative.toLowerCase() : relative;
179
- return comparable === '' || (!path.isAbsolute(relative) && comparable !== '..' && !comparable.startsWith(`..${path.sep}`));
260
+ function compareProcessView(records, candidates) {
261
+ const pathLinked = [];
262
+ for (const record of records) {
263
+ const candidateIds = candidates.filter(candidate =>
264
+ [...record.processSites].some(recordSite =>
265
+ [...candidate.processSites].some(candidateSite => overlaps(recordSite, candidateSite))
266
+ )
267
+ ).map(candidate => candidate.id).sort();
268
+ if (candidateIds.length) {
269
+ pathLinked.push({ id: record.id, candidateIds });
270
+ }
271
+ }
272
+ pathLinked.sort((a, b) => a.id.localeCompare(b.id));
273
+
274
+ const recordSites = new Map();
275
+ const candidateSites = new Map();
276
+ for (const record of records) for (const site of record.processSites) {
277
+ const ids = recordSites.get(site) || new Set();
278
+ ids.add(record.id);
279
+ recordSites.set(site, ids);
280
+ }
281
+ for (const candidate of candidates) for (const site of candidate.processSites) {
282
+ const ids = candidateSites.get(site) || new Set();
283
+ ids.add(candidate.id);
284
+ candidateSites.set(site, ids);
285
+ }
286
+ const sharedPathHits = [...recordSites.entries()]
287
+ .filter(([site, recordIds]) => recordIds.size > 1 && candidateSites.has(site))
288
+ .map(([site, recordIds]) => ({
289
+ site,
290
+ recordIds: [...recordIds].sort(),
291
+ candidateIds: [...candidateSites.get(site)].sort()
292
+ }))
293
+ .sort((a, b) => a.site.localeCompare(b.site));
294
+
295
+ const recordsBySignature = new Map();
296
+ for (const record of records) {
297
+ if (!record.signature) continue;
298
+ const ids = recordsBySignature.get(record.signature) || [];
299
+ ids.push(record.id);
300
+ recordsBySignature.set(record.signature, ids);
301
+ }
302
+ for (const ids of recordsBySignature.values()) ids.sort();
303
+
304
+ const uniqueSigByRecord = new Map();
305
+ const ambiguousBySignature = new Map();
306
+ for (const candidate of candidates) {
307
+ if (!candidate.localStoreSignature) continue;
308
+ const matchedIds = recordsBySignature.get(candidate.localStoreSignature);
309
+ if (!matchedIds || matchedIds.length === 0) continue;
310
+ if (matchedIds.length === 1) {
311
+ const recordId = matchedIds[0];
312
+ const entry = uniqueSigByRecord.get(recordId) || { signature: candidate.localStoreSignature, candidateIds: new Set() };
313
+ entry.candidateIds.add(candidate.id);
314
+ uniqueSigByRecord.set(recordId, entry);
315
+ } else {
316
+ const entry = ambiguousBySignature.get(candidate.localStoreSignature) || {
317
+ signature: candidate.localStoreSignature,
318
+ recordIds: [...matchedIds],
319
+ candidateIds: new Set()
320
+ };
321
+ entry.candidateIds.add(candidate.id);
322
+ ambiguousBySignature.set(candidate.localStoreSignature, entry);
323
+ }
324
+ }
325
+
326
+ const uniqueSignatureLinked = [...uniqueSigByRecord.entries()]
327
+ .map(([id, entry]) => ({ id, signature: entry.signature, candidateIds: [...entry.candidateIds].sort() }))
328
+ .sort((a, b) => a.id.localeCompare(b.id));
329
+
330
+ const ambiguousSignatureMatches = [...ambiguousBySignature.values()]
331
+ .map(entry => ({
332
+ signature: entry.signature,
333
+ recordIds: entry.recordIds,
334
+ candidateIds: [...entry.candidateIds].sort()
335
+ }))
336
+ .sort((a, b) => a.signature.localeCompare(b.signature));
337
+
338
+ const pathByRecordId = new Map(pathLinked.map(item => [item.id, item.candidateIds]));
339
+ const sigByRecordId = new Map(uniqueSignatureLinked.map(item => [item.id, item.candidateIds]));
340
+ const unionLinked = [];
341
+ const pathOnlyRecords = [];
342
+ const uniqueSignatureOnlyRecords = [];
343
+ const bothPathAndUniqueSignatureRecords = [];
344
+ const unlinkedRecords = [];
345
+
346
+ for (const record of [...records].sort((a, b) => a.id.localeCompare(b.id))) {
347
+ const pathCands = pathByRecordId.get(record.id);
348
+ const sigCands = sigByRecordId.get(record.id);
349
+ if (pathCands && sigCands) {
350
+ bothPathAndUniqueSignatureRecords.push(record.id);
351
+ unionLinked.push({
352
+ id: record.id,
353
+ channels: ['path', 'unique-signature'],
354
+ candidateIds: [...new Set([...pathCands, ...sigCands])].sort()
355
+ });
356
+ } else if (pathCands) {
357
+ pathOnlyRecords.push(record.id);
358
+ unionLinked.push({ id: record.id, channels: ['path'], candidateIds: pathCands });
359
+ } else if (sigCands) {
360
+ uniqueSignatureOnlyRecords.push(record.id);
361
+ unionLinked.push({ id: record.id, channels: ['unique-signature'], candidateIds: sigCands });
362
+ } else {
363
+ unlinkedRecords.push(record.id);
364
+ }
365
+ }
366
+
367
+ const pathNonComparable = records.filter(record => record.processSites.size === 0).map(record => record.id).sort();
368
+ const pathComparableRecords = records.length - pathNonComparable.length;
369
+ const ambiguousSignatureRecords = new Set(ambiguousSignatureMatches.flatMap(item => item.recordIds)).size;
370
+ const ambiguousSignatureCandidates = new Set(ambiguousSignatureMatches.flatMap(item => item.candidateIds)).size;
371
+ const rate = (numerator, denominator) => denominator ? numerator / denominator : null;
372
+
373
+ return {
374
+ counts: {
375
+ records: records.length,
376
+ pathComparableRecords,
377
+ pathNonComparableRecords: pathNonComparable.length,
378
+ signatureEligibleRecords: records.filter(record => Boolean(record.signature)).length,
379
+ pathLinkedRecords: pathLinked.length,
380
+ uniqueSignatureLinkedRecords: uniqueSignatureLinked.length,
381
+ unionLinkedRecords: unionLinked.length,
382
+ candidates: candidates.length,
383
+ pathComparableCandidates: candidates.filter(candidate => candidate.processSites.size > 0).length,
384
+ signatureEligibleCandidates: candidates.filter(candidate => Boolean(candidate.localStoreSignature)).length
385
+ },
386
+ coverage: {
387
+ path: {
388
+ linkedRecords: pathLinked.length,
389
+ pathComparableDenominator: pathComparableRecords,
390
+ allRecordsDenominator: records.length,
391
+ ratePathComparable: rate(pathLinked.length, pathComparableRecords),
392
+ rateAll: rate(pathLinked.length, records.length)
393
+ },
394
+ uniqueSignature: {
395
+ linkedRecords: uniqueSignatureLinked.length,
396
+ allRecordsDenominator: records.length,
397
+ rateAll: rate(uniqueSignatureLinked.length, records.length)
398
+ },
399
+ union: {
400
+ linkedRecords: unionLinked.length,
401
+ allRecordsDenominator: records.length,
402
+ rateAll: rate(unionLinked.length, records.length)
403
+ }
404
+ },
405
+ breakdown: {
406
+ counts: {
407
+ pathOnly: pathOnlyRecords.length,
408
+ uniqueSignatureOnly: uniqueSignatureOnlyRecords.length,
409
+ bothPathAndUniqueSignature: bothPathAndUniqueSignatureRecords.length,
410
+ unlinked: unlinkedRecords.length,
411
+ sharedPathHits: sharedPathHits.length,
412
+ ambiguousSignatureMatches: ambiguousSignatureMatches.length,
413
+ ambiguousSignatureRecords,
414
+ ambiguousSignatureCandidates
415
+ },
416
+ pathOnlyRecords,
417
+ uniqueSignatureOnlyRecords,
418
+ bothPathAndUniqueSignatureRecords,
419
+ unlinkedRecords
420
+ },
421
+ metricNote: PROCESS_METRIC_NOTE,
422
+ pathNonComparable,
423
+ pathLinked,
424
+ uniqueSignatureLinked,
425
+ unionLinked,
426
+ sharedPathHits,
427
+ ambiguousSignatureMatches
428
+ };
429
+ }
430
+
431
+ function readLabels(file, reportSha256, candidates, records) {
432
+ let parsed;
433
+ try {
434
+ parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
435
+ } catch (error) {
436
+ failure(`could not read labels file: ${error.message}`);
437
+ }
438
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
439
+ failure('labels file must contain a JSON object');
440
+ }
441
+ if (parsed.schemaVersion !== 1) {
442
+ failure('labels schemaVersion must be 1');
443
+ }
444
+ if (typeof parsed.reportSha256 !== 'string' || !SHA256_HEX.test(parsed.reportSha256)) {
445
+ failure('labels reportSha256 must be a 64-character hex SHA-256 digest');
446
+ }
447
+ if (parsed.reportSha256.toLowerCase() !== reportSha256) {
448
+ failure(`labels reportSha256 mismatch: expected ${reportSha256}`);
449
+ }
450
+ if (typeof parsed.repoSha !== 'string' || !REPO_SHA_HEX.test(parsed.repoSha)) {
451
+ failure('labels repoSha must be a 40-character hex commit SHA');
452
+ }
453
+ if (!Array.isArray(parsed.labels)) {
454
+ failure('labels file must contain a labels array');
455
+ }
456
+
457
+ const candidateIds = new Set(candidates.map(candidate => candidate.id));
458
+ const recordIds = new Set(records.map(record => record.id));
459
+ const byCandidate = new Map();
460
+
461
+ for (let index = 0; index < parsed.labels.length; index++) {
462
+ const entry = parsed.labels[index];
463
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
464
+ failure(`label entry ${index + 1} must be an object`);
465
+ }
466
+ if (typeof entry.candidateId !== 'string' || !entry.candidateId) {
467
+ failure(`label entry ${index + 1} must have a non-empty string candidateId`);
468
+ }
469
+ if (!candidateIds.has(entry.candidateId)) {
470
+ failure(`unknown label candidateId: ${entry.candidateId}`);
471
+ }
472
+ if (byCandidate.has(entry.candidateId)) {
473
+ failure(`duplicate label candidateId: ${entry.candidateId}`);
474
+ }
475
+ if (typeof entry.outcome !== 'string' || !LABEL_OUTCOMES.has(entry.outcome)) {
476
+ failure(`invalid label outcome for ${entry.candidateId}: ${String(entry.outcome)}`);
477
+ }
478
+ const hasLinkedRecordId = Object.prototype.hasOwnProperty.call(entry, 'linkedRecordId');
479
+ if (entry.outcome === 'true-positive-existing') {
480
+ if (!hasLinkedRecordId || typeof entry.linkedRecordId !== 'string' || !entry.linkedRecordId) {
481
+ failure(`linkedRecordId is required for true-positive-existing candidate: ${entry.candidateId}`);
482
+ }
483
+ if (!recordIds.has(entry.linkedRecordId)) {
484
+ failure(`unknown linkedRecordId for ${entry.candidateId}: ${entry.linkedRecordId}`);
485
+ }
486
+ byCandidate.set(entry.candidateId, { outcome: entry.outcome, linkedRecordId: entry.linkedRecordId });
487
+ } else {
488
+ if (hasLinkedRecordId) {
489
+ failure(`linkedRecordId is only allowed for true-positive-existing candidate: ${entry.candidateId}`);
490
+ }
491
+ byCandidate.set(entry.candidateId, { outcome: entry.outcome });
492
+ }
493
+ }
494
+
495
+ return {
496
+ schemaVersion: 1,
497
+ reportSha256,
498
+ repoSha: parsed.repoSha.toLowerCase(),
499
+ byCandidate
500
+ };
501
+ }
502
+
503
+ function evaluateLabels(result, candidates, labelsData) {
504
+ let truePositiveExisting = 0;
505
+ let truePositiveNew = 0;
506
+ let falsePositive = 0;
507
+ let uncertain = 0;
508
+ for (const label of labelsData.byCandidate.values()) {
509
+ if (label.outcome === 'true-positive-existing') truePositiveExisting += 1;
510
+ else if (label.outcome === 'true-positive-new') truePositiveNew += 1;
511
+ else if (label.outcome === 'false-positive') falsePositive += 1;
512
+ else if (label.outcome === 'uncertain') uncertain += 1;
513
+ }
514
+
515
+ const labelled = labelsData.byCandidate.size;
516
+ const decided = truePositiveExisting + truePositiveNew + falsePositive;
517
+ const unlabelled = candidates.length - labelled;
518
+
519
+ let totalPathPairs = 0;
520
+ let auditedPairs = 0;
521
+ let truePairs = 0;
522
+ let falsePairs = 0;
523
+ let uncertainPairs = 0;
524
+ let unlabelledPairs = 0;
525
+ for (const record of result.linked) {
526
+ for (const candidateId of record.candidateIds) {
527
+ totalPathPairs += 1;
528
+ const label = labelsData.byCandidate.get(candidateId);
529
+ if (!label) {
530
+ unlabelledPairs += 1;
531
+ } else if (label.outcome === 'uncertain') {
532
+ uncertainPairs += 1;
533
+ } else {
534
+ auditedPairs += 1;
535
+ if (label.outcome === 'true-positive-existing' && label.linkedRecordId === record.id) {
536
+ truePairs += 1;
537
+ } else {
538
+ falsePairs += 1;
539
+ }
540
+ }
541
+ }
542
+ }
543
+
544
+ const rate = (numerator, denominator) => denominator ? numerator / denominator : null;
545
+ const falseLinkShare = rate(falsePairs, auditedPairs);
546
+ return {
547
+ schemaVersion: labelsData.schemaVersion,
548
+ reportSha256: labelsData.reportSha256,
549
+ repoSha: labelsData.repoSha,
550
+ counts: {
551
+ labelled,
552
+ decided,
553
+ truePositiveExisting,
554
+ truePositiveNew,
555
+ falsePositive,
556
+ uncertain,
557
+ unlabelled
558
+ },
559
+ rates: {
560
+ coverage: rate(labelled, candidates.length),
561
+ precision: rate(truePositiveExisting + truePositiveNew, decided),
562
+ falsePositiveShare: rate(falsePositive, decided),
563
+ falseLinkShare
564
+ },
565
+ pathLinkAudit: {
566
+ totalPathPairs,
567
+ auditedPairs,
568
+ truePairs,
569
+ falsePairs,
570
+ uncertainPairs,
571
+ unlabelledPairs,
572
+ falseLinkShare
573
+ }
574
+ };
575
+ }
576
+
577
+ function isWithin(root, candidate, pathApi) {
578
+ const api = pathApi || (process.platform === 'win32' ? path.win32 : path);
579
+ const windows = api === path.win32 || (!pathApi && process.platform === 'win32');
580
+ const comparisonRoot = windows ? root.toLowerCase() : root;
581
+ const comparisonCandidate = windows ? candidate.toLowerCase() : candidate;
582
+ const relative = api.relative(comparisonRoot, comparisonCandidate);
583
+ return relative === '' || (!api.isAbsolute(relative) && relative !== '..' && !relative.startsWith(`..${api.sep}`));
180
584
  }
181
585
 
182
586
  function canonicalTarget(file) {
@@ -194,31 +598,72 @@ function canonicalTarget(file) {
194
598
  return fs.realpathSync.native(target);
195
599
  } catch (error) {
196
600
  if (error.code !== 'ENOENT') throw error;
197
- return path.join(fs.realpathSync.native(path.dirname(target)), path.basename(target));
601
+ let current = path.dirname(target);
602
+ const suffix = [path.basename(target)];
603
+ while (true) {
604
+ try {
605
+ fs.lstatSync(current);
606
+ return path.join(fs.realpathSync.native(current), ...suffix);
607
+ } catch (inner) {
608
+ if (inner.code !== 'ENOENT' && inner.code !== 'ENOTDIR') throw inner;
609
+ const parent = path.dirname(current);
610
+ if (parent === current) throw inner;
611
+ suffix.unshift(path.basename(current));
612
+ current = parent;
613
+ }
614
+ }
615
+ }
616
+ }
617
+
618
+ function listFilesRecursive(dir) {
619
+ const files = [];
620
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
621
+ const full = path.join(dir, entry.name);
622
+ if (entry.isDirectory()) files.push(...listFilesRecursive(full));
623
+ else if (entry.isFile()) files.push(full);
198
624
  }
625
+ return files;
199
626
  }
200
627
 
201
- function safeOutput(file, ledgerDir, reportFile) {
628
+ function samePath(left, right) {
629
+ return left === right || (process.platform === 'win32' && left.toLowerCase() === right.toLowerCase());
630
+ }
631
+
632
+ function safeOutput(file, ledgerDir, reportFile, labelsFile) {
202
633
  const output = path.resolve(file);
203
634
  const canonicalOutput = canonicalTarget(output);
204
635
  const canonicalLedger = fs.realpathSync.native(ledgerDir);
205
636
  if (isWithin(canonicalLedger, output) || isWithin(canonicalLedger, canonicalOutput)) {
206
637
  failure('--out path is inside the ledger directory');
207
638
  }
208
- const canonicalReport = fs.realpathSync.native(reportFile);
209
- if (canonicalOutput === canonicalReport ||
210
- (process.platform === 'win32' && canonicalOutput.toLowerCase() === canonicalReport.toLowerCase())) {
211
- failure('--out path cannot replace the scan report');
639
+ const protectedFiles = [{ file: reportFile, label: 'the scan report' }];
640
+ if (labelsFile) protectedFiles.push({ file: labelsFile, label: 'the labels file' });
641
+ for (const item of protectedFiles) {
642
+ const canonicalProtected = fs.realpathSync.native(item.file);
643
+ if (samePath(canonicalOutput, canonicalProtected)) {
644
+ failure(`--out path cannot replace ${item.label}`);
645
+ }
212
646
  }
647
+ let outputStat = null;
213
648
  try {
214
- const outputStat = fs.statSync(output);
215
- const reportStat = fs.statSync(reportFile);
216
- if (outputStat.dev === reportStat.dev && outputStat.ino === reportStat.ino) {
217
- failure('--out path cannot replace the scan report');
218
- }
649
+ outputStat = fs.statSync(output, { bigint: true });
219
650
  } catch (error) {
220
651
  if (error.code !== 'ENOENT') throw error;
221
652
  }
653
+ if (outputStat) {
654
+ for (const item of protectedFiles) {
655
+ const protectedStat = fs.statSync(item.file, { bigint: true });
656
+ if (outputStat.dev === protectedStat.dev && outputStat.ino === protectedStat.ino) {
657
+ failure(`--out path cannot replace ${item.label}`);
658
+ }
659
+ }
660
+ for (const ledgerFile of listFilesRecursive(canonicalLedger)) {
661
+ const ledgerStat = fs.statSync(ledgerFile, { bigint: true });
662
+ if (outputStat.dev === ledgerStat.dev && outputStat.ino === ledgerStat.ino) {
663
+ failure('--out path cannot replace a ledger file');
664
+ }
665
+ }
666
+ }
222
667
  return output;
223
668
  }
224
669
 
@@ -234,18 +679,67 @@ function markdown(result) {
234
679
  ['recall (comparable)', rate(result.rates.recallComparable)],
235
680
  ['unmatched candidate share (path overlap)', rate(result.rates.unmatchedShare)]
236
681
  ];
237
- return `${result.metricNote}\n\n| Metric | Value |\n| --- | ---: |\n${rows.map(([label, value]) => `| ${label} | ${value} |`).join('\n')}\n`;
682
+ let out = `${result.metricNote}\n\n| Metric | Value |\n| --- | ---: |\n${rows.map(([label, value]) => `| ${label} | ${value} |`).join('\n')}\n`;
683
+ if (result.labelled) {
684
+ const { counts, rates, pathLinkAudit } = result.labelled;
685
+ const labelledRows = [
686
+ ['labelled candidates', counts.labelled],
687
+ ['decided candidates', counts.decided],
688
+ ['true-positive-existing', counts.truePositiveExisting],
689
+ ['true-positive-new', counts.truePositiveNew],
690
+ ['false-positive', counts.falsePositive],
691
+ ['uncertain', counts.uncertain],
692
+ ['unlabelled candidates', counts.unlabelled],
693
+ ['label coverage', rate(rates.coverage)],
694
+ ['candidate precision (decided candidates)', rate(rates.precision)],
695
+ ['false-positive share among decided candidates', rate(rates.falsePositiveShare)],
696
+ ['audited path pairs (decided)', pathLinkAudit.auditedPairs],
697
+ ['true path pairs', pathLinkAudit.truePairs],
698
+ ['false path pairs', pathLinkAudit.falsePairs],
699
+ ['path-link false-link share (audited pairs)', rate(rates.falseLinkShare)]
700
+ ];
701
+ out += `\n## Labelled Evaluation\n\n| Metric | Value |\n| --- | ---: |\n${labelledRows.map(([label, value]) => `| ${label} | ${value} |`).join('\n')}\n`;
702
+ }
703
+ if (result.processView) {
704
+ const pv = result.processView;
705
+ const processRows = [
706
+ ['records (all denominator)', pv.counts.records],
707
+ ['path-comparable records (path-comparable denominator)', pv.counts.pathComparableRecords],
708
+ ['path-non-comparable records', pv.counts.pathNonComparableRecords],
709
+ ['path-linked records', pv.counts.pathLinkedRecords],
710
+ ['unique-signature-linked records', pv.counts.uniqueSignatureLinkedRecords],
711
+ ['union-linked records', pv.counts.unionLinkedRecords],
712
+ ['path coverage (path-comparable)', rate(pv.coverage.path.ratePathComparable)],
713
+ ['path coverage (all records)', rate(pv.coverage.path.rateAll)],
714
+ ['unique-signature coverage (all records)', rate(pv.coverage.uniqueSignature.rateAll)],
715
+ ['union coverage (all records)', rate(pv.coverage.union.rateAll)],
716
+ ['overlap: path only', pv.breakdown.counts.pathOnly],
717
+ ['overlap: unique-signature only', pv.breakdown.counts.uniqueSignatureOnly],
718
+ ['overlap: both path and unique-signature', pv.breakdown.counts.bothPathAndUniqueSignature],
719
+ ['unlinked records', pv.breakdown.counts.unlinked],
720
+ ['shared path hits (ambiguous paths)', pv.breakdown.counts.sharedPathHits],
721
+ ['ambiguous signature matches (unresolved)', pv.breakdown.counts.ambiguousSignatureMatches],
722
+ ['ambiguous signature records (unresolved)', pv.breakdown.counts.ambiguousSignatureRecords],
723
+ ['ambiguous signature candidates (unresolved)', pv.breakdown.counts.ambiguousSignatureCandidates]
724
+ ];
725
+ out += `\n## Process View\n\n${pv.metricNote}\n\n| Metric | Value |\n| --- | ---: |\n${processRows.map(([label, value]) => `| ${label} | ${value} |`).join('\n')}\n`;
726
+ }
727
+ return out;
238
728
  }
239
729
 
240
730
  function main() {
241
731
  const options = parseArgs(process.argv.slice(2));
242
732
  const reportFile = path.resolve(options.report);
243
733
  const ledgerDir = path.resolve(options.ledger);
244
- const candidates = readReport(reportFile, options.platform);
734
+ const labelsFile = options.labels ? path.resolve(options.labels) : null;
735
+ const { candidates, reportSha256 } = readReport(reportFile, options.platform);
245
736
  const records = readLedger(ledgerDir, options.platform);
737
+ const labelsData = labelsFile ? readLabels(labelsFile, reportSha256, candidates, records) : null;
246
738
  const result = compare(records, candidates);
739
+ if (labelsData) result.labelled = evaluateLabels(result, candidates, labelsData);
740
+ if (options.processView) result.processView = compareProcessView(records, candidates);
247
741
  const output = options.json ? `${JSON.stringify(result, null, 2)}\n` : markdown(result);
248
- if (options.out) fs.writeFileSync(safeOutput(options.out, ledgerDir, reportFile), output);
742
+ if (options.out) fs.writeFileSync(safeOutput(options.out, ledgerDir, reportFile, labelsFile), output);
249
743
  process.stdout.write(output);
250
744
  }
251
745
 
@@ -171,7 +171,8 @@ function render(root = ROOT) {
171
171
 
172
172
  function inspectIndex(index) {
173
173
  try {
174
- const stat = fs.lstatSync(index);
174
+ // Keep 64-bit device/file IDs exact (Windows IDs can exceed Number's safe integer range).
175
+ const stat = fs.lstatSync(index, { bigint: true });
175
176
  if (stat.isSymbolicLink() || !stat.isFile()) {
176
177
  throw new Error('target index must be a regular file inside the errors directory');
177
178
  }
@@ -189,7 +190,7 @@ function readIndex(index) {
189
190
  try {
190
191
  const noFollow = fs.constants.O_NOFOLLOW || 0;
191
192
  fd = fs.openSync(index, fs.constants.O_RDONLY | noFollow);
192
- const opened = fs.fstatSync(fd);
193
+ const opened = fs.fstatSync(fd, { bigint: true });
193
194
  if (!opened.isFile() || opened.dev !== before.dev || opened.ino !== before.ino) {
194
195
  throw new Error('target index changed while it was being read');
195
196
  }
@@ -206,7 +207,7 @@ function writeIndex(index, content, root) {
206
207
  }
207
208
  const previous = inspectIndex(index);
208
209
  const previousBytes = previous ? readIndex(index) : null;
209
- const mode = previous ? previous.mode & 0o777 : 0o666;
210
+ const mode = previous ? Number(previous.mode) & 0o777 : 0o666;
210
211
  let temporary;
211
212
  let fd;
212
213
  try {