harness-everything 0.53.0 → 0.54.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 (83) 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 +26 -0
  5. package/bin/cli.js +1 -0
  6. package/ci/action-gate.test.js +1 -1
  7. package/ci/invariant-routing.test.js +22 -3
  8. package/ci/mechanism-2al-codex-hooks-compat.test.js +56 -2
  9. package/ci/mechanism-2at-fable-execution-phases.test.js +38 -0
  10. package/ci/mechanism-349-ci-change-scope.test.js +78 -57
  11. package/ci/mechanism-397-cycle-import.test.js +18 -3
  12. package/ci/mechanism-check-packet-write-set.test.js +232 -0
  13. package/ci/mechanism-codex-hook-results.test.js +145 -0
  14. package/ci/mechanism-codex-prompt-pass-through.test.js +8 -4
  15. package/ci/mechanism-error-handling-map.test.js +219 -0
  16. package/ci/mechanism-report-writer.test.js +335 -0
  17. package/ci/openai-plugin-runtime.test.js +2 -1
  18. package/ci/prompt-contract-regressions.test.js +6 -2
  19. package/ci/router-workflow-plan.test.js +50 -7
  20. package/docs/architecture.md +4 -3
  21. package/docs/error-handling/README.md +250 -0
  22. package/docs/error-handling/actions/c1-action-map.md +89 -0
  23. package/docs/error-handling/actions/c2-action-map.md +22 -0
  24. package/docs/error-handling/actions/c3-action-map.md +26 -0
  25. package/docs/error-handling/actions/c5-action-map.md +31 -0
  26. package/docs/error-handling/actions/c6-action-map.md +37 -0
  27. package/docs/error-handling/actions/c7-action-map.md +18 -0
  28. package/docs/error-handling/actions/e0002-action-map.md +101 -0
  29. package/docs/error-handling/activity.puml +84 -0
  30. package/docs/error-handling/details/c1-authority-conformance.md +93 -0
  31. package/docs/error-handling/details/c2-test-root-containment.md +35 -0
  32. package/docs/error-handling/details/c3-mode-ownership.md +50 -0
  33. package/docs/error-handling/details/c5-host-replay-contract.md +40 -0
  34. package/docs/error-handling/details/c6-packet-briefing.md +65 -0
  35. package/docs/error-handling/details/c7-write-set-check.md +54 -0
  36. package/docs/error-handling/details/e0002-capture-evidence.md +93 -0
  37. package/docs/error-handling/details/e0002-report-writer.md +116 -0
  38. package/docs/error-handling/nodes.yaml +44 -0
  39. package/docs/error-handling/registry.md +59 -0
  40. package/docs/error-handling/templates/packet-briefing.md +45 -0
  41. package/docs/platform-capabilities.md +20 -1
  42. package/fable-mode/SKILL.md +5 -5
  43. package/fable-mode/execution-guardrails/SKILL.md +1 -1
  44. package/fable-mode/fable-haiku/SKILL.md +1 -1
  45. package/fable-mode/fable-opus/SKILL.md +1 -1
  46. package/fable-mode/fable-sonnet/SKILL.md +1 -1
  47. package/fable-mode/references/execution-phases.md +26 -4
  48. package/hooks/scripts/action-gate.js +5 -0
  49. package/hooks/scripts/codex-action-gate-post.js +3 -12
  50. package/hooks/scripts/codex-user-prompt.js +2 -3
  51. package/hooks/scripts/contract-test.js +17 -7
  52. package/hooks/scripts/lib/codex-tool-outcome.js +28 -0
  53. package/hooks/scripts/rule-of-3-tracker.js +11 -4
  54. package/hooks/scripts/state-persist.js +15 -9
  55. package/hooks/scripts/subagent-scope-guard.js +32 -25
  56. package/hooks/scripts/subagent-start.js +1 -1
  57. package/hooks/scripts/subagent-stop.js +14 -3
  58. package/opencode-plugin/plugin.json +1 -1
  59. package/package.json +2 -1
  60. package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
  61. package/plugins/harness-everything/hooks/hooks.json +6 -6
  62. package/plugins/harness-everything/hooks/scripts/action-gate.js +5 -0
  63. package/plugins/harness-everything/hooks/scripts/codex-action-gate-post.js +3 -12
  64. package/plugins/harness-everything/hooks/scripts/codex-user-prompt.js +2 -3
  65. package/plugins/harness-everything/hooks/scripts/contract-test.js +17 -7
  66. package/plugins/harness-everything/hooks/scripts/lib/codex-tool-outcome.js +28 -0
  67. package/plugins/harness-everything/hooks/scripts/rule-of-3-tracker.js +11 -4
  68. package/plugins/harness-everything/hooks/scripts/state-persist.js +15 -9
  69. package/plugins/harness-everything/hooks/scripts/subagent-scope-guard.js +32 -25
  70. package/plugins/harness-everything/hooks/scripts/subagent-start.js +1 -1
  71. package/plugins/harness-everything/hooks/scripts/subagent-stop.js +14 -3
  72. package/plugins/harness-everything/plugin.json +1 -1
  73. package/plugins/harness-everything/skills/fable-mode/SKILL.md +5 -5
  74. package/plugins/harness-everything/skills/fable-mode/execution-guardrails/SKILL.md +1 -1
  75. package/plugins/harness-everything/skills/fable-mode/fable-haiku/SKILL.md +1 -1
  76. package/plugins/harness-everything/skills/fable-mode/fable-opus/SKILL.md +1 -1
  77. package/plugins/harness-everything/skills/fable-mode/fable-sonnet/SKILL.md +1 -1
  78. package/plugins/harness-everything/skills/fable-mode/references/execution-phases.md +26 -4
  79. package/sbom.cdx.json +7 -7
  80. package/scripts/check-packet-write-set.js +155 -0
  81. package/scripts/codex-hooks-compat.js +46 -5
  82. package/scripts/error-handling-map.js +288 -0
  83. package/scripts/report-writer.js +261 -0
