harness-everything 0.55.4 → 0.56.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.
@@ -0,0 +1,41 @@
1
+ # C8 — Level 2 Action Map (single-run dispatch)
2
+
3
+ > **Implemented coordinator CLI; not a shared launcher.** C8 is a supporting identity under E · Treat. It adds no Level 1 branch, hook, or distributed plugin command. The [Level 3 contract](../details/c8-dispatch-cli.md) owns concrete options and return codes.
4
+
5
+ One invocation selects one runner and model, checks readiness, executes once, and validates fresh delivery.
6
+
7
+ ```mermaid
8
+ flowchart TD
9
+ INPUT["Coordinator supplies runner, model, packet, worktree, scratch and report"] --> VALID{"Inputs valid?"}
10
+ VALID -->|"no"| REFUSE["10 INVALID_INPUT / 11 UNSAFE_SCRATCH"]
11
+ VALID -->|"yes"| READY["Probe the selected runner"]
12
+ READY --> READY_RESULT{"Readiness result?"}
13
+ READY_RESULT -->|"provider throttling"| RATE_LIMITED["13 RUNNER_RATE_LIMITED; no run"]
14
+ READY_RESULT -->|"explicit usage or quota exhaustion"| QUOTA["13 RUNNER_QUOTA; no run"]
15
+ READY_RESULT -->|"missing, other failure, timed out or no READY"| NOT_READY["12 NOT_READY; no run"]
16
+ READY_RESULT -->|"READY"| RUN["Execute once; no retry or fallback"]
17
+ RUN --> RUN_RESULT{"Execution result?"}
18
+ RUN_RESULT -->|"failure or timeout"| RUN_FAILED["15 RUN_FAILED / RUN_TIMEOUT"]
19
+ RUN_RESULT -->|"success"| REPORT{"Fresh report validates?"}
20
+ REPORT -->|"no"| INVALID["16 REPORT_INVALID"]
21
+ REPORT -->|"valid BLOCKED"| BLOCKED["17 WORKER_BLOCKED; preserve reason"]
22
+ REPORT -->|"valid DONE"| DONE["0 DONE"]
23
+ ```
24
+
25
+ ## Coordinator behavior
26
+
27
+ - Choose the runner and its model explicitly. A throttling result says “Reduce concurrency on the affected key or retry later.” A quota result says “Select an authorized runner or model with available quota.” The CLI never switches runners or retries.
28
+ - Other readiness failures return `12 NOT_READY` with “Readiness failed. Keep the available child evidence.” and start no execution.
29
+ - Keep packet and worktree selection with the coordinator. Scratch must be absolute and outside every Git repository or worktree, including linked worktrees and symlinked ancestors.
30
+ - Use `--dry-run` to validate and inspect the planned argv and cwd. It starts no child and creates no scratch or report.
31
+ - Treat readiness, execution, and report validation as separate outcomes. A zero runner exit does not create a DONE report.
32
+ - Codex raw output goes through the report writer. The writer strips a valid terminal host label and checks the final report. OpenCode must create a fresh report that passes the same check.
33
+ - Deliver logs and raw Codex output for failed attempts. Do not present an unvalidated OpenCode file as a completed report.
34
+
35
+ ## Evidence boundary
36
+
37
+ The OpenCode ANSI `Error:` stderr envelope and exit 1 are live-traced. The provider 429 body is from the retained OpenCode log, and a live 429 reproduction remains unchecked. OpenCode usage/quota cause text is also retained log evidence. Codex classification rows are fixture-only; no live Codex 429 or usage-limit trace is claimed.
38
+
39
+ ## Boundary
40
+
41
+ This single-run CLI does not select scratch automatically, manage its lifecycle, enforce launch-path policy, reserve or cap provider keys, or reject packets that need worker `gh`/network access. Those guarantees belong to #466. No live provider run or packaged plugin command is claimed here.
@@ -0,0 +1,75 @@
1
+ # C8 — Level 3 single-run dispatch CLI contract
2
+
3
+ This detail implements the C8 action map for one coordinator-selected runner attempt. It does not provide launcher policy or a live provider integration.
4
+
5
+ ## Invocation
6
+
7
+ ```sh
8
+ npm run --silent dispatch -- --runner <codex|opencode> --model <id> \
9
+ --packet <path> --worktree <git-root> --scratch <absolute-external-path> \
10
+ --report <path> [--dry-run] [--json]
11
+ ```
12
+
13
+ `node scripts/dispatch.js` accepts the same options. `--help` prints this short synopsis. The coordinator supplies every value; packet and report paths may be relative to the worktree or absolute. The worktree must be an existing Git root. Scratch must be absolute and outside every Git repository/worktree. A pre-existing report path is rejected as invalid input.
14
+
15
+ | Option | Meaning |
16
+ | --- | --- |
17
+ | `--runner` | Required explicit selection: `codex` or `opencode`. |
18
+ | `--model` | Required model id for that runner. |
19
+ | `--packet` | Required existing packet file, resolved from the worktree when relative. |
20
+ | `--worktree` | Required existing Git repository or worktree root; child cwd. |
21
+ | `--scratch` | Required absolute path outside all Git repository/worktree roots; child `TMPDIR`. |
22
+ | `--report` | Required fresh report path, resolved from the worktree when relative. |
23
+ | `--dry-run` | Validate inputs and return planned argv/cwd; no child or filesystem writes. |
24
+ | `--json` | Return one JSON object on stdout, including refusals. |
25
+ | `--help` | Return the short usage synopsis with exit 0. |
26
+
27
+ In JSON mode the common shape is `{ok, code, phase, message}` with resolved `runner`, `model`, and existing `evidence` paths when available. Dry run also returns `argv` and `cwd`; Codex's generated raw-output argument uses a `<run-id>` placeholder. Human-mode refusals go to stderr. Child logs and raw output stay in evidence files, not in the JSON result.
28
+
29
+ ## Exit and JSON codes
30
+
31
+ | Exit | JSON `code` | Meaning |
32
+ | --- | --- | --- |
33
+ | `0` | `HELP`, `DRY_RUN_OK`, `DONE` | Help, validated dry run, or a fresh validated DONE report. |
34
+ | `1` | `INTERNAL_ERROR` | Unexpected application failure outside a named phase result. |
35
+ | `10` | `INVALID_INPUT` | Bad/missing option, runner/model, packet/worktree, or a report path that already exists. |
36
+ | `11` | `UNSAFE_SCRATCH` | Scratch is relative, an existing scratch path is not a directory, or it is inside a Git repository/worktree. |
37
+ | `12` | `NOT_READY` | Selected executable is missing or readiness failed, timed out, or omitted `READY`. No run starts. |
38
+ | `13` | `RUNNER_RATE_LIMITED` | The selected runner's failed readiness stderr has a recognized provider throttling diagnostic. No run starts. |
39
+ | `13` | `RUNNER_QUOTA` | The selected runner's failed readiness stderr has an explicit usage/quota exhaustion diagnostic. No run starts. |
40
+ | `15` | `RUN_FAILED`, `RUN_TIMEOUT` | Execution could not start, returned nonzero, timed out, or failed during execution. |
41
+ | `16` | `REPORT_INVALID` | Fresh raw/report input is missing, stale delivery appeared before execution, the writer rejected input, or final validation failed. |
42
+ | `17` | `WORKER_BLOCKED` | A fresh report passed validation with terminal `STATUS: BLOCKED: <reason>`. The reason is retained. |
43
+
44
+ | Readiness code | Coordinator message |
45
+ | --- | --- |
46
+ | `RUNNER_RATE_LIMITED` | Reduce concurrency on the affected key or retry later. |
47
+ | `RUNNER_QUOTA` | Select an authorized runner or model with available quota. |
48
+ | `NOT_READY` | Readiness failed. Keep the available child evidence. |
49
+
50
+ ## Readiness classification and evidence
51
+
52
+ Classification requires a full runner-specific diagnostic line on the failed readiness child's stderr after ANSI stripping. Only a normal nonzero exit is eligible; zero exits, signals, timeouts, stdout, quoted text, a different envelope, and partial or bare `429` text do not receive provider credit. Everything else, including local/cache errors, invalid `--quota`, header timeout, or a missing/ambiguous diagnostic, returns `12 NOT_READY`. The JSON `code` distinguishes throttling from usage/quota exhaustion.
53
+
54
+ | Runner / outcome | Recognized stderr line | Evidence |
55
+ | --- | --- | --- |
56
+ | OpenCode provider rate limit | `Error: Provider request failed with HTTP 429: {"status":429,"title":"Too Many Requests"}` | The ANSI `Error:` stderr envelope and exit 1 are live-traced. The 429 body is from the retained OpenCode log; a live 429 reproduction remains unchecked. |
57
+ | OpenCode usage/quota exhaustion | `Error: Free usage limit reached. Free models work in OpenCode (https://opencode.ai); subscribe to OpenCode Go to keep going: https://opencode.ai/go` | The stderr envelope is live-traced; the cause is from the retained OpenCode log. |
58
+ | Codex provider rate limit | `ERROR: Provider request failed with HTTP 429: {"status":429,"title":"Too Many Requests"}` | Fixture-only; no retained live Codex 429 trace. |
59
+ | Codex usage/quota exhaustion | `ERROR: Free usage limit reached. Free models work in OpenCode (https://opencode.ai); subscribe to OpenCode Go to keep going: https://opencode.ai/go` | Fixture-only; no retained live Codex usage-limit trace. |
60
+
61
+ Each invocation uses one selected runner and one readiness attempt. A `12` or `13` refusal starts no execution, report writer, fallback, or retry; available child evidence remains available to the coordinator.
62
+
63
+ Codex writes raw output with `codex exec -o`; it must contain an explicit terminal DONE or BLOCKED status. `report-writer --from-codex-output` strips an optional valid terminal host label, writes the final report, and `report-writer check` validates it. OpenCode is asked to write the report path directly; the path must remain absent through readiness and the resulting file must pass `report-writer check`. A valid BLOCKED report returns 17. Failed execution returns 15 and preserves its logs/raw output; it may have changed the worktree.
64
+
65
+ ## Evidence boundary
66
+
67
+ | Layer | What it establishes | What it does not establish |
68
+ | --- | --- | --- |
69
+ | Fixture | The real Node entry with stubbed child runners exercises argv, cwd, closed stdin, readiness, quota, timeout, fresh delivery, report writing/checking, and exit/JSON outcomes. | No real provider behavior or live host behavior. |
70
+ | Checkout/package entry | The npm script invokes the checked-in entry, and documented options work through that entry; named repository gates validate local consistency and portability. | No installed npm tarball or distributed plugin integration. |
71
+ | Live (channel probe only) | `opencode run --auto -m <model>`, the exact C8 OpenCode readiness argv, against failing nvidia models on OpenCode 2.1.4 (2026-11-21): provider errors reach stderr as one ANSI `Error: <message>` line, exit 1, empty stdout. | Not a C8 dispatch: no live 429 or quota reproduction (the 429 and quota bodies come from the retained OpenCode log), no Codex provider call, no host dispatch or live report delivery. |
72
+
73
+ ## #466 boundary
74
+
75
+ #466 owns automatic `TMPDIR` selection and lifecycle, enforcement across launch paths, per-key admission/reservation, and refusing packets that declare worker `gh`/network needs. This CLI accepts coordinator-supplied inputs for one attempt and cannot certify those launcher guarantees. It also does not add a distributed plugin command or run a live provider.
@@ -1,5 +1,6 @@
1
1
  # Canonical Action identity source for the Error Handling map (#437 concept, #402 implementation).
