harness-everything 0.54.1 → 0.55.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 (35) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +2 -1
  3. package/CHANGELOG.md +17 -0
  4. package/README.md +1 -0
  5. package/ci/mechanism-error-ledger-oracle.test.js +222 -0
  6. package/ci/mechanism-error-ledger-promote.test.js +520 -0
  7. package/ci/mechanism-error-ledger-scan.test.js +640 -0
  8. package/ci/mechanism-errors-sync-root.test.js +215 -0
  9. package/ci/openai-plugin-package.test.js +1 -1
  10. package/docs/workflows/error-ledger-bootstrap.md +23 -0
  11. package/error-ledger-bootstrap/SKILL.md +33 -0
  12. package/error-ledger-bootstrap/references/workflow.md +79 -0
  13. package/error-ledger-bootstrap/scripts/promote.js +613 -0
  14. package/error-ledger-bootstrap/scripts/scan.js +654 -0
  15. package/evals/error-ledger-bootstrap/eval.yaml +26 -0
  16. package/evals/error-ledger-bootstrap/tasks/negative-error-handling-map.yaml +16 -0
  17. package/evals/error-ledger-bootstrap/tasks/negative-trigger.yaml +16 -0
  18. package/evals/error-ledger-bootstrap/tasks/positive-trigger.yaml +15 -0
  19. package/harness-everything/SKILL.md +1 -1
  20. package/harness-everything/references/skill-registry.md +1 -0
  21. package/harness-everything/scripts/routing-keywords.json +11 -0
  22. package/opencode-plugin/plugin.json +1 -1
  23. package/package.json +1 -1
  24. package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
  25. package/plugins/harness-everything/plugin.json +1 -1
  26. package/plugins/harness-everything/skills/error-ledger-bootstrap/SKILL.md +33 -0
  27. package/plugins/harness-everything/skills/error-ledger-bootstrap/references/workflow.md +79 -0
  28. package/plugins/harness-everything/skills/error-ledger-bootstrap/scripts/promote.js +613 -0
  29. package/plugins/harness-everything/skills/error-ledger-bootstrap/scripts/scan.js +654 -0
  30. package/plugins/harness-everything/skills/harness-everything/SKILL.md +1 -1
  31. package/plugins/harness-everything/skills/harness-everything/references/skill-registry.md +1 -0
  32. package/plugins/harness-everything/skills/harness-everything/scripts/routing-keywords.json +11 -0
  33. package/sbom.cdx.json +7 -7
  34. package/scripts/error-ledger-oracle.js +257 -0
  35. package/scripts/errors-sync.js +175 -12