@@ -8,7 +8,7 @@
8
8
  * newly changed paths as declared, ambiguous, or out-of-scope. Machine-
9
9
  * readable write sets may therefore clear expected changes without weakening
10
10
  * the conservative legacy path: when no stage contract exists, any new
11
- * change still exits 2 and requires explicit review.
11
+ * change still emits a reminder and requires explicit review.
12
12
  *
13
13
  * `writeSet: []` means read-only. Worker attribution is used when the host
14
14
  * exposes a worker/subagent id and the stage contract records the same id;
@@ -106,15 +106,13 @@ function classifyChanges(newlyChanged, declaredContracts, payload) {
106
106
  return { workerId: workerId || null, expected, ambiguous, outOfScope };
107
107
  }
108
108
 
109
- let inputData = '';
110
- process.stdin.on('data', chunk => { inputData += chunk; });
111
- process.stdin.on('end', () => {
109
+ function inspectScope(inputData, { info, warn }) {
112
110
  try {
113
111
  const payload = JSON.parse(inputData);
114
112
  const event = payload.hook_event_name;
115
113
  const toolName = payload.tool_name || payload.tool;
116
114
  const isSubagentEvent = event === 'SubagentStart' || event === 'SubagentStop';
117
- if (!isSubagentEvent && toolName !== 'Task' && toolName !== 'Agent') process.exit(0);
115
+ if (!isSubagentEvent && toolName !== 'Task' && toolName !== 'Agent') return;
118
116
 
119
117
  const root = getWorkspaceRoot(payload);
120
118
  const sessionId = getSessionId(payload);
@@ -134,17 +132,17 @@ process.stdin.on('end', () => {
134
132
  });
135
133
  }
136
134
  }
137
- process.exit(0);
135
+ return;
138
136
  }
139
137
 
140
138
  if (event === 'PostToolUse' || event === 'SubagentStop') {
141
139
  accountWorker(payload, event);
142
- if (!fs.existsSync(stateFile)) process.exit(0);
140
+ if (!fs.existsSync(stateFile)) return;
143
141
 
144
142
  let state;
145
- try { state = JSON.parse(fs.readFileSync(stateFile, 'utf8')); } catch (_) { process.exit(0); }
143
+ try { state = JSON.parse(fs.readFileSync(stateFile, 'utf8')); } catch (_) { return; }
146
144
  const current = gitStatus(root);
147
- if (current === null) process.exit(0);
145
+ if (current === null) return;
148
146
 
149
147
  const baselineLines = new Set(String(state.baseline || '').split('\n').filter(Boolean));
150
148
  const currentLines = current.split('\n').filter(Boolean);
@@ -161,20 +159,20 @@ process.stdin.on('end', () => {
161
159
  atomicWriteJson(path.join(sessionDir, 'subagent-scope-last.json'), audit);
162
160
 
163
161
  if (newlyChanged.length === 0) {
164
- console.log('[Subagent Scope Reminder] No new changed files detected during the subagent burst.');
162
+ info('[Subagent Scope Reminder] No new changed files detected during the subagent burst.');
165
163
  } else if (declaredContracts.length === 0) {
166
- console.error(`[Subagent Scope Reminder] ${newlyChanged.length} file(s) changed with no machine-readable writeSet contract:`);
167
- newlyChanged.forEach(line => console.error(` ${line}`));
168
- console.error('Semantic MUST: reconcile every changed path against the declared scope before trusting or committing this output.');
164
+ warn(`[Subagent Scope Reminder] ${newlyChanged.length} file(s) changed with no machine-readable writeSet contract:`);
165
+ newlyChanged.forEach(line => warn(` ${line}`));
166
+ warn('Semantic MUST: reconcile every changed path against the declared scope before trusting or committing this output.');
169
167
  } else {
170
168
  for (const entry of classified.expected) {
171
- console.log(`[Subagent Scope Reminder] in-scope ${entry.statusLine} -> ${entry.planId}/${entry.runId}/${entry.stageId}${entry.workerId ? ` worker=${entry.workerId}` : ''}`);
169
+ info(`[Subagent Scope Reminder] in-scope ${entry.statusLine} -> ${entry.planId}/${entry.runId}/${entry.stageId}${entry.workerId ? ` worker=${entry.workerId}` : ''}`);
172
170
  }
173
171
  for (const entry of classified.ambiguous) {
174
- console.error(`[Subagent Scope Reminder] ambiguous scope ${entry.statusLine}; matches ${entry.stages.map(stage => `${stage.runId}/${stage.stageId}`).join(', ')}`);
172
+ warn(`[Subagent Scope Reminder] ambiguous scope ${entry.statusLine}; matches ${entry.stages.map(stage => `${stage.runId}/${stage.stageId}`).join(', ')}`);
175
173
  }
176
174
  for (const entry of classified.outOfScope) {
177
- console.error(`[Subagent Scope Reminder] OUT-OF-SCOPE ${entry.statusLine}${entry.workerId ? ` worker=${entry.workerId}` : ''}; MUST reconcile/revert or explicitly re-authorize scope before accepting the result.`);
175
+ warn(`[Subagent Scope Reminder] OUT-OF-SCOPE ${entry.statusLine}${entry.workerId ? ` worker=${entry.workerId}` : ''}; MUST reconcile/revert or explicitly re-authorize scope before accepting the result.`);
178
176
  }
179
177
  }
180
178
 
@@ -188,24 +186,33 @@ process.stdin.on('end', () => {
188
186
  ? newlyChanged.length > 0
189
187
  : classified.ambiguous.length > 0 || classified.outOfScope.length > 0;
190
188
  if (violated) {
191
- console.error('Do not "git add -A"; stage files explicitly so unexpected paths stay visible.');
192
- process.exit(0);
189
+ warn('Do not "git add -A"; stage files explicitly so unexpected paths stay visible.');
193
190
  }
194
- process.exit(0);
195
191
  }
196
-
197
- process.exit(0);
198
192
  } catch (error) {
199
193
  if (error && error.code === 'HARNESS_WORKFLOW_BUDGET') {
200
- console.error(`[Subagent Scope Reminder] ${error.message}`);
201
- process.exit(0);
194
+ warn(`[Subagent Scope Reminder] ${error.message}`);
195
+ return;
202
196
  }
203
197
  // This is otherwise a post-execution visibility gate. Runtime errors fail open;
204
198
  // actionGate has a stricter fail-ask policy for side effects.
205
- process.exit(0);
199
+ return;
206
200
  }
207
- });
201
+ }
202
+
203
+ function run({ info = console.log, warn = console.error, complete = () => {} } = {}) {
204
+ let inputData = '';
205
+ process.stdin.setEncoding('utf8');
206
+ process.stdin.on('data', chunk => { inputData += chunk; });
207
+ process.stdin.on('end', () => {
208
+ inspectScope(inputData, { info, warn });
209
+ complete();
210
+ });
211
+ }
212
+
213
+ if (require.main === module) run();
208
214
 
209
215
  module.exports = {
210
216
  classifyChanges,
217
+ run,
211
218
  };
@@ -16,4 +16,4 @@ process.on('exit', () => {
16
16
  }) + '\n');