2
2
  # A-G are drawing-local aliases, NOT identity or ordered numbering.
3
+ # H is the subordinate C8 dispatch identity under E · Treat; it adds no View 1 flow edge.
3
4
  # IDs use creation category/date/UUIDv4 and never change. Names can change independently.
4
5
  # status: proposed | accepted | retired.
5
6
  # links: Action-to-Action control flow of View 1 in README.md, where the path between the two
@@ -35,6 +36,10 @@ actions:
35
36
  identifier: ERR-20261112-5f7496e6-5e1a-4628-b818-5292dd011580
36
37
  name: Accept and retire
37
38
  status: proposed
39
+ H:
40
+ identifier: ERR-20261120-333c36f7-24f5-4523-b604-7be7981728e1
41
+ name: "One-shot runner dispatch"
42
+ status: proposed
38
43
  links:
39
44
  - { from: A, to: B }
40
45
  - { from: B, to: C }
@@ -6,7 +6,7 @@
6
6
 
7
7
  ## Identity source — reuse the existing Action table
8
8
 
9
- The [Action identity registry](./nodes.yaml) is the only proposed source for the seven existing Action identities. Their UUIDs and names are **not copied into this file**, so edits to Action identity do not require changing two registries. A–G are drawing-local aliases, never global identifiers.
9
+ The [Action identity registry](./nodes.yaml) is the only proposed source for the seven View 1 Action identities and the subordinate C8 dispatch identity H. Their UUIDs and names are **not copied into this file**, so edits to Action identity do not require changing two registries. A–G remain the View 1 drawing aliases; H adds no Level 1 flow edge.
10
10
 
