harness-everything 1.1.0 → 1.2.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 (32) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/CHANGELOG.md +19 -0
  4. package/benchmarks/results/live-host/agy-2026-11-25/README.md +32 -0
  5. package/benchmarks/results/live-host/multi-host-2026-11-25-496-capture/README.md +32 -0
  6. package/benchmarks/results/live-host/multi-host-2026-11-25-496-capture/claude-records.json +1 -0
  7. package/benchmarks/results/live-host/multi-host-2026-11-25-496-capture/codex-hook-trace.txt +24 -0
  8. package/benchmarks/results/live-host/multi-host-2026-11-25-496-capture/opencode-records.json +1 -0
  9. package/benchmarks/results/live-host/multi-host-2026-11-25-496-capture/probe.sh +16 -0
  10. package/ci/mechanism-498-local-store-promote.test.js +402 -0
  11. package/ci/mechanism-498-local-store-scan.test.js +570 -0
  12. package/ci/mechanism-516-windows-verify-and-shell.test.js +328 -0
  13. package/docs/platform-capabilities.md +2 -2
  14. package/docs/platform-compatibility.json +2 -2
  15. package/error-ledger-bootstrap/SKILL.md +1 -1
  16. package/error-ledger-bootstrap/references/workflow.md +15 -1
  17. package/error-ledger-bootstrap/scripts/promote.js +145 -9
  18. package/error-ledger-bootstrap/scripts/scan.js +394 -3
  19. package/hooks/scripts/lib/workflow-isolation.js +1 -1
  20. package/opencode-plugin/plugin.json +1 -1
  21. package/package.json +1 -1
  22. package/plugins/harness-everything/.antigravity-plugin/plugin.json +1 -1
  23. package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
  24. package/plugins/harness-everything/hooks/scripts/lib/workflow-isolation.js +1 -1
  25. package/plugins/harness-everything/plugin.json +1 -1
  26. package/plugins/harness-everything/scripts/lib/verification-contract.js +68 -12
  27. package/plugins/harness-everything/skills/error-ledger-bootstrap/SKILL.md +1 -1
  28. package/plugins/harness-everything/skills/error-ledger-bootstrap/references/workflow.md +15 -1
  29. package/plugins/harness-everything/skills/error-ledger-bootstrap/scripts/promote.js +145 -9
  30. package/plugins/harness-everything/skills/error-ledger-bootstrap/scripts/scan.js +394 -3
  31. package/sbom.cdx.json +7 -7
  32. package/scripts/lib/verification-contract.js +68 -12