17
17
  });
18
18
 
19
- require('./subagent-scope-guard');
19
+ require('./subagent-scope-guard').run();
@@ -1,6 +1,17 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
3
 
4
- // The shared guard emits exit code 2 and stderr when a subagent changed files;
5
- // OpenAI/Codex treats that as a continuation signal for SubagentStop.
6
- require('./subagent-scope-guard');
4
+ const { run } = require('./subagent-scope-guard');
5
+
6
+ // Codex accepts warnings through systemMessage on SubagentStop. Keep the
7
+ // audit advisory and leave stdout empty when there is nothing to reconcile.
8
+ const warnings = [];
9
+ run({
10
+ info() {},
11
+ warn(message) { warnings.push(message); },
12
+ complete() {
13
+ if (warnings.length > 0) {
14
+ process.stdout.write(JSON.stringify({ systemMessage: warnings.join('\n') }) + '\n');
15
+ }
16
+ },
17
+ });
@@ -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.53.0",
4
+ "version": "0.54.1",
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",
@@ -4,7 +4,7 @@ description: "Stage large tasks through plans, named fable agents, failable chec
4
4
  license: Apache-2.0
5
5
  metadata:
6
6
  author: Miya Daniel
7
- version: 0.31.3
7
+ version: 0.54.1
8
8
  ---
