harness-everything 0.54.0 → 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 (72) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +2 -1
  3. package/CHANGELOG.md +25 -0
  4. package/README.md +1 -0
  5. package/ci/action-gate.test.js +1 -1
  6. package/ci/mechanism-2at-fable-execution-phases.test.js +38 -0
  7. package/ci/mechanism-codex-hook-results.test.js +145 -0
  8. package/ci/mechanism-error-ledger-oracle.test.js +222 -0
  9. package/ci/mechanism-error-ledger-promote.test.js +520 -0
  10. package/ci/mechanism-error-ledger-scan.test.js +640 -0
  11. package/ci/mechanism-errors-sync-root.test.js +215 -0
  12. package/ci/openai-plugin-package.test.js +1 -1
  13. package/ci/openai-plugin-runtime.test.js +2 -1
  14. package/ci/prompt-contract-regressions.test.js +6 -2
  15. package/docs/platform-capabilities.md +17 -0
  16. package/docs/workflows/error-ledger-bootstrap.md +23 -0
  17. package/error-ledger-bootstrap/SKILL.md +33 -0
  18. package/error-ledger-bootstrap/references/workflow.md +79 -0
  19. package/error-ledger-bootstrap/scripts/promote.js +613 -0
  20. package/error-ledger-bootstrap/scripts/scan.js +654 -0
  21. package/evals/error-ledger-bootstrap/eval.yaml +26 -0
  22. package/evals/error-ledger-bootstrap/tasks/negative-error-handling-map.yaml +16 -0
  23. package/evals/error-ledger-bootstrap/tasks/negative-trigger.yaml +16 -0
  24. package/evals/error-ledger-bootstrap/tasks/positive-trigger.yaml +15 -0
  25. package/fable-mode/SKILL.md +5 -5
  26. package/fable-mode/execution-guardrails/SKILL.md +1 -1
  27. package/fable-mode/fable-haiku/SKILL.md +1 -1
  28. package/fable-mode/fable-opus/SKILL.md +1 -1
  29. package/fable-mode/fable-sonnet/SKILL.md +1 -1
  30. package/fable-mode/references/execution-phases.md +26 -4
  31. package/harness-everything/SKILL.md +1 -1
  32. package/harness-everything/references/skill-registry.md +1 -0
  33. package/harness-everything/scripts/routing-keywords.json +11 -0
  34. package/hooks/scripts/action-gate.js +5 -0
  35. package/hooks/scripts/codex-action-gate-post.js +3 -12
  36. package/hooks/scripts/contract-test.js +17 -7
  37. package/hooks/scripts/lib/codex-tool-outcome.js +28 -0
  38. package/hooks/scripts/rule-of-3-tracker.js +11 -4
  39. package/hooks/scripts/state-persist.js +15 -9
  40. package/hooks/scripts/subagent-scope-guard.js +32 -25
  41. package/hooks/scripts/subagent-start.js +1 -1
  42. package/hooks/scripts/subagent-stop.js +14 -3
  43. package/opencode-plugin/plugin.json +1 -1
  44. package/package.json +1 -1
  45. package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
  46. package/plugins/harness-everything/hooks/hooks.json +6 -6
  47. package/plugins/harness-everything/hooks/scripts/action-gate.js +5 -0
  48. package/plugins/harness-everything/hooks/scripts/codex-action-gate-post.js +3 -12
  49. package/plugins/harness-everything/hooks/scripts/contract-test.js +17 -7
  50. package/plugins/harness-everything/hooks/scripts/lib/codex-tool-outcome.js +28 -0
  51. package/plugins/harness-everything/hooks/scripts/rule-of-3-tracker.js +11 -4
  52. package/plugins/harness-everything/hooks/scripts/state-persist.js +15 -9
  53. package/plugins/harness-everything/hooks/scripts/subagent-scope-guard.js +32 -25
  54. package/plugins/harness-everything/hooks/scripts/subagent-start.js +1 -1
  55. package/plugins/harness-everything/hooks/scripts/subagent-stop.js +14 -3
  56. package/plugins/harness-everything/plugin.json +1 -1
  57. package/plugins/harness-everything/skills/error-ledger-bootstrap/SKILL.md +33 -0
  58. package/plugins/harness-everything/skills/error-ledger-bootstrap/references/workflow.md +79 -0
  59. package/plugins/harness-everything/skills/error-ledger-bootstrap/scripts/promote.js +613 -0
  60. package/plugins/harness-everything/skills/error-ledger-bootstrap/scripts/scan.js +654 -0
  61. package/plugins/harness-everything/skills/fable-mode/SKILL.md +5 -5
  62. package/plugins/harness-everything/skills/fable-mode/execution-guardrails/SKILL.md +1 -1
  63. package/plugins/harness-everything/skills/fable-mode/fable-haiku/SKILL.md +1 -1
  64. package/plugins/harness-everything/skills/fable-mode/fable-opus/SKILL.md +1 -1
  65. package/plugins/harness-everything/skills/fable-mode/fable-sonnet/SKILL.md +1 -1
  66. package/plugins/harness-everything/skills/fable-mode/references/execution-phases.md +26 -4
  67. package/plugins/harness-everything/skills/harness-everything/SKILL.md +1 -1
  68. package/plugins/harness-everything/skills/harness-everything/references/skill-registry.md +1 -0
  69. package/plugins/harness-everything/skills/harness-everything/scripts/routing-keywords.json +11 -0
  70. package/sbom.cdx.json +7 -7
  71. package/scripts/error-ledger-oracle.js +257 -0
  72. package/scripts/errors-sync.js +175 -12
