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
@@ -10,7 +10,7 @@
10
10
  "name": "harness-everything",
11
11
  "source": "./",
12
12
  "description": "Harness OS: an orchestrated agent operating system — tier routing, circuit breaker guardrails, verification gates, WAL session memory, and self-evolving workspace rules.",
13
- "version": "0.52.0",
13
+ "version": "0.54.0",
14
14
  "author": {
15
15
  "name": "Miya Daniel"
16
16
  },
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "harness-everything",
3
3
  "description": "Harness OS: an orchestrated agent operating system — tier routing, circuit breaker guardrails, verification gates, WAL session memory, and self-evolving workspace rules.",
4
- "version": "0.52.0",
4
+ "version": "0.54.0",
5
5
  "author": {
6
6
  "name": "Miya Daniel"
7
7
  },
package/AGENTS.md CHANGED
@@ -92,7 +92,9 @@ flowchart LR
92
92
  V -. optional .-> N["-- --node22<br/>(Node 22 smoke lane)"]
93
93
  ```
94
94
 
95
- - `npm run verify:all` runs every CI gate category and prints paste-ready evidence. Individual gates: `npm test`, `npm run test:mutations`, `test:mechanism`, `test:consistency`, `test:repo-contract`, `test:docs:capabilities`, `test:references`, `test:release`, `test:collision`, `test:routing:skills`, `test:routing:invariants`, `test:plugin:openai`, `test:plugin:submission`, `test:platform:compatibility`, `test:portability`.
95
+ - `npm run verify:all` runs a local subset of the hosted `ci.yml` gates and prints paste-ready PASS/FAIL/UNCHECKED evidence: 12 rows in the full plan, 4 with `--fast` (`npm test`, `test:mutations`, `test:consistency`, `test:portability`).
96
+ - Full rows: `npm test`, `test:mutations`, `test:consistency`, `test:references`, `test:release`, `test:collision`, `test:routing:skills`, `test:routing:invariants`, `test:plugin:openai`, `test:plugin:submission`, `test:platform:compatibility`, `test:portability`. `test:mechanism` runs inside `npm test`; `test:repo-contract` and `test:docs:capabilities` run inside `test:consistency`. Hosted CI runs the two `test:routing:*` rows inside `self-regression`.
97
+ - Hosted `ci.yml` jobs it does not run: `pilot-offline-evidence`, both System One Windows runtime-pin jobs, `release-semantics` (`test:release:semantics`), `skill-quality` (waza per-skill checks; only the optional `waza:check` row runs, and only when waza is installed), `installer-e2e` (`ci/installer-roundtrip.test.js`) and `npm ci` under Node 22 in `runtime-floor`. Local rows also run on one OS, where hosted `self-regression` and `consistency` run three.
96
98
  - With waza (`~/bin/waza`): `waza check <skill-dir>`, `waza spec verify <skill> evals/<skill>/eval.yaml --fail --threshold 1`, `waza tokens check`.
97
99
  - CI runs Node.js 24 on Ubuntu/Windows/macOS plus a Node.js 22 floor lane ([repository-contract.md](docs/repository-contract.md)). Node 22 install compatibility stays UNCHECKED locally.
98
100
  - Never report "it works" from code reading. Name the evidence layer: package, deterministic mechanism, live host or behavior.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,40 @@
2
2
 
3
3
  All notable changes to this project are documented in this file.
4
4
 
5
+ ## [0.54.0](https://github.com/dyphn1/Harness-everything/compare/v0.53.0...v0.54.0) (2026-11-19)
6
+
7
+ ### Features
8
+
9
+ * **scripts:** add a read-only write-set check for packet slices ([5953f34](https://github.com/dyphn1/Harness-everything/commit/5953f34e04cc0722f74f716ab0e53559dd1ff5ad)), closes [#402](https://github.com/dyphn1/Harness-everything/issues/402)
10
+ * **scripts:** add a report writer that owns the terminal status line ([54beeee](https://github.com/dyphn1/Harness-everything/commit/54beeee19f8eb95d90aa40b91228376493039968)), closes [#402](https://github.com/dyphn1/Harness-everything/issues/402) [#441](https://github.com/dyphn1/Harness-everything/issues/441)
11
+ * **scripts:** add new, set-status and check for the error handling map ([4f9afe2](https://github.com/dyphn1/Harness-everything/commit/4f9afe27de01ca1390a5f1b333831913f0df6a9e)), closes [#437](https://github.com/dyphn1/Harness-everything/issues/437) [#402](https://github.com/dyphn1/Harness-everything/issues/402) [#437](https://github.com/dyphn1/Harness-everything/issues/437)
12
+
13
+ ### Bug Fixes
14
+
15
+ * **codex:** migrate stale tier-router prompt hooks ([d6aa9a7](https://github.com/dyphn1/Harness-everything/commit/d6aa9a711fac5007dc68ccf25732d67da8c448a5))
16
+ * **scripts:** check the write-set of the repository the command runs in ([bcf3c57](https://github.com/dyphn1/Harness-everything/commit/bcf3c577e32a4d6061298059d14caf05eaae210a)), closes [#402](https://github.com/dyphn1/Harness-everything/issues/402)
17
+ * **scripts:** let the cli status complete raw codex output without status ([b61ebea](https://github.com/dyphn1/Harness-everything/commit/b61ebea855fc265feaa0f63715f9500e1ee96f4b)), closes [#402](https://github.com/dyphn1/Harness-everything/issues/402)
18
+
19
+ ## [0.53.0](https://github.com/dyphn1/Harness-everything/compare/v0.52.0...v0.53.0) (2026-11-18)
20
+
21
+ ### Features
22
+
23
+ * **observations:** inject the label contract and record opencode turns ([2fa9d6d](https://github.com/dyphn1/Harness-everything/commit/2fa9d6d4c516c858c763a9a6a5110edf778f5019))
24
+ * **system-one:** import live observations into the cycle store ([aa8af52](https://github.com/dyphn1/Harness-everything/commit/aa8af5256efef61807f6b7927b43927f0b4abaf5))
25
+ * **system-one:** report per-host label acceptance before filtering ([63c817b](https://github.com/dyphn1/Harness-everything/commit/63c817b5e9c8481df1da7206e37673f45275ef8e))
26
+
27
+ ### Bug Fixes
28
+
29
+ * **opencode:** bind each prompt to its session workspace ([861e55e](https://github.com/dyphn1/Harness-everything/commit/861e55ec1627a41b31c6139c6e7ba7b53ef3bb7d))
30
+ * **opencode:** close the observation turn on v2 execution events ([9051c28](https://github.com/dyphn1/Harness-everything/commit/9051c28e2818aa6826e483e0edb4e458c94a4871))
31
+ * **opencode:** read the final reply from the v2 session context ([fb24958](https://github.com/dyphn1/Harness-everything/commit/fb2495817e27f596aa4001ff3a99f97c7d021588))
32
+ * **opencode:** run the router with node inside the bun host ([f7addfc](https://github.com/dyphn1/Harness-everything/commit/f7addfc0290af7622a1e30560b1ea746bb77cd10))
33
+ * **opencode:** settle disposal while completion context is pending ([554b812](https://github.com/dyphn1/Harness-everything/commit/554b81232854b67e3abf4d85a217d8e0277753c3)), closes [#448](https://github.com/dyphn1/Harness-everything/issues/448)
34
+ * **opencode:** stop publishing state after plugin disposal ([a0f8204](https://github.com/dyphn1/Harness-everything/commit/a0f8204a9a70834c990284c9ba5f49652553ec6d)), closes [#448](https://github.com/dyphn1/Harness-everything/issues/448)
35
+ * **opencode:** translate v2 lifecycle events and guard stale bindings ([5371ead](https://github.com/dyphn1/Harness-everything/commit/5371ead206de2622dcb7616380be48855cf3e493))
36
+ * **system-one:** keep cross-month cycle history for trend decisions ([e918e45](https://github.com/dyphn1/Harness-everything/commit/e918e455c47ad53940d8f6c22cb37e9ec0d28d20)), closes [#443](https://github.com/dyphn1/Harness-everything/issues/443) [#446](https://github.com/dyphn1/Harness-everything/issues/446)
37
+ * **system-one:** reject incompatible history on cycle resume ([e6af72f](https://github.com/dyphn1/Harness-everything/commit/e6af72f87cfb552d6683fde9683677f41ae2e892)), closes [#446](https://github.com/dyphn1/Harness-everything/issues/446)
38
+
5
39
  ## [0.52.0](https://github.com/dyphn1/Harness-everything/compare/v0.51.0...v0.52.0) (2026-11-15)
6
40
 
7
41
  ### Features
@@ -54,6 +88,10 @@ All notable changes to this project are documented in this file.
54
88
  * **CI:** Skip the three-platform Node 24 self-regression matrix for pull requests limited to approved documentation, benchmark results, error ledger, or changelog paths.
55
89
  * **doc-reconciliation:** credit only correlated, bounded workflow-state operations for the approved row-17 outline cycle
56
90
 
91
+ ### Bug Fixes
92
+
93
+ * **codex:** report stale npx tier-router prompt hooks and let users migrate them to the JSON adapter (#457).
94
+
57
95
  ## [0.50.0](https://github.com/dyphn1/Harness-everything/compare/v0.49.0...v0.50.0) (2026-11-09)
58
96
 
59
97
  ### Features
@@ -0,0 +1,7 @@
1
+ # OpenCode session workspace field trace
2
+
3
+ **Observed:** OpenCode 2.1.4 on macOS, 2026-11-15. One server process handled sessions from two workspaces.
4
+
5
+ The retained [probe](live-workspace-probe.js) logged setup and prompt field shapes to [JSONL](live-workspace-trace-2026-11-15.jsonl). Setup exposed `ctx.location.directory`; prompt events exposed `sessionID`, `messageID`, `prompt`, `metadata`, and `delivery`, with no event location. For each prompt, `ctx.session.get({sessionID})` returned a session whose `location.directory` matched that session's setup workspace. The server process cwd was a different directory.
6
+
7
+ This trace establishes that the session lookup and directory field were available in these two runs. Both setup locations already matched their session directories, so the trace does not establish behavior for a setup/session mismatch, missing setup location, failed lookup, or V2 router/tool/completion hook firing. It is not a live reproduction of the workspace attribution defect or verification of the fix. The cross-workspace counterexample and fix are covered by the deterministic V2 default-export test `ci/mechanism-397-opencode-observations.test.js`.
@@ -0,0 +1,16 @@
1
+ import { appendFileSync } from "node:fs"
2
+ import { basename } from "node:path"
3
+ const log = o => appendFileSync(process.env.PROBE_TRACE || "trace.jsonl", JSON.stringify(o) + "\n")
4
+ const shape = v => v && typeof v === "object" ? Object.keys(v) : typeof v
5
+ export default {
6
+ id: "probe.workspace",
7
+ async setup(ctx) {
8
+ const id = Math.random().toString(36).slice(2, 8)
9
+ log({ ev: "setup", id, ctxKeys: Object.keys(ctx), location: ctx.location && { keys: Object.keys(ctx.location), dir: ctx.location.directory && basename(ctx.location.directory) }, directory: ctx.directory && basename(ctx.directory), cwd: basename(process.cwd()) })
10
+ await ctx.session.hook("prompt", async event => {
11
+ let info = null
12
+ try { const s = await ctx.session.get({ sessionID: event.sessionID }); info = { keys: shape(s), dir: s && (s.directory || s.location?.directory) ? basename(s.directory || s.location.directory) : null, location: shape(s?.location) } } catch (e) { info = { error: String(e).slice(0, 80) } }
13
+ log({ ev: "prompt", id, eventKeys: Object.keys(event), eventLocation: shape(event.location), session: info })
14
+ })
15
+ },
16
+ }
@@ -0,0 +1,4 @@
1
+ {"ev":"setup","id":"97zahz","ctxKeys":["app","location","options","agent","aisdk","command","credential","event","experimental","generate","model","provider","integration","mcp","permission","plugin","reference","rpc","skill","storage","tool","vcs","websearch","worktree","session","shell"],"location":{"keys":["directory","workspaceID","project"],"dir":"wsA"},"cwd":"probe"}
2
+ {"ev":"prompt","id":"97zahz","eventKeys":["sessionID","messageID","prompt","metadata","delivery"],"eventLocation":"undefined","session":{"keys":["id","projectID","model","cost","tokens","time","location"],"dir":"wsA","location":["directory"]}}
3
+ {"ev":"setup","id":"xlcnsl","ctxKeys":["app","location","options","agent","aisdk","command","credential","event","experimental","generate","model","provider","integration","mcp","permission","plugin","reference","rpc","skill","storage","tool","vcs","websearch","worktree","session","shell"],"location":{"keys":["directory","workspaceID","project"],"dir":"wsB"},"cwd":"probe"}
4
+ {"ev":"prompt","id":"xlcnsl","eventKeys":["sessionID","messageID","prompt","metadata","delivery"],"eventLocation":"undefined","session":{"keys":["id","projectID","model","cost","tokens","time","location"],"dir":"wsB","location":["directory"]}}
package/bin/cli.js CHANGED
@@ -112,6 +112,7 @@ Commands:
112
112
  that fail to mount enabled plugin-bundled hooks.
113
113
  Usage: harness codex-hooks <install|status|uninstall>
114
114
  [--codex-home <path>] [--allow-unreleased-source]
115
+ Install option: --remove-legacy-tier-router
115
116
  Does not trust hooks or modify Codex config.toml.
116
117
  plugin-sync Install or update the native Harness plugin on Claude Code
117
118
  and Codex. Existing installations always take the update
@@ -1,12 +1,31 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
- const fs=require('fs'),path=require('path'),{spawnSync}=require('child_process');
3
+ const fs=require('fs'),path=require('path'),{spawnSync:spawnNodeSync}=require('child_process');
4
+ function spawnSync(command,args,options={}){
5
+ const {systemOneMode='off',...spawnOptions}=options;
6
+ return spawnNodeSync(command,args,{...spawnOptions,env:{...process.env,...(spawnOptions.env||{}),HARNESS_SYSTEM_ONE_MODE:systemOneMode}});
7
+ }
4
8
  const ROOT=path.resolve(__dirname,'..');let failed=0;
5
9
  function check(c,m){if(c)console.log(' PASS '+m);else{console.error(' FAIL '+m);failed++;}}
6
10
  function read(p){return fs.readFileSync(path.join(ROOT,p),'utf8');}
7
11
  console.log('=== Semantic Contract-Strength Routing Contract ===');
8
12
  const kernel=path.join(ROOT,'harness-everything/scripts/kernel-router.js');
9
- const tier2=spawnSync(process.execPath,[kernel,'add a login endpoint with tests and update the implementation'],{cwd:ROOT,encoding:'utf8'});
13
+ function runKernel(prompt, {systemOneMode='off'}={}){
14
+ return spawnSync(process.execPath,[kernel,prompt],{cwd:ROOT,encoding:'utf8',systemOneMode});
15
+ }
16
+ const priorMode=process.env.HARNESS_SYSTEM_ONE_MODE;
17
+ let inheritedLive;
18
+ try{
19
+ process.env.HARNESS_SYSTEM_ONE_MODE='live';
20
+ inheritedLive=runKernel('add a login endpoint with tests and update the implementation');
21
+ }finally{
22
+ if(priorMode===undefined)delete process.env.HARNESS_SYSTEM_ONE_MODE;
23
+ else process.env.HARNESS_SYSTEM_ONE_MODE=priorMode;
24
+ }
25
+ check(inheritedLive.status===0&&!inheritedLive.stdout.includes('SYSTEM ONE REFERENCE CONFIDENCE'),'kernel routing fixture ignores inherited live mode unless explicitly selected');
26
+ const explicitLive=runKernel('add a login endpoint with tests and update the implementation',{systemOneMode:'live'});
27
+ check(explicitLive.status===0&&explicitLive.stdout.includes('SYSTEM ONE REFERENCE CONFIDENCE'),'kernel routing fixture retains an explicit live-mode control');
28
+ const tier2=runKernel('add a login endpoint with tests and update the implementation');
10
29
  check(tier2.status===0,'kernel router exits successfully');
11
30
  check(/RECOMMENDED TIER:\s*Tier 2/i.test(tier2.stdout),'classifier result is preserved');
12
31
  check(tier2.stdout.includes('"strategy":"iterative-single"'),'Tier 2 selects iterative-single workflow');
@@ -30,7 +49,7 @@ check(!tier2.stdout.includes('HARNESS ROUTING CHECKPOINT (REQUIRED VISIBLE STATE
30
49
  check(tier2.stdout.includes('nested bullets when there are multiple items'),'kernel tells agents to split dense evidence into nested bullets');
31
50
  check(tier2.stdout.includes('semantic communication MUST, not a hard execution lock'),'kernel separates semantic MUST from mechanical blocking');
32
51
 
33
- const tier3=spawnSync(process.execPath,[kernel,'audit the entire repository architecture and coordinate multiple modules'],{cwd:ROOT,encoding:'utf8'});
52
+ const tier3=runKernel('audit the entire repository architecture and coordinate multiple modules');
34
53
  check(tier3.status===0,'Tier 3 routing exits successfully');
35
54
  check(/RECOMMENDED TIER:\s*Tier 3/i.test(tier3.stdout),'macro task remains Tier 3');
36
55
  check(tier3.stdout.includes('isolated-worktree-before-mutation'),'Tier 3 keeps the worktree isolation invariant');
@@ -5,6 +5,7 @@ const assert = require('assert');
5
5
  const fs = require('fs');
6
6
  const os = require('os');
7
7
  const path = require('path');
8
+ const { spawnSync } = require('child_process');
8
9
 
9
10
  const compat = require('../scripts/codex-hooks-compat');
10
11
 
@@ -62,6 +63,11 @@ const original = {
62
63
  fs.writeFileSync(hooksFile, JSON.stringify(original, null, 4) + '\n', 'utf8');
63
64
  fs.writeFileSync(configFile, 'model = "test"\n# user trust/config state\n', 'utf8');
64
65
  const configBefore = fs.readFileSync(configFile, 'utf8');
66
+ const npxRouterPath = '_npx/9abc123def/node_modules/harness-everything/harness-everything/scripts/tier-router.js';
67
+ const legacyWindows = {
68
+ type: 'command',
69
+ commandWindows: 'node "C:\\Cache Dir\\' + npxRouterPath.replace(/\//g, '\\') + '"',
70
+ };
65
71
 
66
72
  try {
67
73
  const installed = compat.install({ allowUnreleasedSource: true, codexHome });
@@ -215,6 +221,52 @@ try {
215
221
  fs.readFileSync(path.join(preexistingHome, 'hooks.json'), 'utf8') === preexistingBefore,
216
222
  'uninstall preserves byte-identical hooks that predated compatibility install');
217
223
 
224
+ const legacyHome = path.join(root, 'legacy-codex');
225
+ fs.mkdirSync(legacyHome);
226
+ const legacyFile = path.join(legacyHome, 'hooks.json');
227
+ const legacyConfigFile = path.join(legacyHome, 'config.toml');
228
+ const direct = { type: 'command', command: 'node "/cache dir/' + npxRouterPath + '"' };
229
+ const customized = { ...direct, commandWindows: 'node "C:\\user\\my-prompt-hook.js"' };
230
+ const chained = { ...direct, command: direct.command + ' && echo custom' };
231
+ const localRouter = { ...direct, command: 'node "/user/scripts/tier-router.js"' };
232
+ const preserved = { matcher: '.*', hooks: [customized, chained, localRouter] };
233
+ const otherEvent = { hooks: [direct] };
234
+ fs.writeFileSync(legacyConfigFile, configBefore);
235
+ fs.writeFileSync(legacyFile, JSON.stringify({ hooks: {
236
+ UserPromptSubmit: [{ ...preserved, hooks: [direct, ...preserved.hooks] }, { hooks: [legacyWindows, direct] }],
237
+ Stop: [otherEvent],
238
+ } }));
239
+ const beforeLegacyStatus = fs.readFileSync(legacyFile, 'utf8');
240
+ const legacyStatus = compat.status({ codexHome: legacyHome });
241
+ assert.strictEqual(legacyStatus.installed, false);
242
+ assert.deepStrictEqual(legacyStatus.legacyTierRouterHooks, [direct, legacyWindows, direct]);
243
+ assert.strictEqual(fs.readFileSync(legacyFile, 'utf8'), beforeLegacyStatus);
244
+
245
+ const legacyInstall = compat.install({ allowUnreleasedSource: true, codexHome: legacyHome });
246
+ assert.deepStrictEqual(legacyInstall.legacyTierRouterHooks, legacyStatus.legacyTierRouterHooks);
247
+ assert.deepStrictEqual(compat.status({ codexHome: legacyHome }).legacyTierRouterHooks, legacyStatus.legacyTierRouterHooks);
248
+
249
+ const migration = spawnSync(process.execPath, [
250
+ path.join(__dirname, '..', 'bin', 'cli.js'), 'codex-hooks', 'install',
251
+ '--codex-home', legacyHome, '--allow-unreleased-source', '--remove-legacy-tier-router',
252
+ ], { encoding: 'utf8', timeout: 30000 });
253
+ assert.strictEqual(migration.status, 0, migration.stderr || String(migration.error));
254
+ assert.strictEqual(JSON.parse(migration.stdout).removedLegacyTierRouterHooks, 3);
255
+ const migrated = read(legacyFile);
256
+ assert.deepStrictEqual(migrated.hooks.UserPromptSubmit[0], preserved);
257
+ assert.deepStrictEqual(migrated.hooks.Stop[0], otherEvent);
258
+ const promptCommands = migrated.hooks.UserPromptSubmit.slice(1).flatMap(group => group.hooks);
259
+ assert.deepStrictEqual(promptCommands.map(hook => path.posix.basename(hook.command).replace(/"$/, '')),
260
+ ['codex-user-prompt.js', 'observation-hook.js']);
261
+ assert.strictEqual(fs.readFileSync(legacyConfigFile, 'utf8'), configBefore);
262
+ const migratedStatus = compat.status({ codexHome: legacyHome });
263
+ assert.strictEqual(migratedStatus.healthy, true);
264
+ assert.deepStrictEqual(migratedStatus.legacyTierRouterHooks, []);
265
+ const retried = compat.install({ allowUnreleasedSource: true, codexHome: legacyHome, removeLegacyTierRouter: true });
266
+ assert.strictEqual(retried.removedLegacyTierRouterHooks, 0);
267
+ assert.deepStrictEqual(read(legacyFile), migrated);
268
+ console.log(' PASS opt-in migration removes only legacy prompt handlers, installs one adapter, and is idempotent (#457)');
269
+
218
270
  const forgedManifestHome = path.join(root, 'forged-manifest-codex');
219
271
  fs.mkdirSync(forgedManifestHome, { recursive: true });
220
272
  fs.writeFileSync(path.join(forgedManifestHome, 'hooks.json'),
@@ -241,7 +293,9 @@ try {
241
293
  fs.mkdirSync(failedInstallHome, { recursive: true });
242
294
  const failedInstallHooks = path.join(failedInstallHome, 'hooks.json');
243
295
  fs.writeFileSync(failedInstallHooks,
244
- JSON.stringify({ description: 'must survive', hooks: { PreToolUse: [userHook] } }, null, 4) + '\n',
296
+ JSON.stringify({ description: 'must survive', hooks: {
297
+ PreToolUse: [userHook], UserPromptSubmit: [{ hooks: [legacyWindows] }],
298
+ } }, null, 4) + '\n',
245
299
  'utf8');
246
300
  const failedInstallBefore = fs.readFileSync(failedInstallHooks, 'utf8');
247
301
  const failedManifestPath = path.join(
@@ -254,7 +308,7 @@ try {
254
308
  }
255
309
  return realRenameSync(source, destination);
256
310
  };
257
- try { compat.install({ allowUnreleasedSource: true, codexHome: failedInstallHome }); }
311
+ try { compat.install({ allowUnreleasedSource: true, codexHome: failedInstallHome, removeLegacyTierRouter: true }); }
258
312
  catch (error) { failedInstallRefused = /injected manifest commit failure/.test(error.message); }
259
313
  finally { fs.renameSync = realRenameSync; }
260
314
  check(failedInstallRefused &&
@@ -42,7 +42,7 @@ if (fs.existsSync(pluginManifestFile)) {
42
42
  }
43
43
 
44
44
  helper.check(
45
- '2n. the plugin ships as a single self-contained module (installable by copying one file)',
45
+ '2n. the V1 enforcement factory remains in the plugin entrypoint',
46
46
  fs.existsSync(pluginFile) && !/require\(['"]\.\//.test(fs.readFileSync(pluginFile, 'utf8')),
47
47
  `${pluginFile} missing or imports a sibling file`
48
48
  );
@@ -12,9 +12,11 @@ console.log('\n[2p] opencode 2.x default-export entrypoint: registration and fir
12
12
  // V2 adapter that the real host actually loads.
13
13
 
14
14
  helper.check(
15
- '2p. the plugin ships as a single self-contained module',
16
- fs.existsSync(path.join(helper.root, 'opencode-plugin', 'index.mjs')),
17
- 'index.mjs missing'
15
+ '2p. the plugin entrypoint resolves the canonical router and observations runtime from the source checkout',
16
+ fs.existsSync(path.join(helper.root, 'opencode-plugin', 'index.mjs'))
17
+ && fs.existsSync(path.join(helper.root, 'harness-everything', 'scripts', 'kernel-router.js'))
18
+ && fs.existsSync(path.join(helper.root, 'hooks', 'scripts', 'lib', 'observations.js')),
19
+ 'plugin entrypoint or shared runtime missing'
18
20
  );
19
21
 
20
22
  (async () => {
@@ -41,6 +43,7 @@ helper.check(
41
43
 
42
44
  const prompts = [];
43
45
  const registered = [];
46
+ const sessionHooks = [];
44
47
  let subscribeCount = 0;
45
48
  const eventQueue = [];
46
49
  const fakeCtx = {
@@ -52,10 +55,16 @@ helper.check(
52
55
  },
53
56
  },
54
57
  session: {
58
+ get: async ({ sessionID }) => ({ id: sessionID, location: { directory: workspace } }),
55
59
  prompt: async (input) => {
56
60
  prompts.push(input);
57
61
  return {};
58
62
  },
63
+ hook: async (name, callback) => {
64
+ sessionHooks.push({ name, callback });
65
+ return { dispose: async () => {} };
66
+ },
67
+ context: async () => [],
59
68
  },
60
69
  event: {
61
70
  subscribe: (options) => {
@@ -108,6 +117,12 @@ helper.check(
108
117
  JSON.stringify(registered.map((r) => r.name))
109
118
  );
110
119
 
120
+ helper.check(
121
+ '2p. setup registers documented prompt admission and model context hooks',
122
+ sessionHooks.some((r) => r.name === 'prompt') && sessionHooks.some((r) => r.name === 'context'),
123
+ JSON.stringify(sessionHooks.map((r) => r.name))
124
+ );
125
+
111
126
  helper.check('2p. setup subscribes to the event stream exactly once', subscribeCount === 1, `subscribes: ${subscribeCount}`);
112
127
 
113
128
  const before = registered.find((r) => r.name === 'execute.before').callback;
@@ -161,11 +161,16 @@ const helper = require('./test-helper');
161
161
 
162
162
  // The V2 adapter must keep consuming reset/delete events while idle
163
163
  // verification is pending, and its disposer must await child cleanup.
164
- const queue = [], registrations = new Map();
164
+ const queue = [], registrations = new Map(), sessionHooks = new Map();
165
165
  const dispose = await mod.default.setup({
166
166
  location: { directory: workspace },
167
167
  tool: { hook: async (name, callback) => { registrations.set(name, callback); } },
168
- session: { prompt: async value => { prompts.push(value.text); } },
168
+ session: {
169
+ get: async ({ sessionID }) => ({ id: sessionID, location: { directory: workspace } }),
170
+ hook: async (name, callback) => { sessionHooks.set(name, callback); return { dispose: async () => {} }; },
171
+ prompt: async value => { prompts.push(value.text); },
172
+ context: async () => [],
173
+ },
169
174
  event: { subscribe: async function* ({ signal }) {
170
175
  while (!signal.aborted) {
171
176
  if (queue.length) yield queue.shift();
@@ -196,9 +201,21 @@ const helper = require('./test-helper');
196
201
  queue.push({ type: 'session.idle', sessionID: 'v2-disposed' });
197
202
  await waitFor(() => fs.existsSync(v2Ready));
198
203
  await dispose();
204
+ const v2DisposedDir = path.join(sessions, 'v2-disposed');
205
+ const disposeStateFiles = ['edit-state.json', 'circuit-breaker.json', 'compliance.json']
206
+ .map(name => path.join(v2DisposedDir, name));
207
+ const stateAtDispose = disposeStateFiles.map(file => fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : null);
199
208
  const stopped = fs.statSync(v2Heartbeat).size;
200
209
  await new Promise(resolve => setTimeout(resolve, 150));
201
- helper.check('338. V2 disposal waits for active child cleanup without a stale follow-up', fs.statSync(v2Heartbeat).size === stopped && prompts.length === beforeConcurrent);
210
+ const stateStable = disposeStateFiles.every((file, index) =>
211
+ (fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : null) === stateAtDispose[index]);
212
+ const editAtDispose = JSON.parse(stateAtDispose[0]);
213
+ const complianceAtDispose = JSON.parse(stateAtDispose[2]);
214
+ helper.check('338. V2 disposal waits for active child cleanup without late follow-up, breaker, or compliance writes',
215
+ fs.statSync(v2Heartbeat).size === stopped && prompts.length === beforeConcurrent && stateStable
216
+ && editAtDispose.verificationPending === true && editAtDispose.followUpPending === false
217
+ && complianceAtDispose.verifiedEdits === 0 && complianceAtDispose.circuitBreakerTrips === 0,
218
+ JSON.stringify({ stateStable, editAtDispose, complianceAtDispose, prompts: prompts.length - beforeConcurrent }));
202
219
  // A new idle can arrive while an edit-cancelled child is still being reaped.
203
220
  // That idle must verify the newer revision after cleanup, rather than vanish.
204
221
  fs.unlinkSync(path.join(workspace, 'ready.txt'));
@@ -143,11 +143,17 @@ function createEventStream() {
143
143
  async function startPlugin(workspace) {
144
144
  const plugin = await import(pathToFileURL(path.join(ROOT, 'opencode-plugin/index.mjs')).href);
145
145
  const registered = new Map();
146
+ const sessionHooks = new Map();
146
147
  const stream = createEventStream();
147
148
  const dispose = await plugin.default.setup({
148
149
  location: { directory: workspace },
149
150
  tool: { hook: async (name, callback) => registered.set(name, callback) },
150
- session: { prompt: async () => ({}) },
151
+ session: {
152
+ get: async ({ sessionID }) => ({ id: sessionID, location: { directory: workspace } }),
153
+ hook: async (name, callback) => { sessionHooks.set(name, callback); return { dispose: async () => {} }; },
154
+ prompt: async () => ({}),
155
+ context: async () => [],
156
+ },
151
157
  event: { subscribe: ({ signal }) => stream.subscribe(signal) },
152
158
  });
153
159
  return { registered, stream, dispose };
@@ -11,7 +11,6 @@ const { classifyPaths, classifyChangeSet } = require('../scripts/ci-change-scope
11
11
 
12
12
  const ROOT = path.resolve(__dirname, '..');
13
13
  const SCRIPT = path.join(ROOT, 'scripts', 'ci-change-scope.js');
14
- const BASELINE_SHA = '71a8706061f2fdec657b1c2b348571aa6c40e877';
15
14
  const CHANGE_SCOPE_JOB = 'ci-change-scope';
16
15
  const SELF_REGRESSION_IF = "${{ !cancelled() && (needs.ci-change-scope.result != 'success' || needs.ci-change-scope.outputs.scope != 'docs-only') }}";
17
16
 
@@ -42,16 +41,79 @@ function runClassifier(event, base, head, cwd = ROOT) {
42
41
  return result.stdout.trim();
43
42
  }
44
43
 
45
- function baselineFile(file) {
46
- // Pin the pre-change tree; GitHub's pull_request HEAD is the candidate merge ref.
47
- return execFileSync('git', ['show', `${BASELINE_SHA}:${file}`], { cwd: ROOT, encoding: 'utf8' });
48
- }
49
-
50
44
  // This models the condition's truth table, not GitHub's scheduler.
51
45
  function shouldRunSelfRegression(workflowCancelled, result, scope) {
52
46
  return !workflowCancelled && (result !== 'success' || scope !== 'docs-only');
53
47
  }
54
48
 
49
+ // Assert the intended scope-gating invariants against parsed workflow documents.
50
+ // Taking documents (not git history or whole-file text) keeps unrelated CI edits
51
+ // green and lets the oracle be replayed against mutated copies of the YAML.
52
+ function assertScopeGating({ ci, release, governance }) {
53
+ const jobs = ci.jobs;
54
+ const classifier = jobs[CHANGE_SCOPE_JOB];
55
+ const selfRegression = jobs['self-regression'];
56
+ assert.ok(classifier, 'the ci-change-scope job exists');
57
+ assert.ok(selfRegression, 'the self-regression job exists');
58
+
59
+ // Only self-regression may be gated by the classifier. Other jobs, their
60
+ // steps and later added ungated jobs are deliberately left unpinned.
61
+ for (const [jobId, job] of Object.entries(jobs)) {
62
+ if (jobId === CHANGE_SCOPE_JOB || jobId === 'self-regression') continue;
63
+ assert.ok(!Object.hasOwn(job, 'if'), `${jobId} must not be gated`);
64
+ }
65
+
66
+ // The classifier runs only on pull requests and wires its scope output.
67
+ assert.equal(classifier.if, "${{ github.event_name == 'pull_request' }}");
68
+ assert.deepEqual(classifier.outputs, { scope: '${{ steps.scope.outputs.scope }}' });
69
+ const checkout = classifier.steps.find(step => step.uses === 'actions/checkout@v7');
70
+ assert.ok(checkout, 'the classifier checks out the repository');
71
+ assert.equal(checkout.with['fetch-depth'], 0, 'the classifier has complete Git history');
72
+ const node = classifier.steps.find(step => step.uses === 'actions/setup-node@v7');
73
+ assert.ok(node, 'the classifier sets up Node');
74
+ assert.equal(node.with['node-version'], 24);
75
+ const scope = classifier.steps.find(step => step.id === 'scope');
76
+ assert.ok(scope, 'the classifier produces the scope output');
77
+ assert.equal(scope.env.GITHUB_EVENT_NAME, undefined, 'the runner-provided GITHUB_EVENT_NAME is not overwritten');
78
+ assert.equal(scope.env.PR_BASE_SHA, '${{ github.event.pull_request.base.sha }}');
79
+ assert.equal(scope.env.PR_HEAD_SHA, '${{ github.event.pull_request.head.sha }}');
80
+ assert.match(scope.run, /node scripts\/ci-change-scope\.js "\$GITHUB_EVENT_NAME" "\$PR_BASE_SHA" "\$PR_HEAD_SHA"/);
81
+ assert.match(scope.run, /printf 'scope=%s\\n' "\$scope" >> "\$GITHUB_OUTPUT"/);
82
+
83
+ // Self-regression depends on the classifier and keeps the exact predicate.
84
+ assert.deepEqual(selfRegression.needs, [CHANGE_SCOPE_JOB]);
85
+ assert.equal(selfRegression.if, SELF_REGRESSION_IF, 'the full fallback predicate stays exact');
86
+ assert.ok(selfRegression.if.includes('!cancelled()'), 'workflow cancellation must disable self-regression');
87
+ assert.ok(!selfRegression.if.includes('always()'), 'always() keeps self-regression eligible during cancellation');
88
+
89
+ // The three-OS matrix stays complete.
90
+ assert.equal(selfRegression.strategy['fail-fast'], false);
91
+ assert.deepEqual(selfRegression.strategy.matrix.os, ['ubuntu-latest', 'windows-latest', 'macos-latest']);
92
+
93
+ // No workflow-level path filter may narrow what the classifier sees.
94
+ assert.ok(ci.on && Object.hasOwn(ci.on, 'push') && Object.hasOwn(ci.on, 'pull_request') &&
95
+ Object.hasOwn(ci.on, 'workflow_call'), 'push, pull_request and workflow_call triggers stay present');
96
+ const events = [ci.on, ci.on.push];
97
+ if (ci.on.pull_request && typeof ci.on.pull_request === 'object') events.push(ci.on.pull_request);
98
+ for (const event of events) {
99
+ assert.ok(!Object.hasOwn(event, 'paths'), 'no workflow-level paths filter');
100
+ assert.ok(!Object.hasOwn(event, 'paths-ignore'), 'no workflow-level paths-ignore filter');
101
+ }
102
+
103
+ // The reusable callers stay ungated, including any job added later.
104
+ assert.deepEqual(release.on.push.branches, ['main']);
105
+ assert.ok(Object.hasOwn(release.on, 'workflow_dispatch'));
106
+ assert.equal(release.jobs.gate.uses, './.github/workflows/ci.yml');
107
+ for (const [label, doc] of [['release.yml', release], ['doc-governance.yml', governance]]) {
108
+ assert.ok(doc && doc.jobs, `${label} declares jobs`);
109
+ for (const [jobId, job] of Object.entries(doc.jobs)) {
110
+ assert.ok(!Object.hasOwn(job, 'if'), `${label} job ${jobId} must not be gated`);
111
+ const needs = Array.isArray(job.needs) ? job.needs : job.needs ? [job.needs] : [];
112
+ assert.ok(!needs.includes(CHANGE_SCOPE_JOB), `${label} job ${jobId} must not depend on the classifier`);
113
+ }
114
+ }
115
+ }
116
+
55
117
  test('each owner-approved path class and their combination classify as docs-only', () => {
56
118
  for (const file of [
57
119
  'docs/guide.md',
@@ -183,49 +245,12 @@ test('real Git merge-base diff includes earlier code, deletions, both rename end
183
245
  });
184
246
 
185
247
  test('the workflow gates only self-regression and fails open on every uncertain dependency/output state', () => {
186
- const workflowFile = '.github/workflows/ci.yml';
187
- const workflowText = fs.readFileSync(path.join(ROOT, workflowFile), 'utf8');
188
- const beforeText = baselineFile(workflowFile);
189
- const workflow = yaml.load(workflowText);
190
- const before = yaml.load(beforeText);
191
-
192
- assert.equal(workflow.name, before.name);
193
- assert.deepEqual(workflow.on, before.on, 'push, pull_request, and reusable-workflow triggers stay unchanged');
194
- assert.deepEqual(workflow.permissions, before.permissions);
195
- assert.deepEqual(workflow.concurrency, before.concurrency);
196
- assert.deepEqual(
197
- Object.keys(workflow.jobs).sort(),
198
- [...Object.keys(before.jobs), CHANGE_SCOPE_JOB].sort(),
199
- 'only the classifier job is added; existing job ids remain present',
200
- );
201
- for (const [jobId, original] of Object.entries(before.jobs)) {
202
- const current = workflow.jobs[jobId];
203
- if (jobId === 'self-regression') {
204
- const { if: _condition, needs: _needs, ...unchanged } = current;
205
- assert.deepEqual(unchanged, original, 'self-regression name, matrix, steps, and runtime stay unchanged');
206
- } else {
207
- assert.deepEqual(current, original, `${jobId} stays unchanged`);
208
- }
209
- }
210
-
211
- const classifier = workflow.jobs[CHANGE_SCOPE_JOB];
212
- assert.equal(classifier.if, "${{ github.event_name == 'pull_request' }}");
213
- assert.deepEqual(classifier.outputs, { scope: '${{ steps.scope.outputs.scope }}' });
214
- const checkout = classifier.steps.find(step => step.uses === 'actions/checkout@v7');
215
- assert.equal(checkout.with['fetch-depth'], 0, 'the classifier has complete Git history');
216
- const node = classifier.steps.find(step => step.uses === 'actions/setup-node@v7');
217
- assert.equal(node.with['node-version'], 24);
218
- const scope = classifier.steps.find(step => step.id === 'scope');
219
- assert.equal(scope.env.GITHUB_EVENT_NAME, undefined, 'the runner-provided GITHUB_EVENT_NAME is not overwritten');
220
- assert.equal(scope.env.PR_BASE_SHA, '${{ github.event.pull_request.base.sha }}');
221
- assert.equal(scope.env.PR_HEAD_SHA, '${{ github.event.pull_request.head.sha }}');
222
- assert.match(scope.run, /node scripts\/ci-change-scope\.js "\$GITHUB_EVENT_NAME" "\$PR_BASE_SHA" "\$PR_HEAD_SHA"/);
223
- assert.match(scope.run, /printf 'scope=%s\\n' "\$scope" >> "\$GITHUB_OUTPUT"/);
224
- const selfRegressionIf = workflow.jobs['self-regression'].if;
225
- assert.ok(selfRegressionIf.includes('!cancelled()'), 'workflow cancellation must disable self-regression');
226
- assert.ok(!selfRegressionIf.includes('always()'), 'always() keeps self-regression eligible during cancellation');
227
- assert.equal(selfRegressionIf, SELF_REGRESSION_IF, 'the full fallback predicate stays exact');
228
- assert.deepEqual(workflow.jobs['self-regression'].needs, [CHANGE_SCOPE_JOB]);
248
+ const readWorkflow = file => yaml.load(fs.readFileSync(path.join(ROOT, file), 'utf8'));
249
+ assertScopeGating({
250
+ ci: readWorkflow('.github/workflows/ci.yml'),
251
+ release: readWorkflow('.github/workflows/release.yml'),
252
+ governance: readWorkflow('.github/workflows/doc-governance.yml'),
253
+ });
229
254
 
230
255
  const gateCases = [
231
256
  ['successful docs-only classifier', false, 'success', 'docs-only', false],
@@ -244,17 +269,13 @@ test('the workflow gates only self-regression and fails open on every uncertain
244
269
  assert.equal(shouldRunSelfRegression(workflowCancelled, result, output), expected, label);
245
270
  }
246
271
 
247
- const releaseFile = '.github/workflows/release.yml';
248
- const governanceFile = '.github/workflows/doc-governance.yml';
249
- assert.equal(fs.readFileSync(path.join(ROOT, releaseFile), 'utf8'), baselineFile(releaseFile));
250
- assert.equal(fs.readFileSync(path.join(ROOT, governanceFile), 'utf8'), baselineFile(governanceFile));
251
- const release = yaml.load(fs.readFileSync(path.join(ROOT, releaseFile), 'utf8'));
252
- assert.deepEqual(release.on.push.branches, ['main']);
253
- assert.ok(Object.hasOwn(release.on, 'workflow_dispatch'));
254
- assert.equal(release.jobs.gate.uses, './.github/workflows/ci.yml');
255
272
  assert.equal(classifyChangeSet('push', 'a'.repeat(40), 'b'.repeat(40), { runGit: unusedGitForWorkflow }), 'full');
256
273
  });
257
274
 
258
275
  function unusedGitForWorkflow() {
259
276
  throw new Error('the release caller is a push/dispatch, so no PR diff may authorize a skip');
260
277
  }
278
+
279
+ // Exported so the in-report mutant harness can replay the same oracle against
280
+ // parsed copies of the workflow documents without registering these tests.
281
+ module.exports = { assertScopeGating };