11
11
  ## Table A — document registry (where to look)
12
12
 
@@ -31,6 +31,8 @@ The [Action identity registry](./nodes.yaml) is the only proposed source for the
31
31
  | `C6-template` | Template · packet briefing | [templates/packet-briefing.md](./templates/packet-briefing.md) | Copy per packet; every field filled or `N/A: <reason>` |
32
32
  | `C7-actions` | Level 2 · C7 write-set | [actions/c7-action-map.md](./actions/c7-action-map.md) | Did the slice stay inside its write-set |
33
33
  | `C7-detail` | Level 3 · C7 checker | [details/c7-write-set-check.md](./details/c7-write-set-check.md) | `scripts/check-packet-write-set.js`, run by the coordinator before accepting a slice |
34
+ | `C8-actions` | Level 2 · C8 single-run dispatch | [actions/c8-action-map.md](./actions/c8-action-map.md) | One coordinator-selected runner attempt and its outcomes |
35
+ | `C8-detail` | Level 3 · C8 CLI contract | [details/c8-dispatch-cli.md](./details/c8-dispatch-cli.md) | Invocation, exit/JSON behavior, evidence limits, and the #466 boundary |
34
36
 
35
37
  `Local reference` values are **table-local lookup keys only**, not new stable Action IDs, graph node identities, persistent state, or workflow instructions.