9
9
 
10
10
  # Fable Mode
@@ -34,10 +34,10 @@ For explanation/profile-only lookup, read only `<this-skill-dir>/references/prof
34
34
  ## Workflow
35
35
 
36
36
  1. Discover the runtime and lock the authorized file scope before edits.
37
- 2. Per stage, set artifact, check, and required/optional bindings; dependency-ready stages disclose them, passing once resolved. Gaps never lock tools or Stop; advisory replans never halt. Rule-of-3 covers same-signature failures.
38
- 3. Resolve the requested behavior profile with `model-selector.js`; `opus`, `sonnet`/`sonnect`, and `haiku` are compatibility aliases, not model bindings.
39
- 4. Delegate by profile: orchestrator coordinates, reasoning takes bounded judgment, mechanical takes low-ambiguity work; workers never spawn workers.
37
+ 2. Plan via `<this-skill-dir>/references/execution-phases.md`.
38
+ 3. Use `model-selector.js`.
39
+ 4. Delegate by profile: orchestrator coordinates, reasoning takes bounded judgment, mechanical takes low-ambiguity work; workers never spawn workers. Before Codex dispatch, load/apply `<this-skill-dir>/references/execution-phases.md#verification-and-handoff`.
40
40
  5. The host runtime-model floor is advisory; record it, never block on model choice alone.
41
- 6. Run stage checks, cold-review high-stakes artifacts, and audit profile/runtime/fallback fields.
41
+ 6. On every Codex handoff or silent stop, load/apply `<this-skill-dir>/references/execution-phases.md#verification-and-handoff` before accepting results or releasing dependent stages. Run stage checks, cold-review high-stakes artifacts, and audit profile/runtime/fallback fields.
42
42
 
43
43
  Deep dive: <this-skill-dir>/references/model-matrix.md
@@ -4,7 +4,7 @@ description: "Reference guardrails for verified warnings and safe replacements;
4
4
  license: Apache-2.0
5
5
  metadata:
6
6
  author: Miya Daniel
7
- version: 0.31.3
7
+ version: 0.54.1
8
8
  ---
9
9
 
10
10
  # Execution Guardrails
@@ -4,7 +4,7 @@ description: "Reference mechanical behavior profile (legacy alias haiku) for bul
4
4
  license: Apache-2.0
5
5
  metadata:
6
6
  author: Miya Daniel
7
- version: 0.31.3
7
+ version: 0.54.1
8
8
  ---
9
9
 
10
10
  # Fable Mode — Haiku
@@ -4,7 +4,7 @@ description: "Reference orchestrator behavior profile (legacy alias opus) for st
4
4
  license: Apache-2.0
5
5
  metadata:
6
6
  author: Miya Daniel
7
- version: 0.31.3
7
+ version: 0.54.1
8
8
  ---
9
9
 
10
10
  # Fable Mode — Opus
@@ -4,7 +4,7 @@ description: "Reference reasoning behavior profile (legacy alias sonnet/sonnect)
4
4
  license: Apache-2.0