@@ -4,7 +4,7 @@ description: "Reference mechanical behavior profile (legacy alias haiku) for bul
4
4
  license: Apache-2.0
5
5
  metadata:
6
6
  author: Miya Daniel
7
- version: 0.31.3
7
+ version: 0.54.1
8
8
  ---
9
9
 
10
10
  # Fable Mode — Haiku
@@ -4,7 +4,7 @@ description: "Reference orchestrator behavior profile (legacy alias opus) for st
4
4
  license: Apache-2.0
5
5
  metadata:
6
6
  author: Miya Daniel
7
- version: 0.31.3
7
+ version: 0.54.1
8
8
  ---
9
9
 
10
10
  # Fable Mode — Opus
@@ -4,7 +4,7 @@ description: "Reference reasoning behavior profile (legacy alias sonnet/sonnect)
4
4
  license: Apache-2.0
5
5
  metadata:
6
6
  author: Miya Daniel
7
- version: 0.31.3
7
+ version: 0.54.1
8
8
  ---
9
9
 
10
10
  # Fable Mode — Sonnet
@@ -17,13 +17,18 @@ flowchart TD
17
17
  Read relevant files and sources before producing an artifact. Record the
18
18
  authorized write scope. Give each stage an objective, dependencies, write set,
19
19
  expected output, exact check command, and pass condition. Required and optional
20
- bindings belong on the stage that needs them. Replan counts are advisory; after
21
- three same-signature failures, use Rule-of-3 `zoom-out`.
20
+ bindings belong on the stage that needs them. Replans are advisory and do not
21
+ halt tools or Stop; after three same-signature failures, use Rule-of-3
22
+ `zoom-out`.
22
23
 
23
24
  ## Profiles and delegation
24
25
 
25
- Resolve a requested behavior profile with Fable's profile selector and record
26
- it separately from the runtime choice. `fable-orchestrator`,
26
+ See the [model matrix](model-matrix.md) for profile details.
27
+
28
+ Resolve a requested behavior profile with Fable's `model-selector.js` and
29
+ record it separately from the runtime choice. `opus`, `sonnet`/`sonnect`, and
30
+ `haiku` are compatibility aliases for behavior profiles, not model bindings.
31
+ `fable-orchestrator`,
27
32
  `fable-worker-sonnet`, and `fable-worker-haiku` name coordination,
28
33
  reasoning/synthesis, and mechanical-work roles. These are behavior-profile
29
34
  aliases; they do not switch the runtime model. Preserve an explicit user or
@@ -104,3 +109,20 @@ Run each named check and review scope-guard evidence before delivery. When the
104
109
  selected plan requires independent verification, the verifier is read-only and
105
110
  uses a distinct worker identity after all other stages pass. Record a blocker
106
111
  or an evidence-backed result; do not discard unresolved requirements.
112
+
113
+ For Codex subagents, the coordinator MUST reconcile scope before accepting a
114
+ result or using it in a dependent stage, even if the stage check passed.
115
+
116
+ 1. Before dispatch, capture the worker worktree's starting state, including
117
+ existing local changes. At handoff, compare the committed, staged, unstaged,
118
+ and untracked changes since dispatch with the stage's declared `writeSet`.
119
+ 2. For unexpected or ambiguously attributed changes, establish ownership and
120
+ record the disposition. Exclude the changes from the result, revert only
121
+ attributable worker changes when authorized, or obtain explicit approval for
122
+ a scope change and follow the replanning rules. Record a blocker if the
123
+ coordinator cannot reconcile a path.
124
+
125
+ Run this check after every handoff, including silent stops. The Codex warning
126
+ and `subagent-scope-last.json` describe the latest hook observation. A clean
127
+ observation can replace an earlier warning while the corresponding change is
128
+ still present.
@@ -4,7 +4,7 @@ description: "Route software/project work through Harness: classify tier/topolog
4
4
  license: Apache-2.0