@@ -0,0 +1,328 @@
1
+ 'use strict';
2
+
3
+ const assert = require('assert');
4
+ const fs = require('fs');
5
+ const os = require('os');
6
+ const path = require('path');
7
+ const { spawnSync } = require('child_process');
8
+
9
+ const ROOT = path.resolve(__dirname, '..');
10
+ const VERIFY = path.join(ROOT, 'harness-everything', 'scripts', 'verify-gate.js');
11
+ const PACKAGED_POST_TOOL = path.join(ROOT, 'plugins', 'harness-everything', 'hooks', 'scripts', 'agy-post-tool.js');
12
+ const PACKAGED_STOP = path.join(ROOT, 'plugins', 'harness-everything', 'hooks', 'scripts', 'agy-stop.js');
13
+
14
+ const temp = fs.mkdtempSync(path.join(os.tmpdir(), 'harness-516-win-'));
15
+ const stateHome = path.join(temp, 'state-home');
16
+ const originalStateHome = process.env.HARNESS_STATE_HOME;
17
+ fs.mkdirSync(stateHome, { recursive: true });
18
+ process.env.HARNESS_STATE_HOME = stateHome;
19
+
20
+ const { isVerificationCommand, detectRoot, parseCwdPrelude } = require('../scripts/lib/verification-contract');
21
+ const { classifyShell } = require('../hooks/scripts/lib/workflow-isolation');
22
+ const { getSessionDir } = require('../plugins/harness-everything/hooks/scripts/lib/harness-state');
23
+
24
+ function git(cwd, args) {
25
+ const res = spawnSync('git', args, { cwd, encoding: 'utf8', timeout: 20000 });
26
+ assert.ifError(res.error);
27
+ assert.strictEqual(res.status, 0, `git ${args.join(' ')} failed: ${res.stderr}`);
28
+ return res.stdout.trim();
29
+ }
30
+
31
+ function initRepo(dir) {
32
+ fs.mkdirSync(dir, { recursive: true });
33
+ git(dir, ['init', '-b', 'main']);
34
+ git(dir, ['config', 'user.name', 'Harness Test']);
35
+ git(dir, ['config', 'user.email', 'harness@example.test']);
36
+ fs.writeFileSync(path.join(dir, 'README.md'), 'seed\n');
37
+ git(dir, ['add', 'README.md']);
38
+ git(dir, ['commit', '-m', 'seed']);
39
+ return fs.realpathSync.native(dir);
40
+ }
41
+
42
+ function runScript(scriptPath, payload) {
43
+ const env = { ...process.env, HARNESS_STATE_HOME: stateHome };
44
+ delete env.HARNESS_REQUIRE_VERIFICATION;
45
+ const res = spawnSync(process.execPath, [scriptPath], {
46
+ input: JSON.stringify(payload),
47
+ encoding: 'utf8',
48
+ env,
49
+ timeout: 20000,
50
+ });
51
+ assert.ifError(res.error);
52
+ assert.strictEqual(res.status, 0, `${path.basename(scriptPath)} failed: ${res.stderr}`);
53
+ return JSON.parse(res.stdout.trim());
54
+ }
55
+
56
+ function runPowerShell(cwd, command) {
57
+ const env = { ...process.env };
58
+ delete env.NODE_TEST_CONTEXT;
59
+ const res = spawnSync('pwsh', ['-NoProfile', '-NonInteractive', '-Command', command], {
60
+ cwd,
61
+ encoding: 'utf8',
62
+ env,
63
+ timeout: 20000,
64
+ });
65
+ assert.ifError(res.error);
66
+ return res;
67
+ }
68
+
69
+ function readHandoff(repo, conversationId) {
70
+ return JSON.parse(fs.readFileSync(path.join(getSessionDir(repo, conversationId), 'handoff-state.json'), 'utf8'));
71
+ }
72
+
73
+ function postShell(repo, conversationId, command, exitCode, cwd = repo) {
74
+ runScript(PACKAGED_POST_TOOL, {
75
+ conversationId,
76
+ workspacePaths: [repo],
77
+ toolCall: { name: 'run_command', args: { CommandLine: command, Cwd: cwd } },
78
+ exitCode,
79
+ });
80
+ return readHandoff(repo, conversationId);
81
+ }
82
+
83
+ try {
84
+ const repo = initRepo(path.join(temp, 'repo'));
85
+ const outside = fs.realpathSync.native(fs.mkdtempSync(path.join(temp, 'outside-')));
86
+ fs.mkdirSync(path.join(repo, 'pkg'), { recursive: true });
87
+ fs.mkdirSync(path.join(repo, 'pkg[1]'));
88
+ fs.mkdirSync(path.join(repo, 'pkg1'));
89
+ const infoQueries = [
90
+ 'node --test --help',
91
+ 'node --test "--version"',
92
+ 'node --test -v',
93
+ 'mkdocs build --help',
94
+ 'poetry run mkdocs build --strict -h',
95
+ 'uv run mkdocs build --"help"',
96
+ '.venv\\Scripts\\mkdocs.exe build --help',
97
+ '.venv/bin/mkdocs build --help',
98
+ 'sphinx-build --version',
99
+ 'sphinx-build -M help docs build',
100
+ '.venv\\Scripts\\sphinx-build.exe -V',
101
+ ];
102
+
103
+ // 1. Windows .cmd wrappers and Node/Docs verifiers
104
+ for (const cmd of [
105
+ 'npm.cmd test',
106
+ 'npm.cmd run test',
107
+ 'npm.cmd run test:consistency',
108
+ 'npm.cmd run verify:all',
109
+ 'pnpm.cmd test',
110
+ 'yarn.cmd lint',
111
+ 'bun.cmd run check',
112
+ 'node --test ci/mechanism-516-agy-post-tool-exit.test.js',
113
+ 'node --test --test-name-pattern "mentions --help in a test name"',
114
+ 'mkdocs build --strict',
115
+ 'poetry run mkdocs build --strict',
116
+ 'uv run mkdocs build --strict',
117
+ '.venv\\Scripts\\mkdocs build --strict',
118
+ '.venv/bin/mkdocs build --strict',
119
+ 'sphinx-build -W docs build',
120
+ 'sphinx-build -v docs build',
121
+ 'sphinx-build -M html docs build',
122
+ ]) {
123
+ assert.strictEqual(isVerificationCommand(cmd, { cwd: repo, root: repo }), true, `must recognize verifier: ${cmd}`);
124
+ }
125
+
126
+ for (const cmd of [
127
+ ...infoQueries,
128
+ 'mkdocs serve',
129
+ 'node -e "console.log(1)"',
130
+ 'npm.cmd install',
131
+ 'npm.cmd run build && rm -rf out',
132
+ 'npm.cmd run test:consistency; Remove-Item -Recurse .',
133
+ ]) {
134
+ assert.strictEqual(isVerificationCommand(cmd, { cwd: repo, root: repo }), false, `must reject non-verifier: ${cmd}`);
135
+ }
136
+
137
+ // Declared contract matches npm.cmd equivalent only in declared cwd
138
+ fs.mkdirSync(path.join(repo, '.harness'), { recursive: true });
139
+ fs.writeFileSync(path.join(repo, '.harness', 'verify.json'), JSON.stringify({
140
+ version: 1,
141
+ checks: [{ id: 'root-test', run: 'npm test', cwd: '.' }],
142
+ }));
143
+ assert.strictEqual(isVerificationCommand('npm.cmd test', { cwd: repo, root: repo }), true, 'declared npm test matches npm.cmd test');
144
+ assert.strictEqual(isVerificationCommand('npm.cmd test', { cwd: path.join(repo, 'pkg'), root: repo }), false, 'declared npm.cmd test must still respect cwd');
145
+ fs.rmSync(path.join(repo, '.harness'), { recursive: true, force: true });
146
+
147
+ // 2. mkdocs.yml detection
148
+ const docsRepo = initRepo(path.join(temp, 'mkdocs-repo'));
149
+ fs.writeFileSync(path.join(docsRepo, 'mkdocs.yml'), 'site_name: Demo\n');
150
+ fs.writeFileSync(path.join(docsRepo, 'pyproject.toml'), '[tool.poetry]\nname = "demo"\n');
151
+ const detected = detectRoot(docsRepo);
152
+ const runs = detected.candidates.map(c => c.run);
153
+ assert.ok(runs.includes('mkdocs build --strict'), `missing mkdocs candidate: ${JSON.stringify(runs)}`);
154
+ assert.ok(runs.includes('poetry run mkdocs build --strict'), `missing poetry mkdocs candidate: ${JSON.stringify(runs)}`);
155
+ for (const prefix of ['mkdocs build --strict', 'poetry run mkdocs build --strict']) {
156
+ assert.strictEqual(isVerificationCommand(prefix, { cwd: docsRepo, root: docsRepo }), true);
157
+ assert.strictEqual(isVerificationCommand(prefix + ' --help', { cwd: docsRepo, root: docsRepo }), false);
158
+ assert.ok(!postShell(docsRepo, 'docs-help', prefix + ' --help', 0).lastVerifyAt);
159
+ }
160
+
161
+ const gateOut = spawnSync(process.execPath, [VERIFY, '--json'], { cwd: docsRepo, encoding: 'utf8', timeout: 20000 });
162
+ assert.strictEqual(gateOut.status, 0);
163
+ const gateReport = JSON.parse(gateOut.stdout);
164
+ assert.strictEqual(gateReport.status, 'UNCHECKED_DISCOVERED');
165
+ assert.ok(gateReport.candidates.some(c => c.run === 'mkdocs build --strict'));
166
+
167
+ // 3. PowerShell Set-Location prelude
168
+ const changeLocation = dir => `Set-Location -LiteralPath '${dir}' -ErrorAction Stop`;
169
+ const testCommand = 'node --test verify.test.js';
170
+ const verifyInPkg = `${changeLocation('./pkg')} && ${testCommand}`;
171
+ const failedPrelude = `${changeLocation('./missing')} && ${testCommand}`;
172
+ const unconditionalPrelude = `Set-Location -Path './missing'; ${testCommand}`;
173
+ const wildcardPrelude = `Set-Location -Path './pkg[1]' -ErrorAction Stop && ${testCommand}`;
174
+ const literalBracketsPrelude = `${changeLocation('./pkg[1]')} && ${testCommand}`;
175
+ const posixRepo = repo.replace(/\\/g, '/');
176
+ fs.mkdirSync(path.join(repo, '.harness'));
177
+ const pkgContract = JSON.stringify({
178
+ version: 1,
179
+ checks: [{ id: 'pkg-test', run: testCommand, cwd: 'pkg' }],
180
+ });
181
+ const contractPath = path.join(repo, '.harness', 'verify.json');
182
+ fs.writeFileSync(contractPath, pkgContract);
183
+ for (const cmd of [
184
+ verifyInPkg,
185
+ `${changeLocation(path.join(repo, 'pkg'))} && ${testCommand}`,
186
+ `${changeLocation(posixRepo + '/pkg')} && ${testCommand}`,
187
+ `cd ./pkg && ${testCommand}`,
188
+ ]) {
189
+ assert.strictEqual(isVerificationCommand(cmd, { cwd: repo, root: repo }), true, `must unwrap matching prelude: ${cmd}`);
190
+ }
191
+ if (process.platform === 'win32') {
192
+ assert.strictEqual(isVerificationCommand(`${changeLocation('.\\pkg')} && ${testCommand}`, { cwd: repo, root: repo }), true);
193
+ }
194
+
195
+ let successfulExit = 0;
196
+ let failedExit = 1;
197
+ let wildcardExit = 0;
198
+ if (process.platform === 'win32' || process.env.HARNESS_TEST_PWSH === '1') {
199
+ fs.writeFileSync(path.join(repo, 'verify.test.js'), 'require("node:test")("root verifier", () => {});\n');
200
+ fs.writeFileSync(path.join(repo, 'pkg', 'verify.test.js'), 'require("node:test")("package verifier", () => {});\n');
201
+ fs.writeFileSync(path.join(repo, 'pkg1', 'verify.test.js'), 'require("node:test")("wildcard verifier", () => {});\n');
202
+ fs.writeFileSync(path.join(repo, 'pkg[1]', 'verify.test.js'), 'require("node:test")("literal verifier", () => {});\n');
203
+
204
+ const success = runPowerShell(repo, verifyInPkg);
205
+ assert.strictEqual(success.status, 0, success.stderr);
206
+ assert.match(success.stdout, /package verifier/);
207
+ successfulExit = success.status;
208
+
209
+ const failure = runPowerShell(repo, failedPrelude);
210
+ assert.strictEqual(failure.status, 1, failure.stderr);
211
+ assert.doesNotMatch(failure.stdout, /verifier/);
212
+ failedExit = failure.status;
213
+
214
+ const unconditional = runPowerShell(repo, unconditionalPrelude);
215
+ assert.strictEqual(unconditional.status, 0, unconditional.stderr);
216
+ assert.match(unconditional.stdout, /root verifier/);
217
+
218
+ const wildcard = runPowerShell(repo, wildcardPrelude);
219
+ assert.strictEqual(wildcard.status, 0, wildcard.stderr);
220
+ assert.match(wildcard.stdout, /wildcard verifier/);
221
+ wildcardExit = wildcard.status;
222
+
223
+ const literal = runPowerShell(repo, literalBracketsPrelude);
224
+ assert.strictEqual(literal.status, 0, literal.stderr);
225
+ assert.match(literal.stdout, /literal verifier/);
226
+ }
227
+
228
+ for (const cmd of [
229
+ failedPrelude,
230
+ unconditionalPrelude,
231
+ `Set-Location -Path './pkg' -ErrorAction Stop && ${testCommand}`,
232
+ `Set-Location -LiteralPath './pkg' && ${testCommand}`,
233
+ `${changeLocation('./pkg')}; ${testCommand}`,
234
+ literalBracketsPrelude,
235
+ wildcardPrelude,
236
+ `${changeLocation('./pkg1')} && ${testCommand}`,
237
+ `${changeLocation('./pkg1/../pkg')} && ${testCommand}`,
238
+ `${changeLocation('FileSystem::./pkg')} && ${testCommand}`,
239
+ `${changeLocation(outside)} && ${testCommand}`,
240
+ `${changeLocation('./pkg')} && ${testCommand} && echo done`,
241
+ ]) {
242
+ assert.strictEqual(isVerificationCommand(cmd, { cwd: repo, root: repo }), false, `must reject unsafe Set-Location prelude: ${cmd}`);
243
+ assert.ok(!postShell(repo, 'rejected-prelude', cmd, 0).lastVerifyAt, `must not credit prelude: ${cmd}`);
244
+ }
245
+ assert.ok(!postShell(repo, 'failed-prelude', failedPrelude, failedExit).lastVerifyAt);
246
+ assert.strictEqual(parseCwdPrelude(`${changeLocation(outside)} && ${testCommand}`, { cwd: repo, root: repo }), null);
247
+ assert.ok(!postShell(repo, 'wrong-tool-cwd', testCommand, 0).lastVerifyAt);
248
+ assert.ok(postShell(repo, 'tool-cwd', testCommand, 0, path.join(repo, 'pkg')).lastVerifyAt);
249
+ // The wildcard fixture is checked against the directory the literal path
250
+ // would credit, so a contract mismatch cannot mask incorrect recognition.
251
+ fs.writeFileSync(contractPath, JSON.stringify({
252
+ version: 1,
253
+ checks: [{ id: 'literal-test', run: testCommand, cwd: 'pkg[1]' }],
254
+ }));
255
+ for (const command of [wildcardPrelude, literalBracketsPrelude]) {
256
+ assert.ok(!postShell(repo, 'wildcard-prelude', command, wildcardExit).lastVerifyAt);
257
+ }
258
+ fs.rmSync(contractPath);
259
+ for (const cmd of infoQueries) {
260
+ assert.ok(!postShell(repo, 'verifier-info', cmd, 0).lastVerifyAt, `must not credit info query: ${cmd}`);
261
+ }
262
+ fs.writeFileSync(contractPath, pkgContract);
263
+
264
+ // 4. Read-only PowerShell cmdlets & agy CLI read commands
265
+ for (const cmd of [
266
+ 'Get-Command agy',
267
+ 'Get-FileHash hooks/scripts/agy-stop.js',
268
+ 'Get-ChildItem | Select-Object Name',
269
+ 'Get-ChildItem | Sort-Object LastWriteTime | Format-Table Name',
270
+ 'agy --version',
271
+ 'agy plugin list --json',
272
+ 'agy plugin validate --json ./plugins/harness-everything',
273
+ ]) {
274
+ assert.strictEqual(classifyShell(cmd), 'read-only', `must classify as read-only: ${cmd}`);
275
+ }
276
+
277
+ assert.strictEqual(classifyShell('Get-ChildItem | ForEach-Object { Remove-Item $_.FullName }'), 'untrusted');
278
+ assert.notStrictEqual(classifyShell('Set-Location C:\\outside; git status'), 'read-only');
279
+ assert.strictEqual(classifyShell('Get-Content a.txt > b.txt'), 'untrusted');
280
+
281
+ // 5. End-to-end packaged AGY hooks: read-only PowerShell doesn't trigger false Stop;
282
+ // A successful, contained Set-Location verifier allows Stop.
283
+ const convReadOnly = 'win-readonly-' + Date.now();
284
+ runScript(PACKAGED_POST_TOOL, {
285
+ conversationId: convReadOnly,
286
+ workspacePaths: [repo],
287
+ toolCall: { name: 'run_command', args: { CommandLine: 'Get-ChildItem | Select-Object Name', Cwd: repo } },
288
+ });
289
+ runScript(PACKAGED_POST_TOOL, {
290
+ conversationId: convReadOnly,
291
+ workspacePaths: [repo],
292
+ toolCall: { name: 'run_command', args: { CommandLine: 'agy plugin list --json', Cwd: repo } },
293
+ });
294
+ const handoffReadOnly = JSON.parse(fs.readFileSync(path.join(getSessionDir(repo, convReadOnly), 'handoff-state.json'), 'utf8'));
295
+ assert.ok(!handoffReadOnly.lastEditAt, `read-only PowerShell/agy commands must not set lastEditAt: ${JSON.stringify(handoffReadOnly)}`);
296
+ assert.deepStrictEqual(
297
+ runScript(PACKAGED_STOP, { conversationId: convReadOnly, workspacePaths: [repo], terminationReason: 'NO_TOOL_CALL' }),
298
+ { decision: 'allow' }
299
+ );
300
+
301
+ const convEditVerify = 'win-edit-verify-' + Date.now();
302
+ const target = path.join(repo, 'README.md');
303
+ fs.writeFileSync(target, 'edited\n');
304
+ runScript(PACKAGED_POST_TOOL, {
305
+ conversationId: convEditVerify,
306
+ workspacePaths: [repo],
307
+ toolCall: { name: 'write_file', args: { Path: target, Content: 'edited\n' } },
308
+ });
309
+ const afterEdit = readHandoff(repo, convEditVerify);
310
+ for (const exitCode of [undefined, '0']) {
311
+ const unverified = postShell(repo, convEditVerify, verifyInPkg, exitCode);
312
+ assert.strictEqual(unverified.lastEditAt, afterEdit.lastEditAt);
313
+ assert.strictEqual(unverified.lastVerifyAt, afterEdit.lastVerifyAt);
314
+ }
315
+ assert.strictEqual(postShell(repo, convEditVerify, verifyInPkg, 1).lastVerifyAt, afterEdit.lastVerifyAt);
316
+ const afterPass = postShell(repo, convEditVerify, verifyInPkg, successfulExit);
317
+ assert.ok(afterPass.lastVerifyAt >= afterEdit.lastEditAt, 'confirmed Set-Location verifier must advance lastVerifyAt');
318
+ assert.deepStrictEqual(
319
+ runScript(PACKAGED_STOP, { conversationId: convEditVerify, workspacePaths: [repo], terminationReason: 'NO_TOOL_CALL' }),
320
+ { decision: 'allow' }
321
+ );
322
+
323
+ console.log('Windows verification-contract, PowerShell read-only classification, and packaged AGY hook flow verified.');
324
+ } finally {
325
+ if (originalStateHome === undefined) delete process.env.HARNESS_STATE_HOME;
326
+ else process.env.HARNESS_STATE_HOME = originalStateHome;
327
+ fs.rmSync(temp, { recursive: true, force: true });
328
+ }
@@ -15,7 +15,7 @@ Statuses are intentionally explicit:
15
15
  - `Unsupported`: official host documentation explicitly rules out the capability.
