harness-everything 0.54.1 → 0.55.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +2 -1
  3. package/CHANGELOG.md +23 -0
  4. package/README.md +1 -0
  5. package/ci/mechanism-2ao-plugin-sync.test.js +18 -2
  6. package/ci/mechanism-349-ci-change-scope.test.js +68 -7
  7. package/ci/mechanism-check-packet-write-set.test.js +13 -3
  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/docs/error-handling/README.md +5 -5
  14. package/docs/error-handling/details/e0002-report-writer.md +25 -27
  15. package/docs/error-handling/registry.md +1 -1
  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/harness-everything/SKILL.md +1 -1
  26. package/harness-everything/references/skill-registry.md +1 -0
  27. package/harness-everything/scripts/routing-keywords.json +11 -0
  28. package/opencode-plugin/plugin.json +1 -1
  29. package/package.json +1 -1
  30. package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
  31. package/plugins/harness-everything/plugin.json +1 -1
  32. package/plugins/harness-everything/skills/error-ledger-bootstrap/SKILL.md +33 -0
  33. package/plugins/harness-everything/skills/error-ledger-bootstrap/references/workflow.md +79 -0
  34. package/plugins/harness-everything/skills/error-ledger-bootstrap/scripts/promote.js +613 -0
  35. package/plugins/harness-everything/skills/error-ledger-bootstrap/scripts/scan.js +654 -0
  36. package/plugins/harness-everything/skills/harness-everything/SKILL.md +1 -1
  37. package/plugins/harness-everything/skills/harness-everything/references/skill-registry.md +1 -0
  38. package/plugins/harness-everything/skills/harness-everything/scripts/routing-keywords.json +11 -0
  39. package/sbom.cdx.json +7 -7
  40. package/scripts/error-ledger-oracle.js +257 -0
  41. package/scripts/errors-sync.js +175 -12