@@ -0,0 +1,654 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const crypto = require('node:crypto');
5
+ const childProcess = require('node:child_process');
6
+ const fs = require('node:fs');
7
+ const os = require('node:os');
8
+ const path = require('node:path');
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]';
11
+ const HASH = /^[0-9a-f]{40}$/i;
12
+ const SOURCE_STATUSES = new Set(['used', 'missing', 'disabled', 'unverified']);
13
+ const GIT_MAX_BUFFER = 32 * 1024 * 1024;
14
+
15
+ function failure(message, exitCode = 2) {
16
+ const error = new Error(message);
17
+ error.exitCode = exitCode;
18
+ throw error;
19
+ }
20
+
21
+ function parseArgs(args) {
22
+ const options = { memory: [], instructions: [], tracker: [], noMemory: false, hideLedger: false, json: false };
23
+ const seen = new Set();
24
+ const values = new Set(['--root', '--out', '--home', '--memory', '--instructions', '--tracker']);
25
+ for (let i = 0; i < args.length; i++) {
26
+ const arg = args[i];
27
+ if (arg === '--no-memory' || arg === '--hide-ledger' || arg === '--json') {
28
+ if (seen.has(arg)) failure(`duplicate option: ${arg}`);
29
+ seen.add(arg);
30
+ if (arg === '--no-memory') options.noMemory = true;
31
+ if (arg === '--hide-ledger') options.hideLedger = true;
32
+ if (arg === '--json') options.json = true;
33
+ continue;
34
+ }
35
+ if (!values.has(arg)) failure(`unknown option: ${arg}`);
36
+ if (i + 1 >= args.length || args[i + 1].startsWith('--')) failure(`missing value for ${arg}`);
37
+ const value = args[++i];
38
+ if (arg === '--memory' || arg === '--instructions' || arg === '--tracker') {
39
+ options[arg.slice(2)].push(value);
40
+ continue;
41
+ }
42
+ if (seen.has(arg)) failure(`duplicate option: ${arg}`);
43
+ seen.add(arg);
44
+ options[arg.slice(2)] = value;
45
+ }
46
+ if (!options.root) failure(`--root is required; ${USAGE}`);
47
+ return options;
48
+ }
49
+
50
+ function git(root, args, encoding = 'utf8', exitCode = 1) {
51
+ try {
52
+ return childProcess.execFileSync('git', ['-C', root, ...args], {
53
+ encoding, stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: GIT_MAX_BUFFER
54
+ });
55
+ } catch (cause) {
56
+ if (cause.code === 'ENOBUFS') {
57
+ failure(`git ${args[0] || 'command'} output exceeded the configured limit of ${GIT_MAX_BUFFER} bytes for the target repository`, exitCode);
58
+ }
59
+ failure(`git ${args[0] || 'command'} failed for the target repository`, exitCode);
60
+ }
61
+ }
62
+
63
+ function canonical(file) {
64
+ return fs.realpathSync.native ? fs.realpathSync.native(file) : fs.realpathSync(file);
65
+ }
66
+
67
+ function isWithin(root, candidate, pathApi) {
68
+ const api = pathApi || (process.platform === 'win32' ? path.win32 : path);
69
+ const windows = api === path.win32 || (!pathApi && process.platform === 'win32');
70
+ const comparisonRoot = windows ? root.toLowerCase() : root;
71
+ const comparisonCandidate = windows ? candidate.toLowerCase() : candidate;
72
+ const relative = api.relative(comparisonRoot, comparisonCandidate);
73
+ return relative === '' || (!api.isAbsolute(relative) && relative !== '..' && !relative.startsWith(`..${api.sep}`));
74
+ }
75
+
76
+ function resolveWithSymlinks(candidate) {
77
+ let current = path.resolve(candidate);
78
+ const suffix = [];
79
+ while (true) {
80
+ try {
81
+ fs.lstatSync(current);
82
+ return path.join(canonical(current), ...suffix);
83
+ } catch (cause) {
84
+ if (cause.code !== 'ENOENT' && cause.code !== 'ENOTDIR') throw cause;
85
+ const parent = path.dirname(current);
86
+ if (parent === current) throw cause;
87
+ suffix.unshift(path.basename(current));
88
+ current = parent;
89
+ }
90
+ }
91
+ }
92
+
93
+ function isLedgerPath(relative) {
94
+ const rel = relative.replace(/\\/g, '/').replace(/^\.\//, '');
95
+ return rel === '.agents/harness-everything/errors' ||
96
+ rel.startsWith('.agents/harness-everything/errors/') ||
97
+ rel === 'docs/error-handling' || rel.startsWith('docs/error-handling/');
98
+ }
99
+
100
+ function isDocumentationPath(relative) {
101
+ return relative.toLowerCase().endsWith('.md') || relative.startsWith('docs/');
102
+ }
103
+
104
+ function normalizedRepoPath(relative) {
105
+ return relative.replace(/\\/g, '/').replace(/^\.\//, '');
106
+ }
107
+
108
+ function parseHistory(root, hideLedger) {
109
+ const tokens = git(root, ['log', '-z', '--name-status', '--format=%H%x00%s']).split('\0');
110
+ const groups = new Map();
111
+ for (let i = 0; i < tokens.length;) {
112
+ const sha = tokens[i++];
113
+ if (!sha) continue;
114
+ if (!HASH.test(sha) || i >= tokens.length) failure('git history returned an invalid record', 1);
115
+ const subject = tokens[i++];
116
+ const relevant = /^(?:fix(?:\([^\r\n)]*\))?!?:\s|revert(?:\([^\r\n)]*\))?!?:\s|Revert ".+"$)/.test(subject);
117
+ const changed = new Set();
118
+ while (i < tokens.length && !HASH.test(tokens[i])) {
119
+ const status = tokens[i++].replace(/^\r?\n/, '');
120
+ if (!status) continue;
121
+ if (!/^[ACDMRTUXB]\d*$/.test(status)) failure('git history returned an invalid file status', 1);
122
+ const count = /^[RC]/.test(status) ? 2 : 1;
123
+ for (let n = 0; n < count; n++) {
124
+ if (i >= tokens.length) failure('git history returned an incomplete file record', 1);
125
+ const site = normalizedRepoPath(tokens[i++]);
126
+ if (!hideLedger || !isLedgerPath(site)) changed.add(site);
127
+ }
128
+ }
129
+ if (relevant) {
130
+ for (const site of changed) {
131
+ const type = isDocumentationPath(site) ? 'doc' : 'git';
132
+ const key = `${type}\0${site}`;
133
+ const commits = groups.get(key) || new Map();
134
+ commits.set(sha, { sha, subject });
135
+ groups.set(key, commits);
136
+ }
137
+ }
138
+ }
139
+ return [...groups.entries()]
140
+ .filter(([, commits]) => commits.size >= 2)
141
+ .sort(([left], [right]) => left.localeCompare(right))
142
+ .map(([key, commits]) => {
143
+ const [type, site] = key.split('\0');
144
+ return makeCandidate({
145
+ title: `Repeated fix history for ${site}`,
146
+ signature: `repeated-fix:${site}`,
147
+ sites: [site],
148
+ sources: [...commits.values()].sort((a, b) => a.sha.localeCompare(b.sha)).map(commit => type === 'doc'
149
+ ? { type, path: site, sha: commit.sha }
150
+ : { type, sha: commit.sha, subject: commit.subject })
151
+ });
152
+ });
153
+ }
154
+
155
+ function repoFiles(root) {
156
+ return git(root, ['ls-files', '--cached', '--others', '--exclude-standard', '-z'])
157
+ .split('\0').filter(Boolean).map(normalizedRepoPath);
158
+ }
159
+
160
+ function safeRead(file) {
161
+ try {
162
+ if (fs.lstatSync(file).isSymbolicLink()) return null;
163
+ return fs.readFileSync(file, 'utf8');
164
+ } catch (_) {
165
+ return null;
166
+ }
167
+ }
168
+
169
+ function walkMarkdown(directory) {
170
+ const found = [];
171
+ function visit(dir) {
172
+ let entries;
173
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch (_) { return; }
174
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
175
+ const file = path.join(dir, entry.name);
176
+ if (entry.isSymbolicLink()) continue;
177
+ if (entry.isDirectory()) visit(file);
178
+ else if (entry.isFile() && entry.name.toLowerCase().endsWith('.md')) found.push(file);
179
+ }
180
+ }
181
+ visit(directory);
182
+ return found;
183
+ }
184
+
185
+ function flatMarkdown(directory) {
186
+ try {
187
+ return fs.readdirSync(directory, { withFileTypes: true })
188
+ .filter(entry => entry.isFile() && entry.name.toLowerCase().endsWith('.md'))
189
+ .map(entry => path.join(directory, entry.name))
190
+ .sort((a, b) => a.localeCompare(b));
191
+ } catch (_) {
192
+ return [];
193
+ }
194
+ }
195
+
196
+ function explicitFiles(input, root, hideLedger) {
197
+ const absolute = path.resolve(input);
198
+ let stat;
199
+ try { stat = fs.statSync(absolute); } catch (_) { return []; }
200
+ const files = stat.isDirectory() ? walkMarkdown(absolute) : stat.isFile() ? [absolute] : [];
201
+ return files.filter(file => {
202
+ if (!hideLedger) return true;
203
+ let resolved;
204
+ try { resolved = resolveWithSymlinks(file); } catch (_) { resolved = file; }
205
+ return !isWithin(root, resolved) || !isLedgerPath(normalizedRepoPath(path.relative(root, resolved)));
206
+ });
207
+ }
208
+
209
+ function localSourceId(file) {
210
+ return `local/${crypto.createHash('sha256').update(path.resolve(file)).digest('hex')}`;
211
+ }
212
+
213
+ function labelPath(file, root) {
214
+ const resolved = path.resolve(file);
215
+ if (isWithin(root, resolved)) return `repo/${normalizedRepoPath(path.relative(root, resolved)) || '.'}`;
216
+ return localSourceId(resolved);
217
+ }
218
+
219
+ function markdownTitle(text) {
220
+ const frontmatter = /^---\s*\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(text);
221
+ if (frontmatter) {
222
+ const title = /^title:\s*(.+?)\s*$/m.exec(frontmatter[1]);
223
+ if (title) return title[1].replace(/^['"]|['"]$/g, '');
224
+ }
225
+ const section = /^#{1,6}\s*(?:cue|lesson)\s*\r?\n+([\s\S]*?)(?=\r?\n#{1,6}\s|$)/im.exec(text);
226
+ if (section) return section[1].trim().split(/\r?\n/).find(Boolean) || '';
227
+ const heading = /^#\s+(.+)$/m.exec(text);
228
+ return heading ? heading[1].trim() : '';
229
+ }
230
+
231
+ function lessonSites(text, knownFiles) {
232
+ const sites = new Set();
233
+ const expression = /(?<![A-Za-z0-9_.:/\\])((?:[A-Za-z0-9_.-]+\/)+[A-Za-z0-9_.-]+\.[A-Za-z0-9_-]+)\b/g;
234
+ for (const match of text.matchAll(expression)) {
235
+ const site = path.posix.normalize(match[1]);
236
+ if (!path.posix.isAbsolute(site) && !site.split('/').includes('..') && !/^[A-Za-z]:/.test(site) &&
237
+ (!knownFiles || knownFiles.has(site))) sites.add(site);
238
+ }
239
+ return [...sites].sort();
240
+ }
241
+
242
+ function isLesson(text, file) {
243
+ const frontmatter = /^---\s*\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(text);
244
+ const feedback = frontmatter && /^type:\s*['"]?feedback(?:['"]?\s|$)/mi.test(frontmatter[1]);
245
+ return Boolean(feedback || /^lesson-/i.test(path.basename(file)) || /^#{1,6}\s*(?:cue|lesson)\b/im.test(text));
246
+ }
247
+
248
+ function publicText(value, root, home) {
249
+ let text = String(value || '');
250
+ for (const [absolute, label] of [[root, '<repo>'], [home, '<home>']]) {
251
+ if (absolute) text = text.split(absolute).join(label);
252
+ }
253
+ return text
254
+ .replace(/\b[A-Za-z]:[\\/][^\s"'`<>]+/g, '[path]')
255
+ .replace(/(?<![A-Za-z0-9])\/(?:[^/\s"'`<>]+\/)*[^/\s"'`<>]+/g, '[path]')
256
+ .replace(/[\r\n\t]+/g, ' ')
257
+ .trim();
258
+ }
259
+
260
+ function shortTitle(value, root, home) {
261
+ return publicText(value, root, home).slice(0, 120) || 'Unverified lesson';
262
+ }
263
+
264
+ function slug(value) {
265
+ return value.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 80) || 'lesson';
266
+ }
267
+
268
+ function makeCandidate({ title, signature, sites, sources }) {
269
+ const sortedSites = [...new Set(sites)].sort();
270
+ const sortedSources = [...sources].sort((a, b) => `${a.type}:${a.sha || a.ref}`.localeCompare(`${b.type}:${b.sha || b.ref}`));
271
+ const identity = JSON.stringify(['error-candidate', sortedSites, sortedSources.map(source => `${source.type}:${source.sha || source.ref}`)]);
272
+ return {
273
+ id: crypto.createHash('sha256').update(identity).digest('hex').slice(0, 20),
274
+ kind: 'error-candidate',
275
+ domain: sortedSites.length ? sortedSites[0].split('/')[0] : 'unknown',
276
+ title,
277
+ signature,
278
+ sites: sortedSites,
279
+ sources: sortedSources,
280
+ attachments: [],
281
+ status: 'UNVERIFIED'
282
+ };
283
+ }
284
+
285
+ function candidatesFromFiles(files, type, root, home, knownFiles, privateInput = false) {
286
+ const candidates = [];
287
+ for (const file of files) {
288
+ const text = safeRead(file);
289
+ if (text === null || !isLesson(text, file)) continue;
290
+ const privateSource = type === 'memory' || privateInput || !isWithin(root, path.resolve(file));
291
+ const title = privateSource ? `Local ${type} lead` :
292
+ shortTitle(markdownTitle(text) || path.basename(file, path.extname(file)), root, home);
293
+ const ref = privateSource ? localSourceId(file) : labelPath(file, root);
294
+ candidates.push(makeCandidate({
295
+ title,
296
+ signature: slug(title),
297
+ sites: lessonSites(text, privateSource ? knownFiles : undefined),
298
+ sources: [{ type, ref }]
299
+ }));
300
+ }
301
+ return candidates;
302
+ }
303
+
304
+ function autoMemory(root, home) {
305
+ const slugDir = path.join(home, '.claude', 'projects', path.resolve(root).replace(/[^a-z0-9]/gi, '-'));
306
+ const directory = path.join(slugDir, 'memory');
307
+ const files = flatMarkdown(directory);
308
+ let reason = fs.existsSync(directory) ? 'hinted memory directory contains no Markdown files' : 'hinted memory directory is missing';
309
+ const marker = path.join(slugDir, 'MEMORY.md');
310
+ let verified = fs.existsSync(marker);
311
+ let verificationRef = verified ? marker : undefined;
312
+ if (verified) reason = 'automatic memory marker found';
313
+ else if (files.length) {
314
+ for (const file of files) {
315
+ const text = safeRead(file) || '';
316
+ if (text.includes(path.basename(root)) || text.includes(root)) {
317
+ verified = true;
318
+ verificationRef = file;
319
+ reason = 'a memory file names the target repository';
320
+ break;
321
+ }
322
+ }
323
+ if (!verified) reason = 'automatic memory marker absent and no memory file names the target repository';
324
+ }
325
+ return { directory, files, verified, reason, verificationRef };
326
+ }
327
+
328
+ function sourceStatus(type, origin, status, details = {}) {
329
+ return { type, origin, status, ...details };
330
+ }
331
+
332
+ function trackerSites(body, root, files) {
333
+ const text = typeof body === 'string' ? body : '';
334
+ return files.filter(file => {
335
+ if (!fs.existsSync(path.join(root, file))) return false;
336
+ const escaped = file.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
337
+ return new RegExp(`(?<![A-Za-z0-9_./-])(?:\\.\\/)?${escaped}(?![A-Za-z0-9_./-])`).test(text);
338
+ });
339
+ }
340
+
341
+ function collectTracker(options, root, home, files) {
342
+ const candidates = [];
343
+ if (!options.tracker.length) {
344
+ return {
345
+ sources: [sourceStatus('tracker', 'offline', 'missing', { reason: 'no --tracker file provided' })],
346
+ candidates
347
+ };
348
+ }
349
+
350
+ const sources = [];
351
+ for (const input of options.tracker) {
352
+ const file = path.resolve(input);
353
+ let issues;
354
+ try {
355
+ issues = JSON.parse(fs.readFileSync(file, 'utf8'));
356
+ } catch (_) {
357
+ failure('cannot read tracker export as JSON', 2);
358
+ }
359
+ if (!Array.isArray(issues)) failure('tracker export must be a JSON array', 2);
360
+ sources.push(sourceStatus('tracker', 'offline', 'used', { ref: labelPath(file, root) }));
361
+ for (const issue of issues) {
362
+ if (!issue || typeof issue !== 'object' || Array.isArray(issue)) failure('tracker export contains an invalid issue', 2);
363
+ const title = typeof issue.title === 'string' ? issue.title : '';
364
+ const labels = Array.isArray(issue.labels) ? issue.labels : [];
365
+ const qualifies = labels.some(label => /^(?:bug|regression|flake)$/i.test(String(label && label.name || ''))) ||
366
+ /^\s*(?:fix|bug)\b/i.test(title);
367
+ if (!qualifies) continue;
368
+ if (!Number.isSafeInteger(issue.number) || issue.number < 1 || !title.trim()) {
369
+ failure('tracker issue is missing a valid number or title', 2);
370
+ }
371
+ const ref = `#${issue.number}`;
372
+ const candidateTitle = shortTitle(title, root, home);
373
+ candidates.push(makeCandidate({
374
+ title: candidateTitle,
375
+ signature: slug(candidateTitle),
376
+ sites: trackerSites(issue.body, root, files),
377
+ sources: [{ type: 'tracker', ref }]
378
+ }));
379
+ }
380
+ }
381
+ return { sources, candidates };
382
+ }
383
+
384
+ function collectSources(options, root, home, files, historyCandidates) {
385
+ const documentation = historyCandidates.some(item => item.sources.some(source => source.type === 'doc'));
386
+ const knownFiles = new Set(files);
387
+ const tracker = collectTracker(options, root, home, files);
388
+ const sources = [
389
+ sourceStatus('git', 'history', 'used'),
390
+ sourceStatus('doc', 'history', documentation ? 'used' : 'missing',
391
+ documentation ? {} : { reason: 'no repeated Markdown or docs paths found' }),
392
+ ...tracker.sources
393
+ ];
394
+ const candidates = [...tracker.candidates];
395
+ if (options.noMemory) {
396
+ sources.push(sourceStatus('memory', 'auto', 'disabled', { verified: false, reason: 'disabled by --no-memory' }));
397
+ sources.push(sourceStatus('instruction', 'repository', 'disabled', { reason: 'disabled by --no-memory' }));
398
+ sources.push(sourceStatus('instruction', 'global-explicit', 'disabled', { reason: 'disabled by --no-memory' }));
399
+ for (const input of options.memory) sources.push(sourceStatus('memory', 'explicit', 'disabled', { ref: localSourceId(input), reason: 'disabled by --no-memory' }));
400
+ for (const input of options.instructions) sources.push(sourceStatus('instruction', 'global-explicit', 'disabled', { ref: localSourceId(input), reason: 'disabled by --no-memory' }));
401
+ return { sources, candidates };
402
+ }
403
+
404
+ const auto = autoMemory(root, home);
405
+ sources.push(sourceStatus('memory', 'auto', auto.files.length ? (auto.verified ? 'used' : 'unverified') : 'missing', {
406
+ verified: auto.verified, reason: auto.reason,
407
+ ref: localSourceId(auto.directory),
408
+ ...(auto.verificationRef ? { verificationRef: localSourceId(auto.verificationRef) } : {})
409
+ }));
410
+ if (auto.verified) candidates.push(...candidatesFromFiles(auto.files, 'memory', root, home, knownFiles));
411
+
412
+ if (options.memory.length) {
413
+ for (const input of options.memory) {
414
+ const selected = explicitFiles(input, root, options.hideLedger);
415
+ sources.push(sourceStatus('memory', 'explicit', selected.length ? 'used' : 'missing', {
416
+ ref: localSourceId(input),
417
+ ...(selected.length ? {} : { reason: 'no readable files at the selected path' })
418
+ }));
419
+ candidates.push(...candidatesFromFiles(selected, 'memory', root, home, knownFiles));
420
+ }
421
+ } else {
422
+ sources.push(sourceStatus('memory', 'explicit', 'missing', { reason: 'no --memory path provided' }));
423
+ }
424
+
425
+ const instructionFiles = files.filter(file => ['AGENTS.md', 'CLAUDE.md'].includes(path.posix.basename(file)) &&
426
+ (!options.hideLedger || !isLedgerPath(file)));
427
+ sources.push(sourceStatus('instruction', 'repository', instructionFiles.length ? 'used' : 'missing', {
428
+ ...(instructionFiles.length ? { refs: instructionFiles } : { reason: 'no repository AGENTS.md or CLAUDE.md files found' })
429
+ }));
430
+ candidates.push(...candidatesFromFiles(instructionFiles.map(file => path.join(root, file)), 'instruction', root, home, knownFiles));
431
+
432
+ if (options.instructions.length) {
433
+ for (const input of options.instructions) {
434
+ const selected = explicitFiles(input, root, options.hideLedger);
435
+ sources.push(sourceStatus('instruction', 'global-explicit', selected.length ? 'used' : 'missing', {
436
+ ref: localSourceId(input),
437
+ ...(selected.length ? {} : { reason: 'no readable files at the selected path' })
438
+ }));
439
+ candidates.push(...candidatesFromFiles(selected, 'instruction', root, home, knownFiles, true));
440
+ }
441
+ } else {
442
+ sources.push(sourceStatus('instruction', 'global-explicit', 'disabled', { reason: 'global instructions require --instructions' }));
443
+ }
444
+ return { sources, candidates };
445
+ }
446
+
447
+ function addAttachments(candidates, files, root, hideLedger) {
448
+ const testFiles = files.filter(file => {
449
+ const base = path.posix.basename(file);
450
+ const testLike = /(?:^|[./_-])(?:test|tests|spec)(?:[./_-]|$)/i.test(base) || /(^|\/)(?:test|tests|__tests__)\//i.test(file);
451
+ return testLike && (!hideLedger || !isLedgerPath(file));
452
+ });
453
+ for (const file of testFiles) {
454
+ const full = path.join(root, file);
455
+ const text = safeRead(full);
456
+ if (text === null) continue;
457
+ for (const item of candidates) {
458
+ if (item.sites.some(site => text.includes(site) || importsSite(text, file, site)) &&
459
+ !item.attachments.some(link => link.ref === file)) {
460
+ item.attachments.push({ type: 'test-link', ref: file });
461
+ }
462
+ }
463
+ }
464
+ for (const item of candidates) item.attachments.sort((a, b) => a.ref.localeCompare(b.ref));
465
+ }
466
+
467
+ function importsSite(text, testFile, site) {
468
+ const specifiers = /(?:\brequire(?:\.resolve)?\s*\(\s*|\bfrom\s+|\bimport\s*(?:\(\s*)?)['"]([^'"]+)['"]/g;
469
+ for (const match of text.matchAll(specifiers)) {
470
+ if (!match[1].startsWith('.')) continue;
471
+ const resolved = path.posix.normalize(path.posix.join(path.posix.dirname(testFile), match[1]));
472
+ if (resolved === site || (!path.posix.extname(resolved) &&
473
+ (site.startsWith(`${resolved}.`) || site.startsWith(`${resolved}/index.`)))) return true;
474
+ }
475
+ return false;
476
+ }
477
+
478
+ function markdownReport(report) {
479
+ const lines = [
480
+ '# Error ledger candidate report',
481
+ '',
482
+ `- Schema version: ${report.schemaVersion}`,
483
+ `- Root: \`${report.root}\``,
484
+ `- Generated: ${report.generatedAt}`,
485
+ `- Candidates: ${report.candidates.length}`,
486
+ '',
487
+ '## Options',
488
+ '',
489
+ `- hideLedger: ${report.options.hideLedger}`,
490
+ `- noMemory: ${report.options.noMemory}`,
491
+ `- memory: ${report.options.memory.length ? report.options.memory.map(value => `\`${value}\``).join(', ') : 'none'}`,
492
+ `- instructions: ${report.options.instructions.length ? report.options.instructions.map(value => `\`${value}\``).join(', ') : 'none'}`,
493
+ `- homeOverridden: ${report.options.homeOverridden}`,
494
+ '',
495
+ '## Sources',
496
+ ''
497
+ ];
498
+ for (const source of report.sources) {
499
+ const label = source.ref || (source.refs && source.refs.join(', ')) || source.origin;
500
+ lines.push(`- \`${source.type}\` (${source.origin}) — **${source.status}** — ${label}${source.reason ? ` — ${source.reason}` : ''}${source.verified === undefined ? '' : ` — verified: ${source.verified}`}${source.verificationRef ? ` — verification: ${source.verificationRef}` : ''}`);
501
+ }
502
+ lines.push('', '## Candidates', '');
503
+ for (const item of report.candidates) {
504
+ 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:');
505
+ for (const source of item.sources) {
506
+ lines.push(` - \`${source.type}\` ${source.ref || source.path || source.sha}${source.path && source.sha ? ` — ${source.sha}` : ''}${source.subject ? ` — ${source.subject}` : ''}`);
507
+ }
508
+ lines.push('- Attachments:');
509
+ if (item.attachments.length) {
510
+ for (const attachment of item.attachments) lines.push(` - \`${attachment.type}\` \`${attachment.ref}\``);
511
+ } else lines.push(' - none');
512
+ lines.push('');
513
+ }
514
+ return `${lines.join('\n')}\n`;
515
+ }
516
+
517
+ function reportOptions(options, root, home) {
518
+ return {
519
+ hideLedger: options.hideLedger,
520
+ noMemory: options.noMemory,
521
+ memory: options.memory.map(localSourceId),
522
+ instructions: options.instructions.map(localSourceId),
523
+ homeOverridden: Boolean(options.home)
524
+ };
525
+ }
526
+
527
+ function outputDirectory(options, root) {
528
+ if (!options.out) {
529
+ const tempRoot = path.resolve(os.tmpdir());
530
+ const physicalTempRoot = resolveWithSymlinks(tempRoot);
531
+ if (isWithin(root, tempRoot) || isWithin(root, physicalTempRoot)) {
532
+ failure('system temporary directory is inside the target repository', 2);
533
+ }
534
+ const directory = fs.mkdtempSync(path.join(tempRoot, 'error-ledger-candidates-'));
535
+ const physical = resolveWithSymlinks(directory);
536
+ if (isWithin(root, directory) || isWithin(root, physical)) {
537
+ fs.rmSync(directory, { recursive: true, force: true });
538
+ failure('refusing output inside the target repository', 2);
539
+ }
540
+ try { fs.chmodSync(directory, 0o700); } catch (_) { /* mode bits are not available on every host */ }
541
+ return { directory: physical, privateDefault: true };
542
+ }
543
+ const lexical = path.resolve(options.out);
544
+ const resolved = resolveWithSymlinks(lexical);
545
+ if (isWithin(root, lexical) || isWithin(root, resolved)) failure('refusing output inside the target repository', 2);
546
+ fs.mkdirSync(resolved, { recursive: true, mode: 0o700 });
547
+ const physical = resolveWithSymlinks(resolved);
548
+ if (isWithin(root, physical)) failure('refusing output inside the target repository', 2);
549
+ return { directory: physical, privateDefault: false };
550
+ }
551
+
552
+ function writeReports(directory, report, root) {
553
+ const jsonPath = path.join(directory, 'candidates.json');
554
+ const markdownPath = path.join(directory, 'candidates.md');
555
+ for (const target of [jsonPath, markdownPath]) {
556
+ const lexical = path.resolve(target);
557
+ const resolved = resolveWithSymlinks(target);
558
+ if (isWithin(root, lexical) || isWithin(root, resolved)) failure('refusing report file inside the target repository', 2);
559
+ if (fs.existsSync(target)) failure(`report output already exists: ${path.basename(target)}`, 2);
560
+ }
561
+ const files = [
562
+ [jsonPath, `${JSON.stringify(report, null, 2)}\n`],
563
+ [markdownPath, markdownReport(report)]
564
+ ];
565
+ const temps = [];
566
+ const written = [];
567
+ try {
568
+ for (const [target, contents] of files) {
569
+ const temp = path.join(directory, `.scan-${process.pid}-${crypto.randomBytes(6).toString('hex')}.tmp`);
570
+ temps.push(temp);
571
+ fs.writeFileSync(temp, contents, { flag: 'wx', mode: 0o600 });
572
+ fs.renameSync(temp, target);
573
+ written.push(target);
574
+ }
575
+ } catch (cause) {
576
+ for (const file of [...temps, ...written]) {
577
+ try { fs.rmSync(file, { force: true }); } catch (_) {}
578
+ }
579
+ failure(`cannot write candidate reports: ${cause.message}`, 1);
580
+ }
581
+ return { reportJson: jsonPath, reportMd: markdownPath };
582
+ }
583
+
584
+ function scan(options) {
585
+ const rootInput = path.resolve(options.root);
586
+ let root;
587
+ try {
588
+ if (!fs.statSync(rootInput).isDirectory()) failure('--root must be a directory');
589
+ root = canonical(rootInput);
590
+ } catch (cause) {
591
+ if (cause.exitCode) throw cause;
592
+ failure('--root must be an existing Git repository directory');
593
+ }
594
+ const top = canonical(git(root, ['rev-parse', '--show-toplevel'], 'utf8', 2).trim());
595
+ if (top !== root) failure('--root must be the Git repository root');
596
+ const home = options.home ? path.resolve(options.home) : os.homedir();
597
+ const historyCandidates = parseHistory(root, options.hideLedger);
598
+ const files = repoFiles(root);
599
+ const selected = collectSources(options, root, home, files, historyCandidates);
600
+ const candidates = [...new Map([...historyCandidates, ...selected.candidates].map(item => [item.id, item])).values()];
601
+ addAttachments(candidates, files, root, options.hideLedger);
602
+ for (const item of candidates) {
603
+ for (const source of item.sources) {
604
+ if (source.subject) source.subject = publicText(source.subject, root, home);
605
+ }
606
+ }
607
+ candidates.sort((a, b) => a.id.localeCompare(b.id));
608
+ if (selected.sources.some(source => !SOURCE_STATUSES.has(source.status))) failure('invalid source status', 1);
609
+ const report = {
610
+ schemaVersion: 1,
611
+ root: path.basename(root),
612
+ generatedAt: new Date().toISOString(),
613
+ options: reportOptions(options, root, home),
614
+ sources: selected.sources,
615
+ candidates
616
+ };
617
+ const output = outputDirectory(options, root);
618
+ const paths = writeReports(output.directory, report, root);
619
+ return {
620
+ report,
621
+ ...paths,
622
+ counts: {
623
+ candidates: candidates.length,
624
+ git: historyCandidates.filter(item => item.sources.some(source => source.type === 'git')).length,
625
+ doc: historyCandidates.filter(item => item.sources.some(source => source.type === 'doc')).length,
626
+ tracker: candidates.filter(item => item.sources.some(source => source.type === 'tracker')).length,
627
+ memory: candidates.filter(item => item.sources.some(source => source.type === 'memory')).length,
628
+ instruction: candidates.filter(item => item.sources.some(source => source.type === 'instruction')).length
629
+ }
630
+ };
631
+ }
632
+
633
+ function main(args) {
634
+ const jsonRequested = args.includes('--json');
635
+ try {
636
+ const options = parseArgs(args);
637
+ const result = scan(options);
638
+ if (options.json) {
639
+ process.stdout.write(`${JSON.stringify({ ok: true, reportJson: result.reportJson, reportMd: result.reportMd, counts: result.counts })}\n`);
640
+ } else {
641
+ process.stdout.write('Candidate reports written.\n');
642
+ }
643
+ return 0;
644
+ } catch (cause) {
645
+ const message = String(cause && cause.message || 'scan failed').replace(/[\r\n]+/g, ' ').trim() || 'scan failed';
646
+ process.stderr.write(`${message}\n`);
647
+ if (jsonRequested) process.stdout.write(`${JSON.stringify({ ok: false, error: message })}\n`);
648
+ return cause && cause.exitCode === 2 ? 2 : 1;
649
+ }
650
+ }
651
+
652
+ if (require.main === module) process.exitCode = main(process.argv.slice(2));
653
+
654
+ module.exports = { isWithin };
@@ -0,0 +1,26 @@
1
+ name: error-ledger-bootstrap-routing-eval
2
+ description: Trigger precision eval for the error-ledger-bootstrap skill.
3
+ skill: error-ledger-bootstrap
4
+ version: "1.0"
5
+ config:
6
+ trials_per_task: 1
7
+ timeout_seconds: 300
8
+ parallel: false
9
+ executor: copilot-sdk
10
+ model: claude-sonnet-4.6
11
+ metrics:
12
+ - name: task_completion
13
+ weight: 0.7
14
+ threshold: 0.8
15
+ description: Did repository-wide bootstrap trigger only for the intended inventory and promotion task?
16
+ - name: efficiency
17
+ weight: 0.3
18
+ threshold: 0.7
19
+ description: Did the skill stay within its privacy and approval boundaries?
20
+ graders:
21
+ - type: behavior
22
+ name: token-budget
23
+ config:
24
+ max_tokens: 1200
25
+ tasks:
26
+ - "tasks/*.yaml"