16
16
  - `Unknown`: the capability or its current host behavior was not established.
17
17
 
18
- Codex, Antigravity (AGY), and OpenCode are `Partial` in `liveHostVerification`. The Codex artifact verifies user-hook compatibility capture for two consecutive turns on one Windows Codex CLI host; native plugin-hook mounting and other host/version combinations remain unverified. The AGY artifact covers global Desktop App `2.34.0` and `agy` CLI `1.5.15` (macOS) for plugin loading/validation and lifecycle hooks under host-limited `PostToolUse` shell outcomes; IDE write tools, live `exitCode: 0` shell verification credit, live `model_stop`, and full project-scope isolation remain unverified. OpenCode supports the **V2 plugin API only** (OpenCode 1.x / V1 is unsupported): V2 live evidence covers one isolated `2.1.4` (macOS 26.6.2) long-lived server lifecycle trace (V2 default-export load, V2 tool hooks, V2 event envelope + `session.execution.succeeded`, and completion → verification → reminder delivery; standalone `opencode run` exits before verification finishes), alongside earlier `2.1.3` macOS server-log load-only and `2.1.4` macOS workspace traces; router/context injection, observation recording, ledger lessons, session create/delete reset, cancellation, global scope, npm-package install, and other versions/OSes remain unverified, while the retained OpenCode 1.18.31 (macOS) project-scope `.js` loading and edit/verification state artifact is historical/unsupported V1 evidence only. No fresh artifacts exist yet for the other surfaces, managed-workspace import, or public OpenAI approval.
18
+ Codex, Antigravity (AGY), and OpenCode are `Partial` in `liveHostVerification`. The Codex artifact verifies user-hook compatibility capture for two consecutive turns on one Windows Codex CLI host; native plugin-hook mounting and other host/version combinations remain unverified. The AGY artifact covers global Desktop App `2.34.0` and `agy` CLI `1.5.15` (macOS), plus Windows Desktop and `agy` CLI `1.5.16` (`harness-everything` `1.0.1`), for plugin loading/validation and lifecycle hooks (including bounded 1-continuation `Stop` on Windows) under host-limited `PostToolUse` shell outcomes; IDE write tools, live `exitCode: 0` shell verification credit, live `model_stop`, and full project-scope isolation remain unverified. OpenCode supports the **V2 plugin API only** (OpenCode 1.x / V1 is unsupported): V2 live evidence covers one isolated `2.1.4` (macOS 26.6.2) long-lived server lifecycle trace (V2 default-export load, V2 tool hooks, V2 event envelope + `session.execution.succeeded`, and completion → verification → reminder delivery; standalone `opencode run` exits before verification finishes), alongside earlier `2.1.3` macOS server-log load-only and `2.1.4` macOS workspace traces; router/context injection, observation recording, ledger lessons, session create/delete reset, cancellation, global scope, npm-package install, and other versions/OSes remain unverified, while the retained OpenCode 1.18.31 (macOS) project-scope `.js` loading and edit/verification state artifact is historical/unsupported V1 evidence only. No fresh artifacts exist yet for the other surfaces, managed-workspace import, or public OpenAI approval.
19
19
 