5
5
  metadata:
6
6
  author: Miya Daniel
7
- version: 0.52.0
7
+ version: 0.55.0
8
8
  ---
9
9
 
10
10
  # Harness Everything
@@ -33,6 +33,7 @@ Every skill in this repository is reachable from this router. If a task matches
33
33
  | `to-tickets` | Tier 2/3 (advisory, never a gate) | Breaking a `to-spec` feature spec (or an already-settled plan/conversation) into tracer-bullet tickets with declared blocking edges. Reuses `to-spec`'s own `check-project-docs.js` gate — never a second setup interview. Explicit-invoke only — never auto-executed. |
34
34
  | `zoom-out` | Circuit breaker | Rule of 3 trips (§3). |
35
35
  | `self-evolve` | Evolution | Post-breaker resolution or major breakthrough (§4). |
36
+ | `error-ledger-bootstrap` | Error ledger | Inventory local lessons for an existing repository and promote only owner-approved entries. |
36
37
  | `find-skills` | Meta | No static/generated/already-installed skill covers the user's need (checked live via `npx skills list`, not manifest-cached) — searches skills.sh/`npx skills` and, only with explicit approval, applies it ephemerally via a self-expiring OS-temp cache (`scripts/use-skill.js`, the default — zero persistent footprint) or, only if the user wants to keep it, installs via `npx skills add` (the rare exception). Deliberately not manifest-tracked or router-auto-surfaced like `self-evolve`'s `generated[]` — third-party content isn't lifecycle-owned by Harness the way self-authored skills are. |
37
38
  | `skill-style` | Meta | Authoring or modifying any SKILL.md in this repository — the terse Skill Contract format spec. |
38
39
  | `skill-creator` | Meta | Creating a new skill from scratch, auditing/refactoring an existing SKILL.md, or `self-evolve`'s dynamic skill generation step (§4) — the fuller authoring, quality-checklist, and testing workflow built on `skill-style`. |
@@ -563,6 +563,17 @@
563
563
  "find-skills"
564
564
  ]
565
565
  },
