harness-everything 0.52.0 → 0.54.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 (71) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/AGENTS.md +3 -1
  4. package/CHANGELOG.md +38 -0
  5. package/benchmarks/results/live-host/opencode-2026-11-15-workspace/README.md +7 -0
  6. package/benchmarks/results/live-host/opencode-2026-11-15-workspace/live-workspace-probe.js +16 -0
  7. package/benchmarks/results/live-host/opencode-2026-11-15-workspace/live-workspace-trace-2026-11-15.jsonl +4 -0
  8. package/bin/cli.js +1 -0
  9. package/ci/invariant-routing.test.js +22 -3
  10. package/ci/mechanism-2al-codex-hooks-compat.test.js +56 -2
  11. package/ci/mechanism-2n-opencode-plugin.test.js +1 -1
  12. package/ci/mechanism-2p-opencode-v2-entrypoint.test.js +18 -3
  13. package/ci/mechanism-338-opencode-async.test.js +20 -3
  14. package/ci/mechanism-341-opencode-lane.test.js +7 -1
  15. package/ci/mechanism-349-ci-change-scope.test.js +78 -57
  16. package/ci/mechanism-397-cycle-import.test.js +414 -0
  17. package/ci/mechanism-397-host-acceptance.test.js +119 -0
  18. package/ci/mechanism-397-opencode-observations.test.js +1922 -0
  19. package/ci/mechanism-check-packet-write-set.test.js +232 -0
  20. package/ci/mechanism-codex-prompt-pass-through.test.js +8 -4
  21. package/ci/mechanism-error-handling-map.test.js +219 -0
  22. package/ci/mechanism-report-writer.test.js +335 -0
  23. package/ci/mechanism-system-one-curves.test.js +17 -0
  24. package/ci/mechanism-system-one-cycle.test.js +621 -2
  25. package/ci/router-workflow-plan.test.js +50 -7
  26. package/docs/architecture.md +4 -3
  27. package/docs/error-handling/README.md +250 -0
  28. package/docs/error-handling/actions/c1-action-map.md +89 -0
  29. package/docs/error-handling/actions/c2-action-map.md +22 -0
  30. package/docs/error-handling/actions/c3-action-map.md +26 -0
  31. package/docs/error-handling/actions/c5-action-map.md +31 -0
  32. package/docs/error-handling/actions/c6-action-map.md +37 -0
  33. package/docs/error-handling/actions/c7-action-map.md +18 -0
  34. package/docs/error-handling/actions/e0002-action-map.md +101 -0
  35. package/docs/error-handling/activity.puml +84 -0
  36. package/docs/error-handling/details/c1-authority-conformance.md +93 -0
  37. package/docs/error-handling/details/c2-test-root-containment.md +35 -0
  38. package/docs/error-handling/details/c3-mode-ownership.md +50 -0
  39. package/docs/error-handling/details/c5-host-replay-contract.md +40 -0
  40. package/docs/error-handling/details/c6-packet-briefing.md +65 -0
  41. package/docs/error-handling/details/c7-write-set-check.md +54 -0
  42. package/docs/error-handling/details/e0002-capture-evidence.md +93 -0
  43. package/docs/error-handling/details/e0002-report-writer.md +116 -0
  44. package/docs/error-handling/nodes.yaml +44 -0
  45. package/docs/error-handling/registry.md +59 -0
  46. package/docs/error-handling/templates/packet-briefing.md +45 -0
  47. package/docs/platform-capabilities.md +16 -7
  48. package/docs/system-one-cycle.md +12 -3
  49. package/docs/system-one-observations.md +35 -4
  50. package/hooks/scripts/codex-user-prompt.js +2 -3
  51. package/hooks/scripts/lib/observations.js +5 -3
  52. package/opencode-plugin/README.md +22 -8
  53. package/opencode-plugin/index.mjs +424 -44
  54. package/opencode-plugin/plugin.json +1 -1
  55. package/package.json +2 -1
  56. package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
  57. package/plugins/harness-everything/hooks/scripts/codex-user-prompt.js +2 -3
  58. package/plugins/harness-everything/hooks/scripts/lib/observations.js +5 -3
  59. package/plugins/harness-everything/plugin.json +1 -1
  60. package/sbom.cdx.json +7 -7
  61. package/scripts/check-packet-write-set.js +155 -0
  62. package/scripts/codex-hooks-compat.js +46 -5
  63. package/scripts/error-handling-map.js +288 -0
  64. package/scripts/report-writer.js +261 -0
  65. package/scripts/system-one-curves.js +154 -14
  66. package/scripts/system-one-cycle/collect.js +20 -3
  67. package/scripts/system-one-cycle/common.js +39 -1
  68. package/scripts/system-one-cycle/evaluate.js +8 -5
  69. package/scripts/system-one-cycle.js +7 -2
  70. package/scripts/system-one-observations-export.js +29 -0
  71. package/scripts/system-one-observations-import-store.js +128 -0