20
20
  ### Codex PR metadata action-gate boundary
21
21
 
@@ -73,7 +73,7 @@ A shared matcher (`hooks/scripts/lib/ledger-match.js`) selects workspace ledger
73
73
  | Platform surface | Standalone skills | Plugin support | Hooks/lifecycle | Project scope | Global scope | Current evidence boundary |
74
74
  | --- | --- | --- | --- | --- | --- | --- |
75
75
  | Codex | `Supported` | `Mechanism verified` | `Partial`: user-hook compatibility capture is live-verified for `UserPromptSubmit` and `Stop` on one Windows Codex CLI host; native plugin hooks remain mechanism-verified | `.agents/skills/`, `AGENTS.md` | `~/.agents/skills/` | [Live evidence](../benchmarks/results/live-host/codex-2026-10-13/README.md) verifies two consecutive turns on Codex CLI 0.162.1; native plugin mounting, other lifecycle events, and other versions remain unverified. |
76
- | Antigravity (AGY) | `Supported` | `Partial` (`Mechanism verified`; global Desktop App `2.34.0` load and `agy` CLI `1.5.15` `validate`/`list --json` live-verified on macOS; `validate --strict` fails on 2 multi-host warnings; temp `.agents/plugins/` hook discovery observed via `agy --print`) | `Partial`: `Mechanism verified` for all adapters; Desktop App `2.34.0` + CLI `1.5.15` (macOS) live-verified `SessionStart`, `PreInvocation` dedup, `PreToolUse` (`write_file`/`run_command`), `PostToolUse` edit tracking, and `Stop` (`NO_TOOL_CALL`); `PostToolUse` omits `exitCode`/`error` on shell non-zero exit (`1`) on both `2.34.0` and CLI `1.5.15`, so unknown shell outcomes grant no verification credit (`exitCode === 0` required); IDE write tools (`write_to_file`/`replace_file_content`/`multi_replace_file_content`) and live `model_stop` remain mechanism-only | `.agents/plugins/harness-everything/`, `.agents/rules/AGENTS.md` | `~/.gemini/config/plugins/harness-everything/` | [Mechanism evidence](../benchmarks/results/live-host/agy-2026-11-22/README.md) + [partial live-host evidence](../benchmarks/results/live-host/agy-2026-11-23/README.md) (Antigravity 2.0 Desktop App `2.34.0` + `agy` CLI `1.5.15`, macOS); `/hooks` TUI view, full project-scope `harness-everything` isolation, IDE write tools, live shell `exitCode: 0` verification credit, and live `Stop` `model_stop` remain open in issue #514. |
76
+ | Antigravity (AGY) | `Supported` | `Partial` (`Mechanism verified`; global Desktop App `2.34.0` load and `agy` CLI `1.5.15` `validate`/`list --json` live-verified on macOS, plus `agy` CLI `1.5.16` `validate`/`list --json` on Windows; `validate --strict` fails on 2 multi-host warnings; temp `.agents/plugins/` hook discovery observed via `agy --print`) | `Partial`: `Mechanism verified` for all adapters; Desktop App `2.34.0` + CLI `1.5.15` (macOS) live-verified `SessionStart`, `PreInvocation` dedup, `PreToolUse` (`write_file`/`run_command`), `PostToolUse` edit tracking, and `Stop` (`NO_TOOL_CALL`); Windows Desktop + CLI `1.5.16` (`harness-everything` `1.0.1`) live-verified `SessionStart`, `PreInvocation`, and bounded 1-continuation `Stop`; `PostToolUse` omits `exitCode`/`error` on shell outcomes on macOS `2.34.0`/CLI `1.5.15` and Windows Desktop, so unknown shell outcomes grant no verification credit (`exitCode === 0` required); IDE write tools (`write_to_file`/`replace_file_content`/`multi_replace_file_content`) and live `model_stop` remain mechanism-only | `.agents/plugins/harness-everything/`, `.agents/rules/AGENTS.md` | `~/.gemini/config/plugins/harness-everything/` | [Mechanism evidence](../benchmarks/results/live-host/agy-2026-11-22/README.md) + [macOS partial live-host evidence](../benchmarks/results/live-host/agy-2026-11-23/README.md) + [Windows partial live-host evidence](../benchmarks/results/live-host/agy-2026-11-25/README.md); `/hooks` TUI view, full project-scope `harness-everything` isolation, IDE write tools, live shell `exitCode: 0` verification credit, and live `Stop` `model_stop` remain open in issue #514. |
77
77
  | ChatGPT / OpenAI Plugin | `Unknown` for a repository-local standalone path | `Mechanism verified` | `Partial`: local Work/Codex hooks are separate from ordinary Chat | Managed workspace marketplace | Not established | The public Skills-only bundle is mechanically reproducible; import, approval, and live behavior remain `Unknown`. |