36
38
 
@@ -43,6 +45,7 @@ The [Action identity registry](./nodes.yaml) is the only proposed source for the
43
45
  | `E0002-actions` | `E0002-capture` | Detail supporting Capture / evidence | Read when raw evidence/provenance is required |
44
46
  | `E0002-actions` | `E0002-writer` | Detail supporting Treat / Report CLI | Read when producing or validating a report through the shipped W1 script |
45
47
  | `E0002-actions` | `E0002-ledger` | Existing class evidence / history | Read for Identify/history relevance; do not copy or reclassify the ledger |
48
+ | `C8-actions` | `C8-detail` | Concrete coordinator CLI contract | Read when invoking or verifying the single-run dispatch CLI |
46
49
 
47
50
  **Maintenance contract (lightweight):** when a document moves, update its **Table A path**; Table B continues to refer to the same local key. When a new Level 2 behavior block or Level 3 reference is added, add only the relevant row and reference. Removing an obsolete procedure removes its registry relationship without rewriting Level 1. **Do not re-encode Mermaid/PlantUML execution arrows as registry edges**: the source diagrams own flow semantics, while the tables own *navigation/lookup*.
48
51
 
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "harness-enforcement",
3
3
  "description": "Repository inventory for the opencode enforcement plugin and its standalone helper",
4
- "version": "0.55.4",
4
+ "version": "0.56.0",
5
5
  "runtime": "index.mjs",