566
+ {
567
+ "id": "error-ledger-bootstrap",
568
+ "keywords": [
569
+ "error ledger",
570
+ "ledger bootstrap",
571
+ "error-ledger-bootstrap"
572
+ ],
573
+ "bindings": [
574
+ "error-ledger-bootstrap"
575
+ ]
576
+ },
566
577
  {
567
578
  "id": "security",
568
579
  "keywords": [
package/sbom.cdx.json CHANGED
@@ -2,23 +2,23 @@
2
2
  "$schema": "https://cyclonedx.org/schema/bom-1.7.schema.json",
3
3
  "bomFormat": "CycloneDX",
4
4
  "specVersion": "1.7",
5
- "serialNumber": "urn:uuid:b02b30cc-bd77-5327-8115-742afb9149ff",
5
+ "serialNumber": "urn:uuid:88917d13-bddd-5e04-939a-2a15464c6baa",
6
6
  "version": 1,
7
7
  "metadata": {
8
- "timestamp": "2026-11-19T05:40:53.563Z",
8
+ "timestamp": "2026-11-20T03:38:35.301Z",
9
9
  "tools": [
10
10
  {
11
11
  "vendor": "Harness Everything",
12
12
  "name": "generate-sbom.js",
13
- "version": "0.54.0"
13
+ "version": "0.55.0"
14
14
  }
15
15
  ],
16
16
  "component": {
17
17
  "type": "application",
18
- "bom-ref": "pkg:npm/harness-everything@0.54.0",
18
+ "bom-ref": "pkg:npm/harness-everything@0.55.0",
19
19
  "name": "harness-everything",
20
- "version": "0.54.0",
21
- "purl": "pkg:npm/harness-everything@0.54.0"
20
+ "version": "0.55.0",
21
+ "purl": "pkg:npm/harness-everything@0.55.0"
22
22
  }
23
23
  },
24
24
  "components": [
@@ -2033,7 +2033,7 @@
2033
2033
  ]
2034
2034
  },
2035
2035
  {
2036
- "ref": "pkg:npm/harness-everything@0.54.0",
2036
+ "ref": "pkg:npm/harness-everything@0.55.0",
2037
2037
  "dependsOn": [
2038
2038
  "pkg:npm/%40commitlint/cli@19.8.1",
2039
2039
  "pkg:npm/%40commitlint/config-conventional@19.8.1",
@@ -0,0 +1,257 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const fs = require('node:fs');
5
+ const path = require('node:path');
6
+ const yaml = require('js-yaml');
7
+
8
+ const USAGE = 'usage: node scripts/error-ledger-oracle.js --report <scan-report.json> --ledger <errors dir> [--json] [--out <file>] [--platform <platform>]';
9
+ 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.';
10
+
11
+ function failure(message) {
12
+ const error = new Error(message);
13
+ error.exitCode = 2;
14
+ throw error;
15
+ }
16
+
17
+ function parseArgs(args) {
18
+ const options = { json: false, platform: process.platform };
19
+ const values = new Set(['--report', '--ledger', '--out', '--platform']);
20
+ const seen = new Set();
21
+ for (let i = 0; i < args.length; i++) {
22
+ const arg = args[i];
23
+ if (arg === '--json') {
24
+ if (seen.has(arg)) failure(`duplicate option: ${arg}`);
25
+ seen.add(arg);
26
+ options.json = true;
27
+ continue;
28
+ }
29
+ if (!values.has(arg)) failure(`unknown option: ${arg}`);
30
+ if (seen.has(arg)) failure(`duplicate option: ${arg}`);
31
+ if (i + 1 >= args.length || !args[i + 1] || args[i + 1].startsWith('--')) failure(`missing value for ${arg}`);
32
+ seen.add(arg);
33
+ options[arg.slice(2)] = args[++i];
34
+ }
35
+ if (!options.report || !options.ledger) failure(`${USAGE}; --report and --ledger are required`);
36
+ return options;
37
+ }
38
+
39
+ function normalizeSite(value, platform) {
40
+ let site = value.trim().replace(/\s+\(.*\)\s*$/, '').trim().replace(/\\/g, '/');
41
+ site = site.replace(/^(?:\.\/)+/, '');
42
+ if (!site || site.startsWith('/') || /^[a-z]:/i.test(site) || /^~(?:\/|$)/.test(site) ||
43
+ /^[a-z][a-z\d+.-]*:\/\//i.test(site)) return null;
44
+ site = path.posix.normalize(site);
45
+ if (site === '.' || site === '..' || site.startsWith('../') || site.startsWith('/')) return null;
46
+ return platform === 'win32' ? site.toLowerCase() : site;
47
+ }
48
+
49
+ function normalizedSites(sites, platform) {
50
+ return new Set(sites.map(site => normalizeSite(site, platform)).filter(Boolean));
51
+ }
52
+
53
+ function readReport(file, platform) {
54
+ let report;
55
+ try {
56
+ report = JSON.parse(fs.readFileSync(file, 'utf8'));
57
+ } catch (error) {
58
+ failure(`could not read scan report: ${error.message}`);
59
+ }
60
+ if (!report || !Array.isArray(report.candidates)) failure('scan report must contain a candidates array');
61
+ const ids = new Set();
62
+ return report.candidates.map((candidate, index) => {
63
+ if (!candidate || typeof candidate.id !== 'string' || !candidate.id || !Array.isArray(candidate.sites) ||
64
+ !candidate.sites.every(site => typeof site === 'string')) {
65
+ failure(`scan report candidate ${index + 1} must have a string id and sites array`);
66
+ }
67
+ if (ids.has(candidate.id)) failure(`duplicate candidate id: ${candidate.id}`);
68
+ ids.add(candidate.id);
69
+ return { id: candidate.id, sites: normalizedSites(candidate.sites, platform) };
70
+ });
71
+ }
72
+
73
+ function readLedger(dir, platform) {
74
+ let files;
75
+ try {
76
+ files = fs.readdirSync(dir, { withFileTypes: true })
77
+ .filter(entry => entry.isFile() && /^E-.*\.md$/i.test(entry.name))
78
+ .map(entry => entry.name).sort();
79
+ } catch (error) {
80
+ failure(`could not read ledger directory: ${error.message}`);
81
+ }
82
+ const ids = new Set();
83
+ return files.map(file => {
84
+ let contents;
85
+ try {
86
+ contents = fs.readFileSync(path.join(dir, file), 'utf8');
87
+ } catch (error) {
88
+ failure(`could not read ledger record ${file}: ${error.message}`);
89
+ }
90
+ const frontmatter = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(contents);
91
+ if (!frontmatter) failure(`ledger record has no YAML frontmatter: ${file}`);
92
+ let metadata;
93
+ try {
94
+ metadata = yaml.load(frontmatter[1]);
95
+ } catch (error) {
96
+ failure(`invalid YAML frontmatter in ${file}: ${error.message.split('\n')[0]}`);
97
+ }
98
+ if (!metadata || typeof metadata.id !== 'string' || !metadata.id || !Array.isArray(metadata.sites) ||
99
+ !metadata.sites.every(site => typeof site === 'string')) {
100
+ failure(`ledger record ${file} must have a string id and sites array`);
101
+ }
102
+ if (ids.has(metadata.id)) failure(`duplicate ledger id: ${metadata.id}`);
103
+ ids.add(metadata.id);
104
+ return { id: metadata.id, sites: normalizedSites(metadata.sites, platform) };
105
+ });
106
+ }
107
+
108
+ function contains(parent, child) {
109
+ return child === parent || child.startsWith(parent.endsWith('/') ? parent : `${parent}/`);
110
+ }
111
+
112
+ function overlaps(left, right) {
113
+ return contains(left, right) || contains(right, left);
114
+ }
115
+
116
+ function compare(records, candidates) {
117
+ const linked = [];
118
+ const linkedCandidates = new Set();
119
+ for (const record of records) {
120
+ const candidateIds = candidates.filter(candidate =>
121
+ [...record.sites].some(recordSite => [...candidate.sites].some(candidateSite => overlaps(recordSite, candidateSite)))
122
+ ).map(candidate => candidate.id).sort();
123
+ if (candidateIds.length) {
124
+ linked.push({ id: record.id, candidateIds });
125
+ candidateIds.forEach(id => linkedCandidates.add(id));
126
+ }
127
+ }
128
+
129
+ const recordSites = new Map();
130
+ const candidateSites = new Map();
131
+ for (const record of records) for (const site of record.sites) {
132
+ const ids = recordSites.get(site) || new Set();
133
+ ids.add(record.id);
134
+ recordSites.set(site, ids);
135
+ }
136
+ for (const candidate of candidates) for (const site of candidate.sites) {
137
+ const ids = candidateSites.get(site) || new Set();
138
+ ids.add(candidate.id);
139
+ candidateSites.set(site, ids);
140
+ }
141
+ const sharedPathHits = [...recordSites.entries()]
142
+ .filter(([site, recordIds]) => recordIds.size > 1 && candidateSites.has(site))
143
+ .map(([site, recordIds]) => ({
144
+ site,
145
+ recordIds: [...recordIds].sort(),
146
+ candidateIds: [...candidateSites.get(site)].sort()
147
+ }))
148
+ .sort((a, b) => a.site.localeCompare(b.site));
149
+
150
+ const nonComparable = records.filter(record => record.sites.size === 0).map(record => record.id).sort();
151
+ const linkedIds = new Set(linked.map(record => record.id));
152
+ const linkedRecords = linked.length;
153
+ const unmatchedCandidates = candidates.length - linkedCandidates.size;
154
+ const rate = (numerator, denominator) => denominator ? numerator / denominator : null;
155
+ return {
156
+ counts: {
157
+ records: records.length,
158
+ comparableRecords: records.length - nonComparable.length,
159
+ linkedRecords,
160
+ candidates: candidates.length,
161
+ unmatchedCandidates
162
+ },
163
+ rates: {
164
+ recallAll: rate(linkedRecords, records.length),
165
+ recallComparable: rate(linkedRecords, records.length - nonComparable.length),
166
+ unmatchedShare: rate(unmatchedCandidates, candidates.length)
167
+ },
168
+ metricNote: METRIC_NOTE,
169
+ nonComparable,
170
+ linked,
171
+ unlinked: records.filter(record => !linkedIds.has(record.id)).map(record => record.id).sort(),
172
+ sharedPathHits
173
+ };
174
+ }
175
+
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}`));
180
+ }
181
+
182
+ function canonicalTarget(file) {
183
+ const target = path.resolve(file);
184
+ try {
185
+ const stat = fs.lstatSync(target);
186
+ if (stat.isSymbolicLink()) {
187
+ try {
188
+ return fs.realpathSync.native(target);
189
+ } catch (error) {
190
+ if (error.code === 'ENOENT') failure('--out path cannot be a dangling symlink');
191
+ throw error;
192
+ }
193
+ }
194
+ return fs.realpathSync.native(target);
195
+ } catch (error) {
196
+ if (error.code !== 'ENOENT') throw error;
197
+ return path.join(fs.realpathSync.native(path.dirname(target)), path.basename(target));
198
+ }
199
+ }
200
+
201
+ function safeOutput(file, ledgerDir, reportFile) {
202
+ const output = path.resolve(file);
203
+ const canonicalOutput = canonicalTarget(output);
204
+ const canonicalLedger = fs.realpathSync.native(ledgerDir);
205
+ if (isWithin(canonicalLedger, output) || isWithin(canonicalLedger, canonicalOutput)) {
206
+ failure('--out path is inside the ledger directory');
207
+ }
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');
212
+ }
213
+ 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
+ }
219
+ } catch (error) {
220
+ if (error.code !== 'ENOENT') throw error;
221
+ }
222
+ return output;
223
+ }
224
+
225
+ function markdown(result) {
226
+ const rate = value => value === null ? 'n/a' : `${(value * 100).toFixed(1)}%`;
227
+ const rows = [
228
+ ['records', result.counts.records],
229
+ ['comparable records', result.counts.comparableRecords],
230
+ ['linked records', result.counts.linkedRecords],
231
+ ['candidates', result.counts.candidates],
232
+ ['unmatched candidates', result.counts.unmatchedCandidates],
233
+ ['recall (all)', rate(result.rates.recallAll)],
234
+ ['recall (comparable)', rate(result.rates.recallComparable)],
235
+ ['unmatched candidate share (path overlap)', rate(result.rates.unmatchedShare)]
236
+ ];
237
+ return `${result.metricNote}\n\n| Metric | Value |\n| --- | ---: |\n${rows.map(([label, value]) => `| ${label} | ${value} |`).join('\n')}\n`;
238
+ }
239
+
240
+ function main() {
241
+ const options = parseArgs(process.argv.slice(2));
242
+ const reportFile = path.resolve(options.report);
243
+ const ledgerDir = path.resolve(options.ledger);
244
+ const candidates = readReport(reportFile, options.platform);
245
+ const records = readLedger(ledgerDir, options.platform);
246
+ const result = compare(records, candidates);
247
+ const output = options.json ? `${JSON.stringify(result, null, 2)}\n` : markdown(result);
248
+ if (options.out) fs.writeFileSync(safeOutput(options.out, ledgerDir, reportFile), output);
249
+ process.stdout.write(output);
250
+ }
251
+
252
+ try {
253
+ main();
254
+ } catch (error) {
255
+ process.stderr.write(`${error.message}\n`);
256
+ process.exitCode = error.exitCode || 1;
257
+ }
@@ -6,18 +6,60 @@
6
6
 
7
7
  const fs = require('fs');
8
8
  const path = require('path');
9
+ const crypto = require('crypto');
9
10
  const yaml = require('js-yaml');
10
11
 
11
12
  const ROOT = path.resolve(__dirname, '..');
12
- const DIR = path.join(ROOT, '.agents', 'harness-everything', 'errors');
13
- const INDEX = path.join(DIR, 'index.jsonl');
13
+ const ERRORS_PATH = path.join('.agents', 'harness-everything', 'errors');
14
+ const DIR = path.join(ROOT, ERRORS_PATH);
15
+ const INDEX_NAME = 'index.jsonl';
14
16
  const RECORD = /^E-\d{4}-[a-z0-9-]+\.md$/;
15
17
  const REQUIRED = ['id', 'signature', 'class', 'scope', 'status'];
16
18
  const SCOPES = new Set(['in', 'out', 'unresolved']);
17
19
  const STATUSES = new Set(['open', 'lesson', 'mechanism']);
18
20
 
19
- function parseRecord(file) {
20
- const text = fs.readFileSync(path.join(DIR, file), 'utf8').replace(/\r\n/g, '\n');
21
+ function errorsDirectory(root) {
22
+ const resolvedRoot = path.resolve(root);
23
+ let canonicalRoot;
24
+ try {
25
+ canonicalRoot = fs.realpathSync.native ? fs.realpathSync.native(resolvedRoot) : fs.realpathSync(resolvedRoot);
26
+ if (!fs.statSync(canonicalRoot).isDirectory()) throw new Error('not a directory');
27
+ } catch (_) {
28
+ throw new Error(`root ${JSON.stringify(resolvedRoot)} must exist and contain ${ERRORS_PATH}`);
29
+ }
30
+
31
+ let dir = canonicalRoot;
32
+ for (const part of ERRORS_PATH.split(path.sep)) {
33
+ const candidate = path.join(dir, part);
34
+ let stat;
35
+ try {
36
+ stat = fs.lstatSync(candidate);
37
+ dir = fs.realpathSync.native ? fs.realpathSync.native(candidate) : fs.realpathSync(candidate);
38
+ } catch (_) {
39
+ throw new Error(`root ${JSON.stringify(resolvedRoot)} must exist and contain ${ERRORS_PATH}`);
40
+ }
41
+ const inside = path.relative(canonicalRoot, dir);
42
+ if (path.isAbsolute(inside) || inside === '..' || inside.startsWith(`..${path.sep}`)) {
43
+ throw new Error(`ledger path ${part} resolves outside target root`);
44
+ }
45
+ if (part === 'errors' && (stat.isSymbolicLink() || !samePath(candidate, dir))) {
46
+ throw new Error('errors directory must not be a symlink or junction');
47
+ }
48
+ if (!fs.statSync(dir).isDirectory()) {
49
+ throw new Error(`root ${JSON.stringify(resolvedRoot)} must exist and contain ${ERRORS_PATH}`);
50
+ }
51
+ }
52
+ return dir;
53
+ }
54
+
55
+ function samePath(left, right) {
56
+ return process.platform === 'win32'
57
+ ? left.toLowerCase() === right.toLowerCase()
58
+ : left === right;
59
+ }
60
+
61
+ function parseRecord(file, dir = DIR) {
62
+ const text = fs.readFileSync(path.join(dir, file), 'utf8').replace(/\r\n/g, '\n');
21
63
  const match = /^---\n([\s\S]*?)\n---\n/.exec(text);
22
64
  if (!match) throw new Error(`${file}: missing YAML frontmatter`);
23
65
  const meta = yaml.load(match[1]);
@@ -50,11 +92,11 @@ function parseRecord(file) {
50
92
  };
51
93
  }
52
94
 
53
- function render() {
54
- const files = fs.readdirSync(DIR).filter(f => RECORD.test(f)).sort();
95
+ function renderDirectory(dir) {
96
+ const files = fs.readdirSync(dir).filter(f => RECORD.test(f)).sort();
55
97
  const ids = new Set();
56
98
  const lines = files.map(file => {
57
- const record = parseRecord(file);
99
+ const record = parseRecord(file, dir);
58
100
  if (ids.has(record.id)) throw new Error(`${file}: duplicate id ${record.id}`);
59
101
  ids.add(record.id);
60
102
  return JSON.stringify(record);
@@ -62,18 +104,134 @@ function render() {
62
104
  return lines.length ? `${lines.join('\n')}\n` : '';
63
105
  }
64
106
 
107
+ function render(root = ROOT) {
108
+ return renderDirectory(errorsDirectory(root));
109
+ }
110
+
111
+ function inspectIndex(index) {
112
+ try {
113
+ const stat = fs.lstatSync(index);
114
+ if (stat.isSymbolicLink() || !stat.isFile()) {
115
+ throw new Error('target index must be a regular file inside the errors directory');
116
+ }
117
+ return stat;
118
+ } catch (error) {
119
+ if (error.code === 'ENOENT') return null;
120
+ throw error;
121
+ }
122
+ }
123
+
124
+ function readIndex(index) {
125
+ const before = inspectIndex(index);
126
+ if (!before) return null;
127
+ let fd;
128
+ try {
129
+ const noFollow = fs.constants.O_NOFOLLOW || 0;
130
+ fd = fs.openSync(index, fs.constants.O_RDONLY | noFollow);
131
+ const opened = fs.fstatSync(fd);
132
+ if (!opened.isFile() || opened.dev !== before.dev || opened.ino !== before.ino) {
133
+ throw new Error('target index changed while it was being read');
134
+ }
135
+ return fs.readFileSync(fd, 'utf8');
136
+ } finally {
137
+ if (fd !== undefined) fs.closeSync(fd);
138
+ }
139
+ }
140
+
141
+ function writeIndex(index, content, root) {
142
+ const dir = path.dirname(index);
143
+ if (!samePath(path.resolve(errorsDirectory(root)), path.resolve(dir))) {
144
+ throw new Error('errors directory changed before index publication');
145
+ }
146
+ const previous = inspectIndex(index);
147
+ const previousBytes = previous ? readIndex(index) : null;
148
+ const mode = previous ? previous.mode & 0o777 : 0o666;
149
+ let temporary;
150
+ let fd;
151
+ try {
152
+ for (let attempt = 0; attempt < 5; attempt++) {
153
+ temporary = path.join(dir, `.${INDEX_NAME}.${process.pid}.${crypto.randomBytes(8).toString('hex')}.tmp`);
154
+ try {
155
+ fd = fs.openSync(temporary, 'wx', mode);
156
+ break;
157
+ } catch (error) {
158
+ temporary = undefined;
159
+ if (error.code !== 'EEXIST') throw error;
160
+ }
161
+ }
162
+ if (fd === undefined) throw new Error('could not allocate an exclusive temporary index file');
163
+ if (previous) fs.fchmodSync(fd, mode);
164
+ fs.writeFileSync(fd, content, 'utf8');
165
+ const openFd = fd;
166
+ fd = undefined;
167
+ fs.closeSync(openFd);
168
+
169
+ const currentDir = errorsDirectory(root);
170
+ if (!samePath(path.resolve(currentDir), path.resolve(dir))) throw new Error('errors directory changed before index publication');
171
+ const current = inspectIndex(index);
172
+ if (Boolean(current) !== Boolean(previous) || (current && (
173
+ current.dev !== previous.dev || current.ino !== previous.ino || readIndex(index) !== previousBytes
174
+ ))) throw new Error('target index changed before publication');
175
+ fs.renameSync(temporary, index);
176
+ temporary = undefined;
177
+ } finally {
178
+ if (fd !== undefined) {
179
+ try { fs.closeSync(fd); } catch (_) { /* still remove the temporary file */ }
180
+ }
181
+ if (temporary) {
182
+ try { fs.unlinkSync(temporary); } catch (error) { if (error.code !== 'ENOENT') throw error; }
183
+ }
184
+ }
185
+ }
186
+
65
187
  function main() {
66
- const check = process.argv.includes('--check');
188
+ const args = process.argv.slice(2);
189
+ let check = false;
190
+ let root = ROOT;
191
+ for (let i = 0; i < args.length; i++) {
192
+ if (args[i] === '--check') {
193
+ check = true;
194
+ } else if (args[i] === '--root') {
195
+ if (!args[i + 1] || args[i + 1].startsWith('--')) {
196
+ console.error('errors:sync: --root requires a directory');
197
+ process.exit(1);
198
+ }
199
+ root = path.resolve(args[++i]);
200
+ } else if (args[i].startsWith('--root=')) {
201
+ const value = args[i].slice('--root='.length);
202
+ if (!value) {
203
+ console.error('errors:sync: --root requires a directory');
204
+ process.exit(1);
205
+ }
206
+ root = path.resolve(value);
207
+ } else {
208
+ console.error(`errors:sync: unsupported argument ${JSON.stringify(args[i])}`);
209
+ process.exit(1);
210
+ }
211
+ }
212
+
67
213
  let next;
214
+ let index;
215
+ let directory;
68
216
  try {
69
- next = render();
217
+ root = path.resolve(root);
218
+ directory = errorsDirectory(root);
219
+ index = path.join(directory, INDEX_NAME);
220
+ inspectIndex(index);
221
+ next = renderDirectory(directory);
70
222
  } catch (error) {
71
223
  console.error(`errors:sync: ${error.message}`);
72
224
  process.exit(1);
73
225
  }
74
- const rel = path.relative(ROOT, INDEX).replace(/\\/g, '/');
226
+ const rel = path.relative(root, index).replace(/\\/g, '/');
75
227
  if (check) {
76
- const current = fs.existsSync(INDEX) ? fs.readFileSync(INDEX, 'utf8') : null;
228
+ let current;
229
+ try {
230
+ current = readIndex(index);
231
+ } catch (error) {
232
+ console.error(`errors:sync: ${error.message}`);
233
+ process.exit(1);
234
+ }
77
235
  if (current !== next) {
78
236
  console.error(`${rel} is stale. Run npm run errors:sync.`);
79
237
  process.exit(1);
@@ -81,7 +239,12 @@ function main() {
81
239
  console.log(`${rel} is current.`);
82
240
  return;
83
241
  }
84
- fs.writeFileSync(INDEX, next, 'utf8');
242
+ try {
243
+ writeIndex(index, next, root);
244
+ } catch (error) {
245
+ console.error(`errors:sync: ${error.message}`);
246
+ process.exit(1);
247
+ }
85
248
  console.log(`Updated ${rel}`);
86
249
  }
87
250