@@ -345,7 +345,7 @@ function transcriptMessage(file, turnId) {
345
345
 
346
346
  function detectHost(payload, hints) {
347
347
  const direct = String(payload.host || payload.runtime || '').toLowerCase();
348
- if (['claude', 'codex'].includes(direct)) return direct;
348
+ if (['claude', 'codex', 'opencode'].includes(direct)) return direct;
349
349
  if (hints.codex || payload.turn_id || payload.last_agent_message) return 'codex';
350
350
  if (process.env.CLAUDE_PLUGIN_ROOT || process.env.CLAUDECODE || process.env.CLAUDE_CODE_ENTRYPOINT || process.env.CLAUDE) return 'claude';
351
351
  if (process.env.CODEX_HOME || process.env.CODEX_THREAD_ID) return 'codex';
@@ -587,6 +587,8 @@ function collectEvents(root, sessionId, turn) {
587
587
  function startTurn(payload, root) {
588
588
  const file = sessionFile(root, payload.session_id);
589
589
  const session = readJson(file, null) || { turn: 0, lastFinal: '', pending: null };
590
+ const turnId = String(payload.turn_id || payload.turnId || '');
591
+ if (session.pending && turnId && session.pending.turnId === turnId) return;
590
592
  if (session.pending) finishPending(session, payload, root, { text: null, reason: 'stop-missing' });
591
593
  if (!session.lastFinalAt || Date.now() - Date.parse(session.lastFinalAt) > RETENTION_MS) session.lastFinal = '';
592
594
  // Events left from an earlier turn arrived after its Stop; they belong to no record.
@@ -594,7 +596,7 @@ function startTurn(payload, root) {
594
596
  session.turn++;
595
597
  session.pending = {
596
598
  turn: session.turn,
597
- turnId: String(payload.turn_id || payload.turnId || ''),
599
+ turnId,
598
600
  startedAt: new Date().toISOString(),
599
601
  prompt: redact(typeof payload.prompt === 'string' ? payload.prompt : ''),
600
602
  previous: session.lastFinal || '',
@@ -654,7 +656,7 @@ function finishPending(session, payload, root, final) {
654
656
  selfReport: label,
655
657
  selfReportReason: reason,
656
658
  };
657
- appendRecord(root, record, textExpired ? null : text);
659
+ appendRecordDetailed(root, record, textExpired ? null : text, { dedupeById: true, dedupeByTurn: true });
658
660
  fs.rmSync(eventsDir(root, payload.session_id, pending.turn), { recursive: true, force: true });
659
661
  session.lastFinal = final.text ? redact(tailBytes(stripLabels(final.text), PREVIOUS_BYTES)) : '';
660
662
  session.lastFinalAt = observedAt;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
3
3
  "name": "harness-everything",
4
- "version": "0.52.0",
4
+ "version": "0.54.0",
5
5
  "description": "Invariant-first engineering harness for routing, verification, and failure recovery while preserving agent autonomy.",
6
6
  "author": {
7
7
  "name": "Miya Daniel",
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:49383d62-3852-5313-8190-f642a744c8f7",
5
+ "serialNumber": "urn:uuid:b02b30cc-bd77-5327-8115-742afb9149ff",
6
6
  "version": 1,
7
7
  "metadata": {
8
- "timestamp": "2026-11-15T08:18:38.741Z",
8
+ "timestamp": "2026-11-19T05:40:53.563Z",
9
9
  "tools": [
10
10
  {
11
11
  "vendor": "Harness Everything",
12
12
  "name": "generate-sbom.js",
13
- "version": "0.52.0"
13
+ "version": "0.54.0"
14
14
  }
15
15
  ],
16
16
  "component": {
17
17
  "type": "application",
18
- "bom-ref": "pkg:npm/harness-everything@0.52.0",
18
+ "bom-ref": "pkg:npm/harness-everything@0.54.0",
19
19
  "name": "harness-everything",
20
- "version": "0.52.0",
21
- "purl": "pkg:npm/harness-everything@0.52.0"
20
+ "version": "0.54.0",
21
+ "purl": "pkg:npm/harness-everything@0.54.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.52.0",
2036
+ "ref": "pkg:npm/harness-everything@0.54.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,155 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const fs = require('node:fs');
5
+ const path = require('node:path');
6
+ const { spawnSync } = require('node:child_process');
7
+
8
+ const USAGE = 'Usage: node scripts/check-packet-write-set.js --base <sha> [--head <rev>] --allow <path-or-glob>... [--allow-file <file>]';
9
+
10
+ class UsageError extends Error {}
11
+
12
+ function parseArgs(argv) {
13
+ const options = { allow: [] };
14
+ for (let index = 0; index < argv.length; index += 1) {
15
+ const name = argv[index];
16
+ if (!['--base', '--head', '--allow', '--allow-file'].includes(name)) {
17
+ throw new UsageError(`unknown option ${JSON.stringify(name)}`);
18
+ }
19
+ const value = argv[index + 1];
20
+ if (!value || value.startsWith('--')) throw new UsageError(`${name} requires a value`);
21
+ index += 1;
22
+ if (name === '--base' || name === '--head' || name === '--allow-file') {
23
+ const key = name.slice(2).replace(/-([a-z])/g, (_match, letter) => letter.toUpperCase());
24
+ if (options[key] !== undefined) throw new UsageError(`${name} may be used only once`);
25
+ options[key] = value;
26
+ } else {
27
+ options.allow.push(value);
28
+ }
29
+ }
30
+ if (!options.base) throw new UsageError('--base is required');
31
+ if (!options.allow.length && !options.allowFile) throw new UsageError('at least one --allow or --allow-file is required');
32
+ return options;
33
+ }
34
+
35
+ function git(args, cwd = process.cwd()) {
36
+ const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith('GIT_')));
37
+ if (process.env.GIT_CONFIG_GLOBAL !== undefined) env.GIT_CONFIG_GLOBAL = process.env.GIT_CONFIG_GLOBAL;
38
+ Object.assign(env, {
39
+ GIT_CONFIG_NOSYSTEM: '1',
40
+ GIT_OPTIONAL_LOCKS: '0',
41
+ GIT_TERMINAL_PROMPT: '0',
42
+ });
43
+ const result = spawnSync('git', ['-c', 'core.fsmonitor=false', '-c', 'core.untrackedCache=false', ...args], {
44
+ cwd,
45
+ encoding: null,
46
+ shell: false,
47
+ env,
48
+ maxBuffer: 16 * 1024 * 1024,
49
+ });
50
+ if (result.error) throw new Error(`could not run git: ${result.error.message}`);
51
+ return result;
52
+ }
53
+
54
+ function repositoryRoot() {
55
+ const result = git(['rev-parse', '--show-toplevel']);
56
+ if (result.status !== 0) throw new UsageError('current working directory is not inside a Git repository');
57
+ return result.stdout.toString('utf8').trim();
58
+ }
59
+
60
+ function commit(revision, label, repo) {
61
+ const result = git(['rev-parse', '--verify', '--quiet', '--end-of-options', `${revision}^{commit}`], repo);
62
+ if (result.status !== 0) throw new UsageError(`invalid ${label} commit ${JSON.stringify(revision)}`);
63
+ return result.stdout.toString('utf8').trim();
64
+ }
65
+
66
+ function pathsFrom(result, args) {
67
+ if (result.status !== 0) {
68
+ const detail = result.stderr.toString('utf8').trim();
69
+ throw new Error(`git ${args[0]} failed${detail ? `: ${detail}` : ''}`);
70
+ }
71
+ return result.stdout.toString('utf8').split('\0').filter(Boolean);
72
+ }
73
+
74
+ function globRegExp(pattern) {
75
+ let source = '^';
76
+ for (let index = 0; index < pattern.length; index += 1) {
77
+ const character = pattern[index];
78
+ if (character === '*') {
79
+ if (pattern[index + 1] === '*') {
80
+ index += 1;
81
+ if (pattern[index + 1] === '/') {
82
+ source += '(?:[\\s\\S]*/)?';
83
+ index += 1;
84
+ } else {
85
+ source += '[\\s\\S]*';
86
+ }
87
+ } else {
88
+ source += '[^/]*';
89
+ }
90
+ } else if (character === '?') {
91
+ source += '[^/]';
92
+ } else {
93
+ source += character.replace(/[|\\{}()[\]^$+?.]/g, '\\$&');
94
+ }
95
+ }
96
+ return new RegExp(`${source}$`);
97
+ }
98
+
99
+ function readAllowPatterns(options) {
100
+ const patterns = [...options.allow];
101
+ if (options.allowFile) {
102
+ const file = path.resolve(process.cwd(), options.allowFile);
103
+ const lines = fs.readFileSync(file, 'utf8').split(/\r?\n/).filter(Boolean);
104
+ patterns.push(...lines);
105
+ }
106
+ if (!patterns.length) throw new UsageError('allow file contains no path patterns');
107
+ return patterns.map(pattern => {
108
+ if (pattern.includes('\0')) throw new UsageError('allow patterns cannot contain NUL bytes');
109
+ return globRegExp(pattern);
110
+ });
111
+ }
112
+
113
+ function changedPaths(base, head, includeWorkingTree, repo) {
114
+ const paths = new Set();
115
+ const diffs = [['diff', '--no-ext-diff', '--no-textconv', '--no-renames', '--name-only', '-z', base, head]];
116
+ if (includeWorkingTree) diffs.push(
117
+ ['diff', '--no-ext-diff', '--no-textconv', '--no-renames', '--name-only', '-z', '--cached', 'HEAD'],
118
+ ['diff', '--no-ext-diff', '--no-textconv', '--no-renames', '--name-only', '-z'],
119
+ );
120
+ for (const args of diffs) {
121
+ for (const file of pathsFrom(git(args, repo), args)) paths.add(file);
122
+ }
123
+ if (includeWorkingTree) {
124
+ const untrackedArgs = ['ls-files', '--others', '--exclude-standard', '-z'];
125
+ for (const file of pathsFrom(git(untrackedArgs, repo), untrackedArgs)) paths.add(file);
126
+ }
127
+ return [...paths].sort();
128
+ }
129
+
130
+ function main() {
131
+ let options;
132
+ try {
133
+ options = parseArgs(process.argv.slice(2));
134
+ const allowed = readAllowPatterns(options);
135
+ const repo = repositoryRoot();
136
+ const base = commit(options.base, 'base', repo);
137
+ const head = commit(options.head || 'HEAD', 'head', repo);
138
+ const currentHead = options.head ? commit('HEAD', 'worktree HEAD', repo) : head;
139
+ const includeWorkingTree = head === currentHead;
140
+ if (!includeWorkingTree) console.log('Comparison: commits only (--head is not the current HEAD).');
141
+ let outOfSet = 0;
142
+ for (const file of changedPaths(base, head, includeWorkingTree, repo)) {
143
+ const isAllowed = allowed.some(pattern => pattern.test(file));
144
+ console.log(`${isAllowed ? 'ALLOWED' : 'OUT_OF_SET'} ${JSON.stringify(file)}`);
145
+ if (!isAllowed) outOfSet += 1;
146
+ }
147
+ process.exitCode = outOfSet ? 1 : 0;
148
+ } catch (error) {
149
+ console.error(`error: ${error.message}`);
150
+ if (error instanceof UsageError) console.error(USAGE);
151
+ process.exitCode = 2;
152
+ }
153
+ }
154
+
155
+ if (require.main === module) main();
@@ -308,6 +308,37 @@ function removePriorEntries(config, prior) {
308
308
  return { config: { ...config, hooks: nextHooks }, drift, removed };
309
309
  }
310
310
 
311
+ function isLegacyTierRouterCommand(command) {
312
+ if (typeof command !== 'string') return false;
313
+ const match = /^node(?:\.exe)?[ \t]+(?:"([^"\r\n]+)"|'([^'\r\n]+)'|([^\s"']+))[ \t]*$/i.exec(command);
314
+ if (!match) return false;
315
+ const script = (match[1] || match[2] || match[3]).replace(/\\/g, '/');
316
+ // Only a bare Node invocation of the legacy npx package entry point.
317
+ return !/[$%`&;|<>!^()]/.test(script) &&
318
+ /^(?:[a-z]:\/|\/)(?:[^/]+\/)*_npx\/[0-9a-f]+\/node_modules\/harness-everything\/harness-everything\/scripts\/tier-router\.js$/i.test(script);
319
+ }
320
+
321
+ function legacyTierRouterHooks(config) {
322
+ const groups = config.hooks.UserPromptSubmit || [];
323
+ return groups.flatMap(group => (Array.isArray(group?.hooks) ? group.hooks : []).filter(hook => {
324
+ if (hook?.type !== 'command') return false;
325
+ const commands = [hook.command, hook.commandWindows].filter(command => command !== undefined);
326
+ return commands.length > 0 && commands.every(isLegacyTierRouterCommand);
327
+ }));
328
+ }
329
+
330
+ function removeLegacyTierRouterHooks(config, candidates) {
331
+ if (candidates.length === 0) return config;
332
+ const remove = new Set(candidates);
333
+ const groups = config.hooks.UserPromptSubmit.flatMap(group => {
334
+ if (!Array.isArray(group?.hooks)) return [group];
335
+ const hooks = group.hooks.filter(hook => !remove.has(hook));
336
+ if (hooks.length === group.hooks.length) return [group];
337
+ return hooks.length > 0 ? [{ ...group, hooks }] : [];
338
+ });
339
+ return { ...config, hooks: { ...config.hooks, UserPromptSubmit: groups } };
340
+ }
341
+
311
342
  function hookEntriesFrom(pluginRoot, runtimeDir) {
312
343
  const sourceFile = path.join(pluginRoot, 'hooks', 'hooks.json');
313
344
  const source = readHooksFile(sourceFile);
@@ -543,11 +574,12 @@ function install(options = {}) {
543
574
  return withOwnerLock(p, options, () => installLocked(p, {
544
575
  codexHome, sourcePluginRoot, include, packageVersion, sourceHash,
545
576
  onRuntimeReady: options.onRuntimeReady,
577
+ removeLegacyTierRouter: options.removeLegacyTierRouter === true,
546
578
  }));
547
579
  }
548
580
 
549
581
  // Every manifest read and runtime/hooks write happens inside the owner lock.
550
- function installLocked(p, { codexHome, sourcePluginRoot, include, packageVersion, sourceHash, onRuntimeReady }) {
582
+ function installLocked(p, { codexHome, sourcePluginRoot, include, packageVersion, sourceHash, onRuntimeReady, removeLegacyTierRouter }) {
551
583
  const existedBefore = fs.existsSync(p.hooksFile);
552
584
  const hooksBefore = existedBefore ? fs.readFileSync(p.hooksFile) : null;
553
585
  const runtimeExistedBefore = fs.existsSync(p.runtimeDir);
@@ -562,6 +594,8 @@ function installLocked(p, { codexHome, sourcePluginRoot, include, packageVersion
562
594
  }
563
595
  base = removal.config;
564
596
  }
597
+ const legacyHooks = legacyTierRouterHooks(base);
598
+ if (removeLegacyTierRouter) base = removeLegacyTierRouterHooks(base, legacyHooks);
565
599
 
566
600
  ensureRuntime(p.runtimeDir, sourceHash, sourcePluginRoot, include);
567
601
  // Test seam: lets regressions force two installers to overlap before commit.
@@ -627,6 +661,8 @@ function installLocked(p, { codexHome, sourcePluginRoot, include, packageVersion
627
661
  packageVersion,
628
662
  sourcePluginSha256: sourceHash,
629
663
  entries: generated.length,
664
+ legacyTierRouterHooks: removeLegacyTierRouter ? [] : legacyHooks,
665
+ removedLegacyTierRouterHooks: removeLegacyTierRouter ? legacyHooks.length : 0,
630
666
  trustChanged: false,
631
667
  };
632
668
  }
@@ -688,9 +724,11 @@ function status(options = {}) {
688
724
  const p = pathsFor(codexHome);
689
725
  assertCompatibilityPaths(p);
690
726
  const prior = readManifest(p.manifestFile, p);
727
+ const config = readHooksFile(p.hooksFile);
728
+ const legacyHooks = legacyTierRouterHooks(config);
691
729
  if (!prior) return { installed: false, codexHome, hooksFile: p.hooksFile, trustChanged: false,
730
+ legacyTierRouterHooks: legacyHooks,
692
731
  observationCapture: { status: 'inactive', reason: 'compatibility-hooks-not-installed', trustRequired: true } };
693
- const config = readHooksFile(p.hooksFile);
694
732
  const removal = removePriorEntries(config, prior);
695
733
  const expected = prior.entries.length;
696
734
  const currentHealthy = fs.existsSync(prior.runtimeDir) && treeHash(prior.runtimeDir) === prior.sourcePluginSha256;
@@ -714,6 +752,7 @@ function status(options = {}) {
714
752
  expectedEntries: expected,
715
753
  exactEntriesPresent: removal.removed.length,
716
754
  drift: removal.drift,
755
+ legacyTierRouterHooks: legacyHooks,
717
756
  healthy,
718
757
  observationCapture: {
719
758
  // A lost previous runtime breaks older sessions, not new-session capture.
@@ -728,16 +767,18 @@ function status(options = {}) {
728
767
  function parseArgs(argv) {
729
768
  const action = argv[0] || 'status';
730
769
  if (!['install', 'uninstall', 'status'].includes(action)) {
731
- throw new Error('Usage: harness codex-hooks <install|uninstall|status> [--codex-home <path>] [--allow-unreleased-source]');
770
+ throw new Error('Usage: harness codex-hooks <install|uninstall|status> [--codex-home <path>] [--allow-unreleased-source] [--remove-legacy-tier-router (install only)]');
732
771
  }
733
772
  let codexHome;
734
773
  let allowUnreleasedSource = false;
774
+ let removeLegacyTierRouter = false;
735
775
  for (let i = 1; i < argv.length; i++) {
736
776
  if (argv[i] === '--codex-home') codexHome = path.resolve(argv[++i]);
737
777
  else if (argv[i] === '--allow-unreleased-source') allowUnreleasedSource = true;
778
+ else if (argv[i] === '--remove-legacy-tier-router' && action === 'install') removeLegacyTierRouter = true;
738
779
  else throw new Error('unknown argument: ' + argv[i]);
739
780
  }
740
- return { action, codexHome, allowUnreleasedSource };
781
+ return { action, codexHome, allowUnreleasedSource, removeLegacyTierRouter };
741
782
  }
742
783
 
743
784
  function main(argv = process.argv.slice(2)) {
@@ -750,7 +791,7 @@ function main(argv = process.argv.slice(2)) {
750
791
 
751
792
  try {
752
793
  const result = args.action === 'install'
753
- ? install({ codexHome: args.codexHome, allowUnreleasedSource: args.allowUnreleasedSource })
794
+ ? install(args)
754
795
  : args.action === 'uninstall'
755
796
  ? uninstall({ codexHome: args.codexHome })
756
797
  : status({ codexHome: args.codexHome });
@@ -0,0 +1,288 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const crypto = require('node:crypto');
5
+ const fs = require('node:fs');
6
+ const path = require('node:path');
7
+ const yaml = require('js-yaml');
8
+
9
+ const STATUSES = new Set(['proposed', 'accepted', 'retired']);
10
+ const ALIAS = /^[A-Z]$/;
11
+ const MERMAID_ID = /^[A-Za-z_][A-Za-z0-9_-]*$/;
12
+ const IDENTIFIER = /^ERR-\d{8}-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
13
+ const USAGE = 'Usage: node scripts/error-handling-map.js <new|set-status|check> [--map <nodes.yaml>] [--diagram <README.md>] [--alias <X> --name <text> [--date YYYYMMDD] | --id <identifier> --status <proposed|accepted|retired>]';
14
+
15
+ function parseArgs(argv) {
16
+ const verb = argv[0];
17
+ if (!['new', 'set-status', 'check'].includes(verb)) throw new Error(USAGE);
18
+ const options = {};
19
+ const allowed = new Set(['map', 'diagram', ...(verb === 'new' ? ['alias', 'name', 'date'] : []), ...(verb === 'set-status' ? ['id', 'status'] : [])]);
20
+ for (let i = 1; i < argv.length; i++) {
21
+ const flag = argv[i];
22
+ if (!flag.startsWith('--') || !allowed.has(flag.slice(2))) throw new Error('Unknown option: ' + flag + '\n' + USAGE);
23
+ const key = flag.slice(2);
24
+ if (Object.hasOwn(options, key)) throw new Error('Duplicate option: ' + flag);
25
+ if (argv[i + 1] === undefined || argv[i + 1].startsWith('--')) throw new Error('Missing value for ' + flag);
26
+ options[key] = argv[++i];
27
+ }
28
+ if (verb === 'new') {
29
+ if (!options.alias || !options.name) throw new Error('new requires --alias and --name');
30
+ if (!ALIAS.test(options.alias)) throw new Error('Invalid Action alias: ' + options.alias + ' (use one uppercase letter)');
31
+ if (!options.name.trim()) throw new Error('Action name must not be empty');
32
+ if (options.date && !validDate(options.date)) throw new Error('Invalid date: ' + options.date + ' (expected a real YYYYMMDD date)');
33
+ }
34
+ if (verb === 'set-status') {
35
+ if (!options.id || !options.status) throw new Error('set-status requires --id and --status');
36
+ if (!STATUSES.has(options.status)) throw new Error('Invalid status: ' + options.status + ' (use proposed, accepted, or retired)');
37
+ }
38
+ return { verb, options };
39
+ }
40
+
41
+ function validDate(value) {
42
+ if (!/^\d{8}$/.test(value)) return false;
43
+ const year = Number(value.slice(0, 4));
44
+ const month = Number(value.slice(4, 6));
45
+ const day = Number(value.slice(6, 8));
46
+ if (year < 1000 || month < 1 || month > 12 || day < 1 || day > 31) return false;
47
+ const date = new Date(Date.UTC(year, month - 1, day));
48
+ return date.toISOString().slice(0, 10).replace(/-/g, '') === value;
49
+ }
50
+
51
+ function readMap(file) {
52
+ const realPath = fs.realpathSync(file);
53
+ const source = fs.readFileSync(realPath, 'utf8');
54
+ let data;
55
+ try {
56
+ data = yaml.load(source);
57
+ } catch (error) {
58
+ throw new Error('Invalid map YAML: ' + error.message);
59
+ }
60
+ validateMap(data);
61
+ return { file: realPath, source, data };
62
+ }
63
+
64
+ function validateMap(data) {
65
+ if (!data || typeof data !== 'object' || Array.isArray(data)) throw new Error('Map root must be a YAML object');
66
+ if (!data.actions || typeof data.actions !== 'object' || Array.isArray(data.actions)) throw new Error('Map must contain an actions object');
67
+ const identifiers = new Map();
68
+ for (const [alias, action] of Object.entries(data.actions)) {
69
+ if (!ALIAS.test(alias)) throw new Error('Invalid Action alias in map: ' + alias);
70
+ if (!action || typeof action !== 'object' || Array.isArray(action)) throw new Error('Action ' + alias + ' must be an object');
71
+ if (typeof action.identifier !== 'string' || !IDENTIFIER.test(action.identifier)) {
72
+ throw new Error('Action ' + alias + ' has an invalid identifier: ' + String(action.identifier));
73
+ }
74
+ const identity = action.identifier.toLowerCase();
75
+ const previousAlias = identifiers.get(identity);
76
+ if (previousAlias) throw new Error('Duplicate identifier ' + action.identifier + ' on aliases ' + previousAlias + ' and ' + alias);
77
+ identifiers.set(identity, alias);
78
+ if (typeof action.name !== 'string' || !action.name.trim()) throw new Error('Action ' + alias + ' must have a non-empty name');
79
+ if (!STATUSES.has(action.status)) throw new Error('Action ' + alias + ' has invalid status: ' + String(action.status));
80
+ }
81
+ if (!Array.isArray(data.links)) throw new Error('Map must contain a links array');
82
+ const links = new Set();
83
+ for (let i = 0; i < data.links.length; i++) {
84
+ const link = data.links[i];
85
+ if (!link || typeof link !== 'object' || Array.isArray(link)) throw new Error('links[' + i + '] must contain from and to aliases');
86
+ for (const field of ['from', 'to']) {
87
+ if (typeof link[field] !== 'string' || !ALIAS.test(link[field])) {
88
+ throw new Error('links[' + i + '].' + field + ' must be a one-letter Action alias');
89
+ }
90
+ if (!Object.hasOwn(data.actions, link[field])) {
91
+ throw new Error('links[' + i + '].' + field + ' uses unknown Action alias: ' + link[field]);
92
+ }
93
+ }
94
+ const key = pairKey(link.from, link.to);
95
+ if (links.has(key)) throw new Error('Duplicate link ' + link.from + ' -> ' + link.to);
96
+ links.add(key);
97
+ }
98
+ }
99
+
100
+ function pairKey(from, to) {
101
+ return from + '\0' + to;
102
+ }
103
+
104
+ function parseView1(diagramText) {
105
+ const lines = diagramText.split(/\r?\n/);
106
+ const fence = String.fromCharCode(96).repeat(3);
107
+ let view1 = false;
108
+ let inside = false;
109
+ const diagram = [];
110
+ for (const line of lines) {
111
+ if (!view1) {
112
+ if (/^## View 1(?:[ \t]|$)/.test(line)) view1 = true;
113
+ continue;
114
+ }
115
+ if (/^## View 2(?:[ \t]|$)/.test(line)) break;
116
+ if (!inside) {
117
+ if (line.trim() === fence + 'mermaid') inside = true;
118
+ continue;
119
+ }
120
+ if (line.trim() === fence) return diagram.join('\n');
121
+ diagram.push(line);
122
+ }
123
+ throw new Error('Could not find the View 1 Mermaid block before View 2');
124
+ }
125
+
126
+ function endpoint(raw, lineNumber, side) {
127
+ let value = raw.trim();
128
+ if (side === 'to' && value.startsWith('|')) {
129
+ const end = value.indexOf('|', 1);
130
+ if (end < 0) throw new Error('Invalid Mermaid edge label at View 1 line ' + lineNumber);
131
+ value = value.slice(end + 1).trim();
132
+ }
133
+ const match = /^([A-Za-z_][A-Za-z0-9_-]*)([\s\S]*)$/.exec(value);
134
+ if (!match) throw new Error('Invalid Mermaid ' + side + ' node at View 1 line ' + lineNumber);
135
+ const suffix = match[2].trim();
136
+ const declaration = /^\[[\s\S]*\]$/.test(suffix) ||
137
+ /^\{[\s\S]*\}$/.test(suffix) ||
138
+ /^\(\([\s\S]*\)\)$/.test(suffix);
139
+ if (suffix && !declaration) throw new Error('Unsupported Mermaid node declaration at View 1 line ' + lineNumber);
140
+ return match[1];
141
+ }
142
+
143
+ function diagramEdges(diagramText) {
144
+ const adjacency = new Map();
145
+ const lines = parseView1(diagramText).split('\n');
146
+ for (let i = 0; i < lines.length; i++) {
147
+ const line = lines[i].trim();
148
+ if (!line || line.startsWith('%%')) continue;
149
+ const arrows = line.match(/-->/g) || [];
150
+ if (arrows.length > 1) throw new Error('Unsupported chained Mermaid edges at View 1 line ' + (i + 1));
151
+ if (arrows.length === 0) {
152
+ if (/(?:---|==>|-\.\-|--[ox]|<--|<==)/.test(line)) {
153
+ throw new Error('Unsupported Mermaid edge operator at View 1 line ' + (i + 1));
154
+ }
155
+ continue;
156
+ }
157
+ const arrowAt = line.indexOf('-->');
158
+ const from = endpoint(line.slice(0, arrowAt), i + 1, 'from');
159
+ const to = endpoint(line.slice(arrowAt + 3), i + 1, 'to');
160
+ if (!adjacency.has(from)) adjacency.set(from, new Set());
161
+ adjacency.get(from).add(to);
162
+ }
163
+ return adjacency;
164
+ }
165
+
166
+ function expectedLinks(actions, adjacency) {
167
+ const expected = new Set();
168
+ const aliases = new Set(actions);
169
+ for (const from of aliases) {
170
+ const pending = [...(adjacency.get(from) || [])];
171
+ const visited = new Set();
172
+ while (pending.length) {
173
+ const node = pending.shift();
174
+ if (aliases.has(node)) {
175
+ if (node !== from) expected.add(pairKey(from, node));
176
+ } else if (!visited.has(node)) {
177
+ visited.add(node);
178
+ pending.push(...(adjacency.get(node) || []));
179
+ }
180
+ }
181
+ }
182
+ return expected;
183
+ }
184
+
185
+ function check(mapPath, diagramPath) {
186
+ const { data } = readMap(mapPath);
187
+ const diagram = fs.readFileSync(fs.realpathSync(diagramPath), 'utf8');
188
+ const expected = expectedLinks(Object.keys(data.actions), diagramEdges(diagram));
189
+ const actual = new Set(data.links.map(link => pairKey(link.from, link.to)));
190
+ const labels = key => key.split('\0').join(' -> ');
191
+ const missing = [...expected].filter(key => !actual.has(key)).sort();
192
+ const extra = [...actual].filter(key => !expected.has(key)).sort();
193
+ if (missing.length || extra.length) {
194
+ const errors = [
195
+ ...missing.map(key => 'Missing link ' + labels(key) + ' (present in View 1)'),
196
+ ...extra.map(key => 'Extra link ' + labels(key) + ' (not present in View 1)'),
197
+ ];
198
+ throw new Error(errors.join('\n'));
199
+ }
200
+ console.log('OK: ' + expected.size + ' Action link(s) match View 1.');
201
+ }
202
+
203
+ function editStatus(source, alias, status) {
204
+ const actionStart = new RegExp('^ ' + alias + ':[ \\t]*(?:#[^\\r\\n]*)?$', 'm').exec(source);
205
+ if (!actionStart) throw new Error('Could not locate Action ' + alias + ' in map text');
206
+ const bodyStart = actionStart.index + actionStart[0].length;
207
+ const remainder = source.slice(bodyStart);
208
+ const boundary = /^(?: [A-Z]:[ \t]*(?:#[^\r\n]*)?|links:[ \t]*(?:#[^\r\n]*)?)/m.exec(remainder);
209
+ const end = boundary ? bodyStart + boundary.index : source.length;
210
+ const block = source.slice(actionStart.index, end);
211
+ const statusLines = [...block.matchAll(/^[ \t]{4}status:/gm)];
212
+ if (statusLines.length !== 1) throw new Error('Action ' + alias + ' must have exactly one status line');
213
+ const statusLine = /^([ \t]{4}status:[ \t]*)\S+([ \t]*(?:#.*)?)(\r?)$/m.exec(block);
214
+ if (!statusLine) throw new Error('Could not read Action ' + alias + ' status line');
215
+ const replacement = statusLine[1] + status + statusLine[2] + statusLine[3];
216
+ const updatedBlock = block.slice(0, statusLine.index) + replacement + block.slice(statusLine.index + statusLine[0].length);
217
+ return source.slice(0, actionStart.index) + updatedBlock + source.slice(end);
218
+ }
219
+
220
+ function addAction(source, alias, identifier, name) {
221
+ const linksLine = /^links:[ \t]*(?:#[^\r\n]*)?$/m.exec(source);
222
+ if (!linksLine) throw new Error('Could not locate root links section in map text');
223
+ const newline = source.includes('\r\n') ? '\r\n' : '\n';
224
+ const prefix = source.slice(0, linksLine.index);
225
+ const separator = prefix && !prefix.endsWith('\n') ? newline : '';
226
+ const block = [
227
+ ' ' + alias + ':',
228
+ ' identifier: ' + identifier,
229
+ ' name: ' + JSON.stringify(name),
230
+ ' status: proposed',
231
+ '',
232
+ ].join(newline);
233
+ return prefix + separator + block + source.slice(linksLine.index);
234
+ }
235
+
236
+ function writeAtomically(file, contents) {
237
+ const mode = fs.statSync(file).mode & 0o777;
238
+ const temporary = path.join(path.dirname(file), '.' + path.basename(file) + '.' + process.pid + '.' + crypto.randomUUID() + '.tmp');
239
+ let fd;
240
+ try {
241
+ fd = fs.openSync(temporary, 'wx', mode);
242
+ fs.writeFileSync(fd, contents, 'utf8');
243
+ fs.closeSync(fd);
244
+ fd = undefined;
245
+ fs.renameSync(temporary, file);
246
+ } catch (error) {
247
+ if (fd !== undefined) fs.closeSync(fd);
248
+ try { fs.unlinkSync(temporary); } catch (_) {}
249
+ throw new Error('Could not atomically update ' + file + ': ' + error.message);
250
+ }
251
+ }
252
+
253
+ function create(mapPath, alias, name, requestedDate) {
254
+ const { file, source, data } = readMap(mapPath);
255
+ if (Object.hasOwn(data.actions, alias)) throw new Error('Action alias already exists: ' + alias);
256
+ const date = requestedDate || new Date().toISOString().slice(0, 10).replace(/-/g, '');
257
+ let identifier;
258
+ do {
259
+ identifier = 'ERR-' + date + '-' + crypto.randomUUID();
260
+ } while (Object.values(data.actions).some(action => action.identifier.toLowerCase() === identifier.toLowerCase()));
261
+ writeAtomically(file, addAction(source, alias, identifier, name));
262
+ console.log(identifier);
263
+ }
264
+
265
+ function setStatus(mapPath, identifier, status) {
266
+ const { file, source, data } = readMap(mapPath);
267
+ const entry = Object.entries(data.actions).find(([, action]) => action.identifier.toLowerCase() === identifier.toLowerCase());
268
+ if (!entry) throw new Error('No Action found with identifier: ' + identifier);
269
+ writeAtomically(file, editStatus(source, entry[0], status));
270
+ console.log('Updated ' + identifier + ' status to ' + status + '.');
271
+ }
272
+
273
+ function main() {
274
+ const { verb, options } = parseArgs(process.argv.slice(2));
275
+ const mapPath = path.resolve(options.map || 'docs/error-handling/nodes.yaml');
276
+ const diagramPath = path.resolve(options.diagram || 'docs/error-handling/README.md');
277
+ if (verb === 'check') check(mapPath, diagramPath);
278
+ else if (verb === 'new') create(mapPath, options.alias, options.name, options.date);
279
+ else setStatus(mapPath, options.id, options.status);
280
+ }
281
+
282
+ try {
283
+ main();
284
+ } catch (error) {
285
+ console.error('[error-handling-map] ' + error.message);
286
+ process.exitCode = 1;
287
+ }
288
+