78
78
  | Claude Code | `Supported` | `Supported` | `Mechanism verified` for Harness configuration | `.claude/skills/` | `~/.claude/skills/` | Native Claude surfaces and the state-specific plugin sync command are mechanically checked; fresh-host execution is not preserved here. |
79
79
  | OpenCode | `Supported` | `Partial` (V2 plugin API only; OpenCode 1.x / V1 unsupported; V2 default-export load verified live on OpenCode 2.1.3 macOS via server-log only and in the 2.1.4 macOS 26.6.2 V2 lifecycle trace, plus a 2.1.4 macOS workspace trace; router injection and observation capture are mechanism-tested on V2) | `Partial` (V2 default-export load, V2 tool hooks, V2 event envelope + `session.execution.succeeded`, and completion → verification → reminder delivery on a long-lived server are live-observed on one OpenCode 2.1.4 macOS 26.6.2 run; router/context injection, observations, ledger lessons, session create/delete reset, and cancellation remain mechanism-verified only; retained 1.18.31 project-scope `.js` loading and edit/verification state artifact is historical/unsupported V1 evidence) | `.opencode/skills/`, `.agents/skills/`, `.opencode/plugins/` | `~/.config/opencode/skills/`, `~/.agents/skills/`, `~/.config/opencode/plugins/` | **V2-only support boundary (#453):** OpenCode V2 plugin API family only (OpenCode 1.x / V1 unsupported; no validated minimum patch version claimed). Tested V2 live observations: an isolated [OpenCode 2.1.4/macOS 26.6.2 V2 lifecycle trace](../benchmarks/results/live-host/opencode-2026-11-24-v2-lifecycle/README.md) (one host/version/run establishing V2 default-export load, V2 tool hooks, V2 event envelope + `session.execution.succeeded` completion, and completion → verification → reminder delivery on a long-lived server; `opencode run --standalone` exits before verification finishes), V2 default-export load on OpenCode 2.1.3 (macOS, 2026-10-23, server-log evidence only), and a separate [OpenCode 2.1.4/macOS session workspace trace](../benchmarks/results/live-host/opencode-2026-11-15-workspace/README.md) observing `ctx.session.get({sessionID})` returning `location.directory` for two sessions matching setup (no mismatch test or V2 hook fire). Router/context injection, observation recording, ledger lessons, session create/delete reset, cancellation, and workspace mismatch handling remain mechanism evidence only. [Retained historical/unsupported V1 evidence](../benchmarks/results/live-host/opencode-2026-09-16/README.md) (OpenCode 1.18.31, macOS) documents project-scope `.js` loading and edit/verification state in one V1 host session, with a post-reset final snapshot, hard lock only an interactive observation with no retained blocked-tool trace, and operator-seeded then agent-rewritten reflection; it is preserved as historical/unsupported evidence only and does not establish current V2 support. `.mjs` auto-discovery is silently ignored (issue #127); global scope, npm-package installation, and other host versions remain unverified. |
@@ -294,11 +294,11 @@
294
294
  "bundledSkills": {"status": "Mechanism verified", "paths": {"skills": ["plugins/harness-everything/skills/<name>/SKILL.md"]}, "notes": "Package checks verify all 28 canonical skills, and agy plugin validate --json (1.5.15) counted skills: 28; live invocation across all 28 skills remains unverified."},
295
295
  "hooksLifecycle": {"status": "Partial", "notes": "Deterministic mechanism tests cover SessionStart, PreInvocation, PreToolUse, PostToolUse, and Stop. Desktop App 2.34.0 and CLI 1.5.15 (macOS) live-verified SessionStart, PreInvocation, PreToolUse (write_file/run_command), PostToolUse edit timestamps, and Stop (NO_TOOL_CALL). Host limits: PostToolUse omits exitCode and error on shell non-zero exit (1) on both Desktop 2.34.0 and CLI 1.5.15, so unknown shell outcomes grant no verification credit and preserve failed state (explicit exitCode === 0 required); IDE write tools (write_to_file, replace_file_content, multi_replace_file_content) and live Stop model_stop remain unverified."},
296
296
  "projectScope": {"status": "Partial", "paths": {"plugins": [".agents/plugins/harness-everything"], "rules": [".agents/rules/AGENTS.md"]}, "notes": "agy CLI 1.5.15 plugin list --json only lists global plugins, while agy --print discovered and executed project-scope .agents/plugins/ hooks from a temporary probe plugin. Full project-scope harness-everything isolation without global install and Desktop App project-scope loading remain unverified."},
297
- "globalScope": {"status": "Partial", "paths": {"plugins": ["~/.gemini/config/plugins/harness-everything"]}, "notes": "Global load and hook execution are live-verified on Antigravity 2.0 Desktop App 2.34.0 (macOS) and agy CLI 1.5.15 (agy plugin list --json); Windows, Linux, and other AGY versions remain unverified."},
297
+ "globalScope": {"status": "Partial", "paths": {"plugins": ["~/.gemini/config/plugins/harness-everything"]}, "notes": "Global load and hook execution are live-verified on Antigravity 2.0 Desktop App 2.34.0 (macOS), agy CLI 1.5.15 (macOS), and Windows Antigravity Desktop + agy CLI 1.5.16; Linux and other AGY versions remain unverified."},
298
298
  "installUninstallSymmetry": {"status": "Mechanism verified", "notes": "scripts/plugin-sync.js --host agy install/update/dry-run and staged rollback are covered by mechanism tests and synced live to global scope; plugin-sync.js does not provide uninstall symmetry."},
299
299
  "assetsReferences": {"status": "Mechanism verified", "notes": "Packaged skills, rules/AGENTS.md byte-for-byte parity, and packaged agy-*.js hook scripts are verified by ci/mechanism-agy-plugin-package.test.js."},
300
300
  "updateSync": {"status": "Partial", "notes": "scripts/plugin-sync.js --host agy --json is mechanism-tested and was observed live updating ~/.gemini/config/plugins/harness-everything on macOS; other OSes and project-scope sync live behavior remain unverified."},
301
- "liveHostVerification": {"status": "Partial", "evidence": "benchmarks/results/live-host/agy-2026-11-23/README.md", "notes": "Partial live-host evidence covers global Antigravity 2.0 Desktop App 2.34.0 (macOS) and agy CLI 1.5.15 (macOS): plugin validate/list, SessionStart, PreInvocation, PreToolUse (write_file/run_command), PostToolUse edit timestamps, Stop (NO_TOOL_CALL), and temporary project-scope hook discovery. IDE write tools, live shell exitCode: 0 verification credit, live Stop model_stop, full project-scope isolation, and non-macOS hosts remain unverified."}
301
+ "liveHostVerification": {"status": "Partial", "evidence": "benchmarks/results/live-host/agy-2026-11-23/README.md", "notes": "Partial live-host evidence covers global Antigravity 2.0 Desktop App 2.34.0 (macOS), agy CLI 1.5.15 (macOS), and Windows Desktop + agy CLI 1.5.16 (benchmarks/results/live-host/agy-2026-11-25/README.md): plugin validate/list, SessionStart, PreInvocation, PreToolUse (write_file/run_command), PostToolUse edit timestamps, bounded Stop continuation (NO_TOOL_CALL / direct revision + workspace fingerprint), and temporary project-scope hook discovery. IDE write tools, live shell exitCode: 0 verification credit, live Stop model_stop, full project-scope isolation, and Linux hosts remain unverified."}
302
302
  }