6
6
  "hooks": {
7
7
  "verify": "hooks/verify.js"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "harness-everything",
3
- "version": "0.55.4",
3
+ "version": "0.56.0",
4
4
  "description": "Harness OS: An Orchestrated Agent Operating System for AI-driven Development",
5
5
  "main": "harness-everything/scripts/bootstrap.js",
6
6
  "bin": {
@@ -19,6 +19,7 @@
19
19
  "docs:sync": "node scripts/sync-current-docs.js",
20
20
  "errors:sync": "node scripts/errors-sync.js",
21
21
  "report": "node scripts/report-writer.js",
22
+ "dispatch": "node scripts/dispatch.js",
22
23
  "test:repo-contract": "node ci/repository-contract.test.js",
23
24
  "test:consistency": "node ci/consistency-check.js && node ci/doc-capability-consistency.test.js && node ci/repository-contract.test.js && node ci/mechanism-2ao-plugin-sync.test.js && node ci/prompt-contract-regressions.test.js",
24
25
  "test:docs:capabilities": "node ci/doc-capability-consistency.test.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "harness-everything",
3
- "version": "0.55.4",
3
+ "version": "0.56.0",
4
4
  "description": "Invariant-first engineering harness for routing, verification, and failure recovery while preserving agent autonomy.",
5
5
  "author": {
6
6
  "name": "Miya Daniel",
@@ -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.55.4",
4
+ "version": "0.56.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:c9ac3731-0280-5a2b-8070-86240b1f4efb",
5
+ "serialNumber": "urn:uuid:bc28802c-0dc6-530f-8e3d-ca93205aa25d",
6
6
  "version": 1,
7
7
  "metadata": {
8
- "timestamp": "2026-11-21T01:29:55.079Z",
8
+ "timestamp": "2026-11-21T02:57:26.008Z",
9
9
  "tools": [
10
10
  {
11
11
  "vendor": "Harness Everything",
12
12
  "name": "generate-sbom.js",
13
- "version": "0.55.4"
13
+ "version": "0.56.0"
14
14
  }
15
15
  ],
16
16
  "component": {
17
17
  "type": "application",
18
- "bom-ref": "pkg:npm/harness-everything@0.55.4",
18
+ "bom-ref": "pkg:npm/harness-everything@0.56.0",
19
19
  "name": "harness-everything",
20
- "version": "0.55.4",
21
- "purl": "pkg:npm/harness-everything@0.55.4"
20
+ "version": "0.56.0",
21
+ "purl": "pkg:npm/harness-everything@0.56.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.55.4",
2036
+ "ref": "pkg:npm/harness-everything@0.56.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,340 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const { spawnSync } = require('node:child_process');
5
+ const fs = require('node:fs');
6
+ const path = require('node:path');
7
+
8
+ const REPORT_WRITER = path.join(__dirname, 'report-writer.js');
9
+ const USAGE = 'Usage: dispatch --runner <codex|opencode> --model <id> --packet <path> --worktree <path> --scratch <absolute-path> --report <path> [--dry-run] [--json] [--help]';
10
+ const VALUE_OPTIONS = new Set(['--runner', '--model', '--packet', '--worktree', '--scratch', '--report']);
11
+ let evidencePaths = {};
12
+
13
+ class DispatchFailure extends Error {
14
+ constructor(exitCode, code, phase, message) {
15
+ super(message);
16
+ this.exitCode = exitCode;
17
+ this.code = code;
18
+ this.phase = phase;
19
+ }
20
+ }
21
+
22
+ function fail(exitCode, code, phase, message) {
23
+ throw new DispatchFailure(exitCode, code, phase, message);
24
+ }
25
+
26
+ function parseArgs(argv) {
27
+ const options = {};
28
+ for (let index = 0; index < argv.length; index += 1) {
29
+ const flag = argv[index];
30
+ if (flag === '--json' || flag === '--dry-run' || flag === '--help') {
31
+ if (options[flag]) fail(10, 'INVALID_INPUT', 'input', `duplicate option: ${flag}`);
32
+ options[flag] = true;
33
+ } else if (VALUE_OPTIONS.has(flag)) {
34
+ if (options[flag] !== undefined) fail(10, 'INVALID_INPUT', 'input', `duplicate option: ${flag}`);
35
+ const value = argv[index + 1];
36
+ if (!value || value.startsWith('--')) fail(10, 'INVALID_INPUT', 'input', `missing value for ${flag}`);
37
+ options[flag] = value;
38
+ index += 1;
39
+ } else {
40
+ fail(10, 'INVALID_INPUT', 'input', `unknown option: ${flag}`);
41
+ }
42
+ }
43
+ return options;
44
+ }
45
+
46
+ function realPath(file) {
47
+ try { return fs.realpathSync.native(file); } catch { return null; }
48
+ }
49
+
50
+ function hasGitMetadata(directory) {
51
+ try {
52
+ return fs.statSync(path.join(directory, 'HEAD')).isFile()
53
+ && fs.statSync(path.join(directory, 'objects')).isDirectory()
54
+ && fs.statSync(path.join(directory, 'refs')).isDirectory()
55
+ && fs.statSync(path.join(directory, 'config')).isFile();
56
+ } catch { return false; }
57
+ }
58
+
59
+ function isGitRoot(directory) {
60
+ const marker = path.join(directory, '.git');
61
+ try {
62
+ const stat = fs.statSync(marker);
63
+ if (stat.isDirectory()) return hasGitMetadata(marker);
64
+ if (stat.isFile()) {
65
+ const match = /^gitdir:\s*(.+)\s*$/i.exec(fs.readFileSync(marker, 'utf8'));
66
+ if (!match) return false;
67
+ const gitdir = path.resolve(directory, match[1]);
68
+ const commonFile = path.join(gitdir, 'commondir');
69
+ const commonDir = fs.existsSync(commonFile) ? path.resolve(gitdir, fs.readFileSync(commonFile, 'utf8').trim()) : gitdir;
70
+ return hasGitMetadata(commonDir);
71
+ }
72
+ } catch {}
73
+ return hasGitMetadata(directory);
74
+ }
75
+
76
+ function canonicalFuturePath(file) {
77
+ let ancestor = path.resolve(file);
78
+ const suffix = [];
79
+ while (!fs.existsSync(ancestor)) {
80
+ const parent = path.dirname(ancestor);
81
+ if (parent === ancestor) break;
82
+ suffix.unshift(path.basename(ancestor));
83
+ ancestor = parent;
84
+ }
85
+ const canonicalAncestor = realPath(ancestor);
86
+ return canonicalAncestor ? path.resolve(canonicalAncestor, ...suffix) : path.resolve(file);
87
+ }
88
+
89
+ function gitAncestor(directory) {
90
+ let current = directory;
91
+ while (true) {
92
+ if (isGitRoot(current)) return current;
93
+ const parent = path.dirname(current);
94
+ if (parent === current) return null;
95
+ current = parent;
96
+ }
97
+ }
98
+
99
+ function validateScratch(value) {
100
+ if (!path.isAbsolute(value)) fail(11, 'UNSAFE_SCRATCH', 'validation', 'scratch must be an absolute path outside every Git repository or worktree');
101
+ const scratch = canonicalFuturePath(value);
102
+ if (fs.existsSync(value) && !fs.statSync(value).isDirectory()) {
103
+ fail(11, 'UNSAFE_SCRATCH', 'validation', 'scratch must be a directory outside every Git repository or worktree');
104
+ }
105
+ const repository = gitAncestor(scratch);
106
+ if (repository) fail(11, 'UNSAFE_SCRATCH', 'validation', `scratch is inside a Git repository or worktree: ${repository}`);
107
+ return path.resolve(value);
108
+ }
109
+
110
+ function pathFrom(base, value) {
111
+ return path.resolve(base, value);
112
+ }
113
+
114
+ function validateInput(options) {
115
+ const runner = options['--runner'];
116
+ const model = options['--model'];
117
+ if (!['codex', 'opencode'].includes(runner)) fail(10, 'INVALID_INPUT', 'input', '--runner must be codex or opencode');
118
+ if (!model || !model.trim()) fail(10, 'INVALID_INPUT', 'input', '--model must be a nonempty id');
119
+ for (const flag of ['--packet', '--worktree', '--scratch', '--report']) {
120
+ if (!options[flag]) fail(10, 'INVALID_INPUT', 'input', `missing required option: ${flag}`);
121
+ }
122
+
123
+ const requestedWorktree = path.resolve(options['--worktree']);
124
+ const worktree = realPath(requestedWorktree);
125
+ if (!worktree || !fs.statSync(worktree).isDirectory() || !isGitRoot(worktree)) {
126
+ fail(10, 'INVALID_INPUT', 'input', '--worktree must name an existing Git repository or worktree root');
127
+ }
128
+ const packet = pathFrom(worktree, options['--packet']);
129
+ if (!fs.existsSync(packet) || !fs.statSync(packet).isFile()) fail(10, 'INVALID_INPUT', 'input', '--packet must name an existing file');
130
+ const report = pathFrom(worktree, options['--report']);
131
+ if (!fs.existsSync(path.dirname(report)) || !fs.statSync(path.dirname(report)).isDirectory()) {
132
+ fail(10, 'INVALID_INPUT', 'input', '--report parent directory must already exist');
133
+ }
134
+ if (fs.existsSync(report)) fail(10, 'INVALID_INPUT', 'input', '--report already exists; choose a fresh report path');
135
+ const scratch = validateScratch(options['--scratch']);
136
+ return { runner, model: model.trim(), packet, worktree, scratch, report };
137
+ }
138
+
139
+ function response(options, outcome, evidence = evidencePaths, input) {
140
+ const message = String(outcome.message || '').slice(0, 1000);
141
+ const result = {
142
+ ok: outcome.exitCode === 0,
143
+ code: outcome.code,
144
+ phase: outcome.phase,
145
+ message,
146
+ };
147
+ const runner = input?.runner ?? options['--runner'];
148
+ const model = input?.model ?? options['--model'];
149
+ if (runner === 'codex' || runner === 'opencode') result.runner = runner;
150
+ if (model) result.model = model;
151
+ if (outcome.argv) result.argv = outcome.argv;
152
+ if (outcome.cwd) result.cwd = outcome.cwd;
153
+ const paths = Object.fromEntries(Object.entries(evidence).filter(([, value]) => value && fs.existsSync(value)));
154
+ if (Object.keys(paths).length) result.evidence = paths;
155
+ if (options['--json']) process.stdout.write(`${JSON.stringify(result)}\n`);
156
+ else if (outcome.exitCode === 0) process.stdout.write(`${message}\n`);
157
+ else process.stderr.write(`dispatch: ${message}\n`);
158
+ process.exitCode = outcome.exitCode;
159
+ }
160
+
161
+ function childTimeout(timeout) {
162
+ // Keep fixture timeout cases bounded while production retains its fixed limits.
163
+ const testTimeout = Number(process.env.DISPATCH_TEST_TIMEOUT_MS);
164
+ return process.env.NODE_ENV === 'test' && Number.isSafeInteger(testTimeout) && testTimeout > 0
165
+ ? Math.min(timeout, testTimeout)
166
+ : timeout;
167
+ }
168
+
169
+ function runChild(command, args, worktree, scratch, logPath, timeout, appendLog = false) {
170
+ const result = spawnSync(command, args, {
171
+ cwd: worktree,
172
+ env: { ...process.env, TMPDIR: scratch },
173
+ encoding: 'utf8',
174
+ stdio: ['ignore', 'pipe', 'pipe'],
175
+ timeout: childTimeout(timeout),
176
+ maxBuffer: 16 * 1024 * 1024,
177
+ });
178
+ const stdout = result.stdout || '';
179
+ const stderr = result.stderr || '';
180
+ const log = `${stdout}${stderr ? `${stdout ? '\n' : ''}[stderr]\n${stderr}` : ''}`;
181
+ if (appendLog) fs.appendFileSync(logPath, log);
182
+ else fs.writeFileSync(logPath, log);
183
+ return { ...result, stdout, stderr };
184
+ }
185
+
186
+ function runnerArgs(input, prompt, outputPath) {
187
+ if (input.runner === 'codex') {
188
+ return ['exec', '-m', input.model, '-s', 'workspace-write', '-C', input.worktree, '-o', outputPath, prompt];
189
+ }
190
+ return ['run', '--auto', '-m', input.model, prompt];
191
+ }
192
+
193
+ const READINESS_DIAGNOSTICS = {
194
+ codex: [
195
+ { line: 'ERROR: Provider request failed with HTTP 429: {"status":429,"title":"Too Many Requests"}', code: 'RUNNER_RATE_LIMITED', message: 'Reduce concurrency on the affected key or retry later.' },
196
+ { line: 'ERROR: Free usage limit reached. Free models work in OpenCode (https://opencode.ai); subscribe to OpenCode Go to keep going: https://opencode.ai/go', code: 'RUNNER_QUOTA', message: 'Select an authorized runner or model with available quota.' },
197
+ ],
198
+ opencode: [
199
+ { line: 'Error: Provider request failed with HTTP 429: {"status":429,"title":"Too Many Requests"}', code: 'RUNNER_RATE_LIMITED', message: 'Reduce concurrency on the affected key or retry later.' },
200
+ { line: 'Error: Free usage limit reached. Free models work in OpenCode (https://opencode.ai); subscribe to OpenCode Go to keep going: https://opencode.ai/go', code: 'RUNNER_QUOTA', message: 'Select an authorized runner or model with available quota.' },
201
+ ],
202
+ };
203
+
204
+ function readinessDiagnostic(runner, stderr) {
205
+ const output = stderr.replace(/\u001b\[[0-?]*[ -/]*[@-~]/g, '');
206
+ const lines = output.split(/\r?\n/);
207
+ const matches = READINESS_DIAGNOSTICS[runner].filter(diagnostic => lines.includes(diagnostic.line));
208
+ return matches.length === 1 ? matches[0] : null;
209
+ }
210
+
211
+ function readiness(input, paths) {
212
+ const outputPath = input.runner === 'codex' ? paths.readinessOutput : null;
213
+ const prompt = 'Reply exactly with READY.';
214
+ const result = runChild(input.runner, runnerArgs(input, prompt, outputPath), input.worktree, input.scratch, paths.readinessLog, 120000);
215
+ if (result.status !== 0) {
216
+ const diagnostic = Number.isInteger(result.status) && result.status !== 0 && !result.signal && !result.error
217
+ ? readinessDiagnostic(input.runner, result.stderr)
218
+ : null;
219
+ if (diagnostic) fail(13, diagnostic.code, 'readiness', diagnostic.message);
220
+ fail(12, 'NOT_READY', 'readiness', 'Readiness failed. Keep the available child evidence.');
221
+ }
222
+ const answer = input.runner === 'codex'
223
+ ? (fs.existsSync(outputPath) ? fs.readFileSync(outputPath, 'utf8').trim() : '')
224
+ : result.stdout.trim();
225
+ if (answer !== 'READY') fail(12, 'NOT_READY', 'readiness', 'Readiness failed. Keep the available child evidence.');
226
+ }
227
+
228
+ function reportedStatus(raw) {
229
+ const lines = raw.split(/\r?\n/);
230
+ if (lines.at(-1) === '') lines.pop();
231
+ if (lines.at(-1)?.startsWith('<!-- harness-label ')) lines.pop();
232
+ const line = lines.at(-1) || '';
233
+ if (line === 'STATUS: DONE') return { status: 'DONE' };
234
+ const blocked = /^STATUS: BLOCKED: (.+)$/.exec(line);
235
+ if (blocked && blocked[1].trim()) return { status: 'BLOCKED', reason: blocked[1].trim() };
236
+ fail(16, 'REPORT_INVALID', 'report', 'Codex output must end with STATUS: DONE or STATUS: BLOCKED: <reason>');
237
+ }
238
+
239
+ function reportWriter(input, paths, command, args) {
240
+ const result = runChild(process.execPath, [REPORT_WRITER, ...args], input.worktree, input.scratch, paths.writerLog, 120000, true);
241
+ if (result.status !== 0) fail(16, 'REPORT_INVALID', 'report', result.stderr.trim() || `${command} rejected the report`);
242
+ return result;
243
+ }
244
+
245
+ function executionPrompt(input) {
246
+ return input.runner === 'codex'
247
+ ? `Execute the packet at ${input.packet} and return the complete report body.`
248
+ : `Execute the packet at ${input.packet} and write the complete report to ${input.report}.`;
249
+ }
250
+
251
+ function execute(input, options) {
252
+ fs.mkdirSync(input.scratch, { recursive: true });
253
+ const runId = `${process.pid}-${Date.now()}`;
254
+ const paths = {
255
+ readinessOutput: path.join(input.scratch, `${runId}.readiness.txt`),
256
+ readinessLog: path.join(input.scratch, `${runId}.readiness.log`),
257
+ rawOutput: path.join(input.scratch, `${runId}.raw.txt`),
258
+ runLog: path.join(input.scratch, `${runId}.run.log`),
259
+ writerLog: path.join(input.scratch, `${runId}.report-writer.log`),
260
+ };
261
+ evidencePaths = {
262
+ readinessOutput: input.runner === 'codex' ? paths.readinessOutput : null,
263
+ readinessLog: paths.readinessLog,
264
+ rawOutput: input.runner === 'codex' ? paths.rawOutput : null,
265
+ runLog: paths.runLog,
266
+ reportWriterLog: paths.writerLog,
267
+ report: input.report,
268
+ };
269
+
270
+ readiness(input, paths);
271
+ if (fs.existsSync(input.report)) fail(16, 'REPORT_INVALID', 'report', 'report path was populated before execution; refusing stale delivery');
272
+ const prompt = executionPrompt(input);
273
+ const outputPath = input.runner === 'codex' ? paths.rawOutput : null;
274
+ const run = runChild(input.runner, runnerArgs(input, prompt, outputPath), input.worktree, input.scratch, paths.runLog, 2700000);
275
+ if (run.status !== 0) {
276
+ const timedOut = run.error?.code === 'ETIMEDOUT';
277
+ fail(15, timedOut ? 'RUN_TIMEOUT' : 'RUN_FAILED', 'execution', timedOut ? 'runner execution timed out' : `runner execution failed${run.error ? `: ${run.error.message}` : ''}`);
278
+ }
279
+
280
+ if (input.runner === 'codex') {
281
+ if (!fs.existsSync(paths.rawOutput) || fs.existsSync(input.report)) fail(16, 'REPORT_INVALID', 'report', 'fresh Codex output or report path is missing');
282
+ const status = reportedStatus(fs.readFileSync(paths.rawOutput, 'utf8'));
283
+ const writeArgs = ['write', '--from-codex-output', paths.rawOutput, '--output', input.report, '--status', status.status];
284
+ if (status.reason) writeArgs.push('--reason', status.reason);
285
+ reportWriter(input, paths, 'write', writeArgs);
286
+ } else if (!fs.existsSync(input.report)) {
287
+ fail(16, 'REPORT_INVALID', 'report', 'runner did not create a fresh report');
288
+ }
289
+
290
+ const checked = reportWriter(input, paths, 'check', ['check', '--file', input.report]);
291
+ if (/valid \(STATUS: BLOCKED: (.+)\)/.test(checked.stdout)) {
292
+ const reason = /valid \(STATUS: BLOCKED: (.+)\)/.exec(checked.stdout)[1];
293
+ fail(17, 'WORKER_BLOCKED', 'report', `worker delivered a valid BLOCKED report: ${reason}`);
294
+ }
295
+ response(options, {
296
+ exitCode: 0,
297
+ code: 'DONE',
298
+ phase: 'report',
299
+ message: `Dispatch completed and the report is valid: ${input.report}`,
300
+ }, evidencePaths, input);
301
+ }
302
+
303
+ function main() {
304
+ const argv = process.argv.slice(2);
305
+ const jsonRequested = argv.includes('--json');
306
+ let options = { '--json': jsonRequested };
307
+ let input;
308
+ evidencePaths = {};
309
+ try {
310
+ if (argv.includes('--help')) {
311
+ if (argv.some(arg => !['--help', '--json'].includes(arg))) fail(10, 'INVALID_INPUT', 'input', 'help cannot be combined with dispatch options');
312
+ options = { '--json': jsonRequested };
313
+ response(options, { exitCode: 0, code: 'HELP', phase: 'help', message: USAGE });
314
+ return;
315
+ }
316
+ options = parseArgs(argv);
317
+ input = validateInput(options);
318
+ if (options['--dry-run']) {
319
+ const outputPath = input.runner === 'codex' ? path.join(input.scratch, '<run-id>.raw.txt') : null;
320
+ response(options, {
321
+ exitCode: 0,
322
+ code: 'DRY_RUN_OK',
323
+ phase: 'dry-run',
324
+ message: `Validated ${input.runner} model ${input.model} for packet ${input.packet} in ${input.worktree}; scratch ${input.scratch}; report ${input.report}`,
325
+ argv: [input.runner, ...runnerArgs(input, executionPrompt(input), outputPath)],
326
+ cwd: input.worktree,
327
+ }, evidencePaths, input);
328
+ return;
329
+ }
330
+ execute(input, options);
331
+ } catch (cause) {
332
+ if (cause instanceof DispatchFailure) {
333
+ response(options, cause, evidencePaths, input);
334
+ return;
335
+ }
336
+ response(options, new DispatchFailure(1, 'INTERNAL_ERROR', 'application', cause.message || 'unexpected dispatch error'), evidencePaths, input);
337
+ }
338
+ }
339
+
340
+ main();