@@ -0,0 +1,613 @@
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 path = require('node:path');
8
+
9
+ const ERRORS = path.join('.agents', 'harness-everything', 'errors');
10
+ const INDEX = 'index.jsonl';
11
+ const RECORD_NAME = /^E-(\d{4})-[a-z0-9-]+\.md$/;
12
+ const HASH = /^[a-f0-9]{64}$/i;
13
+ const COMMIT = /^[a-f0-9]{40}$/i;
14
+ const SIGNATURE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
15
+ const SCOPES = new Set(['in', 'out', 'unresolved']);
16
+ const STATUSES = new Set(['open', 'lesson', 'mechanism']);
17
+ const LOCK = '.promote.lock';
18
+
19
+ function problem(message, exitCode = 2) {
20
+ const error = new Error(message);
21
+ error.exitCode = exitCode;
22
+ throw error;
23
+ }
24
+
25
+ function canonical(file) {
26
+ return fs.realpathSync.native ? fs.realpathSync.native(file) : fs.realpathSync(file);
27
+ }
28
+
29
+ function samePath(left, right) {
30
+ return process.platform === 'win32'
31
+ ? left.toLowerCase() === right.toLowerCase()
32
+ : left === right;
33
+ }
34
+
35
+ function isWithin(root, candidate, api = path) {
36
+ const windows = api === path.win32 || process.platform === 'win32';
37
+ const left = windows ? root.toLowerCase() : root;
38
+ const right = windows ? candidate.toLowerCase() : candidate;
39
+ const relative = api.relative(left, right);
40
+ return relative === '' || (!api.isAbsolute(relative) && relative !== '..' && !relative.startsWith(`..${api.sep}`));
41
+ }
42
+
43
+ function parseArgs(args) {
44
+ const options = {};
45
+ const seen = new Set();
46
+ for (let i = 0; i < args.length; i++) {
47
+ const name = args[i];
48
+ if (name === '--json') {
49
+ if (seen.has(name)) problem('duplicate option: --json');
50
+ seen.add(name);
51
+ options.json = true;
52
+ continue;
53
+ }
54
+ if (!['--target', '--report', '--approval', '--harness'].includes(name)) problem(`unknown option: ${name}`);
55
+ if (seen.has(name)) problem(`duplicate option: ${name}`);
56
+ if (!args[i + 1] || args[i + 1].startsWith('--')) problem(`${name} requires a value`);
57
+ seen.add(name);
58
+ options[name.slice(2)] = args[++i];
59
+ }
60
+ for (const name of ['target', 'report', 'approval', 'harness']) {
61
+ if (!options[name]) problem(`--${name} is required`);
62
+ }
63
+ return options;
64
+ }
65
+
66
+ function readInput(file, label) {
67
+ try {
68
+ return fs.readFileSync(file);
69
+ } catch (error) {
70
+ problem(`${label} cannot be read: ${error.message}`);
71
+ }
72
+ }
73
+
74
+ function readJson(bytes, label) {
75
+ try {
76
+ return JSON.parse(bytes.toString('utf8'));
77
+ } catch (error) {
78
+ problem(`${label} is not valid JSON: ${error.message}`);
79
+ }
80
+ }
81
+
82
+ function nonempty(value) {
83
+ return typeof value === 'string' && value.trim().length > 0 && !value.includes('\0');
84
+ }
85
+
86
+ function hasAbsolutePath(value) {
87
+ return /(?:^|[\s("'`=(:,;])(?:\/(?!\/)|[A-Za-z]:[\\/]|\\\\)/.test(value);
88
+ }
89
+
90
+ function safeRepoPath(value) {
91
+ if (!nonempty(value) || hasAbsolutePath(value)) return false;
92
+ const normalized = value.replace(/\\/g, '/');
93
+ return !path.posix.isAbsolute(normalized) && !/^[A-Za-z]:/.test(normalized) &&
94
+ !normalized.split('/').includes('..') && normalized !== '.';
95
+ }
96
+
97
+ function isTargetFile(root, value) {
98
+ if (!safeRepoPath(value)) return false;
99
+ const candidate = path.resolve(root, value.replace(/\\/g, path.sep));
100
+ if (!isWithin(root, candidate)) return false;
101
+ try {
102
+ const resolved = canonical(candidate);
103
+ return isWithin(root, resolved) && fs.statSync(resolved).isFile();
104
+ } catch (_) {
105
+ return false;
106
+ }
107
+ }
108
+
109
+ function validateSites(sites, root, label) {
110
+ if (!Array.isArray(sites) || sites.some(site => !isTargetFile(root, site))) {
111
+ problem(`${label} must contain only existing target-repository files`);
112
+ }
113
+ }
114
+
115
+ function validateApproval(approval) {
116
+ if (!approval || approval.schemaVersion !== 1) problem('approval schemaVersion must be 1');
117
+ if (typeof approval.candidateId !== 'string' || !/^[a-f0-9]{20}$/i.test(approval.candidateId)) {
118
+ problem('approval candidateId must be a 20-character report id');
119
+ }
120
+ if (typeof approval.reportSha256 !== 'string' || !HASH.test(approval.reportSha256)) {
121
+ problem('approval reportSha256 must be a SHA-256 hex digest');
122
+ }
123
+ if (typeof approval.targetRoot !== 'string' || !path.isAbsolute(approval.targetRoot)) {
124
+ problem('approval targetRoot must be an absolute path');
125
+ }
126
+ if (!nonempty(approval.approvedBy) || !nonempty(approval.approvedAt) || !Number.isFinite(Date.parse(approval.approvedAt))) {
127
+ problem('approval must include approvedBy and a valid approvedAt timestamp');
128
+ }
129
+ const record = approval.record;
130
+ if (!record || typeof record !== 'object' || Array.isArray(record)) problem('approval record must be an object');
131
+ if (!nonempty(record.signature) || !SIGNATURE.test(record.signature)) problem('record signature must be kebab-case');
132
+ for (const field of ['class', 'title', 'violates', 'sourcesNote']) {
133
+ if (!nonempty(record[field])) problem(`record ${field} is required`);
134
+ }
135
+ if (!SCOPES.has(record.scope)) problem('record scope must be in, out or unresolved');
136
+ if (!STATUSES.has(record.status)) problem('record status must be open, lesson or mechanism');
137
+ if (!Array.isArray(record.sites) || record.sites.some(site => !safeRepoPath(site))) {
138
+ problem('record sites must be repository-relative paths');
139
+ }
140
+ for (const field of ['approvedBy', 'approvedAt']) {
141
+ if (hasAbsolutePath(approval[field])) problem(`approval ${field} must not contain an absolute path`);
142
+ }
143
+ for (const field of ['class', 'title', 'violates', 'sourcesNote']) {
144
+ if (hasAbsolutePath(record[field])) problem(`record ${field} must not contain an absolute path`);
145
+ }
146
+ }
147
+
148
+ function directoryInfo(targetRoot) {
149
+ const errorsPath = path.join(targetRoot, ERRORS);
150
+ let errorsDir;
151
+ try {
152
+ errorsDir = canonical(errorsPath);
153
+ if (!fs.statSync(errorsDir).isDirectory()) problem(`target must contain ${ERRORS}/`);
154
+ } catch (error) {
155
+ if (error.exitCode) throw error;
156
+ problem(`target must contain an existing ${ERRORS}/ directory`);
157
+ }
158
+ if (!isWithin(targetRoot, errorsDir)) problem('errors directory resolves outside the target root');
159
+ const index = path.join(errorsDir, INDEX);
160
+ inspectIndex(index);
161
+ return { errorsDir, index };
162
+ }
163
+
164
+ function inspectIndex(index) {
165
+ try {
166
+ const stat = fs.lstatSync(index);
167
+ if (stat.isSymbolicLink() || !stat.isFile()) problem('target index must be a regular file inside the errors directory');
168
+ } catch (error) {
169
+ if (error.code !== 'ENOENT') {
170
+ if (error.exitCode) throw error;
171
+ problem(`target index cannot be inspected: ${error.message}`);
172
+ }
173
+ }
174
+ }
175
+
176
+ function harnessTool(harnessInput) {
177
+ let root;
178
+ try {
179
+ root = canonical(path.resolve(harnessInput));
180
+ if (!fs.statSync(root).isDirectory()) problem('--harness must be a Harness checkout directory');
181
+ } catch (error) {
182
+ if (error.exitCode) throw error;
183
+ problem(`Harness checkout is unavailable: ${error.message}; pass --harness to an installed Harness checkout with Node dependencies`);
184
+ }
185
+ const script = path.join(root, 'scripts', 'errors-sync.js');
186
+ try {
187
+ if (!fs.statSync(script).isFile() || !isWithin(root, canonical(script))) {
188
+ problem('Harness checkout is missing scripts/errors-sync.js; pass --harness to a trusted Harness checkout');
189
+ }
190
+ } catch (error) {
191
+ if (error.exitCode) throw error;
192
+ problem(`Harness checkout is missing scripts/errors-sync.js; pass --harness to a trusted Harness checkout (${error.message})`);
193
+ }
194
+ try { require.resolve('js-yaml', { paths: [path.dirname(script)] }); }
195
+ catch (error) {
196
+ problem(`Harness checkout cannot resolve js-yaml; install its Node dependencies and retry with that checkout (${error.message})`);
197
+ }
198
+ return script;
199
+ }
200
+
201
+ function durableSources(candidate) {
202
+ const sources = new Set();
203
+ 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)) {
205
+ sources.add(`commit ${source.sha.toLowerCase()}`);
206
+ }
207
+ }
208
+ return [...sources].sort();
209
+ }
210
+
211
+ function assertApprovalUnused(errorsDir, approvalHash) {
212
+ for (const name of fs.readdirSync(errorsDir)) {
213
+ if (!RECORD_NAME.test(name)) continue;
214
+ const file = path.join(errorsDir, name);
215
+ const stat = fs.lstatSync(file);
216
+ if (stat.isSymbolicLink()) problem(`ledger record is a symlink: ${name}`);
217
+ if (fs.readFileSync(file, 'utf8').includes(`approval-sha256: ${approvalHash}`)) {
218
+ problem('this approval has already been promoted');
219
+ }
220
+ }
221
+ }
222
+
223
+ function yaml(value) {
224
+ return JSON.stringify(value);
225
+ }
226
+
227
+ function recordText(approval, candidate, id, reportHash, approvalHash) {
228
+ const record = approval.record;
229
+ const sources = [...new Set([
230
+ ...durableSources(candidate),
231
+ ...record.sites.map(site => `repo/${site.replace(/\\/g, '/')}`)
232
+ ])].sort();
233
+ return [
234
+ '---',
235
+ `id: ${yaml(id)}`,
236
+ `signature: ${yaml(record.signature)}`,
237
+ `class: ${yaml(record.class)}`,
238
+ `title: ${yaml(record.title)}`,
239
+ `violates: ${yaml(record.violates)}`,
240
+ `scope: ${yaml(record.scope)}`,
241
+ `status: ${yaml(record.status)}`,
242
+ 'mechanism_ref: null',
243
+ ...(record.sites.length ? ['sites:', ...record.sites.map(site => ` - ${yaml(site)}`)] : ['sites: []']),
244
+ 'episodes: []',
245
+ '---',
246
+ '',
247
+ '## Cue',
248
+ '',
249
+ record.title,
250
+ '',
251
+ '## What happened',
252
+ '',
253
+ `Owner-approved promotion of report candidate \`${candidate.id}\`.`,
254
+ '',
255
+ '## Lesson',
256
+ '',
257
+ record.sourcesNote,
258
+ '',
259
+ '## Evidence',
260
+ '',
261
+ `- Approved by \`${approval.approvedBy}\` at \`${approval.approvedAt}\``,
262
+ `- Report SHA-256: \`${reportHash}\``,
263
+ `- Durable candidate sources: ${sources.map(source => `\`${source}\``).join(', ')}`,
264
+ `- approval-sha256: ${approvalHash}`,
265
+ ''
266
+ ].join('\n');
267
+ }
268
+
269
+ function hash(bytes) {
270
+ return crypto.createHash('sha256').update(bytes).digest('hex');
271
+ }
272
+
273
+ function candidateFrom(report, approval) {
274
+ if (!report || report.schemaVersion !== 1 || !Array.isArray(report.candidates)) {
275
+ problem('report must be a schemaVersion 1 candidate report');
276
+ }
277
+ const matches = report.candidates.filter(item => item && item.id === approval.candidateId);
278
+ if (!matches.length) problem(`approved candidate ${approval.candidateId} is not present in the report`);
279
+ if (matches.length !== 1) problem(`approved candidate ${approval.candidateId} is ambiguous in the report`);
280
+ return matches[0];
281
+ }
282
+
283
+ function nextId(errorsDir, index) {
284
+ let maximum = 0;
285
+ for (const name of fs.readdirSync(errorsDir)) {
286
+ const match = /^E-(\d{4})-/.exec(name);
287
+ if (match) maximum = Math.max(maximum, Number(match[1]));
288
+ }
289
+ try {
290
+ for (const line of fs.readFileSync(index, 'utf8').split(/\r?\n/)) {
291
+ const match = /"id":"E-(\d{4})"/.exec(line);
292
+ if (match) maximum = Math.max(maximum, Number(match[1]));
293
+ }
294
+ } catch (error) {
295
+ if (error.code !== 'ENOENT') throw error;
296
+ }
297
+ if (maximum >= 9999) problem('no unused E-NNNN ids remain');
298
+ const number = maximum + 1;
299
+ return { id: `E-${String(number).padStart(4, '0')}`, number };
300
+ }
301
+
302
+ function checkDestination(errorsDir, id, signature, lockPath) {
303
+ const file = `${id}-${signature}.md`;
304
+ const destination = path.join(errorsDir, file);
305
+ if (path.dirname(destination) !== errorsDir || !isWithin(errorsDir, destination)) problem('record destination escapes the errors directory');
306
+ if (samePath(destination, lockPath)) problem('record destination conflicts with the promotion lock');
307
+ try {
308
+ const stat = fs.lstatSync(destination);
309
+ if (stat.isSymbolicLink()) problem('record destination is a symlink and may escape the errors directory');
310
+ problem(`record destination already exists: ${file}`);
311
+ } catch (error) {
312
+ if (error.code !== 'ENOENT') {
313
+ if (error.exitCode) throw error;
314
+ problem(`record destination cannot be inspected: ${error.message}`);
315
+ }
316
+ }
317
+ return { file, destination };
318
+ }
319
+
320
+ function preflight(options) {
321
+ const reportBytes = readInput(options.report, 'report');
322
+ const approvalBytes = readInput(options.approval, 'approval');
323
+ const reportHash = hash(reportBytes);
324
+ const approvalHash = hash(approvalBytes);
325
+ const report = readJson(reportBytes, 'report');
326
+ const approval = readJson(approvalBytes, 'approval');
327
+ validateApproval(approval);
328
+ if (reportHash.toLowerCase() !== approval.reportSha256.toLowerCase()) problem('report SHA-256 does not match the approval');
329
+ const candidate = candidateFrom(report, approval);
330
+ let targetRoot;
331
+ try {
332
+ targetRoot = canonical(path.resolve(options.target));
333
+ if (!fs.statSync(targetRoot).isDirectory()) problem('--target must be a repository directory');
334
+ } catch (error) {
335
+ if (error.exitCode) throw error;
336
+ problem(`--target must be an existing repository directory: ${error.message}`);
337
+ }
338
+ if (!samePath(targetRoot, approval.targetRoot)) problem('approval targetRoot does not match the resolved --target');
339
+ validateSites(candidate.sites, targetRoot, 'selected report candidate sites');
340
+ validateSites(approval.record.sites, targetRoot, 'approved record sites');
341
+ if (!durableSources(candidate).length) problem('selected report candidate has no durable source evidence');
342
+ const { errorsDir, index } = directoryInfo(targetRoot);
343
+ const syncScript = harnessTool(options.harness);
344
+ const lockPath = path.join(errorsDir, LOCK);
345
+ try {
346
+ fs.lstatSync(lockPath);
347
+ problem('another promotion is active or a stale .promote.lock remains; verify no promotion is running, then remove it and retry');
348
+ } catch (error) {
349
+ if (error.code !== 'ENOENT') {
350
+ if (error.exitCode) throw error;
351
+ problem(`promotion lock cannot be inspected: ${error.message}`);
352
+ }
353
+ }
354
+ const next = nextId(errorsDir, index);
355
+ const destination = checkDestination(errorsDir, next.id, approval.record.signature, lockPath);
356
+ assertApprovalUnused(errorsDir, approvalHash);
357
+ return { approval, candidate, targetRoot, errorsDir, index, syncScript, lockPath, destination, reportHash, approvalHash };
358
+ }
359
+
360
+ function runSync(script, targetRoot, check) {
361
+ const result = childProcess.spawnSync(process.execPath, [
362
+ script,
363
+ ...(check ? ['--check'] : []),
364
+ '--root', targetRoot
365
+ ], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
366
+ if (result.error || result.status !== 0) {
367
+ const detail = (result.stderr || result.error && result.error.message || result.stdout || `exit ${result.status}`).trim();
368
+ throw new Error(`errors-sync${check ? ' --check' : ''} failed: ${detail}`);
369
+ }
370
+ }
371
+
372
+ function savedIndex(index) {
373
+ try {
374
+ return indexState(index);
375
+ } catch (error) {
376
+ if (error.exitCode) throw error;
377
+ problem(`target index cannot be saved: ${error.message}`);
378
+ }
379
+ }
380
+
381
+ function indexState(index) {
382
+ let fd;
383
+ try {
384
+ const current = fs.lstatSync(index);
385
+ if (current.isSymbolicLink() || !current.isFile()) throw new Error('index was replaced with a non-regular file');
386
+ fd = fs.openSync(index, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0));
387
+ const opened = fs.fstatSync(fd);
388
+ if (!opened.isFile() || opened.dev !== current.dev || opened.ino !== current.ino) {
389
+ throw new Error('index changed while it was being read');
390
+ }
391
+ return { bytes: fs.readFileSync(fd), stat: opened };
392
+ } catch (error) {
393
+ if (error.code === 'ENOENT') return { bytes: null, stat: null };
394
+ throw error;
395
+ } finally {
396
+ if (fd !== undefined) {
397
+ try { fs.closeSync(fd); } catch (_) { /* read failure is reported above */ }
398
+ }
399
+ }
400
+ }
401
+
402
+ function writePreviousIndex(index, saved, current, expected) {
403
+ if (saved.bytes === null) {
404
+ const latest = indexState(index);
405
+ if (!latest.bytes || !latest.bytes.equals(expected) || latest.stat.dev !== current.stat.dev || latest.stat.ino !== current.stat.ino) {
406
+ throw new Error('index changed before the owned replacement could be removed');
407
+ }
408
+ fs.unlinkSync(index);
409
+ return;
410
+ }
411
+
412
+ const dir = path.dirname(index);
413
+ let temporary;
414
+ let fd;
415
+ try {
416
+ for (let attempt = 0; attempt < 5; attempt++) {
417
+ temporary = path.join(dir, `.${INDEX}.${process.pid}.${crypto.randomBytes(8).toString('hex')}.tmp`);
418
+ try {
419
+ fd = fs.openSync(temporary, 'wx', saved.stat.mode & 0o777);
420
+ break;
421
+ } catch (error) {
422
+ temporary = undefined;
423
+ if (error.code !== 'EEXIST') throw error;
424
+ }
425
+ }
426
+ if (fd === undefined) throw new Error('could not allocate a temporary rollback index');
427
+ fs.fchmodSync(fd, saved.stat.mode & 0o777);
428
+ fs.writeFileSync(fd, saved.bytes);
429
+ const openFd = fd;
430
+ fd = undefined;
431
+ fs.closeSync(openFd);
432
+
433
+ const latest = indexState(index);
434
+ if (!latest.bytes || !latest.bytes.equals(expected) || latest.stat.dev !== current.stat.dev || latest.stat.ino !== current.stat.ino) {
435
+ throw new Error('index changed before the owned replacement could be restored');
436
+ }
437
+ fs.renameSync(temporary, index);
438
+ temporary = undefined;
439
+ } finally {
440
+ if (fd !== undefined) {
441
+ try { fs.closeSync(fd); } catch (_) { /* preserve the original rollback error */ }
442
+ }
443
+ if (temporary) {
444
+ try { fs.unlinkSync(temporary); } catch (error) { if (error.code !== 'ENOENT') throw error; }
445
+ }
446
+ }
447
+ }
448
+
449
+ function restoreIndex(index, saved, expected) {
450
+ let current;
451
+ try {
452
+ current = indexState(index);
453
+ } catch (error) {
454
+ return error.message;
455
+ }
456
+ if ((!saved.bytes && !current.bytes) || (saved.bytes && current.bytes && current.bytes.equals(saved.bytes))) return null;
457
+ if (!expected || !current.bytes || !current.bytes.equals(expected)) {
458
+ return 'index replacement is not verifiably owned by this promotion; it was preserved. Reconcile the target ledger, then run errors-sync --root <target>.';
459
+ }
460
+ try {
461
+ writePreviousIndex(index, saved, current, expected);
462
+ } catch (error) {
463
+ return `owned index replacement could not be rolled back: ${error.message}`;
464
+ }
465
+ return null;
466
+ }
467
+
468
+ function rollback(context, saved, destination, identity, beforeNames) {
469
+ const problems = [];
470
+ let expectedIndex;
471
+ try {
472
+ const current = indexState(context.index);
473
+ const unchanged = (!saved.bytes && !current.bytes) || (saved.bytes && current.bytes && current.bytes.equals(saved.bytes));
474
+ if (!unchanged) {
475
+ const sync = require(context.syncScript);
476
+ if (typeof sync.render !== 'function') throw new Error('trusted errors-sync does not expose its renderer');
477
+ expectedIndex = Buffer.from(sync.render(context.targetRoot));
478
+ }
479
+ } catch (error) {
480
+ problems.push(`index ownership could not be verified (${error.message})`);
481
+ }
482
+ if (identity) {
483
+ try {
484
+ const current = fs.lstatSync(destination);
485
+ if (current.dev !== identity.dev || current.ino !== identity.ino || current.isSymbolicLink()) {
486
+ problems.push('new record was replaced by another writer');
487
+ } else fs.unlinkSync(destination);
488
+ } catch (error) {
489
+ if (error.code !== 'ENOENT') problems.push(`new record could not be removed: ${error.message}`);
490
+ }
491
+ }
492
+ const indexProblem = restoreIndex(context.index, saved, expectedIndex);
493
+ if (indexProblem) problems.push(indexProblem);
494
+ try {
495
+ if (JSON.stringify(fs.readdirSync(context.errorsDir).filter(name => name !== LOCK).sort()) !== JSON.stringify(beforeNames)) {
496
+ problems.push('errors directory listing differs from its pre-promotion state');
497
+ }
498
+ } catch (error) {
499
+ problems.push(`errors directory state could not be verified: ${error.message}`);
500
+ }
501
+ return problems;
502
+ }
503
+
504
+ function promote(context) {
505
+ let lockFd;
506
+ let lockAcquired = false;
507
+ let destination;
508
+ let identity;
509
+ let saved;
510
+ let beforeNames;
511
+ let indexUpdated = false;
512
+ let syncStarted = false;
513
+ let failure;
514
+ try {
515
+ lockFd = fs.openSync(context.lockPath, 'wx', 0o600);
516
+ lockAcquired = true;
517
+ fs.closeSync(lockFd);
518
+ lockFd = undefined;
519
+
520
+ beforeNames = fs.readdirSync(context.errorsDir).filter(name => name !== LOCK).sort();
521
+ saved = savedIndex(context.index);
522
+ assertApprovalUnused(context.errorsDir, context.approvalHash);
523
+ const next = nextId(context.errorsDir, context.index);
524
+ 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);
526
+ let recordFd;
527
+ try {
528
+ recordFd = fs.openSync(destination.destination, 'wx', 0o644);
529
+ identity = fs.fstatSync(recordFd);
530
+ fs.writeFileSync(recordFd, text, 'utf8');
531
+ fs.closeSync(recordFd);
532
+ recordFd = undefined;
533
+ } catch (error) {
534
+ if (recordFd !== undefined) fs.closeSync(recordFd);
535
+ if (error.code === 'EEXIST') problem(`record destination already exists: ${destination.file}`);
536
+ throw error;
537
+ }
538
+
539
+ syncStarted = true;
540
+ runSync(context.syncScript, context.targetRoot, false);
541
+ runSync(context.syncScript, context.targetRoot, true);
542
+ indexUpdated = true;
543
+ } catch (error) {
544
+ if (error.code === 'EEXIST' && !lockAcquired) {
545
+ failure = Object.assign(new Error('another promotion is active or a stale .promote.lock remains; verify no promotion is running, then remove it and retry'), { exitCode: 2 });
546
+ } else {
547
+ failure = error;
548
+ }
549
+ }
550
+
551
+ if (lockFd !== undefined) {
552
+ try { fs.closeSync(lockFd); } catch (_) { /* already closed */ }
553
+ }
554
+ const releaseLock = () => {
555
+ if (!lockAcquired) return;
556
+ try {
557
+ fs.unlinkSync(context.lockPath);
558
+ lockAcquired = false;
559
+ } catch (error) {
560
+ if (error.code === 'ENOENT') lockAcquired = false;
561
+ else failure = new Error(`${failure ? `${failure.message}; ` : ''}promotion lock cleanup failed: ${error.message}`);
562
+ }
563
+ };
564
+ if (!failure) releaseLock();
565
+
566
+ let rollbackProblems = [];
567
+ if (failure) {
568
+ try {
569
+ rollbackProblems = saved && beforeNames && (identity || syncStarted)
570
+ ? rollback(context, saved, destination && destination.destination, identity, beforeNames)
571
+ : saved && beforeNames
572
+ ? (JSON.stringify(fs.readdirSync(context.errorsDir).filter(name => name !== LOCK).sort()) === JSON.stringify(beforeNames)
573
+ ? [] : ['errors directory listing differs from its pre-promotion state'])
574
+ : [];
575
+ } catch (error) {
576
+ rollbackProblems.push(`rollback failed: ${error.message}`);
577
+ }
578
+ releaseLock();
579
+ }
580
+
581
+ if (failure) {
582
+ const lockStale = lockAcquired;
583
+ const detail = rollbackProblems.length || lockStale
584
+ ? `; recovery needed: ${[...rollbackProblems, ...(lockStale ? ['verify no promotion is running, then remove .promote.lock'] : [])].join('; ')}`
585
+ : '; ledger restored to its pre-promotion state';
586
+ problem(`${failure.message}${detail}`, failure.exitCode || 1);
587
+ }
588
+
589
+ return {
590
+ ok: true,
591
+ id: path.basename(destination.file).slice(0, 6),
592
+ file: path.posix.join(ERRORS.split(path.sep).join('/'), destination.file),
593
+ indexUpdated
594
+ };
595
+ }
596
+
597
+ function main() {
598
+ const json = process.argv.includes('--json');
599
+ try {
600
+ const result = promote(preflight(parseArgs(process.argv.slice(2))));
601
+ if (json) process.stdout.write(`${JSON.stringify(result)}\n`);
602
+ else process.stdout.write(`Promoted ${result.id} to ${result.file}; target index is current.\n`);
603
+ } catch (error) {
604
+ const payload = { ok: false, error: error.message };
605
+ if (json) process.stdout.write(`${JSON.stringify(payload)}\n`);
606
+ else process.stderr.write(`error-ledger promote: ${error.message}\n`);
607
+ process.exitCode = error.exitCode || 1;
608
+ }
609
+ }
610
+
611
+ if (require.main === module) main();
612
+
613
+ module.exports = { isWithin };