303
303
  }
304
304
  ]
@@ -4,7 +4,7 @@ description: "Bootstrap a local error ledger for an existing repository by inven
4
4
  license: Apache-2.0
5
5
  metadata:
6
6
  author: Miya Daniel
7
- version: 0.55.0
7
+ version: 1.2.0
8
8
  ---
9
9
 
10
10
  # Error Ledger Bootstrap
@@ -14,6 +14,18 @@ Bug/regression/flake labels or `fix`/`bug` title prefixes qualify; reports keep
14
14
  - `--hide-ledger` excludes existing error-ledger files from the scan.
15
15
  - `--home <dir>` changes the local home used to resolve automatic memory.
16
16
 
17
+ ## Optional local error store
18
+
19
+ Local observations are opt-in: `--source local-store --destination harness|project`. With no `--source` option, the scanner keeps the legacy report bytes and source set. `--destination` is required with this source and accepts only `harness` or `project`; it is the operator's declaration for the canonical Git `--root`.
20
+
21
+ The scanner derives the workspace key from that root, calls the supported reader as `listRecords({ workspaceRoot, workspaceKey })`, and accepts only returned rows carrying that key. A bound host workspace that disagrees fails closed. The report binds the resolved destination to an opaque `workspaceRef`; each record ref is `p-local-<sha256>` over the workspace key and validated stored provisional ID. Raw provisional IDs are never reported. If the reader contract is absent (including the packaged Skills-only copy), the scan succeeds with source status `unavailable` and reason `reader-unavailable`.
22
+
23
+ The `local-store` source status is `used`, `missing`, `unverified`, or `unavailable`. Missing indexes use `index-missing`; unreadable or corrupt input uses a sanitized reason such as `store-unreadable`, `store-corrupt`, or `store-unsupported`. An empty reader result is `unverified` (`empty-reader-result`) because the reader returns an empty array for both an empty workspace and several read failures. Invalid rows are skipped and counted as `malformed`; they are never quoted. The report separately counts valid rows assigned to another destination and rows whose destination is `unknown`.
24
+
25
+ Each valid destination-matched provisional lesson yields one neutral local lead. Occurrences are grouped by exact signature and suppressed when a selected lesson covers that signature. JSON and Markdown contain only opaque refs, validated destination/kind/command-class metadata, signatures, counts, and dedupe/evidence results. They never include excerpts, cues, lesson text, issue URLs, paths, session IDs, or tool-use IDs. Keep the reports local; the local store and destination ledger are read-only during scan.
26
+
27
+ Each lead's `local` object includes `evidenceReadiness: needs-evidence`, `occurrenceCount`, and `dedupe`. The dedupe object contains `status` (`none`, `existing`, `ambiguous`, or `unverified`), sorted `classIds`, sorted `matchedBy` values (`signature` and/or `whole-rule`), and `newClassEligible`. The scanner checks only the selected destination's `index.jsonl`: a unique exact signature or exact whole-rule match (validated with the existing matcher validator) reports `existing` and its E-ID; matches to multiple E-IDs report `ambiguous`; an unreadable index reports `unverified`; otherwise the status is `none`. Only `none` sets `newClassEligible: true`, and that means only that exact dedupe found no existing class. The local lead still needs independently corroborated Git or documentation evidence and fresh item approval before promotion. Fuzzy matches remain for local classification.
28
+
17
29
  Treat memory and instructions as private input. A local report may include opaque source IDs, a neutral generated title or a short summary the operator reviewed locally, and only site paths verified to exist in the target repository. Keep raw source text, excerpts, private filenames and paths, credentials, and personal identifiers out of both report formats. The scanner emits reports outside the target repository: by default, into a private temporary directory; `--out <dir>` must also resolve outside the target, including through symlinks. Keep both reports local, including for company repositories.
18
30
 
19
31
  ## Classify candidates locally
@@ -26,6 +38,8 @@ Obtain explicit owner approval for each candidate. Bind the approval to the exac
26
38
 