5
5
  metadata:
6
6
  author: Miya Daniel
7
- version: 0.31.3
7
+ version: 0.54.1
8
8
  ---
9
9
 
10
10
  # Fable Mode — Sonnet
@@ -17,13 +17,18 @@ flowchart TD
17
17
  Read relevant files and sources before producing an artifact. Record the
18
18
  authorized write scope. Give each stage an objective, dependencies, write set,
19
19
  expected output, exact check command, and pass condition. Required and optional
20
- bindings belong on the stage that needs them. Replan counts are advisory; after
21
- three same-signature failures, use Rule-of-3 `zoom-out`.
20
+ bindings belong on the stage that needs them. Replans are advisory and do not
21
+ halt tools or Stop; after three same-signature failures, use Rule-of-3
22
+ `zoom-out`.
22
23
 
23
24
  ## Profiles and delegation
24
25
 
25
- Resolve a requested behavior profile with Fable's profile selector and record
26
- it separately from the runtime choice. `fable-orchestrator`,
26
+ See the [model matrix](model-matrix.md) for profile details.
27
+
28
+ Resolve a requested behavior profile with Fable's `model-selector.js` and
29
+ record it separately from the runtime choice. `opus`, `sonnet`/`sonnect`, and
30
+ `haiku` are compatibility aliases for behavior profiles, not model bindings.
31
+ `fable-orchestrator`,
27
32
  `fable-worker-sonnet`, and `fable-worker-haiku` name coordination,
28
33
  reasoning/synthesis, and mechanical-work roles. These are behavior-profile
29
34
  aliases; they do not switch the runtime model. Preserve an explicit user or
@@ -104,3 +109,20 @@ Run each named check and review scope-guard evidence before delivery. When the
104
109
  selected plan requires independent verification, the verifier is read-only and
105
110
  uses a distinct worker identity after all other stages pass. Record a blocker
106
111
  or an evidence-backed result; do not discard unresolved requirements.
112
+
113
+ For Codex subagents, the coordinator MUST reconcile scope before accepting a
114
+ result or using it in a dependent stage, even if the stage check passed.
115
+
116
+ 1. Before dispatch, capture the worker worktree's starting state, including
117
+ existing local changes. At handoff, compare the committed, staged, unstaged,
118
+ and untracked changes since dispatch with the stage's declared `writeSet`.
119
+ 2. For unexpected or ambiguously attributed changes, establish ownership and
120
+ record the disposition. Exclude the changes from the result, revert only
121
+ attributable worker changes when authorized, or obtain explicit approval for
122
+ a scope change and follow the replanning rules. Record a blocker if the
123
+ coordinator cannot reconcile a path.
124
+
125
+ Run this check after every handoff, including silent stops. The Codex warning
126
+ and `subagent-scope-last.json` describe the latest hook observation. A clean
127
+ observation can replace an earlier warning while the corresponding change is
128
+ still present.
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:afabb965-abc6-52fb-92e7-1220041eadbf",
5
+ "serialNumber": "urn:uuid:6ba544c0-8daa-5aff-b49e-eb42f5255dd2",
6
6
  "version": 1,
7
7
  "metadata": {
8
- "timestamp": "2026-11-18T03:27:42.456Z",
8
+ "timestamp": "2026-11-20T02:06:23.594Z",
9
9
  "tools": [
10
10
  {
11
11
  "vendor": "Harness Everything",
12
12
  "name": "generate-sbom.js",
13
- "version": "0.53.0"
13
+ "version": "0.54.1"
14
14
  }
15
15
  ],
16
16
  "component": {
17
17
  "type": "application",
18
- "bom-ref": "pkg:npm/harness-everything@0.53.0",
18
+ "bom-ref": "pkg:npm/harness-everything@0.54.1",
19
19
  "name": "harness-everything",
20
- "version": "0.53.0",
21
- "purl": "pkg:npm/harness-everything@0.53.0"
20
+ "version": "0.54.1",
21
+ "purl": "pkg:npm/harness-everything@0.54.1"
22
22
  }
23
23
  },
24
24
  "components": [
@@ -2033,7 +2033,7 @@
2033
2033
  ]
2034
2034
  },
2035
2035
  {
2036
- "ref": "pkg:npm/harness-everything@0.53.0",
2036
+ "ref": "pkg:npm/harness-everything@0.54.1",
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 });