27
39
  The top-level approval JSON has `schemaVersion: 1`, a 20-character hexadecimal `candidateId`, a 64-character hexadecimal `reportSha256` of the exact report bytes, an absolute canonical `targetRoot` matching `--target`, a non-empty `approvedBy`, and a parseable `approvedAt` timestamp. Its `record` object has a kebab-case `signature`; non-empty `class`, `title`, `violates`, and `sourcesNote`; `scope` of `in`, `out`, or `unresolved`; `status` of `open`, `lesson`, or `mechanism`; and `sites`, an array of existing target-repository files named by relative paths without absolute paths or `.` or `..` components. Do not put absolute paths in `approvedBy`, `approvedAt`, or the record text fields. The approved candidate must occur exactly once in the report, and the selected and approved site files must exist in the target.
28
40
 
41
+ For a candidate with a `local-store` source, also include top-level `destination: harness` or `destination: project` in the approval. Promotion requires one `used` workspace binding whose opaque ref resolves to canonical `--target` through the trusted Harness checkout's local-store reader; every candidate ref must still resolve to a row for that workspace and destination. The report's exact-dedupe result must be eligible, and the candidate must carry a verified Git or documentation commit source that exists in the target repository on that same candidate. Promotion rechecks exact signature and whole-rule dedupe against the current destination ledger while holding the promotion lock. Missing, unknown, mismatched, stale, or unreadable local bindings fail closed before ledger changes. Legacy reports without a local-store source keep their existing approval shape. A stored issue URL is only a local lead and never satisfies the durable-source requirement.
42
+
29
43
  Use this complete example as the approval file structure, replacing the sample candidate ID and digest with the exact report values, `targetRoot` with the target's absolute canonical path, and the approver, timestamp, and reviewed record content with the owner's approval:
30
44
 
31
45
  ```json
@@ -59,7 +73,7 @@ mkdir -p "<target repo>/.agents/harness-everything/errors"
59
73
 
60
74
  Promotion refuses when the directory is absent. No index file is needed beforehand; successful promotion updates the index through the sync command below.
61
75
 
62
- Before promotion, resolve a trusted local Harness checkout containing `scripts/errors-sync.js` and verify its Node dependencies are installed. The current sync script requires `js-yaml`; a read-only preflight is:
76
+ Before promotion, resolve a trusted local Harness checkout containing `scripts/errors-sync.js` and verify its Node dependencies are installed. Local-store candidates also require `hooks/scripts/lib/local-errors.js` in that checkout. The current sync script requires `js-yaml`; a read-only preflight is:
63
77
 
64
78
  ```sh
65
79
  test -f "<Harness checkout>/scripts/errors-sync.js"
@@ -195,19 +195,141 @@ function harnessTool(harnessInput) {
195
195
  catch (error) {
196
196
  problem(`Harness checkout cannot resolve js-yaml; install its Node dependencies and retry with that checkout (${error.message})`);
197
197
  }
198
- return script;
198
+ return { root, syncScript: script };
199
199
  }
200
200
 
201
- function durableSources(candidate) {
201
+ function localStoreTool(harnessRoot) {
202
+ const file = path.join(harnessRoot, 'hooks', 'scripts', 'lib', 'local-errors.js');
203
+ try {
204
+ const store = require(file);
205
+ if (typeof store.resolveWorkspaceKey !== 'function' || typeof store.listRecords !== 'function' ||
206
+ typeof store.validateMatch !== 'function') throw new Error('local-store reader contract is incomplete');
207
+ return store;
208
+ } catch (_) {
209
+ problem('local-store promotion requires hooks/scripts/lib/local-errors.js in the trusted Harness checkout');
210
+ }
211
+ }
212
+
213
+ function workspaceRef(workspaceKey) {
214
+ return `w-local-${hash(workspaceKey)}`;
215
+ }
216
+
217
+ function localStoreRef(workspaceKey, provisionalId) {
218
+ return `p-local-${hash(JSON.stringify([workspaceKey, provisionalId]))}`;
219
+ }
220
+
221
+ function validateLocalLead(report, candidate, approval, targetRoot, harnessRoot) {
222
+ const localSources = Array.isArray(candidate.sources)
223
+ ? candidate.sources.filter(source => source && source.type === 'local-store') : [];
224
+ if (!localSources.length) return null;
225
+
226
+ const bindings = Array.isArray(report.sources)
227
+ ? report.sources.filter(source => source && source.type === 'local-store') : [];
228
+ if (bindings.length !== 1 || bindings[0].origin !== 'workspace' || bindings[0].status !== 'used') {
229
+ problem('local-store report must contain one used workspace binding');
230
+ }
231
+ const binding = bindings[0];
232
+ if (binding.destination === 'unknown' || !['harness', 'project'].includes(binding.destination) ||
233
+ !['harness', 'project'].includes(approval.destination)) {
234
+ problem('local-store promotion requires a known harness or project destination');
235
+ }
236
+ if (binding.destination !== approval.destination ||
237
+ localSources.some(source => source.destination !== binding.destination)) {
238
+ problem('approved destination does not match the local-store report destination');
239
+ }
240
+ if (candidate.local?.evidenceReadiness !== 'needs-evidence' ||
241
+ candidate.local?.dedupe?.status !== 'none' || candidate.local?.dedupe?.newClassEligible !== true ||
242
+ !Array.isArray(candidate.local?.dedupe?.classIds) || candidate.local.dedupe.classIds.length !== 0) {
243
+ problem('local-store candidate is not eligible under its scanned exact-dedupe result');
244
+ }
245
+
246
+ const store = localStoreTool(harnessRoot);
247
+ let workspaceKey;
248
+ try { workspaceKey = store.resolveWorkspaceKey({ workspaceRoot: targetRoot }); }
249
+ catch (_) { problem('cannot resolve the local-store workspace for the canonical --target'); }
250
+ if (!/^w-local-[a-f0-9]{64}$/.test(binding.workspaceRef || '') || binding.workspaceRef !== workspaceRef(workspaceKey)) {
251
+ problem('local-store report workspace binding does not match the canonical --target');
252
+ }
253
+
254
+ let records;
255
+ try { records = store.listRecords({ workspaceRoot: targetRoot, workspaceKey }); }
256
+ catch (_) { problem('cannot read local-store records for the canonical --target'); }
257
+ const seen = new Set();
258
+ const matchedRecords = [];
259
+ for (const source of localSources) {
260
+ if (typeof source.ref !== 'string' || !/^p-local-[a-f0-9]{64}$/.test(source.ref) ||
261
+ source.signature !== candidate.signature || seen.has(source.ref)) {
262
+ problem('local-store candidate contains an invalid or duplicate opaque reference');
263
+ }
264
+ seen.add(source.ref);
265
+ const matches = records.filter(record => localStoreRef(workspaceKey, record.provisionalId) === source.ref);
266
+ if (matches.length !== 1 || matches[0].workspaceKey !== workspaceKey ||
267
+ matches[0].destination !== binding.destination || matches[0].signature !== candidate.signature ||
268
+ matches[0].kind !== source.kind) {
269
+ problem('local-store candidate reference is unavailable or does not match its report binding');
270
+ }
271
+ matchedRecords.push(matches[0]);
272
+ }
273
+ return { store, records: matchedRecords };
274
+ }
275
+
276
+ function hasTargetCommit(targetRoot, sha) {
277
+ const result = childProcess.spawnSync('git', ['-C', targetRoot, 'cat-file', '-e', `${sha}^{commit}`], {
278
+ env: { ...process.env, GIT_CONFIG_NOSYSTEM: '1' },
279
+ stdio: 'ignore'
280
+ });
281
+ return !result.error && result.status === 0;
282
+ }
283
+
284
+ function durableSources(candidate, targetRoot, verifyTarget = false) {
202
285
  const sources = new Set();
203
286
  for (const source of Array.isArray(candidate.sources) ? candidate.sources : []) {
204
- if (source && ['git', 'doc'].includes(source.type) && typeof source.sha === 'string' && COMMIT.test(source.sha)) {
287
+ if (source && ['git', 'doc'].includes(source.type) && typeof source.sha === 'string' &&
288
+ COMMIT.test(source.sha) && (!verifyTarget || hasTargetCommit(targetRoot, source.sha))) {
205
289
  sources.add(`commit ${source.sha.toLowerCase()}`);
206
290
  }
207
291
  }
208
292
  return [...sources].sort();
209
293
  }
210
294
 
295
+ function canonicalMatch(match, store) {
296
+ const validated = store.validateMatch(match);
297
+ const normalized = {};
298
+ for (const phase of ['actions', 'failures']) {
299
+ if (!validated[phase]) continue;
300
+ normalized[phase] = validated[phase].map(rule => ({
301
+ ...rule,
302
+ ...(rule.diagnostics ? { diagnostics: [...rule.diagnostics].sort() } : {})
303
+ })).sort((left, right) => JSON.stringify(left).localeCompare(JSON.stringify(right)));
304
+ }
305
+ return JSON.stringify(normalized);
306
+ }
307
+
308
+ function assertFreshDedupe(context) {
309
+ let rendered;
310
+ try {
311
+ const sync = require(context.syncScript);
312
+ if (typeof sync.render !== 'function') throw new Error('trusted errors-sync does not expose its renderer');
313
+ rendered = sync.render(context.targetRoot);
314
+ } catch (_) {
315
+ problem('destination ledger cannot be read safely for exact dedupe');
316
+ }
317
+ const current = indexState(context.index);
318
+ if (!current.bytes || current.bytes.toString('utf8') !== rendered) {
319
+ problem('destination ledger index is stale or unavailable; refresh it and rescan before promotion');
320
+ }
321
+
322
+ const signatures = new Set([context.candidate.signature, context.approval.record.signature]);
323
+ const rules = new Set(context.localLead.records.filter(record => record.match)
324
+ .map(record => canonicalMatch(record.match, context.localLead.store)));
325
+ const rows = rendered.split(/\r?\n/).filter(Boolean).map(line => JSON.parse(line));
326
+ for (const row of rows) {
327
+ if (signatures.has(row.signature) || (row.match && rules.has(canonicalMatch(row.match, context.localLead.store)))) {
328
+ problem('destination ledger contains an exact duplicate class; rescan and obtain fresh approval');
329
+ }
330
+ }
331
+ }
332
+
211
333
  function assertApprovalUnused(errorsDir, approvalHash) {
212
334
  for (const name of fs.readdirSync(errorsDir)) {
213
335
  if (!RECORD_NAME.test(name)) continue;
@@ -224,10 +346,10 @@ function yaml(value) {
224
346
  return JSON.stringify(value);
225
347
  }
226
348
 
227
- function recordText(approval, candidate, id, reportHash, approvalHash) {
349
+ function recordText(approval, candidate, id, reportHash, approvalHash, targetRoot, verifyTarget) {
228
350
  const record = approval.record;
229
351
  const sources = [...new Set([
230
- ...durableSources(candidate),
352
+ ...durableSources(candidate, targetRoot, verifyTarget),
231
353
  ...record.sites.map(site => `repo/${site.replace(/\\/g, '/')}`)
232
354
  ])].sort();
233
355
  return [
@@ -338,9 +460,18 @@ function preflight(options) {
338
460
  if (!samePath(targetRoot, approval.targetRoot)) problem('approval targetRoot does not match the resolved --target');
339
461
  validateSites(candidate.sites, targetRoot, 'selected report candidate sites');
340
462
  validateSites(approval.record.sites, targetRoot, 'approved record sites');
341
- if (!durableSources(candidate).length) problem('selected report candidate has no durable source evidence');
463
+ const hasLocalSource = Array.isArray(candidate.sources) &&
464
+ candidate.sources.some(source => source && source.type === 'local-store');
465
+ let harness = hasLocalSource ? harnessTool(options.harness) : null;
466
+ const localLead = hasLocalSource
467
+ ? validateLocalLead(report, candidate, approval, targetRoot, harness.root) : null;
468
+ if (!durableSources(candidate, targetRoot, Boolean(localLead)).length) {
469
+ problem(localLead
470
+ ? 'selected report candidate has no verified durable source evidence in the target repository'
471
+ : 'selected report candidate has no durable source evidence');
472
+ }
473
+ if (!harness) harness = harnessTool(options.harness);
342
474
  const { errorsDir, index } = directoryInfo(targetRoot);
343
- const syncScript = harnessTool(options.harness);
344
475
  const lockPath = path.join(errorsDir, LOCK);
345
476
  try {
346
477
  fs.lstatSync(lockPath);
@@ -354,7 +485,10 @@ function preflight(options) {
354
485
  const next = nextId(errorsDir, index);
355
486
  const destination = checkDestination(errorsDir, next.id, approval.record.signature, lockPath);
356
487
  assertApprovalUnused(errorsDir, approvalHash);
357
- return { approval, candidate, targetRoot, errorsDir, index, syncScript, lockPath, destination, reportHash, approvalHash };
488
+ return {
489
+ approval, candidate, targetRoot, errorsDir, index, syncScript: harness.syncScript,
490
+ localLead, lockPath, destination, reportHash, approvalHash
491
+ };
358
492
  }
359
493
 
360
494
  function runSync(script, targetRoot, check) {
@@ -519,10 +653,12 @@ function promote(context) {
519
653
 
520
654
  beforeNames = fs.readdirSync(context.errorsDir).filter(name => name !== LOCK).sort();
521
655
  saved = savedIndex(context.index);
656
+ if (context.localLead) assertFreshDedupe(context);
522
657
  assertApprovalUnused(context.errorsDir, context.approvalHash);
523
658
  const next = nextId(context.errorsDir, context.index);
524
659
  destination = checkDestination(context.errorsDir, next.id, context.approval.record.signature, context.lockPath);
525
- const text = recordText(context.approval, context.candidate, next.id, context.reportHash, context.approvalHash);
660
+ const text = recordText(context.approval, context.candidate, next.id, context.reportHash, context.approvalHash,
661
+ context.targetRoot, Boolean(context.localLead));
526
662
  let recordFd;
527
663
  try {
528
664
  recordFd = fs.openSync(destination.destination, 'wx', 0o644);