From 0851f188409df77164714dec78401f8f519f98a6 Mon Sep 17 00:00:00 2001 From: thxCode Date: Mon, 30 Nov 2026 18:39:40 +0800 Subject: [PATCH 01/26] docs(specs): specify Managed Controller in-process execution - Add command.v1 as a Managed Controller check under an explicit direct backend - Add the exec role adapter so loopwright run completes DAGs with local commands - Phase two: portable campaign snapshots and an in-process benchmark gate - Record boundaries, risks, alternatives, and open questions Signed-off-by: thxCode --- ...managed-controller-in-process-execution.md | 415 ++++++++++++++++++ 1 file changed, 415 insertions(+) create mode 100644 specs/2026-11-30-managed-controller-in-process-execution.md diff --git a/specs/2026-11-30-managed-controller-in-process-execution.md b/specs/2026-11-30-managed-controller-in-process-execution.md new file mode 100644 index 00000000..2d1a4f76 --- /dev/null +++ b/specs/2026-11-30-managed-controller-in-process-execution.md @@ -0,0 +1,415 @@ +# Spec: Managed Controller in-process execution: `command.v1` checks, exec roles, and portable campaign state + +Status: Specified +Type: Feature + +## Summary + +Let a Managed Controller run execute entirely on an already isolated host: a restricted Pod that +owns exactly one accelerator, has no Docker socket, no relay, and no provider credentials. +Add `command.v1` to the Managed Controller handler table so a protected script in the task +repository becomes the verifier, executed in the controller's own environment under an explicit +`direct` backend. Add an `exec` role adapter so `loopwright run` hands each agent step to a +local command and captures the overlay with the same scope and overlay checks as a delegated +submit. Keep the fencing authority, the `pi` adapter, and Taskpack mode unchanged. In a second +phase, make evolution campaigns portable (`evolve export --snapshot`, `evolve import`) and allow +`benchmark-gate.v1` to run in-process on a host that already owns the device. The first consumer +is the gpustack-operator `ModelDeploymentForger` sandbox runner (gpustack/forgevo). + +## Motivation + +### Goals + +1. **G1 · Unattended Managed Controller runs in an isolated container.** A run whose checks are + protected scripts and whose roles are local commands completes with `loopwright run` in a + `restricted` Pod: no Docker, no relay, no provider token in the Loopwright process. +2. **G2 · Evidence stays honest.** A `command.v1` check is `local_execution` evidence bound to + the candidate digest. An `exec` step's overlay passes `scope.v1`, overlay limits, and the + symlink, hard-link, and protected-path invariants that a delegated submit passes. +3. **G3 · No regression.** `pi` and `delegated` roles, Taskpack `command.v1`, lease fencing, + and the closure matrix keep their current behavior. New capability rows record only what + tests prove. +4. **G4 · Portable campaign state (phase 2).** A campaign archive exports to a verified, + self-contained snapshot and imports into a fresh `campaign.sqlite`, so a campaign can + continue across hosts without a remote database. +5. **G5 · In-process hardware gate (phase 2).** `benchmark-gate.v1` runs without a relay and a + Docker worker when the host already dedicates the device to the run. + +### Non-Goals + +- A remote state store (PostgreSQL, Redis, object storage) for run or campaign authority. The + local fenced SQLite store stays the authority ([ADR 0001](../docs/contribute/adr/0001-local-state-authority.md)). +- Shipping SQLite write-ahead logs or pages to object storage. +- Changing Taskpack mode's `command.v1`, its sandbox backends, or its host policy. +- Running the `pi` adapter without Docker, or on a profile other than `linux/arm64`. +- Mixing `delegated` and `exec` roles in one plan. +- Multi-host concurrent mutation of one campaign. +- Analytics exports (Parquet, JSONL) of run or campaign metrics. + +## Proposal + +### User Stories + +#### Story 1 + +As a sandbox runner author, I want the verifier to be a script committed under a protected path +of my task repository, so that compile, correctness, and timing run in the Pod's own toolchain +without an HTTP gate, a secret, or a listener. + +#### Story 2 + +As a sandbox runner author, I want Loopwright to start my author command for each agent step, +so that `loopwright run` completes the whole DAG unattended and my runner only renders +configuration and assembles outputs. + +#### Story 3 + +As a Loopwright operator on a laptop, I want the existing `pi`, `delegated`, and Taskpack paths +to behave exactly as before, so that this change costs me nothing until I opt in. + +#### Story 4 + +As a kernel engineer, I want a campaign to continue on the next host from a verified snapshot, +so that a bounded Pod lifetime does not reset the search. + +### Core Features & Acceptance Criteria + +#### F1. `command.v1` as a Managed Controller check handler (phase 1) + +`TrustedRegistry.spec.handlers[]` accepts `implementation: command.v1` with +`kind: check` and `capabilities: ['local_execution', 'read_only']`. + +- Parameters: `checkId` (identifier), `script` (repository-relative path), `args` (0..64 + strings), `env` (0..32 entries, names `^[A-Z][A-Z0-9_]{0,63}$`, `LOOPWRIGHT_*` names refused), + `toolchainPaths` (0..32 repository-relative paths), `networkMode` (`none` | `loopback-only`, + default `none`), `timeoutMs` (1000..3600000). +- `script` and every `toolchainPaths` entry must resolve inside `scope.protected` and must exist + in the repository at `target.sourceRevision`. The script file must carry the executable bit in + the committed tree. Unknown keys fail `CONFIG_SCHEMA`, as for every handler. +- Execution requires an explicit host-owned declaration: `spec.controls.localChecks: + { backend: direct }`. Without it, a registry that contains a `command.v1` handler fails + `check` with `CONFIG_SCHEMA`. Loopwright never detects or falls back to `direct`. +- `direct` means: the controller's own environment is the sandbox. The controller documents the + required host properties (single-tenant container or VM, no Docker socket, no shared writable + paths with untrusted processes) and refuses nothing else; the operator attests. +- Script contract (same names and semantics as Taskpack `command.v1`, see + [taskpack-and-contract-schema.md](../docs/references/taskpack-and-contract-schema.md)): + - The script's parent directory is available read-only with its whole-tree digest recorded in + the run lock. + - Environment: `PATH` defaults to `/usr/local/bin:/usr/bin:/bin` plus `toolchainPaths`; + `HOME` and `TMPDIR` point at a disposable scratch directory; `LANG=C.UTF-8`; `TERM=dumb`; + `LOOPWRIGHT_CANDIDATE_DIR` is a disposable materialization of the captured candidate, + writable during the check and discarded after it; `LOOPWRIGHT_BASE_DIR` is the read-only + baseline tree; `LOOPWRIGHT_STAGED_DIR` is the read-only staged context; `LOOPWRIGHT_CHECK_OUT` + is the only output file; `LOOPWRIGHT_RUN_ID`, `LOOPWRIGHT_STEP_ID`, `LOOPWRIGHT_CHECK_ID` + identify the slot. No controller credential reaches the environment. + - `$LOOPWRIGHT_CHECK_OUT` is strict JSON `{ detail?, metrics?, findings? }` with at most 64 KiB; + `passed` and `summary` keys are refused. `metrics` and `findings` pass the same bounds as gate + verdicts ([gate.ts](../packages/controller/src/gate.ts)). + - Exit `0` is `passed`. Any other exit is `failed` with reason `check_failed`. A run past + `timeoutMs` is `failed` with reason `check_timeout`; the process group is killed. + - The check output and a bounded stderr tail are stored as the verifier output artifact bound to + `candidateDigest`, exported by `inspect` in `verification.json`, and `detail` reaches the + author through `onRework` exactly as a gate denial does today + ([controller.ts](../packages/controller/src/controller.ts)). +- Budgets: the check consumes wall time. `check` refuses a `timeoutMs` that cannot fit between + `controls.drainReserveMs` and `budgets.wallTimeMs` at admission. +- One implementation of the script contract: the shared pieces (environment names, output + parsing, path rules) move to a module both Taskpack mode and the controller import. The + Taskpack sandbox backends stay where they are + ([sandbox.ts](../packages/taskpack/src/sandbox.ts)). +- Acceptance: + - `loopwright check` accepts a registry with a `command.v1` handler plus + `controls.localChecks.backend: direct`, and refuses the same registry without the control + (`CONFIG_SCHEMA`), with a script outside `scope.protected` (`TASKPACK_SCOPE_VIOLATION` + equivalent), and with a reserved `env` name. + - A controller test runs a two-step plan (agent via `exec`, check via `command.v1`) where the + script writes `$LOOPWRIGHT_CHECK_OUT` with metrics; the run settles `completed`, the output + artifact carries the metrics, and `onRework` returns `detail` to the author when the script + exits non-zero. + - A test proves the candidate materialization is discarded and the captured overlay is + byte-identical before and after the check. + - `closure --verify-failures` keeps its counts with one new `closed_local` row for the + feature and no falsified promotion. + +#### F2. `exec` adapter for agent roles (phase 1) + +`roleProfiles[]` accepts `adapter: exec`. + +- Required keys: `id`, `adapter: exec`, `selection` (routing metadata), `tools`, `runtimeRef: + null`, `providerCredentialRef: null`, `mcp: null`, and `exec: { command, args?, env?, + credentialRefs?, timeoutMs, captureBytes? }`. +- `command` is 1..64 argv entries without NUL, newline, or a leading `-`. `env` holds non-secret + values; `${NAME}` templates resolve through `environmentBindings` as today. `credentialRefs` + names `credentialBindings` with the new `consumer: exec`; their `environmentNames` are placed + in the child environment from the in-memory vault. +- Dispatch contract per agent step: + - argv = `[...command, ...args, , ]`. The prompt file holds the + effective prompt including any rework appendix. `candidateDir` is the attempt's writable + staging directory with its read-only context files. + - Environment is an allowlist: `PATH`, `HOME` and `TMPDIR` (the attempt scratch directory), + `LANG`, `TERM`, the configured `env`, the bound credentials, and `LOOPWRIGHT_RUN_ID`, + `LOOPWRIGHT_STEP_ID`, `LOOPWRIGHT_ROLE_ID`, `LOOPWRIGHT_ATTEMPT_ID`, + `LOOPWRIGHT_SCOPE_WRITABLE` (colon-separated globs), `LOOPWRIGHT_ALLOWED_TOOLS`, + `LOOPWRIGHT_CONTEXT_FILES`. The controller never passes its own `process.env`. + - `cwd` is `candidateDir`. `stdin` is closed. `stdout` and `stderr` are captured up to + `captureBytes` (default 65536) and scrubbed by `SecretScrubber`. + - Exit `0` is `completed`. Exit `3` is `blocked` with the last non-empty stderr line as the + reason. Any other exit is `failed`. A run past `timeoutMs` is `failed` with reason + `exec_timeout`; the process group is killed. + - After the exit, the controller captures the overlay through the code path `step submit` + uses: `scope.v1`, overlay limits, symlink and hard-link refusal, protected-path invariance. + The captured stdout is the attempt's assistant record. + - Optional usage file: if `LOOPWRIGHT_USAGE_OUT` names a file the command wrote, the controller + reads `{ inputTokens, outputTokens, requests, costMicrousd }` (bounded, scrubbed) into the + usage ledger with `source: external`. Without it, token usage records zero and + `budgets.tokens` has nothing to account; `wallTime`, `modelCalls` (one per dispatch), and + `concurrency` enforce as hard admission. +- Lease and authority: an `exec` step runs under the same attempt, owner nonce, generation, and + deadline as any agent step. A controller crash mid-exec leaves the attempt in the existing + recovery path; `maxAttempts` bounds re-dispatch. +- `loopwright run` and `resume` accept plans whose roles are all `exec`. `step next` is refused + for such plans with `CONFIG_SCHEMA` (`step` is for `delegated` roles). A plan that mixes + `delegated` and `exec` roles fails admission. +- The format-repair policy does not apply to `exec` steps: the overlay is the artifact. If the + DAG adds a reviewer step with a verdict schema, the reviewer must be `pi` or `delegated`. +- Acceptance: + - `loopwright check` accepts an `exec` profile and refuses a missing `exec` block, a non-null + `runtimeRef`, a `credentialRefs` entry without `consumer: exec`, and a mixed plan. + - A controller test runs a plan whose `exec` command writes a file inside `scope.writable` and + exits `0`; the run settles `completed` and `inspect` exports the file. A second test writes + outside the scope; the run fails `scope.v1`. A third test exits `3` and the run settles + `blocked` with the stderr reason. + - A test proves the child environment contains no variable from the controller process beyond + the allowlist, and that a bound credential never appears in `inspect` output. + - A test kills a sleeping `exec` child at `timeoutMs` and asserts the process group is gone. + +#### F3. Closure matrix and documentation (phase 1) + +- [closure-matrix.md](../docs/contribute/closure-matrix.md) gains two rows: Managed Controller + `command.v1` under `direct`, and the `exec` role adapter. Each row's evidence names the tests + above. The split counts change from 23 to 25 rows; no row is promoted without evidence. +- [controller-and-registry.md](../docs/configuration/controller-and-registry.md): add + `command.v1` to the handler table, `exec` to the role profiles, `controls.localChecks` to the + controls table, and `consumer: exec` to credential bindings. +- New walkthrough `docs/walkthroughs/managed-controller-in-isolated-host.md`: a registry + and controller for a single-accelerator Pod, the host properties `direct` requires, and the + inspection of the evidence bundle. +- [cli.md](../docs/operations/cli.md): `run` and `resume` accept `exec` roles; `step` does not. +- [coding-agents.md](../docs/operations/coding-agents.md) and + [task-contract.md](../docs/configuration/task-contract.md): cross-reference the new adapter. +- Acceptance: `npm run lint:docs` and `npm run site` pass; `docs/README.md` module map still + routes correctly. + +#### F4. Portable campaign state (phase 2) + +- `loopwright evolve export --campaign --snapshot --out ` writes + `campaign-snapshot.v1`: `manifest.json` (`campaignId`, generation range, `parentDigest` when + the campaign was imported, member digests and lengths), `individuals.jsonl` (one record per + evaluated candidate with CAS digests for code, evidence, and verdict receipt), `lineage.jsonl`, + `islands.json`, `bandit.json`, `scratchpad/`, `team_configs.jsonl`, `blobs/sha256/`, and + `receipts/.verdict.json`. Receipts are verified fail-closed as in + [bundle.ts](../packages/evolution/src/bundle.ts); `synthetic_fixture` receipts are refused + without `--allow-synthetic-probe`. +- `loopwright evolve import --bundle --state ` verifies every digest and receipt, + creates a fresh `campaign.sqlite` through the existing store + ([store.ts](../packages/evolution/src/store.ts)), restores every table verbatim, records + `parentDigest`, and refuses a state directory that already holds a campaign. +- `loopwright evolve check --bundle ` validates a snapshot offline. +- Acceptance: export → import → `evolve run` continues the campaign with the Pareto archive, + lineage, and bandit state intact; a tampered member or receipt fails the import; a synthetic + receipt fails without the flag. + +#### F5. In-process `benchmark-gate.v1` (phase 2) + +- A worker configuration may declare `deviceOwnership: host`. With it, `sandboxBackend: + native_os` is allowed together with `probeMode: physical`, because the host already dedicates + the device to the worker ([config.ts](../packages/hardware-runner/src/config.ts), + [evaluator.ts](../packages/hardware-runner/src/evaluator.ts)). +- `loopwright runner inline --config worker.yaml` serves the relay and one worker in one process + on loopback, for a controller whose `gateEndpoints` entry points at it. The two-stage + isolation (Stage A without held-out workloads, Stage B read-only with them) is unchanged. +- Acceptance: a loopback end-to-end test runs `benchmark-gate.v1` through the inline runner on + `synthetic_fixture`; a physical run is qualified on a CUDA host with `deviceOwnership: host`. + `closure --verify-failures` reports the physical row as `blocked_external` until that + qualification exists. + +### Notes / Constraints / Caveats + +- Host profile: the controller runs as a non-root user with all capabilities dropped, + `allowPrivilegeEscalation: false`, RuntimeDefault seccomp, no service account token, no host + paths. It needs egress only to the model provider, and only the `exec` child makes that call. +- SQLite profile: ADR 0001 accepts only the measured darwin/arm64 Node SQLite profile. Managed + Controller runs in Pods execute on linux/amd64 and linux/arm64. The state package tests must + pass on those profiles in CI before F1 and F2 ship. +- Handler digests: `installedHandlerDigests()` keeps hashing the installed tree + ([handlers.ts](../packages/controller/src/handlers.ts)); adding `command.v1` to the controller + changes the digests of existing installations once, as any controller change does. +- Limits reuse [limits.ts](../packages/core/src/limits.ts): `detail` 16384 chars, 64 metrics, + 64 findings. New limits: `captureBytes` 1024..1048576, `exec.command` entries 1..64, + `localChecks.timeoutMs` 1000..3600000. +- Evidence levels: `command.v1` is `local_execution`; the Taskpack vocabulary in + [contracts.ts](../packages/core/src/contracts.ts) already names it. + +### Boundaries + +- **Always:** fail closed when `controls.localChecks.backend: direct` is absent; scrub every + captured byte with `SecretScrubber`; pass an allowlisted environment only; apply the delegated + overlay checks to `exec`; kill the child's process group on timeout and cancel; record + `local_execution` evidence bound to the candidate digest. +- **Ask first:** new environment variable names; any change to Taskpack `command.v1` parameters + or host policy; any change to the closure split beyond the two new rows; a `docker` backend + for Managed Controller checks. +- **Never:** auto-detect or fall back to `direct`; let an `exec` role write outside + `scope.writable`; serialize a credential; weaken owner, generation, or nonce fencing; let a + `command.v1` script read the run store, the registry, or other runs' artifacts. + +### Risks and Mitigations + +- `direct` is used on a shared host → the control is explicit and documented; the walkthrough + states the required host properties; `check` prints the attestation in its summary. +- Child environment leaks a controller secret → allowlisted environment, vault assertion on + captured output, and a test that diffs the child environment against the allowlist. +- Long checks starve `drainReserveMs` → admission refuses a `timeoutMs` that cannot fit; the + deadline check runs before launch and during execution. +- `node:sqlite` behaves differently on linux/amd64 → CI runs the state and controller suites on + both linux profiles; the state package keeps `--concurrency 1`. +- An `exec` child ignores `allowedTools` → the overlay is re-validated by the controller; tools + are advisory for `exec`, as for any external agent. +- Identical failures halt a lineage early → intended; `detail` is part of the evidence digest, + so a different stderr tail is a different signature. + +## Design Details + +### Commands + +```sh +npm ci +npm run build +npm run typecheck +npm run lint +npm run lint:docs +npm run site +node scripts/run-tests.mjs --pkg controller +node scripts/run-tests.mjs --pkg state --concurrency 1 +node scripts/run-tests.mjs --pkg taskpack +node scripts/run-tests.mjs --pkg evolution --concurrency 1 +node packages/cli/dist/main.js closure --verify-failures +``` + +### Project Structure + +```text +packages/core/src/contracts.ts # evidence vocabulary, new limits +packages/core/src/limits.ts # captureBytes, command entries, localChecks timeout +packages/controller/src/registry.ts # command.v1 handler parameters, exec role profile, consumer: exec +packages/controller/src/config.ts # controls.localChecks, admission consistency +packages/controller/src/verification.ts # command.v1 slot execution under direct +packages/controller/src/verifier-worker.ts +packages/controller/src/controller.ts # exec dispatch instead of awaiting_role; refusal of mixed plans +packages/controller/src/step.ts # exec roles never yield; capture path shared with submit +packages/controller/src/credentials.ts # consumer: exec bindings, scrubbing of captured output +packages/taskpack/src/sandbox.ts # imports the shared script-contract module (no behavior change) +packages/cli/src/closure.ts # two new rows +packages/cli/src/evolve.ts # phase 2: export --snapshot, import, check --bundle +packages/evolution/src/bundle.ts # phase 2: campaign-snapshot.v1 writer and reader +packages/hardware-runner/src/config.ts # phase 2: deviceOwnership +docs/configuration/controller-and-registry.md +docs/contribute/closure-matrix.md +docs/walkthroughs/managed-controller-in-isolated-host.md +docs/operations/cli.md +``` + +### Code Style + +Strict ESM NodeNext, no `any`, untrusted records validated with the existing `record`/`list` +helpers. The registry entry and the role profile a sandbox runner writes: + +```yaml +handlers: + - id: forge-evaluate + version: 1 + kind: check + implementation: command.v1 + digest: { algorithm: sha256, hex: } + parameters: + checkId: forge-evaluate + script: scripts/forge-evaluate.sh + args: [] + env: { FORGEVO_KERNEL_ID: rmsnorm_0123456789abcdef } + toolchainPaths: [] + networkMode: none + timeoutMs: 600000 + capabilities: [local_execution, read_only] +roleProfiles: + - id: author + adapter: exec + selection: { provider: openai, model: gpt-5, thinking: medium } + tools: [read, write, edit] + runtimeRef: null + providerCredentialRef: null + mcp: null + exec: + command: [forgevo-author] + env: { FORGEVO_LLM_BASE_URL: "https://api.example.com/v1" } + credentialRefs: [llm-token] + timeoutMs: 600000 +``` + +```ts +/** What the controller hands a `command.v1` script and what it reads back. */ +export interface LocalCheckSpec { + readonly script: string; + readonly args: readonly string[]; + readonly env: Readonly>; + readonly toolchainPaths: readonly string[]; + readonly networkMode: 'none' | 'loopback-only'; + readonly timeoutMs: number; +} + +export interface LocalCheckOutcome { + readonly status: 'passed' | 'failed'; + readonly reason: 'check_passed' | 'check_failed' | 'check_timeout'; + readonly output: { readonly detail?: string; readonly metrics?: MetricsMap; readonly findings?: readonly StructuredFinding[] }; + readonly stderrTail: string; +} +``` + +### Implementation Plan + +> TODO — completed by `my-plan`. + +### Test Plan + +> TODO — completed by `my-plan`. + +## Alternatives + +- **Loopback `gate.v1` service in the sandbox.** Works today; needs an HMAC secret, a listener, + and a second protocol inside an already isolated Pod. Rejected once `command.v1` runs in-process. +- **Driving `loopwright step next` / `step submit` from the runner** (delegated roles). Works + today; keeps an orchestration loop inside every runner and leaves `run` unusable unattended. + Rejected in favor of the `exec` adapter. +- **Taskpack mode for sandbox runs.** It already has `command.v1`; it also brings triggers, + upstreams, publication, and a different trust model. The requirement is Managed Controller. +- **Docker-in-Pod for the `pi` adapter.** Needs a socket or a sidecar daemon, which a `restricted` + Pod forbids. Delegated and `exec` roles need no container runtime. +- **Remote state store or WAL shipping.** Rejected for run and campaign authority: the store is + the fence (ADR 0001). Portable snapshots give cross-host continuity without a service. +- **A `docker` backend for Managed Controller checks.** Useful on shared hosts; not needed by the + first consumer. Deferred; the `runtimeProfiles` docker settings are the natural home. + +## Open Questions + +1. Which CI runners qualify `node:sqlite` for the state package on linux/amd64 and linux/arm64, + and does the frozen profile (`synchronous EXTRA`, `fullfsync`) hold there? +2. Should `direct` be a controller-level control (this spec) or a per-handler parameter when a + plan mixes local and remote checks? +3. Is the optional usage file the right shape for `exec` token accounting, or should `exec` + report usage on stdout as a trailing JSON line? +4. Should phase 2 allow `exec` and `delegated` roles in one plan by running `exec` inline during + `step submit`? +5. Does the inline runner (F5) need its own relay authentication, or may it bind the controller + and worker identities in-process without HMAC? +6. Which analytics export format (Parquet or JSONL) would operators read, and is it worth a + dependency on a Parquet writer? From c02bc16af95f655fdebba5a44106103bc406b628 Mon Sep 17 00:00:00 2001 From: thxCode Date: Mon, 30 Nov 2026 19:26:58 +0800 Subject: [PATCH 02/26] docs(specs): plan Managed Controller in-process execution after design review - Add the task DAG and test plan for command.v1 under direct and the exec adapter - Move the direct attestation into the registry and add the host_execution evidence level - Settle unknown exec and check outcomes without re-dispatch and import campaigns with a fresh authority - Fold the 26 review findings into features, boundaries, risks, and tests Signed-off-by: thxCode --- ...managed-controller-in-process-execution.md | 725 ++++++++++++------ 1 file changed, 501 insertions(+), 224 deletions(-) diff --git a/specs/2026-11-30-managed-controller-in-process-execution.md b/specs/2026-11-30-managed-controller-in-process-execution.md index 2d1a4f76..f5bd7610 100644 --- a/specs/2026-11-30-managed-controller-in-process-execution.md +++ b/specs/2026-11-30-managed-controller-in-process-execution.md @@ -1,20 +1,23 @@ # Spec: Managed Controller in-process execution: `command.v1` checks, exec roles, and portable campaign state -Status: Specified +Status: Planned Type: Feature ## Summary Let a Managed Controller run execute entirely on an already isolated host: a restricted Pod that -owns exactly one accelerator, has no Docker socket, no relay, and no provider credentials. +owns exactly one accelerator, has no Docker socket, no relay, and makes no model call itself. Add `command.v1` to the Managed Controller handler table so a protected script in the task -repository becomes the verifier, executed in the controller's own environment under an explicit -`direct` backend. Add an `exec` role adapter so `loopwright run` hands each agent step to a -local command and captures the overlay with the same scope and overlay checks as a delegated -submit. Keep the fencing authority, the `pi` adapter, and Taskpack mode unchanged. In a second -phase, make evolution campaigns portable (`evolve export --snapshot`, `evolve import`) and allow -`benchmark-gate.v1` to run in-process on a host that already owns the device. The first consumer -is the gpustack-operator `ModelDeploymentForger` sandbox runner (gpustack/forgevo). +repository becomes the verifier, executed in the controller's own environment under a `direct` +backend that the TrustedRegistry attests. Its evidence is a new level, `host_execution`, which +no other handler produces, so a consumer can tell it apart from sandboxed local execution. Add +an `exec` role adapter so `loopwright run` hands each agent step to a local command and captures +the overlay with the same scope and overlay checks as a delegated submit, with the same +unknown-outcome discipline as the other adapters. Keep the fencing authority, the `pi` adapter, +and Taskpack mode unchanged. In a second phase, make evolution campaigns portable (`evolve +export --snapshot`, `evolve import`) and run `benchmark-gate.v1` in-process on a host that +already owns the device. The first consumer is the gpustack-operator `ModelDeploymentForger` +sandbox runner (gpustack/forgevo). ## Motivation @@ -22,27 +25,35 @@ is the gpustack-operator `ModelDeploymentForger` sandbox runner (gpustack/forgev 1. **G1 · Unattended Managed Controller runs in an isolated container.** A run whose checks are protected scripts and whose roles are local commands completes with `loopwright run` in a - `restricted` Pod: no Docker, no relay, no provider token in the Loopwright process. -2. **G2 · Evidence stays honest.** A `command.v1` check is `local_execution` evidence bound to - the candidate digest. An `exec` step's overlay passes `scope.v1`, overlay limits, and the - symlink, hard-link, and protected-path invariants that a delegated submit passes. + `restricted` Pod: no Docker, no relay, and no model call from the Loopwright process. The + only credential Loopwright handles is the exec child's, resolved in memory for that child. +2. **G2 · Evidence stays honest.** A `command.v1` check under `direct` yields `host_execution` + evidence, bound to the candidate digest and to the registry that attested the host. An + `exec` step's overlay passes `scope.v1`, overlay limits, and the symlink, hard-link, and + protected-path invariants that a delegated submit passes. A crashed or unknown outcome is + never retried silently. 3. **G3 · No regression.** `pi` and `delegated` roles, Taskpack `command.v1`, lease fencing, and the closure matrix keep their current behavior. New capability rows record only what tests prove. 4. **G4 · Portable campaign state (phase 2).** A campaign archive exports to a verified, - self-contained snapshot and imports into a fresh `campaign.sqlite`, so a campaign can - continue across hosts without a remote database. + self-contained snapshot and imports into a fresh `campaign.sqlite` with a fresh authority, + so a campaign can continue across hosts without a remote database. 5. **G5 · In-process hardware gate (phase 2).** `benchmark-gate.v1` runs without a relay and a - Docker worker when the host already dedicates the device to the run. + Docker worker when the host already dedicates the device to the run, and its receipts say + that the isolation was attested by the host, not enforced by a container. ### Non-Goals - A remote state store (PostgreSQL, Redis, object storage) for run or campaign authority. The local fenced SQLite store stays the authority ([ADR 0001](../docs/contribute/adr/0001-local-state-authority.md)). - Shipping SQLite write-ahead logs or pages to object storage. -- Changing Taskpack mode's `command.v1`, its sandbox backends, or its host policy. +- Changing Taskpack mode's `command.v1`, its sandbox backends, its host policy, or its script + contract. Managed Controller `command.v1` is a sibling contract defined here, not a shared + implementation. +- Enforcing isolation that the host does not provide under `direct`: no mount namespaces, no + network policy, no process-tree containment. - Running the `pi` adapter without Docker, or on a profile other than `linux/arm64`. -- Mixing `delegated` and `exec` roles in one plan. +- Mixing `exec` with `pi` or `delegated` roles in one plan. - Multi-host concurrent mutation of one campaign. - Analytics exports (Parquet, JSONL) of run or campaign metrics. @@ -76,248 +87,364 @@ so that a bounded Pod lifetime does not reset the search. #### F1. `command.v1` as a Managed Controller check handler (phase 1) -`TrustedRegistry.spec.handlers[]` accepts `implementation: command.v1` with -`kind: check` and `capabilities: ['local_execution', 'read_only']`. - -- Parameters: `checkId` (identifier), `script` (repository-relative path), `args` (0..64 - strings), `env` (0..32 entries, names `^[A-Z][A-Z0-9_]{0,63}$`, `LOOPWRIGHT_*` names refused), - `toolchainPaths` (0..32 repository-relative paths), `networkMode` (`none` | `loopback-only`, - default `none`), `timeoutMs` (1000..3600000). -- `script` and every `toolchainPaths` entry must resolve inside `scope.protected` and must exist - in the repository at `target.sourceRevision`. The script file must carry the executable bit in - the committed tree. Unknown keys fail `CONFIG_SCHEMA`, as for every handler. -- Execution requires an explicit host-owned declaration: `spec.controls.localChecks: - { backend: direct }`. Without it, a registry that contains a `command.v1` handler fails - `check` with `CONFIG_SCHEMA`. Loopwright never detects or falls back to `direct`. -- `direct` means: the controller's own environment is the sandbox. The controller documents the - required host properties (single-tenant container or VM, no Docker socket, no shared writable - paths with untrusted processes) and refuses nothing else; the operator attests. -- Script contract (same names and semantics as Taskpack `command.v1`, see - [taskpack-and-contract-schema.md](../docs/references/taskpack-and-contract-schema.md)): - - The script's parent directory is available read-only with its whole-tree digest recorded in - the run lock. - - Environment: `PATH` defaults to `/usr/local/bin:/usr/bin:/bin` plus `toolchainPaths`; - `HOME` and `TMPDIR` point at a disposable scratch directory; `LANG=C.UTF-8`; `TERM=dumb`; - `LOOPWRIGHT_CANDIDATE_DIR` is a disposable materialization of the captured candidate, - writable during the check and discarded after it; `LOOPWRIGHT_BASE_DIR` is the read-only - baseline tree; `LOOPWRIGHT_STAGED_DIR` is the read-only staged context; `LOOPWRIGHT_CHECK_OUT` - is the only output file; `LOOPWRIGHT_RUN_ID`, `LOOPWRIGHT_STEP_ID`, `LOOPWRIGHT_CHECK_ID` - identify the slot. No controller credential reaches the environment. - - `$LOOPWRIGHT_CHECK_OUT` is strict JSON `{ detail?, metrics?, findings? }` with at most 64 KiB; - `passed` and `summary` keys are refused. `metrics` and `findings` pass the same bounds as gate - verdicts ([gate.ts](../packages/controller/src/gate.ts)). - - Exit `0` is `passed`. Any other exit is `failed` with reason `check_failed`. A run past - `timeoutMs` is `failed` with reason `check_timeout`; the process group is killed. - - The check output and a bounded stderr tail are stored as the verifier output artifact bound to - `candidateDigest`, exported by `inspect` in `verification.json`, and `detail` reaches the - author through `onRework` exactly as a gate denial does today - ([controller.ts](../packages/controller/src/controller.ts)). -- Budgets: the check consumes wall time. `check` refuses a `timeoutMs` that cannot fit between - `controls.drainReserveMs` and `budgets.wallTimeMs` at admission. -- One implementation of the script contract: the shared pieces (environment names, output - parsing, path rules) move to a module both Taskpack mode and the controller import. The - Taskpack sandbox backends stay where they are - ([sandbox.ts](../packages/taskpack/src/sandbox.ts)). +`TrustedRegistry.spec.handlers[]` accepts `implementation: command.v1` with `kind: check` and +`capabilities: ['host_execution']`. `host_execution` is a new capability and a new evidence +level in [contracts.ts](../packages/core/src/contracts.ts): repository code ran in the +controller's own environment on a host whose isolation the registry attests. + +- **Attestation lives in the registry.** `TrustedRegistry.spec.host.localChecks: { backend: + direct }` is required when the registry holds a `command.v1` handler. The registry is + digest-pinned and outside every untrusted root + ([config.ts](../packages/controller/src/config.ts)), so the attestation enters `planDigest` + and the run lock. `ControllerConfig` carries nothing about execution backends. `check` + refuses the registry without it (`CONFIG_SCHEMA`) and refuses any other backend value. +- **What `direct` means, stated honestly.** The controller's own environment is the sandbox. + Loopwright enforces scope on the overlay, bounds time and output, and records what ran. It + does not enforce read-only paths, network isolation, or secrecy of the run store against a + script that runs under the same user ID: such a script can change file modes, open network + connections the host allows, read the store, and read the controller's `/proc//environ`. + The walkthrough states these limits. An operator who needs them enforced does not attest + `direct`. +- **Parameters.** `checkId` (identifier), `script` (repository-relative path), `args` (0..64 + strings), `env` (0..32 entries, names `^[A-Z][A-Z0-9_]{0,63}$`, `LOOPWRIGHT_*` names + refused), `toolchainPaths` (0..32 repository-relative paths), `timeoutMs` (1000..3600000). + Unknown keys fail `CONFIG_SCHEMA`, as for every handler. +- **Where the script comes from.** The script's parent directory is materialized from the + baseline tree at `target.sourceRevision`, never from the candidate, and that whole directory + must lie under `scope.protected` (a glob such as `scripts/**`). Sibling files in it are + trusted operator code by this rule. The script must carry the executable bit in the committed + tree. +- **Validation split.** `loopwright check` validates the schema, the protected-scope rule, and + the budget fit; it has no repository and does not resolve files. Admission (`run`, `resume`, + `step next`, which take `--repo`) resolves the script and `toolchainPaths` at + `sourceRevision`, checks the executable bit, and records the directory digest in the compiled + slot, which `planDigest` covers. `TaskLock` does not change. A missing or non-executable + script at admission fails `CONFIG_REFERENCE`. +- **Script contract.** Managed Controller defines its own contract; it does not reuse the + Taskpack one. Environment: `PATH` is `/usr/local/bin:/usr/bin:/bin` with `toolchainPaths` + prepended; `HOME` and `TMPDIR` point at a disposable scratch directory; `LANG=C.UTF-8`; + `TERM=dumb`; `LC_ALL=C.UTF-8`; `GIT_CONFIG_NOSYSTEM=1`, `GIT_CONFIG_GLOBAL=/dev/null`, + `GIT_TERMINAL_PROMPT=0`, `GIT_ASKPASS=/usr/bin/false`; `LOOPWRIGHT_CANDIDATE_DIR` is a + disposable materialization of the captured candidate, writable during the check and discarded + after it; `LOOPWRIGHT_BASE_DIR` is the read-only baseline tree; `LOOPWRIGHT_STAGED_DIR` is the + read-only staged context; `LOOPWRIGHT_CHECK_OUT` is the only output file the controller reads; + `LOOPWRIGHT_RUN_ID`, `LOOPWRIGHT_STEP_ID`, `LOOPWRIGHT_CHECK_ID` identify the slot. No + controller credential reaches the environment. `$LOOPWRIGHT_CHECK_OUT` is strict JSON + `{ detail?, metrics?, findings? }` with at most 64 KiB; `passed` and `summary` keys are + refused; `metrics` and `findings` pass the bounds in [gate.ts](../packages/controller/src/gate.ts). +- **Authority path.** `LocalCheck.run(job, signal)` mirrors `Gate.run`: intent, dispatch + permit, binding marker, execution, proof marker, receipt, `VerifiedCheck`. The child runs in + its own process group; the group ID is written into the binding marker before the proof + marker exists. Exit `0` is `passed`; any other exit is `failed` with reason `check_failed`; + a run past `timeoutMs` is `failed` with reason `check_timeout` and the process group is + killed. A child that called `setsid` can escape the group; recovery and Pod exit are the + backstops, and the test asserts only the group. An operation that the controller finds + without a proof marker after a crash settles `blocked` with `EVIDENCE_UNAVAILABLE` after the + recorded group is killed; it is never re-dispatched under the same operation. +- **Evidence.** The output artifact and a bounded, scrubbed stderr tail are bound to + `candidateDigest`. The receipt carries `method: 'direct_script'`, the script path, the script + directory digest, and the registry digest. `inspect` exports them in `verification.json`. + `onRework` returns `detail` to the author: the controller's rework summary must extract + `detail` for `command.v1` slots as it does for gate slots today + ([controller.ts](../packages/controller/src/controller.ts)). A run accepts `host_execution` + evidence only when `acceptance.checks[].allowedEvidenceLevels` lists it. +- **Budgets.** The check consumes wall time. `check` refuses a `timeoutMs` that cannot fit + between `controls.drainReserveMs` and `budgets.wallTimeMs`. - Acceptance: - - `loopwright check` accepts a registry with a `command.v1` handler plus - `controls.localChecks.backend: direct`, and refuses the same registry without the control - (`CONFIG_SCHEMA`), with a script outside `scope.protected` (`TASKPACK_SCOPE_VIOLATION` - equivalent), and with a reserved `env` name. - - A controller test runs a two-step plan (agent via `exec`, check via `command.v1`) where the - script writes `$LOOPWRIGHT_CHECK_OUT` with metrics; the run settles `completed`, the output - artifact carries the metrics, and `onRework` returns `detail` to the author when the script - exits non-zero. + - `loopwright check` accepts a registry with a `command.v1` handler and + `host.localChecks.backend: direct`, and refuses the same registry without the attestation + (`CONFIG_SCHEMA`), with an unknown parameter (`CONFIG_SCHEMA`), with a reserved `env` name + (`CONFIG_SCHEMA`), and with capabilities other than `['host_execution']` + (`CAPABILITY_UNSUPPORTED`). + - Admission refuses a script outside `scope.protected` (`CONFIG_SCHEMA`), a script whose + directory is not fully protected (`CONFIG_SCHEMA`), and a missing or non-executable script + (`CONFIG_REFERENCE`). + - A controller test runs a plan whose `command.v1` script writes metrics and exits `0`; the + check passes with `host_execution` evidence, the output artifact carries the metrics, and + the receipt names the method and the script digest. A second script exits non-zero and the + author receives `detail` through `onRework`. A third sleeps past `timeoutMs` and the check + settles `check_timeout` with the process group gone. - A test proves the candidate materialization is discarded and the captured overlay is byte-identical before and after the check. - - `closure --verify-failures` keeps its counts with one new `closed_local` row for the - feature and no falsified promotion. + - A test kills the controller between the binding and proof markers; on recovery the operation + settles `blocked` with `EVIDENCE_UNAVAILABLE` and is not re-dispatched. #### F2. `exec` adapter for agent roles (phase 1) -`roleProfiles[]` accepts `adapter: exec`. - -- Required keys: `id`, `adapter: exec`, `selection` (routing metadata), `tools`, `runtimeRef: - null`, `providerCredentialRef: null`, `mcp: null`, and `exec: { command, args?, env?, - credentialRefs?, timeoutMs, captureBytes? }`. -- `command` is 1..64 argv entries without NUL, newline, or a leading `-`. `env` holds non-secret - values; `${NAME}` templates resolve through `environmentBindings` as today. `credentialRefs` - names `credentialBindings` with the new `consumer: exec`; their `environmentNames` are placed - in the child environment from the in-memory vault. -- Dispatch contract per agent step: - - argv = `[...command, ...args, , ]`. The prompt file holds the - effective prompt including any rework appendix. `candidateDir` is the attempt's writable - staging directory with its read-only context files. - - Environment is an allowlist: `PATH`, `HOME` and `TMPDIR` (the attempt scratch directory), - `LANG`, `TERM`, the configured `env`, the bound credentials, and `LOOPWRIGHT_RUN_ID`, - `LOOPWRIGHT_STEP_ID`, `LOOPWRIGHT_ROLE_ID`, `LOOPWRIGHT_ATTEMPT_ID`, - `LOOPWRIGHT_SCOPE_WRITABLE` (colon-separated globs), `LOOPWRIGHT_ALLOWED_TOOLS`, - `LOOPWRIGHT_CONTEXT_FILES`. The controller never passes its own `process.env`. +`roleProfiles[]` accepts `adapter: exec`. `RoleAdapterKind` gains `'exec'` +([types.ts](../packages/controller/src/types.ts)). + +- **Profile keys.** `id`, `adapter: exec`, `selection` (routing metadata), `tools`, an optional + `limits` block, `runtimeRef: null`, `providerCredentialRef: null`, `mcp: null`, and `exec: + { command, args?, env?, credentialRefs?, timeoutMs, captureBytes? }`. `context` is not + required and not read for `exec` roles. `command` is 1..64 entries; `command[0]` is an absolute + path without NUL, newline, or a trailing slash, and no entry starts with `-` unless it is an + argument after `command[0]`. `env` holds non-secret values; `${NAME}` templates resolve + through `environmentBindings` as today. +- **Credentials.** `credentialBindings[]` gains `consumer: exec`. For a bound credential, the + child receives one variable per name in `environmentNames`, each set to the resolved template + value; the names in the template and in the child are the same. Values resolve in memory + through the vault; `vault.assertClean` runs on every captured byte. +- **Dispatch contract per agent step:** + - Before the spawn, the controller records an intent and takes a dispatch permit, as a gate + does, and writes a binding marker with the attempt, step, role, prompt digest, and the + child's process group. + - argv = `[...command, ...args, promptFile, candidateDir]`. The prompt file holds the + effective prompt including any rework appendix. `candidateDir` is a fresh attempt directory + with its read-only context files. + - Environment is an allowlist: `PATH` fixed to `/usr/local/bin:/usr/bin:/bin`, `HOME` and + `TMPDIR` (the attempt scratch directory), `LANG`, `TERM`, the configured `env`, the bound + credentials, and `LOOPWRIGHT_RUN_ID`, `LOOPWRIGHT_STEP_ID`, `LOOPWRIGHT_ROLE_ID`, + `LOOPWRIGHT_ATTEMPT_ID`, `LOOPWRIGHT_SCOPE_WRITABLE` (colon-separated globs), + `LOOPWRIGHT_ALLOWED_TOOLS`, `LOOPWRIGHT_CONTEXT_FILES`. The controller never passes its + own `process.env`. - `cwd` is `candidateDir`. `stdin` is closed. `stdout` and `stderr` are captured up to - `captureBytes` (default 65536) and scrubbed by `SecretScrubber`. + `captureBytes` (default 65536, 1024..1048576), scrubbed, and attached to the attempt record. + - The submission is synthesized exactly as `step submit --status completed|blocked|failed` + synthesizes it today ([step.ts](../packages/controller/src/step.ts)); `completeCapture` + never parses the child's free text, and no `exec` step enters format repair. - Exit `0` is `completed`. Exit `3` is `blocked` with the last non-empty stderr line as the reason. Any other exit is `failed`. A run past `timeoutMs` is `failed` with reason - `exec_timeout`; the process group is killed. - - After the exit, the controller captures the overlay through the code path `step submit` - uses: `scope.v1`, overlay limits, symlink and hard-link refusal, protected-path invariance. - The captured stdout is the attempt's assistant record. - - Optional usage file: if `LOOPWRIGHT_USAGE_OUT` names a file the command wrote, the controller - reads `{ inputTokens, outputTokens, requests, costMicrousd }` (bounded, scrubbed) into the - usage ledger with `source: external`. Without it, token usage records zero and - `budgets.tokens` has nothing to account; `wallTime`, `modelCalls` (one per dispatch), and - `concurrency` enforce as hard admission. -- Lease and authority: an `exec` step runs under the same attempt, owner nonce, generation, and - deadline as any agent step. A controller crash mid-exec leaves the attempt in the existing - recovery path; `maxAttempts` bounds re-dispatch. -- `loopwright run` and `resume` accept plans whose roles are all `exec`. `step next` is refused - for such plans with `CONFIG_SCHEMA` (`step` is for `delegated` roles). A plan that mixes - `delegated` and `exec` roles fails admission. -- The format-repair policy does not apply to `exec` steps: the overlay is the artifact. If the - DAG adds a reviewer step with a verdict schema, the reviewer must be `pi` or `delegated`. + `exec_timeout` and the process group killed. + - After the exit, the controller writes the proof marker and captures the overlay through the + `adoptRoleCapture` path that `step submit` uses: `scope.v1`, overlay limits, symlink and + hard-link refusal, protected-path invariance. +- **Unknown outcomes.** The child's model calls are invisible to the store, so a re-dispatch + would repeat an uncertain external effect. On recovery, an `exec` operation without a proof + marker is settled as unknown: the run requires recovery (`RECOVERY_REQUIRED`), the recorded + process group is killed, and the attempt directory is discarded so that a lingering child + cannot write into the next attempt. `resumeAttempt` never re-runs `role()` for such an attempt. +- **Compilation.** [compile.ts](../packages/controller/src/compile.ts) branches on `exec`: no + runtime profile, no provider credential, no `context` guard; `PlannedRole.policy` for an + `exec` role is `{ tools: the declared tools, mcp: empty, limits: profile.limits or the role + defaults }`; the credential set must equal the vault references named by `credentialRefs`. + [budget-observations.ts](../packages/controller/src/budget-observations.ts) counts an `exec` + dispatch as one model call; [recovery.ts](../packages/controller/src/recovery.ts) handles + `exec` nodes as this section says. +- **Admission.** `run` and `resume` admit plans whose agent roles are all `exec`. A plan that + mixes `exec` with `pi` or `delegated` roles fails admission (`CONFIG_SCHEMA`), and `step next` + refuses `exec` plans. Consequence: in a Pod without Docker, no reviewer step exists in this + version; the measured check is the reviewer. +- **Budgets and usage.** `wallTime`, `modelCalls` (one per dispatch), and `concurrency` enforce + as hard admission; admission is per dispatch and happens before the spawn. Provider calls made + inside one dispatch are the command's responsibility. Optional usage file: if + `LOOPWRIGHT_USAGE_OUT` names a file the command wrote, the controller reads + `{ requests: [{ requestId, inputTokens, outputTokens, costMicrousd }] }` (bounded, scrubbed) + into the usage ledger with `provenance: 'reported'`; without the file, usage records + `provenance: 'unknown'`, never zero ([usage.ts](../packages/core/src/usage.ts)). - Acceptance: - - `loopwright check` accepts an `exec` profile and refuses a missing `exec` block, a non-null - `runtimeRef`, a `credentialRefs` entry without `consumer: exec`, and a mixed plan. + - `loopwright check` accepts an `exec` profile and refuses a missing `exec` block, a + non-null `runtimeRef`, a relative `command[0]`, a `credentialRefs` entry whose binding is + not `consumer: exec`, and a mixed plan (`CONFIG_SCHEMA` or `CONFIG_REFERENCE` as today). - A controller test runs a plan whose `exec` command writes a file inside `scope.writable` and - exits `0`; the run settles `completed` and `inspect` exports the file. A second test writes - outside the scope; the run fails `scope.v1`. A third test exits `3` and the run settles - `blocked` with the stderr reason. - - A test proves the child environment contains no variable from the controller process beyond - the allowlist, and that a bound credential never appears in `inspect` output. + exits `0`; the run settles `completed` and `inspect` exports the file. A second writes + outside the scope; the run fails `scope.v1`. A third exits `3`; the run settles `blocked` + with the stderr reason. A fourth prints free text only; the run settles `completed` and + never enters `repairFormat`. + - A test kills the controller mid-exec; on resume the run reports `RECOVERY_REQUIRED`, the + recorded process group is gone, and the attempt is not re-dispatched. + - A test proves the child environment equals the allowlist plus the configured values, and + that a bound credential appears in no `inspect` output. - A test kills a sleeping `exec` child at `timeoutMs` and asserts the process group is gone. #### F3. Closure matrix and documentation (phase 1) -- [closure-matrix.md](../docs/contribute/closure-matrix.md) gains two rows: Managed Controller - `command.v1` under `direct`, and the `exec` role adapter. Each row's evidence names the tests - above. The split counts change from 23 to 25 rows; no row is promoted without evidence. -- [controller-and-registry.md](../docs/configuration/controller-and-registry.md): add - `command.v1` to the handler table, `exec` to the role profiles, `controls.localChecks` to the - controls table, and `consumer: exec` to credential bindings. -- New walkthrough `docs/walkthroughs/managed-controller-in-isolated-host.md`: a registry - and controller for a single-accelerator Pod, the host properties `direct` requires, and the - inspection of the evidence bundle. +- [closure-matrix.md](../docs/contribute/closure-matrix.md) grows from 23 to 26 rows: Managed + Controller `command.v1` under `direct` and the `exec` role adapter as `closed_local` with the + tests above as evidence, and the in-process benchmark gate as `blocked_external` until its + physical qualification exists. The ledger in [closure.ts](../packages/cli/src/closure.ts) and + its tests change together. `closure --verify-failures` checks the integrated failure matrix, + not the row count; the acceptance is that `closure` reports the new split and + `--verify-failures` still passes. +- [controller-and-registry.md](../docs/configuration/controller-and-registry.md): `command.v1` + in the handler table with the `host_execution` capability, `host.localChecks` beside the + registry fields, `exec` in the role profiles, `consumer: exec` in the credential bindings, and + the `host_execution` evidence level. +- New walkthrough `docs/walkthroughs/managed-controller-in-isolated-host.md`: a registry and + controller for a single-accelerator Pod, the limits of `direct`, the inspection of the + evidence bundle. It is added to `docs/README.md` (All pages and Specs sections), to + `site/data/navigation.yaml`, and to the public site paths in + [check-docs.mjs](../scripts/check-docs.mjs). This spec is listed in the Specs section. - [cli.md](../docs/operations/cli.md): `run` and `resume` accept `exec` roles; `step` does not. - [coding-agents.md](../docs/operations/coding-agents.md) and - [task-contract.md](../docs/configuration/task-contract.md): cross-reference the new adapter. -- Acceptance: `npm run lint:docs` and `npm run site` pass; `docs/README.md` module map still - routes correctly. + [task-contract.md](../docs/configuration/task-contract.md): cross-reference the new adapter + and the new evidence level. +- Acceptance: `npm run lint:docs` and `npm run site` pass; `docs/README.md` routes correctly. #### F4. Portable campaign state (phase 2) - `loopwright evolve export --campaign --snapshot --out ` writes `campaign-snapshot.v1`: `manifest.json` (`campaignId`, generation range, `parentDigest` when the campaign was imported, member digests and lengths), `individuals.jsonl` (one record per - evaluated candidate with CAS digests for code, evidence, and verdict receipt), `lineage.jsonl`, - `islands.json`, `bandit.json`, `scratchpad/`, `team_configs.jsonl`, `blobs/sha256/`, and - `receipts/.verdict.json`. Receipts are verified fail-closed as in - [bundle.ts](../packages/evolution/src/bundle.ts); `synthetic_fixture` receipts are refused - without `--allow-synthetic-probe`. -- `loopwright evolve import --bundle --state ` verifies every digest and receipt, + evaluated candidate, passed or not, with CAS digests for code and evidence and the receipt + digest when one exists), `lineage.jsonl`, `islands.json`, `bandit.json`, `scratchpad/`, + `team_configs.jsonl`, `blobs/sha256/`, and `receipts/.verdict.json` for every + individual that has an approved receipt. A receipt is verified fail-closed as + [bundle.ts](../packages/evolution/src/bundle.ts) verifies it; `synthetic_fixture` receipts are + refused without `--allow-synthetic-probe`. +- `loopwright evolve check --bundle ` validates a snapshot offline with + `--receipt-secret-env NAME` for receipts. +- `loopwright evolve import --bundle --state --receipt-secret-env NAME` verifies + every digest and every receipt, refuses a state directory that already holds a campaign, and creates a fresh `campaign.sqlite` through the existing store - ([store.ts](../packages/evolution/src/store.ts)), restores every table verbatim, records - `parentDigest`, and refuses a state directory that already holds a campaign. -- `loopwright evolve check --bundle ` validates a snapshot offline. -- Acceptance: export → import → `evolve run` continues the campaign with the Pareto archive, - lineage, and bandit state intact; a tampered member or receipt fails the import; a synthetic - receipt fails without the flag. - -#### F5. In-process `benchmark-gate.v1` (phase 2) + ([store.ts](../packages/evolution/src/store.ts)) with a **fresh authority**: a new + `campaign_meta` (new lease, new fence epoch, new clock basis, new store identity), the + individuals, lineage, islands, bandit arms, scratchpad, and team configs copied verbatim, and + the snapshot digest recorded in a new `snapshot_provenance` table. Clock and fence columns are + never copied. A tampered member or receipt fails the import. +- Acceptance: export, import, and `evolve run` continue the campaign on a host whose monotonic + clock is lower than the exporter's, with the Pareto archive, lineage, and bandit state intact + and no `EVOLUTION_CLOCK_DRIFT`; a snapshot with failed or preempted individuals imports with + their status and `receipt: null`; a tampered receipt fails. + +#### F5. In-process `benchmark-gate.v1` (phase 2, feasibility first) - A worker configuration may declare `deviceOwnership: host`. With it, `sandboxBackend: - native_os` is allowed together with `probeMode: physical`, because the host already dedicates - the device to the worker ([config.ts](../packages/hardware-runner/src/config.ts), - [evaluator.ts](../packages/hardware-runner/src/evaluator.ts)). + native_os` is allowed together with `probeMode: physical` in + [config.ts](../packages/hardware-runner/src/config.ts), [worker.ts](../packages/hardware-runner/src/worker.ts), + and [evaluator.ts](../packages/hardware-runner/src/evaluator.ts). `native_os` isolation uses + bubblewrap and user namespaces on Linux + ([evaluator.ts](../packages/hardware-runner/src/evaluator.ts)); a restricted Pod with + RuntimeDefault seccomp usually cannot create them, so the first task is a feasibility probe + in the target Pod profile, and the feature stays behind it. +- `hardwareProvenance` gains `isolation: 'docker' | 'host_attested'`. Receipts carry it; + `evolve export` refuses `host_attested` receipts unless `--allow-host-attested` is passed, so + a host declaration never passes for enforced isolation. - `loopwright runner inline --config worker.yaml` serves the relay and one worker in one process on loopback, for a controller whose `gateEndpoints` entry points at it. The two-stage isolation (Stage A without held-out workloads, Stage B read-only with them) is unchanged. - Acceptance: a loopback end-to-end test runs `benchmark-gate.v1` through the inline runner on - `synthetic_fixture`; a physical run is qualified on a CUDA host with `deviceOwnership: host`. - `closure --verify-failures` reports the physical row as `blocked_external` until that - qualification exists. + `synthetic_fixture`; the receipt records `isolation`; `evolve export` refuses a + `host_attested` receipt without the flag; the closure row stays `blocked_external` until a + CUDA qualification exists. ### Notes / Constraints / Caveats - Host profile: the controller runs as a non-root user with all capabilities dropped, `allowPrivilegeEscalation: false`, RuntimeDefault seccomp, no service account token, no host paths. It needs egress only to the model provider, and only the `exec` child makes that call. -- SQLite profile: ADR 0001 accepts only the measured darwin/arm64 Node SQLite profile. Managed - Controller runs in Pods execute on linux/amd64 and linux/arm64. The state package tests must - pass on those profiles in CI before F1 and F2 ship. +- Limits of `direct`: the check script runs under the controller's user ID. Loopwright records + what ran and bounds time and output; it does not contain the script. The evidence level + `host_execution` exists so that consumers can refuse it. +- SQLite profile: [state.md](../docs/contribute/state.md) already declares Linux arm64 and x64 + qualified, and `test.yml` shards every suite on `ubuntu-24.04` and `ubuntu-24.04-arm`. ADR + 0001 still names only darwin/arm64. ADR 0003 supersedes that sentence with the CI evidence and + records the `fullfsync` semantics on Linux; ADRs are superseded, never edited. - Handler digests: `installedHandlerDigests()` keeps hashing the installed tree - ([handlers.ts](../packages/controller/src/handlers.ts)); adding `command.v1` to the controller - changes the digests of existing installations once, as any controller change does. + ([handlers.ts](../packages/controller/src/handlers.ts)); the new evidence vocabulary lives in + `@loopwright/core`, which that digest already covers. - Limits reuse [limits.ts](../packages/core/src/limits.ts): `detail` 16384 chars, 64 metrics, 64 findings. New limits: `captureBytes` 1024..1048576, `exec.command` entries 1..64, - `localChecks.timeoutMs` 1000..3600000. -- Evidence levels: `command.v1` is `local_execution`; the Taskpack vocabulary in - [contracts.ts](../packages/core/src/contracts.ts) already names it. + `localChecks.timeoutMs` 1000..3600000, `LOOPWRIGHT_CHECK_OUT` 65536 bytes. +- `repeatFailureLimit` is 2. The failure signature is the slot, handler digest, reason, + method, parameters, and candidate digest ([repair.ts](../packages/controller/src/repair.ts)); + the check's `detail` is not part of it. A candidate that fails the same check with the same + reason twice is halted whatever the stderr says, and the author sees `detail` on the first + rework only. ### Boundaries -- **Always:** fail closed when `controls.localChecks.backend: direct` is absent; scrub every - captured byte with `SecretScrubber`; pass an allowlisted environment only; apply the delegated - overlay checks to `exec`; kill the child's process group on timeout and cancel; record - `local_execution` evidence bound to the candidate digest. -- **Ask first:** new environment variable names; any change to Taskpack `command.v1` parameters - or host policy; any change to the closure split beyond the two new rows; a `docker` backend - for Managed Controller checks. -- **Never:** auto-detect or fall back to `direct`; let an `exec` role write outside - `scope.writable`; serialize a credential; weaken owner, generation, or nonce fencing; let a - `command.v1` script read the run store, the registry, or other runs' artifacts. +- **Always:** fail closed when `host.localChecks.backend: direct` is absent; record the method, + script digest, and registry digest in every `command.v1` receipt; scrub every captured byte + with `SecretScrubber`; pass an allowlisted environment only; apply the delegated overlay + checks to `exec`; kill the child's process group on timeout and cancel; settle an operation + without a proof marker as unknown and never re-dispatch it. +- **Ask first:** new environment variable names; any change to Taskpack `command.v1`; any + change to the closure split beyond the three new rows; a `docker` backend for Managed + Controller checks; accepting `host_execution` evidence in any consumer by default. +- **Never:** auto-detect or fall back to `direct`; claim isolation that `direct` does not + provide; let an `exec` role write outside `scope.writable`; serialize a credential; weaken + owner, generation, or nonce fencing; retry an `exec` or `command.v1` operation whose outcome + is unknown. ### Risks and Mitigations -- `direct` is used on a shared host → the control is explicit and documented; the walkthrough - states the required host properties; `check` prints the attestation in its summary. +- `direct` is used on a shared host → the attestation is in the digest-pinned registry, the + walkthrough states the limits, and the evidence level lets consumers refuse the result. +- A check or exec child reads the controller's environment or store under the same user ID → + documented limit of `direct`; credentials reach only the exec child and only through the + allowlist; consumers who cannot accept it do not attest `direct`. - Child environment leaks a controller secret → allowlisted environment, vault assertion on captured output, and a test that diffs the child environment against the allowlist. - Long checks starve `drainReserveMs` → admission refuses a `timeoutMs` that cannot fit; the deadline check runs before launch and during execution. -- `node:sqlite` behaves differently on linux/amd64 → CI runs the state and controller suites on - both linux profiles; the state package keeps `--concurrency 1`. +- A controller crash leaves an orphan child → the process group is recorded before execution and + killed on recovery; `setsid` escapes are documented; the attempt directory is discarded so a + survivor cannot touch the next attempt; the Pod exit is the final backstop. - An `exec` child ignores `allowedTools` → the overlay is re-validated by the controller; tools are advisory for `exec`, as for any external agent. -- Identical failures halt a lineage early → intended; `detail` is part of the evidence digest, - so a different stderr tail is a different signature. +- `node:sqlite` on Linux differs from darwin → CI already runs every suite on both Linux + profiles; ADR 0003 records the qualified profiles and the `fullfsync` semantics. +- `native_os` isolation is unavailable in a restricted Pod → F5 starts with a feasibility probe + and stays behind it; `host_attested` receipts never pass for enforced isolation. ## Design Details ### Commands +Environment: phase 1 runs on the developer machine (macOS arm64, Node 26) and in GitHub Actions +on `ubuntu-24.04` and `ubuntu-24.04-arm`, where `test.yml` already shards every package suite. No +remote host is needed for phase 1. F5's physical qualification needs a CUDA host through +`LOOPWRIGHT_CUDA_SSH_HOST`; without one, that evidence row stays `blocked_external`. + ```sh npm ci npm run build +npx tsc -p tsconfig.test.json npm run typecheck npm run lint npm run lint:docs npm run site +node scripts/run-tests.mjs --pkg core node scripts/run-tests.mjs --pkg controller node scripts/run-tests.mjs --pkg state --concurrency 1 node scripts/run-tests.mjs --pkg taskpack node scripts/run-tests.mjs --pkg evolution --concurrency 1 +node scripts/run-tests.mjs --pkg hardware-runner +node scripts/run-tests.mjs --pkg cli node packages/cli/dist/main.js closure --verify-failures ``` ### Project Structure ```text -packages/core/src/contracts.ts # evidence vocabulary, new limits -packages/core/src/limits.ts # captureBytes, command entries, localChecks timeout -packages/controller/src/registry.ts # command.v1 handler parameters, exec role profile, consumer: exec -packages/controller/src/config.ts # controls.localChecks, admission consistency -packages/controller/src/verification.ts # command.v1 slot execution under direct -packages/controller/src/verifier-worker.ts -packages/controller/src/controller.ts # exec dispatch instead of awaiting_role; refusal of mixed plans -packages/controller/src/step.ts # exec roles never yield; capture path shared with submit -packages/controller/src/credentials.ts # consumer: exec bindings, scrubbing of captured output -packages/taskpack/src/sandbox.ts # imports the shared script-contract module (no behavior change) -packages/cli/src/closure.ts # two new rows -packages/cli/src/evolve.ts # phase 2: export --snapshot, import, check --bundle -packages/evolution/src/bundle.ts # phase 2: campaign-snapshot.v1 writer and reader -packages/hardware-runner/src/config.ts # phase 2: deviceOwnership +packages/core/src/contracts.ts # evidence level and capability host_execution +packages/core/src/limits.ts # captureBytes, exec command entries, localChecks timeout, CHECK_OUT bytes +packages/core/src/local-check-contract.ts # Managed Controller command.v1 contract: env names, CHECK_OUT parser, env name rule +packages/core/src/usage.ts # provenance reported | unknown for exec request records +packages/controller/src/types.ts # RoleAdapterKind gains exec; exec profile and exec PlannedRole types +packages/controller/src/registry.ts # command.v1 handler, host.localChecks, exec profile, consumer: exec +packages/controller/src/config.ts # host.localChecks consistency, timeout fit +packages/controller/src/candidate-workspace.ts # moved from step.ts: materialize and scan a candidate directory +packages/controller/src/local-check.ts # LocalCheck executor and authority (modeled on gate.ts) +packages/controller/src/exec-role.ts # exec runner: spawn, environment allowlist, exit mapping, usage file +packages/controller/src/compile.ts # command.v1 slot preparation at admission, exec branches, mixed-plan refusal +packages/controller/src/controller.ts # slot routing to LocalCheck, exec branch in role(), rework detail for command.v1 +packages/controller/src/step.ts # imports candidate-workspace.ts; refuses exec plans +packages/controller/src/credentials.ts # consumer: exec bindings +packages/controller/src/budget-observations.ts # counts exec dispatches as model calls +packages/controller/src/recovery.ts # exec and command.v1 operations without proof settle unknown +packages/controller/src/capture.ts # adopt path shared with step submit +packages/cli/src/closure.ts # 23 to 26 rows +packages/cli/src/failure-matrix.ts +packages/cli/src/evolve.ts # phase 2: export --snapshot, check --bundle, import +packages/cli/src/main.ts # phase 2: runner inline; evolve subcommands +packages/cli/src/arguments.ts # phase 2: new flags +packages/evolution/src/snapshot.ts # phase 2: campaign-snapshot.v1 writer, verifier, reader +packages/evolution/src/store.ts # phase 2: snapshot_provenance table +packages/evolution/src/bundle.ts # phase 2: refuses host_attested receipts without the flag +packages/hardware-runner/src/config.ts # phase 2: deviceOwnership +packages/hardware-runner/src/worker.ts # phase 2: native_os with physical under deviceOwnership +packages/hardware-runner/src/evaluator.ts +packages/hardware-runner/src/provenance.ts # phase 2: isolation field docs/configuration/controller-and-registry.md docs/contribute/closure-matrix.md +docs/contribute/adr/0003-linux-sqlite-profiles.md docs/walkthroughs/managed-controller-in-isolated-host.md docs/operations/cli.md +docs/README.md +site/data/navigation.yaml +scripts/check-docs.mjs ``` ### Code Style @@ -326,34 +453,36 @@ Strict ESM NodeNext, no `any`, untrusted records validated with the existing `re helpers. The registry entry and the role profile a sandbox runner writes: ```yaml -handlers: - - id: forge-evaluate - version: 1 - kind: check - implementation: command.v1 - digest: { algorithm: sha256, hex: } - parameters: - checkId: forge-evaluate - script: scripts/forge-evaluate.sh - args: [] - env: { FORGEVO_KERNEL_ID: rmsnorm_0123456789abcdef } - toolchainPaths: [] - networkMode: none - timeoutMs: 600000 - capabilities: [local_execution, read_only] -roleProfiles: - - id: author - adapter: exec - selection: { provider: openai, model: gpt-5, thinking: medium } - tools: [read, write, edit] - runtimeRef: null - providerCredentialRef: null - mcp: null - exec: - command: [forgevo-author] - env: { FORGEVO_LLM_BASE_URL: "https://api.example.com/v1" } - credentialRefs: [llm-token] - timeoutMs: 600000 +spec: + host: + localChecks: { backend: direct } + handlers: + - id: forge-evaluate + version: 1 + kind: check + implementation: command.v1 + digest: { algorithm: sha256, hex: } + parameters: + checkId: forge-evaluate + script: scripts/forge-evaluate.sh + args: [] + env: { FORGEVO_KERNEL_ID: rmsnorm_0123456789abcdef } + toolchainPaths: [] + timeoutMs: 600000 + capabilities: [host_execution] + roleProfiles: + - id: author + adapter: exec + selection: { provider: openai, model: gpt-5, thinking: medium } + tools: [read, write, edit] + runtimeRef: null + providerCredentialRef: null + mcp: null + exec: + command: [/usr/local/bin/forgevo-author] + env: { FORGEVO_LLM_BASE_URL: "https://api.example.com/v1" } + credentialRefs: [llm-token] + timeoutMs: 600000 ``` ```ts @@ -363,7 +492,6 @@ export interface LocalCheckSpec { readonly args: readonly string[]; readonly env: Readonly>; readonly toolchainPaths: readonly string[]; - readonly networkMode: 'none' | 'loopback-only'; readonly timeoutMs: number; } @@ -377,11 +505,149 @@ export interface LocalCheckOutcome { ### Implementation Plan -> TODO — completed by `my-plan`. +Phase 1 is T1 to T8 and ships what the first consumer needs. Phase 2 is T9 to T12. T1, T2, T5, +T9, and T11 have disjoint `Owns:` and start together. + +- [ ] **T1 · Prefactor: shared candidate workspace helpers** + Blocked by: None + Owns: `packages/controller/src/candidate-workspace.ts`, `packages/controller/src/step.ts`, `packages/controller/test/step-engine.test.ts` + Gate: review + Acceptance: `materializeAttemptWorkspace` and `scanCandidateDirectory` move verbatim into `candidate-workspace.ts` with exported signatures; `step.ts` imports them; the step tests change only their imports. + Verify: `node scripts/run-tests.mjs --pkg controller` +- [ ] **T2 · Schema tracer: `command.v1`, `host.localChecks`, `exec` profiles, `consumer: exec`, `host_execution`** + Blocked by: None + Owns: `packages/core/src/contracts.ts`, `packages/core/src/limits.ts`, `packages/controller/src/types.ts`, `packages/controller/src/registry.ts`, `packages/controller/src/config.ts`, `packages/controller/test/registry-command-v1.test.ts`, `packages/controller/test/exec-profile.test.ts`, `packages/controller/test/config-local-checks.test.ts`, `packages/core/test/contracts.test.ts` + Acceptance: `validateRegistry` accepts a `command.v1` handler with the F1 parameters and `host.localChecks.backend: direct`, and an `exec` profile with the F2 keys; it refuses the F1 and F2 refusal cases with the codes named there. `loadConfiguration` refuses a registry with a `command.v1` handler but no `host.localChecks`, any backend other than `direct`, and a `timeoutMs` that cannot fit between `drainReserveMs` and `wallTimeMs`. `host_execution` is accepted as an evidence level and a capability, and `RoleAdapterKind` includes `'exec'`. + Verify: `node scripts/run-tests.mjs --pkg controller && node scripts/run-tests.mjs --pkg core` +- [ ] **T3 · `LocalCheck` module: contract, executor, and authority** + Blocked by: T1, T2 + Owns: `packages/core/src/local-check-contract.ts`, `packages/core/src/index.ts`, `packages/core/test/local-check-contract.test.ts`, `packages/controller/src/local-check.ts`, `packages/controller/test/local-check.test.ts`, `packages/controller/test/local-check-fixtures.ts` + Gate: review + Acceptance: the contract module exports the environment names, the env name rule, and the `$LOOPWRIGHT_CHECK_OUT` parser (64 KiB, `passed` and `summary` refused, metric and finding bounds). `LocalCheck.run(job, signal)` follows `Gate.run` and executes the script in its own process group with the binding marker written first: candidate materialized through the T1 helpers into a disposable directory, the F1 environment, `timeoutMs` with process-group kill, exit-code mapping, output artifact bound to `candidateDigest`, scrubbed stderr tail, receipt with `method: 'direct_script'` and the script and registry digests. The captured overlay is byte-identical before and after; an operation without a proof marker settles `blocked` with `EVIDENCE_UNAVAILABLE` and is not re-dispatched. + Verify: `node scripts/run-tests.mjs --pkg core && node scripts/run-tests.mjs --pkg controller` +- [ ] **T4 · `command.v1` controller integration** + Blocked by: T3 + Owns: `packages/controller/src/compile.ts`, `packages/controller/src/controller.ts`, `packages/controller/src/recovery.ts`, `packages/controller/test/compile.test.ts`, `packages/controller/test/rework.test.ts`, `packages/controller/test/local-check-integration.test.ts`, `packages/controller/test/recovery-cycle.test.ts` + Gate: review + Acceptance: admission resolves the script and `toolchainPaths` at `target.sourceRevision` from the baseline tree, requires the executable bit and a fully protected script directory, and records the directory digest in the compiled slot; `check` validates schema and budget only; the controller dispatches `command.v1` slots to `LocalCheck`, extracts `detail` for them in the rework summary, and exports the receipt through `inspect`; recovery settles a `command.v1` operation without a proof marker as `blocked`. A controller cycle test with the deterministic fake adapter as author and the T3 stub scripts settles `completed` for a passing script and reworks with `detail` for a failing one. + Verify: `node scripts/run-tests.mjs --pkg controller` +- [ ] **T5 · `exec` runner module** + Blocked by: T2 + Owns: `packages/controller/src/exec-role.ts`, `packages/controller/test/exec-role.test.ts`, `packages/controller/test/exec-role-fixtures.ts` + Gate: review + Acceptance: `runExecRole(spec, context)` validates an absolute `command[0]`, spawns `[...command, ...args, promptFile, candidateDir]` in its own process group with `cwd = candidateDir` and closed stdin, builds the F2 environment from an allowlist plus the configured `env` and the credentials supplied through a `SecretResolver` interface, captures stdout and stderr up to `captureBytes` and scrubs them, maps exit `0`, `3`, other, and timeout as F2 says, kills the group on timeout, and reads the optional usage file into request records. Tests cover each mapping, an environment diff against the allowlist, scrubbing, and process-group cleanup. + Verify: `node scripts/run-tests.mjs --pkg controller` +- [ ] **T6 · `exec` controller integration** + Blocked by: T4, T5 + Owns: `packages/controller/src/controller.ts`, `packages/controller/src/compile.ts`, `packages/controller/src/step.ts`, `packages/controller/src/credentials.ts`, `packages/controller/src/budget-observations.ts`, `packages/controller/src/recovery.ts`, `packages/controller/src/capture.ts`, `packages/controller/test/delegated-compile.test.ts`, `packages/controller/test/exec-role-integration.test.ts`, `packages/controller/test/recovery-owner.test.ts` + Gate: review + Acceptance: compile branches on `exec` (no runtime profile, provider credential, or context guard; the F2 `policy`; credentials equal the named refs); `role()` records the intent and binding marker, runs the T5 runner, synthesizes the submission as `step submit` does, captures through `adoptRoleCapture`, and never enters format repair; recovery settles an `exec` operation without a proof marker as `RECOVERY_REQUIRED`, kills the recorded group, and discards the attempt directory; `run` and `resume` admit all-`exec` plans and refuse mixes with `pi` or `delegated`; `step next` refuses `exec` plans; `consumer: exec` bindings resolve through the vault. Tests: in-scope write settles `completed` with the file exported; out-of-scope write fails `scope.v1`; exit `3` settles `blocked`; free-text stdout never repairs; a mid-exec kill resumes as `RECOVERY_REQUIRED` without re-dispatch; a bound credential appears in no `inspect` output. + Verify: `node scripts/run-tests.mjs --pkg controller` +- [ ] **T7 · `exec` budgets and usage ledger** + Blocked by: T6 + Owns: `packages/controller/src/budget-observations.ts`, `packages/controller/src/controller.ts`, `packages/core/src/usage.ts`, `packages/core/test/usage.test.ts`, `packages/controller/test/exec-usage.test.ts` + Acceptance: each `exec` dispatch charges one model call under `maxModelCalls` hard admission before the spawn; the optional usage file lands in the ledger as request records with `provenance: 'reported'`; without it, usage records `provenance: 'unknown'`; `usage.json` exports both. + Verify: `node scripts/run-tests.mjs --pkg controller && node scripts/run-tests.mjs --pkg core` +- [ ] **T8 · Closure matrix, ADR, and documentation** + Blocked by: T4, T6, T7 + Owns: `packages/cli/src/closure.ts`, `packages/cli/src/failure-matrix.ts`, `packages/cli/test/closure-and-failure-matrix.test.ts`, `docs/contribute/closure-matrix.md`, `docs/configuration/controller-and-registry.md`, `docs/operations/cli.md`, `docs/operations/coding-agents.md`, `docs/configuration/task-contract.md`, `docs/walkthroughs/managed-controller-in-isolated-host.md`, `docs/contribute/adr/0003-linux-sqlite-profiles.md`, `docs/README.md`, `site/data/navigation.yaml`, `scripts/check-docs.mjs` + Acceptance: the ledger has 26 rows (two `closed_local`, one `blocked_external`) with the tests named; `closure` reports the split and `--verify-failures` passes; ADR 0003 supersedes the profile sentence of ADR 0001 with the CI evidence and the Linux `fullfsync` semantics; the handler table, the registry fields, the role profiles, the credential consumers, the evidence level, the CLI pages, the ADR table, the new walkthrough, and this spec are linked from `docs/README.md`; the walkthrough is in the site navigation and the public site paths. + Verify: `npm run lint:docs && npm run site && node packages/cli/dist/main.js closure --verify-failures` +- [ ] **T9 · Campaign snapshot module (phase 2)** + Blocked by: None + Owns: `packages/evolution/src/snapshot.ts`, `packages/evolution/src/index.ts`, `packages/evolution/src/store.ts`, `packages/evolution/src/bundle.ts`, `packages/evolution/test/snapshot.test.ts` + Gate: review + Acceptance: `writeCampaignSnapshot(store, outDir, { parentDigest })` writes the F4 members, includes every individual with its status and `receipt: null` when no approved receipt exists, verifies receipts fail-closed, and refuses `synthetic_fixture` without the flag; `verifyCampaignSnapshot(bundleDir, { receiptSecret })` validates offline; `importCampaignSnapshot(bundleDir, stateDir, { receiptSecret })` refuses a non-empty state directory, creates a fresh `campaign_meta` and a `snapshot_provenance` row, copies the search tables verbatim, and never copies clock or fence columns. `exportEvolutionBundle` refuses `host_attested` receipts without the flag. + Verify: `node scripts/run-tests.mjs --pkg evolution --concurrency 1` +- [ ] **T10 · Snapshot CLI and documentation (phase 2)** + Blocked by: T8, T9 + Owns: `packages/cli/src/evolve.ts`, `packages/cli/src/main.ts`, `packages/cli/src/arguments.ts`, `packages/cli/test/evolve-snapshot.test.ts`, `docs/configuration/campaign-snapshots.md`, `docs/operations/cli.md`, `docs/README.md`, `site/data/navigation.yaml` + Acceptance: `evolve export --snapshot`, `evolve check --bundle`, and `evolve import` exist with `--receipt-secret-env` and exit codes consistent with the other `evolve` commands; `docs/README.md` and the site navigation index the new page; `lint:docs` and `site` pass. + Verify: `node scripts/run-tests.mjs --pkg cli && npm run lint:docs && npm run site` +- [ ] **T11 · In-process benchmark gate, feasibility first (phase 2)** + Blocked by: None + Owns: `packages/hardware-runner/src/config.ts`, `packages/hardware-runner/src/worker.ts`, `packages/hardware-runner/src/evaluator.ts`, `packages/hardware-runner/src/provenance.ts`, `packages/hardware-runner/src/relay-server.ts`, `packages/hardware-runner/src/index.ts`, `packages/hardware-runner/test/**`, `packages/cli/src/main.ts`, `packages/cli/src/arguments.ts`, `packages/cli/test/runner-inline.test.ts` + Gate: review + Acceptance: first, a recorded probe decides whether `native_os` can create its namespaces under the target Pod profile (RuntimeDefault seccomp, all capabilities dropped); if it cannot, the task reports that and stops before any feature code. Then `deviceOwnership: host` permits `sandboxBackend: native_os` with `probeMode: physical`, `hardwareProvenance.isolation` records `docker` or `host_attested`, and `loopwright runner inline --config worker.yaml` serves relay and worker in one process on loopback; a loopback end-to-end test runs `benchmark-gate.v1` through the inline runner on `synthetic_fixture`; the physical evidence row stays `blocked_external`. + Verify: `node scripts/run-tests.mjs --pkg hardware-runner && node scripts/run-tests.mjs --pkg cli` +- [ ] **T12 · In-process gate documentation (phase 2)** + Blocked by: T8, T10, T11 + Owns: `docs/operations/cli.md`, `docs/configuration/task-contract.md`, `docs/contribute/closure-matrix.md`, `docs/README.md` + Acceptance: `runner inline`, `deviceOwnership`, the `isolation` field, and the `blocked_external` row are documented and indexed. + Verify: `npm run lint:docs && npm run site` ### Test Plan -> TODO — completed by `my-plan`. +- [x] The owners of the involved components may require updates to existing tests to make this code +solid enough prior to committing the changes necessary to implement this enhancement. + +#### Prerequisite testing updates + +- Controller fixtures (`config-fixtures.ts`, `scheduling-fixtures.ts`) gain a registry with a + `command.v1` handler and `host.localChecks: { backend: direct }`, and a stub script directory + under `test/fixtures/scripts/` with four scripts: pass (writes metrics), fail (exits `1` with a + stderr reason), sleep (runs past `timeoutMs`), and write-outside-candidate (attempts a write + under the baseline). +- A stub `exec` command under `packages/controller/test/exec-role-fixtures.ts`: writes one file + inside `scope.writable`, one outside it, exits `3`, sleeps past `timeoutMs`, calls `setsid` + and forks a child, and prints a provided secret to stdout. +- CI: `test.yml` already shards every package on `ubuntu-24.04` and `ubuntu-24.04-arm`; T8 + records that evidence in ADR 0003. No workflow change is expected. + +#### Unit tests + +The repository runs `node:test` without coverage measurement, so no coverage percentage is +tracked. Every new module has a named test file; every changed validation path has a refusal case +with the exact error code asserted. + +- `packages/core`: phase 1 - `local-check-contract.test.ts` (parser bounds, reserved keys, env + name rule), `contracts.test.ts` additions (`host_execution` level and capability), + `usage.test.ts` additions (`provenance: 'reported' | 'unknown'`). +- `packages/controller`: phase 1 - `registry-command-v1.test.ts`, `exec-profile.test.ts`, + `config-local-checks.test.ts`, `local-check.test.ts`, `local-check-integration.test.ts`, + `exec-role.test.ts`, `exec-role-integration.test.ts`, `exec-usage.test.ts`, + `step-engine.test.ts` (imports only), `compile.test.ts`, `rework.test.ts`, + `delegated-compile.test.ts`, `recovery-cycle.test.ts`, `recovery-owner.test.ts` additions. +- `packages/taskpack`: phase 1 - unchanged and green (no Taskpack change in this spec). +- `packages/cli`: phase 1 - `closure-and-failure-matrix.test.ts` rows; phase 2 - `evolve-snapshot.test.ts`, + `runner-inline.test.ts`. +- `packages/evolution`: phase 2 - `snapshot.test.ts` (write, verify, import on a host with a + lower monotonic clock, failed individuals without receipts, tamper, synthetic refusal, + non-empty state refusal, `host_attested` refusal in export). +- `packages/hardware-runner`: phase 2 - `deviceOwnership` validation, the namespace feasibility + probe, `isolation` in provenance, inline relay and worker loopback on `synthetic_fixture`. + +#### Integration tests + +- `local-check-integration.test.ts`: a full controller cycle with the deterministic fake adapter + as author and a `command.v1` script; passing script settles `completed` with `host_execution` + evidence, failing script reworks with `detail`, `verification.json` carries the receipt with + method and digests, and the overlay digest is invariant across the check. +- `exec-role-integration.test.ts`: the stub outcomes through `run` (`completed`, `scope.v1` + failure, `blocked`, `failed`), free-text stdout without `repairFormat`, and `inspect` output + scrubbing. +- Recovery suites: a controller killed between the binding and proof markers of a `LocalCheck` + or an `exec` operation settles `blocked` or `RECOVERY_REQUIRED`, kills the recorded group, + discards the attempt directory, and never re-dispatches the same operation. +- Admission: `check`, `run`, and `step next` refuse `pi` + `exec` and `delegated` + `exec` plans + at admission with the same code. +- Repeated failure: a `command.v1` check that fails twice with the same reason on an unchanged + candidate halts with `REPEAT_FAILURE` whatever the stderr says. +- `evolve-snapshot.test.ts` (phase 2): export, check, import, resume on `synthetic_fixture` + verdicts, including failed and preempted individuals. + +#### e2e tests + +- The first end-to-end consumer is the forgevo runner, whose own e2e drives `loopwright run` + with a real `exec` author and a real `command.v1` harness inside a restricted container; that + test owns the cross-repository e2e, including the `direct` probe: a script that tries to read + the store, the registry, and the controller's `/proc//environ`, asserting that the + receipt and lock mark the `direct` attestation even where the reads succeed. +- This repository adds one manual walkthrough run of + `docs/walkthroughs/managed-controller-in-isolated-host.md` in a `node:26` container on + linux/amd64 before T8 ships, recorded in the walkthrough's verification notes. +- `closure --verify-failures` remains the e2e gate for the failure matrix; the physical CUDA + qualification for T11 is an external qualification and stays `blocked_external` until it runs. ## Alternatives @@ -392,8 +658,19 @@ export interface LocalCheckOutcome { Rejected in favor of the `exec` adapter. - **Taskpack mode for sandbox runs.** It already has `command.v1`; it also brings triggers, upstreams, publication, and a different trust model. The requirement is Managed Controller. +- **Sharing the Taskpack `command.v1` implementation.** Taskpack depends on the controller, not + the reverse; its contract differs in environment names, detail limits, and scrub-versus-refuse + semantics. Unifying them would change Taskpack behavior, a Non-Goal. Managed Controller + defines its own contract in `@loopwright/core`. +- **The `direct` attestation in `ControllerConfig`.** `ControllerConfig` lives in an untrusted + root; a run author could turn on unsandboxed execution. Rejected; the attestation lives in the + digest-pinned registry. - **Docker-in-Pod for the `pi` adapter.** Needs a socket or a sidecar daemon, which a `restricted` Pod forbids. Delegated and `exec` roles need no container runtime. +- **Re-dispatching an `exec` attempt after a crash.** Repeats an uncertain paid call and can leave + two writers in one directory. Rejected; unknown outcomes settle as unknown. +- **Copying a campaign store verbatim across hosts.** Copies clock and fence state and fails the + store's clock guard. Rejected; import creates a fresh authority. - **Remote state store or WAL shipping.** Rejected for run and campaign authority: the store is the fence (ADR 0001). Portable snapshots give cross-host continuity without a service. - **A `docker` backend for Managed Controller checks.** Useful on shared hosts; not needed by the @@ -401,15 +678,15 @@ export interface LocalCheckOutcome { ## Open Questions -1. Which CI runners qualify `node:sqlite` for the state package on linux/amd64 and linux/arm64, - and does the frozen profile (`synchronous EXTRA`, `fullfsync`) hold there? -2. Should `direct` be a controller-level control (this spec) or a per-handler parameter when a - plan mixes local and remote checks? -3. Is the optional usage file the right shape for `exec` token accounting, or should `exec` - report usage on stdout as a trailing JSON line? -4. Should phase 2 allow `exec` and `delegated` roles in one plan by running `exec` inline during - `step submit`? -5. Does the inline runner (F5) need its own relay authentication, or may it bind the controller +1. Should `direct` be a registry-level attestation (this spec) or also allow a per-handler + opt-out when one registry mixes sandboxed and host-attested checks? +2. Is the usage file the right shape for `exec` token accounting, or should `exec` report usage + on stdout as a trailing JSON line? +3. Does the inline runner (F5) need its own relay authentication, or may it bind the controller and worker identities in-process without HMAC? -6. Which analytics export format (Parquet or JSONL) would operators read, and is it worth a +4. Can `native_os` create its namespaces under the target Pod profile at all? T11's probe + answers this before any feature code. +5. Which analytics export format (Parquet or JSONL) would operators read, and is it worth a dependency on a Parquet writer? +6. Should the Taskpack reference page's `command.v1` parameter table gain the `networkMode` + row it accepts today? Out of this spec's scope; noted for the docs owner. From 6039917ffde7fe1e5b93b652bbad462fdad3c5ae Mon Sep 17 00:00:00 2001 From: thxCode Date: Mon, 30 Nov 2026 21:11:47 +0800 Subject: [PATCH 03/26] docs(specs): reconcile exec prompt source, usage file, and timeout fit - exec role binds pi.agent.v1 handler; dispatch follows adapter - controller sets LOOPWRIGHT_USAGE_OUT inside attempt scratch - exec timeoutMs obeys the command.v1 drain-reserve fit rule - T5 follows T2; T1, T2, T9, T11 start together Signed-off-by: thxCode --- ...managed-controller-in-process-execution.md | 29 ++++++++++++------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/specs/2026-11-30-managed-controller-in-process-execution.md b/specs/2026-11-30-managed-controller-in-process-execution.md index f5bd7610..781c3ca8 100644 --- a/specs/2026-11-30-managed-controller-in-process-execution.md +++ b/specs/2026-11-30-managed-controller-in-process-execution.md @@ -190,13 +190,18 @@ controller's own environment on a host whose isolation the registry attests. does, and writes a binding marker with the attempt, step, role, prompt digest, and the child's process group. - argv = `[...command, ...args, promptFile, candidateDir]`. The prompt file holds the - effective prompt including any rework appendix. `candidateDir` is a fresh attempt directory + task prompt of the step's bound `pi.agent.v1` handler (`purpose: task`) plus any rework + appendix. An `exec` role binds to that handler exactly as a `delegated` role does; dispatch is + decided by the role profile's `adapter: exec`, never by the handler implementation. + `candidateDir` is a fresh attempt directory with its read-only context files. - Environment is an allowlist: `PATH` fixed to `/usr/local/bin:/usr/bin:/bin`, `HOME` and `TMPDIR` (the attempt scratch directory), `LANG`, `TERM`, the configured `env`, the bound credentials, and `LOOPWRIGHT_RUN_ID`, `LOOPWRIGHT_STEP_ID`, `LOOPWRIGHT_ROLE_ID`, `LOOPWRIGHT_ATTEMPT_ID`, `LOOPWRIGHT_SCOPE_WRITABLE` (colon-separated globs), - `LOOPWRIGHT_ALLOWED_TOOLS`, `LOOPWRIGHT_CONTEXT_FILES`. The controller never passes its + `LOOPWRIGHT_ALLOWED_TOOLS`, `LOOPWRIGHT_CONTEXT_FILES`, and `LOOPWRIGHT_USAGE_OUT` (a file + path inside the attempt scratch directory; the controller sets it because the command cannot + know that path, reads the file after exit, and scrubs it). The controller never passes its own `process.env`. - `cwd` is `candidateDir`. `stdin` is closed. `stdout` and `stderr` are captured up to `captureBytes` (default 65536, 1024..1048576), scrubbed, and attached to the attempt record. @@ -226,9 +231,11 @@ controller's own environment on a host whose isolation the registry attests. refuses `exec` plans. Consequence: in a Pod without Docker, no reviewer step exists in this version; the measured check is the reviewer. - **Budgets and usage.** `wallTime`, `modelCalls` (one per dispatch), and `concurrency` enforce - as hard admission; admission is per dispatch and happens before the spawn. Provider calls made - inside one dispatch are the command's responsibility. Optional usage file: if - `LOOPWRIGHT_USAGE_OUT` names a file the command wrote, the controller reads + as hard admission; admission is per dispatch and happens before the spawn. `check` refuses an + `exec` `timeoutMs` that cannot fit between `controls.drainReserveMs` and `budgets.wallTimeMs`, + the same rule as `command.v1` `timeoutMs`. Provider calls made inside one dispatch are the + command's responsibility. Optional usage file: the controller sets `LOOPWRIGHT_USAGE_OUT` to a + path inside the attempt scratch directory; if the command wrote that file, the controller reads `{ requests: [{ requestId, inputTokens, outputTokens, costMicrousd }] }` (bounded, scrubbed) into the usage ledger with `provenance: 'reported'`; without the file, usage records `provenance: 'unknown'`, never zero ([usage.ts](../packages/core/src/usage.ts)). @@ -505,8 +512,8 @@ export interface LocalCheckOutcome { ### Implementation Plan -Phase 1 is T1 to T8 and ships what the first consumer needs. Phase 2 is T9 to T12. T1, T2, T5, -T9, and T11 have disjoint `Owns:` and start together. +Phase 1 is T1 to T8 and ships what the first consumer needs. Phase 2 is T9 to T12. T1, T2, T9, +and T11 have disjoint `Owns:` and start together; T5 follows T2. - [ ] **T1 · Prefactor: shared candidate workspace helpers** Blocked by: None @@ -517,7 +524,7 @@ T9, and T11 have disjoint `Owns:` and start together. - [ ] **T2 · Schema tracer: `command.v1`, `host.localChecks`, `exec` profiles, `consumer: exec`, `host_execution`** Blocked by: None Owns: `packages/core/src/contracts.ts`, `packages/core/src/limits.ts`, `packages/controller/src/types.ts`, `packages/controller/src/registry.ts`, `packages/controller/src/config.ts`, `packages/controller/test/registry-command-v1.test.ts`, `packages/controller/test/exec-profile.test.ts`, `packages/controller/test/config-local-checks.test.ts`, `packages/core/test/contracts.test.ts` - Acceptance: `validateRegistry` accepts a `command.v1` handler with the F1 parameters and `host.localChecks.backend: direct`, and an `exec` profile with the F2 keys; it refuses the F1 and F2 refusal cases with the codes named there. `loadConfiguration` refuses a registry with a `command.v1` handler but no `host.localChecks`, any backend other than `direct`, and a `timeoutMs` that cannot fit between `drainReserveMs` and `wallTimeMs`. `host_execution` is accepted as an evidence level and a capability, and `RoleAdapterKind` includes `'exec'`. + Acceptance: `validateRegistry` accepts a `command.v1` handler with the F1 parameters and `host.localChecks.backend: direct`, and an `exec` profile with the F2 keys beside a `pi.agent.v1` agent handler; it refuses the F1 and F2 refusal cases with the codes named there. `loadConfiguration` refuses a registry with a `command.v1` handler but no `host.localChecks`, any backend other than `direct`, and a `command.v1` or `exec` `timeoutMs` that cannot fit between `drainReserveMs` and `wallTimeMs`. `host_execution` is accepted as an evidence level and a capability, and `RoleAdapterKind` includes `'exec'`. Verify: `node scripts/run-tests.mjs --pkg controller && node scripts/run-tests.mjs --pkg core` - [ ] **T3 · `LocalCheck` module: contract, executor, and authority** Blocked by: T1, T2 @@ -535,18 +542,18 @@ T9, and T11 have disjoint `Owns:` and start together. Blocked by: T2 Owns: `packages/controller/src/exec-role.ts`, `packages/controller/test/exec-role.test.ts`, `packages/controller/test/exec-role-fixtures.ts` Gate: review - Acceptance: `runExecRole(spec, context)` validates an absolute `command[0]`, spawns `[...command, ...args, promptFile, candidateDir]` in its own process group with `cwd = candidateDir` and closed stdin, builds the F2 environment from an allowlist plus the configured `env` and the credentials supplied through a `SecretResolver` interface, captures stdout and stderr up to `captureBytes` and scrubs them, maps exit `0`, `3`, other, and timeout as F2 says, kills the group on timeout, and reads the optional usage file into request records. Tests cover each mapping, an environment diff against the allowlist, scrubbing, and process-group cleanup. + Acceptance: `runExecRole(spec, context)` validates an absolute `command[0]`, spawns `[...command, ...args, promptFile, candidateDir]` in its own process group with `cwd = candidateDir` and closed stdin, builds the F2 environment from an allowlist plus the configured `env` and the credentials supplied through a `SecretResolver` interface, captures stdout and stderr up to `captureBytes` and scrubs them, maps exit `0`, `3`, other, and timeout as F2 says, kills the group on timeout, exports the usage-file path from its context as `LOOPWRIGHT_USAGE_OUT`, and reads that file after exit into scrubbed request records. Tests cover each mapping, an environment diff against the allowlist, scrubbing, and process-group cleanup. Verify: `node scripts/run-tests.mjs --pkg controller` - [ ] **T6 · `exec` controller integration** Blocked by: T4, T5 Owns: `packages/controller/src/controller.ts`, `packages/controller/src/compile.ts`, `packages/controller/src/step.ts`, `packages/controller/src/credentials.ts`, `packages/controller/src/budget-observations.ts`, `packages/controller/src/recovery.ts`, `packages/controller/src/capture.ts`, `packages/controller/test/delegated-compile.test.ts`, `packages/controller/test/exec-role-integration.test.ts`, `packages/controller/test/recovery-owner.test.ts` Gate: review - Acceptance: compile branches on `exec` (no runtime profile, provider credential, or context guard; the F2 `policy`; credentials equal the named refs); `role()` records the intent and binding marker, runs the T5 runner, synthesizes the submission as `step submit` does, captures through `adoptRoleCapture`, and never enters format repair; recovery settles an `exec` operation without a proof marker as `RECOVERY_REQUIRED`, kills the recorded group, and discards the attempt directory; `run` and `resume` admit all-`exec` plans and refuse mixes with `pi` or `delegated`; `step next` refuses `exec` plans; `consumer: exec` bindings resolve through the vault. Tests: in-scope write settles `completed` with the file exported; out-of-scope write fails `scope.v1`; exit `3` settles `blocked`; free-text stdout never repairs; a mid-exec kill resumes as `RECOVERY_REQUIRED` without re-dispatch; a bound credential appears in no `inspect` output. + Acceptance: compile branches on `exec` (no runtime profile, provider credential, or context guard; the F2 `policy`; credentials equal the named refs); `role()` records the intent and binding marker, takes the task prompt from the bound `pi.agent.v1` handler, sets `LOOPWRIGHT_USAGE_OUT` to a path inside the attempt scratch directory, runs the T5 runner, synthesizes the submission as `step submit` does, captures through `adoptRoleCapture`, and never enters format repair; recovery settles an `exec` operation without a proof marker as `RECOVERY_REQUIRED`, kills the recorded group, and discards the attempt directory; `run` and `resume` admit all-`exec` plans and refuse mixes with `pi` or `delegated`; `step next` refuses `exec` plans; `consumer: exec` bindings resolve through the vault. Tests: in-scope write settles `completed` with the file exported; out-of-scope write fails `scope.v1`; exit `3` settles `blocked`; free-text stdout never repairs; a mid-exec kill resumes as `RECOVERY_REQUIRED` without re-dispatch; a bound credential appears in no `inspect` output. Verify: `node scripts/run-tests.mjs --pkg controller` - [ ] **T7 · `exec` budgets and usage ledger** Blocked by: T6 Owns: `packages/controller/src/budget-observations.ts`, `packages/controller/src/controller.ts`, `packages/core/src/usage.ts`, `packages/core/test/usage.test.ts`, `packages/controller/test/exec-usage.test.ts` - Acceptance: each `exec` dispatch charges one model call under `maxModelCalls` hard admission before the spawn; the optional usage file lands in the ledger as request records with `provenance: 'reported'`; without it, usage records `provenance: 'unknown'`; `usage.json` exports both. + Acceptance: each `exec` dispatch charges one model call under `maxModelCalls` hard admission before the spawn; the usage file named by the controller-set `LOOPWRIGHT_USAGE_OUT` lands in the ledger as request records with `provenance: 'reported'`; without it, usage records `provenance: 'unknown'`; `usage.json` exports both. Verify: `node scripts/run-tests.mjs --pkg controller && node scripts/run-tests.mjs --pkg core` - [ ] **T8 · Closure matrix, ADR, and documentation** Blocked by: T4, T6, T7 From 5ee90d646c0a81c2e7ae14fa283874de19ce8afb Mon Sep 17 00:00:00 2001 From: thxCode Date: Mon, 30 Nov 2026 21:13:59 +0800 Subject: [PATCH 04/26] docs(specs): assign the optional isolation field to T9 - HardwareProvenance isolation is optional; absent means a docker-era receipt - T9 owns core evidence.ts and evolution schema.ts for the parser - T11 only produces the field; T9 lands the type first Signed-off-by: thxCode --- ...-managed-controller-in-process-execution.md | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/specs/2026-11-30-managed-controller-in-process-execution.md b/specs/2026-11-30-managed-controller-in-process-execution.md index 781c3ca8..bb83c4e8 100644 --- a/specs/2026-11-30-managed-controller-in-process-execution.md +++ b/specs/2026-11-30-managed-controller-in-process-execution.md @@ -314,9 +314,13 @@ controller's own environment on a host whose isolation the registry attests. ([evaluator.ts](../packages/hardware-runner/src/evaluator.ts)); a restricted Pod with RuntimeDefault seccomp usually cannot create them, so the first task is a feasibility probe in the target Pod profile, and the feature stays behind it. -- `hardwareProvenance` gains `isolation: 'docker' | 'host_attested'`. Receipts carry it; - `evolve export` refuses `host_attested` receipts unless `--allow-host-attested` is passed, so - a host declaration never passes for enforced isolation. +- `hardwareProvenance` gains an optional `isolation: 'docker' | 'host_attested'`. Every receipt + the worker signs carries it. An absent `isolation` marks a receipt that predates the field; only + the docker backend could produce such a receipt, because `native_os` refuses `probeMode: physical` + today. The type and schema live in [evidence.ts](../packages/core/src/evidence.ts) and the parser + in [schema.ts](../packages/evolution/src/schema.ts); T9 owns both. `evolve export` refuses + `host_attested` receipts unless `--allow-host-attested` is passed, so a host declaration never + passes for enforced isolation. - `loopwright runner inline --config worker.yaml` serves the relay and one worker in one process on loopback, for a controller whose `gateEndpoints` entry points at it. The two-stage isolation (Stage A without held-out workloads, Stage B read-only with them) is unchanged. @@ -419,6 +423,7 @@ packages/core/src/contracts.ts # evidence level and capability host_e packages/core/src/limits.ts # captureBytes, exec command entries, localChecks timeout, CHECK_OUT bytes packages/core/src/local-check-contract.ts # Managed Controller command.v1 contract: env names, CHECK_OUT parser, env name rule packages/core/src/usage.ts # provenance reported | unknown for exec request records +packages/core/src/evidence.ts # phase 2: optional isolation on hardwareProvenance packages/controller/src/types.ts # RoleAdapterKind gains exec; exec profile and exec PlannedRole types packages/controller/src/registry.ts # command.v1 handler, host.localChecks, exec profile, consumer: exec packages/controller/src/config.ts # host.localChecks consistency, timeout fit @@ -440,6 +445,7 @@ packages/cli/src/arguments.ts # phase 2: new flags packages/evolution/src/snapshot.ts # phase 2: campaign-snapshot.v1 writer, verifier, reader packages/evolution/src/store.ts # phase 2: snapshot_provenance table packages/evolution/src/bundle.ts # phase 2: refuses host_attested receipts without the flag +packages/evolution/src/schema.ts # phase 2: optional isolation in the provenance parser packages/hardware-runner/src/config.ts # phase 2: deviceOwnership packages/hardware-runner/src/worker.ts # phase 2: native_os with physical under deviceOwnership packages/hardware-runner/src/evaluator.ts @@ -562,9 +568,9 @@ and T11 have disjoint `Owns:` and start together; T5 follows T2. Verify: `npm run lint:docs && npm run site && node packages/cli/dist/main.js closure --verify-failures` - [ ] **T9 · Campaign snapshot module (phase 2)** Blocked by: None - Owns: `packages/evolution/src/snapshot.ts`, `packages/evolution/src/index.ts`, `packages/evolution/src/store.ts`, `packages/evolution/src/bundle.ts`, `packages/evolution/test/snapshot.test.ts` + Owns: `packages/evolution/src/snapshot.ts`, `packages/evolution/src/index.ts`, `packages/evolution/src/store.ts`, `packages/evolution/src/bundle.ts`, `packages/evolution/src/schema.ts`, `packages/core/src/evidence.ts`, `packages/evolution/test/snapshot.test.ts` Gate: review - Acceptance: `writeCampaignSnapshot(store, outDir, { parentDigest })` writes the F4 members, includes every individual with its status and `receipt: null` when no approved receipt exists, verifies receipts fail-closed, and refuses `synthetic_fixture` without the flag; `verifyCampaignSnapshot(bundleDir, { receiptSecret })` validates offline; `importCampaignSnapshot(bundleDir, stateDir, { receiptSecret })` refuses a non-empty state directory, creates a fresh `campaign_meta` and a `snapshot_provenance` row, copies the search tables verbatim, and never copies clock or fence columns. `exportEvolutionBundle` refuses `host_attested` receipts without the flag. + Acceptance: `writeCampaignSnapshot(store, outDir, { parentDigest })` writes the F4 members, includes every individual with its status and `receipt: null` when no approved receipt exists, verifies receipts fail-closed, and refuses `synthetic_fixture` without the flag; `verifyCampaignSnapshot(bundleDir, { receiptSecret })` validates offline; `importCampaignSnapshot(bundleDir, stateDir, { receiptSecret })` refuses a non-empty state directory, creates a fresh `campaign_meta` and a `snapshot_provenance` row, copies the search tables verbatim, and never copies clock or fence columns. `HardwareProvenance` gains the optional `isolation` field in core and in the evolution parser; `exportEvolutionBundle` refuses `host_attested` receipts without the flag and accepts them with it. Land that field edit first: T11 produces it. Verify: `node scripts/run-tests.mjs --pkg evolution --concurrency 1` - [ ] **T10 · Snapshot CLI and documentation (phase 2)** Blocked by: T8, T9 @@ -575,7 +581,7 @@ and T11 have disjoint `Owns:` and start together; T5 follows T2. Blocked by: None Owns: `packages/hardware-runner/src/config.ts`, `packages/hardware-runner/src/worker.ts`, `packages/hardware-runner/src/evaluator.ts`, `packages/hardware-runner/src/provenance.ts`, `packages/hardware-runner/src/relay-server.ts`, `packages/hardware-runner/src/index.ts`, `packages/hardware-runner/test/**`, `packages/cli/src/main.ts`, `packages/cli/src/arguments.ts`, `packages/cli/test/runner-inline.test.ts` Gate: review - Acceptance: first, a recorded probe decides whether `native_os` can create its namespaces under the target Pod profile (RuntimeDefault seccomp, all capabilities dropped); if it cannot, the task reports that and stops before any feature code. Then `deviceOwnership: host` permits `sandboxBackend: native_os` with `probeMode: physical`, `hardwareProvenance.isolation` records `docker` or `host_attested`, and `loopwright runner inline --config worker.yaml` serves relay and worker in one process on loopback; a loopback end-to-end test runs `benchmark-gate.v1` through the inline runner on `synthetic_fixture`; the physical evidence row stays `blocked_external`. + Acceptance: first, a recorded probe decides whether `native_os` can create its namespaces under the target Pod profile (RuntimeDefault seccomp, all capabilities dropped); if it cannot, the task reports that and stops before any feature code. Then `deviceOwnership: host` permits `sandboxBackend: native_os` with `probeMode: physical`, `hardwareProvenance.isolation` (the optional T9 field) records `docker` or `host_attested`, and `loopwright runner inline --config worker.yaml` serves relay and worker in one process on loopback; a loopback end-to-end test runs `benchmark-gate.v1` through the inline runner on `synthetic_fixture`; the physical evidence row stays `blocked_external`. Verify: `node scripts/run-tests.mjs --pkg hardware-runner && node scripts/run-tests.mjs --pkg cli` - [ ] **T12 · In-process gate documentation (phase 2)** Blocked by: T8, T10, T11 From e550ecb8fff662411abd3346675b432f8880ff84 Mon Sep 17 00:00:00 2001 From: thxCode Date: Mon, 30 Nov 2026 23:41:22 +0800 Subject: [PATCH 05/26] feat(evolution): add campaign snapshots and optional isolation field - write, verify, import campaign-snapshot.v1 with fresh authority - snapshot_provenance table and single-transaction importCampaignState - HardwareProvenance.isolation optional; export refuses host_attested - move shared bundle helpers into internal bundle-fs.ts - T9 spec check-off; F4 members, Owns widenings, Open Question 3 Task 9 of managed-controller-in-process-execution. Signed-off-by: thxCode --- packages/core/src/evidence.ts | 3 + packages/evolution/src/bundle-fs.ts | 855 ++++++++++ packages/evolution/src/bundle.ts | 841 +--------- packages/evolution/src/index.ts | 1 + packages/evolution/src/schema.ts | 5 + packages/evolution/src/snapshot.ts | 1391 +++++++++++++++++ packages/evolution/src/store.ts | 480 ++++-- packages/evolution/test/snapshot.test.ts | 1056 +++++++++++++ ...managed-controller-in-process-execution.md | 25 +- 9 files changed, 3754 insertions(+), 903 deletions(-) create mode 100644 packages/evolution/src/bundle-fs.ts create mode 100644 packages/evolution/src/snapshot.ts create mode 100644 packages/evolution/test/snapshot.test.ts diff --git a/packages/core/src/evidence.ts b/packages/core/src/evidence.ts index 7d157557..c06b4ee8 100644 --- a/packages/core/src/evidence.ts +++ b/packages/core/src/evidence.ts @@ -29,6 +29,8 @@ export interface HardwareProvenance { readonly topology?: string; readonly workloadDigest: Digest; readonly clockLockMode: 'locked' | 'unlocked' | 'unknown'; + /** Absent on receipts that predate the field; only the docker backend can produce such receipts. */ + readonly isolation?: 'docker' | 'host_attested'; } const hardwareProvenanceSchema: Schema = record({ @@ -44,6 +46,7 @@ const hardwareProvenanceSchema: Schema = record({ topology: optional(printableText(1, 128)), workloadDigest: digestSchema, clockLockMode: enumeration('locked', 'unlocked', 'unknown'), + isolation: optional(enumeration('docker', 'host_attested')), }); export type BucketDimensionValue = number | string; diff --git a/packages/evolution/src/bundle-fs.ts b/packages/evolution/src/bundle-fs.ts new file mode 100644 index 00000000..dbbd215d --- /dev/null +++ b/packages/evolution/src/bundle-fs.ts @@ -0,0 +1,855 @@ +import { createHash, randomBytes } from 'node:crypto'; +import { constants as fsConstants } from 'node:fs'; +import { chmod, lstat, mkdir, open, rename, rm } from 'node:fs/promises'; +import { dirname, isAbsolute, join, resolve } from 'node:path'; +import { + LIMITS, + SecretScrubber, + validateRelativePath, + type BucketMetricEntry, + type Digest, + type HardwareDiagnostics, + type HardwareProvenance, +} from '@loopwright/core'; +import { + MAX_RECEIPT_FILE_BYTES, + verifyBenchmarkVerdictSignature, + type BenchmarkOutputArtifact, + type SignedBenchmarkVerdictReceipt, +} from '@loopwright/hardware-runner'; +import { + parseBucketMetricsJson, + parseHardwareDiagnosticsJson, + parseHardwareProvenanceJson, + parseNullProtoJson, + type NullProtoJson, +} from './schema.js'; +import { EvolutionError, type IndividualRecord } from './types.js'; + +/** + * Internal helpers shared by `bundle.ts` and `snapshot.ts`: symlink-hardened filesystem and CAS + * I/O, atomic staging publication, and fail-closed verdict receipt verification. + * NOT re-exported from `index.ts`; treat every export here as package-private. + */ + +export const DEFAULT_SECRET_SCRUBBER = new SecretScrubber(); + +export const DEFAULT_MAX_BLOB_BYTES = 67_108_864; // 64 MiB + +export const SHA256_HEX_RE = /^[0-9a-f]{64}$/; + +export const SAFE_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/; + +export const SAFE_FILENAME_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/; + +const BUCKET_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]*$/; + +export const PRINTABLE_ASCII_RE = /^[\x20-\x7E]+$/; + +export const LONE_SURROGATE_RE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(? = new Set(['__proto__', 'constructor', 'prototype']); + +const DARWIN_ROOT_SYMLINKS: ReadonlySet = new Set(['/var', '/tmp', '/etc']); + +const RECEIPT_ALLOWED_KEYS: ReadonlySet = new Set([ + 'version', + 'kind', + 'storeId', + 'runId', + 'lockHash', + 'operationId', + 'dispatchId', + 'dispatchGeneration', + 'gateId', + 'checkId', + 'candidateDigest', + 'status', + 'reason', + 'expiresAtMs', + 'preemptionCount', + 'retryablePreemption', + 'detail', + 'metrics', + 'findings', + 'hardwareProvenance', + 'outputArtifacts', + 'bucketMetrics', + 'hardwareDiagnostics', + 'heldOutWorkloadId', + 'signature', +]); + +const RECEIPT_REQUIRED_KEYS: readonly string[] = Object.freeze([ + 'version', + 'kind', + 'storeId', + 'runId', + 'lockHash', + 'operationId', + 'dispatchId', + 'dispatchGeneration', + 'gateId', + 'checkId', + 'candidateDigest', + 'status', + 'reason', + 'expiresAtMs', + 'preemptionCount', + 'signature', +]); + +const ARTIFACT_ENTRY_KEYS: ReadonlySet = new Set(['name', 'digest', 'byteLength', 'mediaType']); + +export type ReceiptSignatureVerifier = ( + receipt: SignedBenchmarkVerdictReceipt, + rawReceiptBytes: Uint8Array, + individualId: string, +) => boolean | Promise; + +export interface ParsedReceiptBundle { + readonly receipt: SignedBenchmarkVerdictReceipt; + readonly rawBytes: Buffer; + readonly rawDigest: Digest; + readonly provenance: HardwareProvenance; + readonly outputArtifacts: readonly BenchmarkOutputArtifact[]; + readonly bucketMetrics?: readonly BucketMetricEntry[]; + readonly hardwareDiagnostics?: HardwareDiagnostics; + readonly heldOutWorkloadId?: string; +} + +export function createNullRecord>(): T { + return Object.create(null) as T; +} + +export function compareUtf16(a: string, b: string): number { + return a < b ? -1 : a > b ? 1 : 0; +} + +export function sha256Hex(bytes: Uint8Array | string): string { + return createHash('sha256').update(bytes).digest('hex'); +} + +export function makeDigest(hex: string): Digest { + if (!SHA256_HEX_RE.test(hex)) { + throw new EvolutionError('ARTIFACT_INVALID', `invalid sha256 digest hex "${hex}"`); + } + const out = createNullRecord<{ algorithm: 'sha256'; hex: string }>(); + out.algorithm = 'sha256'; + out.hex = hex; + return out; +} + +function isAllowedOsRootSymlink(targetPath: string): boolean { + return process.platform === 'darwin' && DARWIN_ROOT_SYMLINKS.has(targetPath); +} + +export function decodeUtf8Strict(bytes: Uint8Array, diagPath: string): string { + try { + return new TextDecoder('utf-8', { fatal: true }).decode(bytes); + } catch { + throw new EvolutionError('ARTIFACT_INVALID', 'payload bytes are not valid UTF-8', diagPath); + } +} + +export function assertCleanSecretText(text: string, scrubber: SecretScrubber, diagPath: string): void { + if (scrubber.containsSecret(text)) { + throw new EvolutionError('SECRET_LEAK_DETECTED', `secret material detected at ${diagPath}`, diagPath); + } +} + +export function validateAbsoluteFilesystemPath(rawPath: string, label: string): string { + if ( + typeof rawPath !== 'string' + || rawPath.length === 0 + || rawPath.length > 4_096 + || /[\0\r\n]/.test(rawPath) + || LONE_SURROGATE_RE.test(rawPath) + ) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', `${label} must be a clean non-empty path`, `/${label}`); + } + const resolved = resolve(rawPath); + if (!isAbsolute(resolved)) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', `${label} must resolve to an absolute path`, `/${label}`); + } + return resolved; +} + +export async function assertNoSymlinkPath( + targetPath: string, + options: { readonly checkLeaf?: boolean; readonly diagPath?: string } = {}, +): Promise { + const diagPath = options.diagPath ?? targetPath; + const normalized = validateAbsoluteFilesystemPath(targetPath, 'path'); + let cursor = options.checkLeaf === false ? dirname(normalized) : normalized; + let depth = 0; + + while (true) { + if (++depth > 128) { + throw new EvolutionError('ARTIFACT_INVALID', `path exceeds maximum directory depth: ${normalized}`, diagPath); + } + const st = await lstat(cursor).catch((err: NodeJS.ErrnoException) => { + if (err.code === 'ENOENT') return null; + if (err.code === 'ELOOP') { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `symlink forbidden along ${normalized}`, diagPath); + } + throw err; + }); + + if (st !== null) { + if (st.isSymbolicLink() && !isAllowedOsRootSymlink(cursor)) { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `symlink forbidden at ${cursor}`, diagPath); + } + const isCheckedLeaf = options.checkLeaf !== false && cursor === normalized; + if (!isCheckedLeaf && !st.isDirectory() && !isAllowedOsRootSymlink(cursor)) { + throw new EvolutionError('ARTIFACT_INVALID', `ancestor component is not a directory: ${cursor}`, diagPath); + } + } + + const parent = dirname(cursor); + if (parent === cursor) break; + cursor = parent; + } +} + +export async function ensureDirectoryChainNoSymlink(targetDir: string, mode = 0o755): Promise { + const normalized = resolve(targetDir); + await assertNoSymlinkPath(normalized, { checkLeaf: true, diagPath: normalized }); + + const missing: string[] = []; + let cursor = normalized; + while (true) { + const st = await lstat(cursor).catch((err: NodeJS.ErrnoException) => { + if (err.code === 'ENOENT') return null; + if (err.code === 'ELOOP') { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `symlink forbidden along ${cursor}`, cursor); + } + throw err; + }); + if (st !== null) { + if (st.isSymbolicLink() && !isAllowedOsRootSymlink(cursor)) { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `directory cannot be a symlink: ${cursor}`, cursor); + } + if (!st.isDirectory() && !isAllowedOsRootSymlink(cursor)) { + throw new EvolutionError('ARTIFACT_INVALID', `expected directory at ${cursor}`, cursor); + } + break; + } + missing.push(cursor); + const parent = dirname(cursor); + if (parent === cursor) break; + cursor = parent; + } + + for (let i = missing.length - 1; i >= 0; i--) { + const dirToMake = missing[i]!; + await mkdir(dirToMake, { mode, recursive: false }).catch((err: NodeJS.ErrnoException) => { + if (err.code !== 'EEXIST') throw err; + }); + const created = await lstat(dirToMake); + if (created.isSymbolicLink() || !created.isDirectory()) { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `created path is not a regular directory: ${dirToMake}`, dirToMake); + } + } +} + +export async function verifyNonSymlinkDirectoryFd(dirPath: string): Promise { + const st = await lstat(dirPath).catch((err: NodeJS.ErrnoException) => { + if (err.code === 'ENOENT') { + throw new EvolutionError('ARTIFACT_MISSING', `directory not found: ${dirPath}`, dirPath); + } + if (err.code === 'ELOOP') { + throw new EvolutionError('ARTIFACT_INVALID', `symlink forbidden along directory: ${dirPath}`, dirPath); + } + throw err; + }); + if (st.isSymbolicLink()) { + throw new EvolutionError('ARTIFACT_INVALID', `directory cannot be a symlink: ${dirPath}`, dirPath); + } + if (!st.isDirectory()) { + throw new EvolutionError('ARTIFACT_INVALID', `expected directory at ${dirPath}`, dirPath); + } + const noFollow = 'O_NOFOLLOW' in fsConstants ? fsConstants.O_NOFOLLOW : 0; + const dirFlag = 'O_DIRECTORY' in fsConstants ? fsConstants.O_DIRECTORY : 0; + const handle = await open(dirPath, fsConstants.O_RDONLY | noFollow | dirFlag).catch((err: NodeJS.ErrnoException) => { + if (err.code === 'ELOOP' || err.code === 'EFTYPE') { + throw new EvolutionError('ARTIFACT_INVALID', `symlink directory forbidden: ${dirPath}`, dirPath); + } + throw err; + }); + try { + const fdStat = await handle.stat(); + if (!fdStat.isDirectory() || fdStat.dev !== st.dev || fdStat.ino !== st.ino) { + throw new EvolutionError('ARTIFACT_INVALID', `directory identity changed during open: ${dirPath}`, dirPath); + } + } finally { + await handle.close(); + } +} + +export async function readVerifiedRegularFileNoFollow( + filePath: string, + options: { + readonly expectedSha256Hex?: string; + readonly expectedByteLength?: number; + readonly maxBytes: number; + readonly missingCode?: 'ARTIFACT_MISSING' | 'ARTIFACT_INVALID'; + }, +): Promise { + const missingCode = options.missingCode ?? 'ARTIFACT_MISSING'; + const st = await lstat(filePath).catch((err: NodeJS.ErrnoException) => { + if (err.code === 'ENOENT') { + throw new EvolutionError(missingCode, `file not found: ${filePath}`, filePath); + } + if (err.code === 'ELOOP') { + throw new EvolutionError('ARTIFACT_INVALID', `symlink forbidden at ${filePath}`, filePath); + } + throw err; + }); + + if (st.isSymbolicLink()) { + throw new EvolutionError('ARTIFACT_INVALID', `symlink artifact is forbidden: ${filePath}`, filePath); + } + if (!st.isFile()) { + throw new EvolutionError('ARTIFACT_INVALID', `artifact must be a regular file: ${filePath}`, filePath); + } + if (st.nlink !== 1) { + throw new EvolutionError( + 'ARTIFACT_INVALID', + `artifact hardlink forbidden (nlink=${st.nlink}, expected 1): ${filePath}`, + filePath, + ); + } + if (st.size > options.maxBytes) { + throw new EvolutionError('ARTIFACT_INVALID', `artifact exceeds maximum size ${options.maxBytes}: ${filePath}`, filePath); + } + if (options.expectedByteLength !== undefined && st.size !== options.expectedByteLength) { + throw new EvolutionError( + 'ARTIFACT_INVALID', + `artifact byteLength mismatch (expected ${options.expectedByteLength}, observed ${st.size}): ${filePath}`, + filePath, + ); + } + + const noFollow = 'O_NOFOLLOW' in fsConstants ? fsConstants.O_NOFOLLOW : 0; + const handle = await open(filePath, fsConstants.O_RDONLY | noFollow).catch((err: NodeJS.ErrnoException) => { + if (err.code === 'ELOOP' || err.code === 'EFTYPE') { + throw new EvolutionError('ARTIFACT_INVALID', `symlink forbidden on open: ${filePath}`, filePath); + } + if (err.code === 'ENOENT') { + throw new EvolutionError(missingCode, `file not found: ${filePath}`, filePath); + } + throw err; + }); + + try { + const fdStat = await handle.stat(); + if ( + !fdStat.isFile() + || fdStat.nlink !== 1 + || fdStat.size !== st.size + || fdStat.dev !== st.dev + || fdStat.ino !== st.ino + || fdStat.size > options.maxBytes + ) { + throw new EvolutionError('ARTIFACT_INVALID', `artifact changed or failed fd stat verification: ${filePath}`, filePath); + } + if (options.expectedByteLength !== undefined && fdStat.size !== options.expectedByteLength) { + throw new EvolutionError( + 'ARTIFACT_INVALID', + `artifact byteLength mismatch on fd stat: ${filePath}`, + filePath, + ); + } + + const buf = Buffer.alloc(fdStat.size); + let offset = 0; + while (offset < fdStat.size) { + const res = await handle.read(buf, offset, fdStat.size - offset, offset); + if (res.bytesRead === 0) break; + offset += res.bytesRead; + } + if (offset !== fdStat.size) { + throw new EvolutionError('ARTIFACT_INVALID', `incomplete read for artifact: ${filePath}`, filePath); + } + if (options.expectedSha256Hex !== undefined) { + const observedHex = sha256Hex(buf); + if (observedHex !== options.expectedSha256Hex) { + throw new EvolutionError( + 'ARTIFACT_INVALID', + `artifact SHA-256 mismatch (expected ${options.expectedSha256Hex}, observed ${observedHex}): ${filePath}`, + filePath, + ); + } + } + return buf; + } finally { + await handle.close(); + } +} + +export async function readVerifiedCasBlob( + campaignRoot: string, + digestHex: string, + options: { + readonly expectedByteLength?: number; + readonly maxBytes: number; + }, +): Promise { + if (!SHA256_HEX_RE.test(digestHex)) { + throw new EvolutionError('ARTIFACT_INVALID', `invalid CAS sha256 hex "${digestHex}"`); + } + await verifyNonSymlinkDirectoryFd(campaignRoot); + const casDir = join(campaignRoot, 'cas'); + const shaDir = join(casDir, 'sha256'); + await verifyNonSymlinkDirectoryFd(casDir); + await verifyNonSymlinkDirectoryFd(shaDir); + + const blobPath = join(shaDir, digestHex); + return readVerifiedRegularFileNoFollow(blobPath, { + expectedSha256Hex: digestHex, + ...(options.expectedByteLength !== undefined ? { expectedByteLength: options.expectedByteLength } : {}), + maxBytes: options.maxBytes, + missingCode: 'ARTIFACT_MISSING', + }); +} + +export async function writeNewFileNoFollow(filePath: string, bytes: Uint8Array, mode = 0o644): Promise { + const noFollow = 'O_NOFOLLOW' in fsConstants ? fsConstants.O_NOFOLLOW : 0; + const handle = await open( + filePath, + fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_WRONLY | noFollow, + mode, + ); + try { + let written = 0; + while (written < bytes.byteLength) { + const res = await handle.write(bytes, written, bytes.byteLength - written, written); + if (res.bytesWritten <= 0) { + throw new EvolutionError('EVOLUTION_STORE_ERROR', `short write staging file ${filePath}`, filePath); + } + written += res.bytesWritten; + } + await handle.sync(); + } finally { + await handle.close(); + } +} + +export function expectRecord( + value: NullProtoJson | undefined, + allowedKeys: ReadonlySet, + requiredKeys: readonly string[], + code: 'ARTIFACT_INVALID' | 'EXPORT_UNVERIFIED_FORBIDDEN', + diagPath: string, +): Record { + if (value === undefined || value === null || typeof value !== 'object' || Array.isArray(value)) { + throw new EvolutionError(code, 'expected object record', diagPath); + } + const obj = value as Record; + for (const key of Object.keys(obj)) { + if (!Object.hasOwn(obj, key)) continue; + if (FORBIDDEN_PROTOTYPE_KEYS.has(key) || !allowedKeys.has(key)) { + throw new EvolutionError(code, `unknown or forbidden field "${key}"`, `${diagPath}/${key}`); + } + } + for (const req of requiredKeys) { + if (!Object.hasOwn(obj, req) || obj[req] === undefined) { + throw new EvolutionError(code, `missing required field "${req}"`, `${diagPath}/${req}`); + } + } + return obj; +} + +export function parseDigestValue( + value: NullProtoJson | undefined, + code: 'ARTIFACT_INVALID' | 'EXPORT_UNVERIFIED_FORBIDDEN', + diagPath: string, +): Digest { + const obj = expectRecord(value, new Set(['algorithm', 'hex']), ['algorithm', 'hex'], code, diagPath); + if (obj['algorithm'] !== 'sha256') { + throw new EvolutionError(code, 'digest algorithm must be "sha256"', `${diagPath}/algorithm`); + } + if (typeof obj['hex'] !== 'string' || !SHA256_HEX_RE.test(obj['hex'])) { + throw new EvolutionError(code, 'digest hex must be 64 lowercase hex characters', `${diagPath}/hex`); + } + return makeDigest(obj['hex']); +} + +function parseReceiptOutputArtifacts( + raw: NullProtoJson | undefined, + maxBlobBytes: number, + diagPath: string, +): readonly BenchmarkOutputArtifact[] { + if (raw === undefined) return []; + if (!Array.isArray(raw) || raw.length > LIMITS.manifest) { + throw new EvolutionError('ARTIFACT_INVALID', 'receipt outputArtifacts must be a bounded array', diagPath); + } + const seenNames = new Set(); + const out: BenchmarkOutputArtifact[] = []; + for (let i = 0; i < raw.length; i++) { + const itemPath = `${diagPath}/${i}`; + const obj = expectRecord(raw[i], ARTIFACT_ENTRY_KEYS, ['name', 'digest', 'byteLength'], 'ARTIFACT_INVALID', itemPath); + const rawName = obj['name']; + if (typeof rawName !== 'string' || rawName.length < 1 || rawName.length > LIMITS.path) { + throw new EvolutionError('ARTIFACT_INVALID', 'invalid artifact name', `${itemPath}/name`); + } + const validRel = validateRelativePath(rawName); + if (!validRel.ok) { + throw new EvolutionError('ARTIFACT_INVALID', `invalid artifact relative path "${rawName}"`, `${itemPath}/name`); + } + if (seenNames.has(validRel.value)) { + throw new EvolutionError('ARTIFACT_INVALID', `duplicate receipt outputArtifact "${validRel.value}"`, `${itemPath}/name`); + } + seenNames.add(validRel.value); + + const digest = parseDigestValue(obj['digest'], 'ARTIFACT_INVALID', `${itemPath}/digest`); + const byteLength = obj['byteLength']; + if ( + typeof byteLength !== 'number' + || !Number.isSafeInteger(byteLength) + || Object.is(byteLength, -0) + || byteLength < 0 + || byteLength > maxBlobBytes + ) { + throw new EvolutionError('ARTIFACT_INVALID', 'invalid artifact byteLength', `${itemPath}/byteLength`); + } + + const entry = createNullRecord<{ + name: string; + digest: Digest; + byteLength: number; + mediaType?: string | null; + }>(); + entry.name = validRel.value; + entry.digest = digest; + entry.byteLength = byteLength; + if (Object.hasOwn(obj, 'mediaType') && obj['mediaType'] !== undefined) { + if (obj['mediaType'] === null) { + entry.mediaType = null; + } else if ( + typeof obj['mediaType'] === 'string' + && obj['mediaType'].length >= 1 + && obj['mediaType'].length <= LIMITS.mediaType + && PRINTABLE_ASCII_RE.test(obj['mediaType']) + ) { + entry.mediaType = obj['mediaType']; + } else { + throw new EvolutionError('ARTIFACT_INVALID', 'invalid artifact mediaType', `${itemPath}/mediaType`); + } + } + out.push(entry as BenchmarkOutputArtifact); + } + return out; +} + +export interface ReceiptVerificationOptions { + readonly individualId: string; + readonly expectedLockHash?: Digest; + readonly expectedTargetCellId?: string; + readonly allowSyntheticProbe: boolean; + readonly allowHostAttested: boolean; + readonly receiptSigningSecret?: string; + readonly verifyReceiptSignature?: ReceiptSignatureVerifier; + readonly scrubber: SecretScrubber; + readonly maxBlobBytes: number; +} + +/** + * Fail-closed verdict receipt verification shared by bundle export, bundle verification, and + * campaign snapshots: bounds, strict UTF-8, `SecretScrubber`, strict key set, HMAC or callback + * signature, `approved` status, hardware provenance, target cell, and probe/isolation gates. + */ + +export async function parseAndVerifyReceiptBytes( + rawBytes: Buffer, + options: ReceiptVerificationOptions, +): Promise { + const diagPath = `/receipts/${options.individualId}`; + if (rawBytes.byteLength === 0 || rawBytes.byteLength > MAX_RECEIPT_FILE_BYTES) { + throw new EvolutionError( + 'ARTIFACT_INVALID', + `receipt exceeds bounds (1..${MAX_RECEIPT_FILE_BYTES} bytes) for ${options.individualId}`, + diagPath, + ); + } + const text = decodeUtf8Strict(rawBytes, diagPath); + assertCleanSecretText(text, options.scrubber, diagPath); + + let parsedRaw: NullProtoJson; + try { + parsedRaw = parseNullProtoJson(text, MAX_RECEIPT_FILE_BYTES, diagPath); + } catch (err: unknown) { + if (err instanceof EvolutionError) { + throw new EvolutionError('ARTIFACT_INVALID', `malformed verdict receipt JSON: ${err.message}`, diagPath); + } + throw err; + } + + const obj = expectRecord( + parsedRaw, + RECEIPT_ALLOWED_KEYS, + RECEIPT_REQUIRED_KEYS, + 'ARTIFACT_INVALID', + diagPath, + ); + + if (obj['version'] !== 1 || obj['kind'] !== 'benchmark_verdict') { + throw new EvolutionError('ARTIFACT_INVALID', 'receipt must have version: 1 and kind: "benchmark_verdict"', diagPath); + } + if (typeof obj['storeId'] !== 'string' || !SAFE_ID_RE.test(obj['storeId'])) { + throw new EvolutionError('ARTIFACT_INVALID', 'invalid receipt storeId', `${diagPath}/storeId`); + } + if (typeof obj['runId'] !== 'string' || obj['runId'].length < 1 || obj['runId'].length > LIMITS.identifier) { + throw new EvolutionError('ARTIFACT_INVALID', 'invalid receipt runId', `${diagPath}/runId`); + } + if (typeof obj['operationId'] !== 'string' || !SAFE_FILENAME_ID_RE.test(obj['operationId'])) { + throw new EvolutionError('ARTIFACT_INVALID', 'invalid receipt operationId', `${diagPath}/operationId`); + } + if (typeof obj['dispatchId'] !== 'string' || !SAFE_ID_RE.test(obj['dispatchId'])) { + throw new EvolutionError('ARTIFACT_INVALID', 'invalid receipt dispatchId', `${diagPath}/dispatchId`); + } + if ( + typeof obj['dispatchGeneration'] !== 'number' + || !Number.isSafeInteger(obj['dispatchGeneration']) + || Object.is(obj['dispatchGeneration'], -0) + || obj['dispatchGeneration'] < 0 + ) { + throw new EvolutionError('ARTIFACT_INVALID', 'invalid receipt dispatchGeneration', `${diagPath}/dispatchGeneration`); + } + if (typeof obj['gateId'] !== 'string' || obj['gateId'].length < 1 || obj['gateId'].length > 128 || !PRINTABLE_ASCII_RE.test(obj['gateId'])) { + throw new EvolutionError('ARTIFACT_INVALID', 'invalid receipt gateId', `${diagPath}/gateId`); + } + if (typeof obj['checkId'] !== 'string' || obj['checkId'].length < 1 || obj['checkId'].length > LIMITS.identifier) { + throw new EvolutionError('ARTIFACT_INVALID', 'invalid receipt checkId', `${diagPath}/checkId`); + } + if (typeof obj['candidateDigest'] !== 'string' || !SHA256_HEX_RE.test(obj['candidateDigest'])) { + throw new EvolutionError('ARTIFACT_INVALID', 'invalid receipt candidateDigest', `${diagPath}/candidateDigest`); + } + if (typeof obj['expiresAtMs'] !== 'string' || !/^(?:0|[1-9][0-9]{0,17})$/.test(obj['expiresAtMs'])) { + throw new EvolutionError('ARTIFACT_INVALID', 'invalid receipt expiresAtMs', `${diagPath}/expiresAtMs`); + } + if ( + typeof obj['preemptionCount'] !== 'number' + || !Number.isSafeInteger(obj['preemptionCount']) + || Object.is(obj['preemptionCount'], -0) + || obj['preemptionCount'] < 0 + || obj['preemptionCount'] > 16 + ) { + throw new EvolutionError('ARTIFACT_INVALID', 'invalid receipt preemptionCount', `${diagPath}/preemptionCount`); + } + + const lockHash = parseDigestValue(obj['lockHash'], 'ARTIFACT_INVALID', `${diagPath}/lockHash`); + if (options.expectedLockHash !== undefined && lockHash.hex !== options.expectedLockHash.hex) { + throw new EvolutionError( + 'EXPORT_UNVERIFIED_FORBIDDEN', + `receipt lockHash mismatch for ${options.individualId}`, + `${diagPath}/lockHash`, + ); + } + + const signature = obj['signature']; + if (typeof signature !== 'string' || !SHA256_HEX_RE.test(signature)) { + throw new EvolutionError( + 'EXPORT_UNVERIFIED_FORBIDDEN', + `receipt missing valid HMAC signature for ${options.individualId}`, + `${diagPath}/signature`, + ); + } + + if (options.receiptSigningSecret !== undefined) { + const validHmac = verifyBenchmarkVerdictSignature( + options.receiptSigningSecret, + obj as Readonly>, + signature, + ); + if (!validHmac) { + throw new EvolutionError( + 'EXPORT_UNVERIFIED_FORBIDDEN', + `verdict receipt HMAC verification failed for ${options.individualId}`, + `${diagPath}/signature`, + ); + } + } + + if (options.verifyReceiptSignature !== undefined) { + const verifiedByCallback = await options.verifyReceiptSignature( + obj as unknown as SignedBenchmarkVerdictReceipt, + rawBytes, + options.individualId, + ); + if (!verifiedByCallback) { + throw new EvolutionError( + 'EXPORT_UNVERIFIED_FORBIDDEN', + `verdict receipt signature verifier rejected ${options.individualId}`, + `${diagPath}/signature`, + ); + } + } + + const status = obj['status']; + if (status !== 'approved') { + throw new EvolutionError( + 'EXPORT_UNVERIFIED_FORBIDDEN', + `verdict receipt status must be "approved" (got "${String(status)}") for ${options.individualId}`, + `${diagPath}/status`, + ); + } + if (obj['reason'] !== null) { + throw new EvolutionError( + 'EXPORT_UNVERIFIED_FORBIDDEN', + `approved verdict receipt must have null reason for ${options.individualId}`, + `${diagPath}/reason`, + ); + } + + if (!Object.hasOwn(obj, 'hardwareProvenance') || obj['hardwareProvenance'] === undefined) { + throw new EvolutionError( + 'EXPORT_UNVERIFIED_FORBIDDEN', + `verdict receipt missing hardwareProvenance for ${options.individualId}`, + `${diagPath}/hardwareProvenance`, + ); + } + + let provenance: HardwareProvenance; + try { + provenance = parseHardwareProvenanceJson( + obj['hardwareProvenance'] as unknown as HardwareProvenance, + `${diagPath}/hardwareProvenance`, + ); + } catch (err: unknown) { + throw new EvolutionError( + 'EXPORT_UNVERIFIED_FORBIDDEN', + `invalid hardwareProvenance on receipt for ${options.individualId}: ${err instanceof Error ? err.message : String(err)}`, + `${diagPath}/hardwareProvenance`, + ); + } + + if (options.expectedTargetCellId !== undefined && provenance.targetCellId !== options.expectedTargetCellId) { + throw new EvolutionError( + 'EXPORT_UNVERIFIED_FORBIDDEN', + `receipt targetCellId "${provenance.targetCellId}" does not match campaign targetCellId "${options.expectedTargetCellId}"`, + `${diagPath}/hardwareProvenance/targetCellId`, + ); + } + + if (provenance.probeKind !== 'physical' && !options.allowSyntheticProbe) { + throw new EvolutionError( + 'EXPORT_UNVERIFIED_FORBIDDEN', + `refusing to export "${provenance.probeKind}" hardware receipt for ${options.individualId} without allowSyntheticProbe: true`, + `${diagPath}/hardwareProvenance/probeKind`, + ); + } + + if (provenance.isolation === 'host_attested' && !options.allowHostAttested) { + throw new EvolutionError( + 'EXPORT_UNVERIFIED_FORBIDDEN', + `refusing to export "host_attested" hardware receipt for ${options.individualId} without allowHostAttested: true`, + `${diagPath}/hardwareProvenance/isolation`, + ); + } + + const outputArtifacts = parseReceiptOutputArtifacts( + obj['outputArtifacts'], + options.maxBlobBytes, + `${diagPath}/outputArtifacts`, + ); + + let bucketMetrics: readonly BucketMetricEntry[] | undefined; + if (Object.hasOwn(obj, 'bucketMetrics') && obj['bucketMetrics'] !== undefined) { + bucketMetrics = parseBucketMetricsJson( + obj['bucketMetrics'] as unknown as readonly BucketMetricEntry[], + options.scrubber, + ); + } + + let hardwareDiagnostics: HardwareDiagnostics | undefined; + if (Object.hasOwn(obj, 'hardwareDiagnostics') && obj['hardwareDiagnostics'] !== undefined) { + hardwareDiagnostics = parseHardwareDiagnosticsJson( + obj['hardwareDiagnostics'] as unknown as HardwareDiagnostics, + options.scrubber, + ); + } + + let heldOutWorkloadId: string | undefined; + if (Object.hasOwn(obj, 'heldOutWorkloadId') && obj['heldOutWorkloadId'] !== undefined) { + const rawWl = obj['heldOutWorkloadId']; + if (typeof rawWl !== 'string' || !BUCKET_ID_RE.test(rawWl) || rawWl.length > LIMITS.bucketId) { + throw new EvolutionError('ARTIFACT_INVALID', 'invalid heldOutWorkloadId on receipt', `${diagPath}/heldOutWorkloadId`); + } + heldOutWorkloadId = rawWl; + } + + return { + receipt: obj as unknown as SignedBenchmarkVerdictReceipt, + rawBytes, + rawDigest: makeDigest(sha256Hex(rawBytes)), + provenance, + outputArtifacts, + ...(bucketMetrics !== undefined ? { bucketMetrics } : {}), + ...(hardwareDiagnostics !== undefined ? { hardwareDiagnostics } : {}), + ...(heldOutWorkloadId !== undefined ? { heldOutWorkloadId } : {}), + }; +} + +export function assertIndividualArtifactsBoundToReceipt( + individual: Pick, + receiptArtifacts: readonly BenchmarkOutputArtifact[], +): void { + if (individual.outputArtifacts.length === 0) return; + const byDigest = new Map(); + for (const art of receiptArtifacts) { + byDigest.set(art.digest.hex, art.byteLength); + } + for (const ref of individual.outputArtifacts) { + const expectedLen = byDigest.get(ref.digest.hex); + if (expectedLen === undefined || expectedLen !== ref.byteLength) { + throw new EvolutionError( + 'ARTIFACT_INVALID', + `individual "${individual.individualId}" outputArtifact "${ref.name}" does not match signed verdict receipt`, + ); + } + } +} + +export async function publishStagingDirectoryAtomically( + stagingDir: string, + targetDir: string, + overwrite: boolean, +): Promise { + const existing = await lstat(targetDir).catch((err: NodeJS.ErrnoException) => { + if (err.code === 'ENOENT') return null; + if (err.code === 'ELOOP') { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `symlink forbidden at outputDir: ${targetDir}`, targetDir); + } + throw err; + }); + + if (existing === null) { + await rename(stagingDir, targetDir); + return; + } + + if (existing.isSymbolicLink()) { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `outputDir cannot be a symlink: ${targetDir}`, targetDir); + } + if (!existing.isDirectory()) { + throw new EvolutionError('ARTIFACT_INVALID', `outputDir exists and is not a directory: ${targetDir}`, targetDir); + } + if (!overwrite) { + throw new EvolutionError('EVOLUTION_CONFLICT', `outputDir already exists: ${targetDir}`, targetDir); + } + + const backupDir = join(dirname(targetDir), `.evolution-bundle-backup-${randomBytes(8).toString('hex')}`); + await rename(targetDir, backupDir); + try { + await rename(stagingDir, targetDir); + } catch (err) { + await rename(backupDir, targetDir).catch(() => undefined); + throw err; + } + await rm(backupDir, { recursive: true, force: true }).catch(async () => { + await chmod(backupDir, 0o700).catch(() => undefined); + await rm(backupDir, { recursive: true, force: true }).catch(() => undefined); + }); +} diff --git a/packages/evolution/src/bundle.ts b/packages/evolution/src/bundle.ts index 3125fa62..724054cb 100644 --- a/packages/evolution/src/bundle.ts +++ b/packages/evolution/src/bundle.ts @@ -1,7 +1,6 @@ -import { createHash, randomBytes } from 'node:crypto'; -import { constants as fsConstants } from 'node:fs'; -import { chmod, lstat, mkdir, open, rename, rm } from 'node:fs/promises'; -import { dirname, isAbsolute, join, resolve } from 'node:path'; +import { randomBytes } from 'node:crypto'; +import { lstat, mkdir, rm } from 'node:fs/promises'; +import { dirname, join } from 'node:path'; import { LIMITS, SecretScrubber, @@ -13,17 +12,12 @@ import { } from '@loopwright/core'; import { MAX_RECEIPT_FILE_BYTES, - verifyBenchmarkVerdictSignature, type BenchmarkOutputArtifact, - type SignedBenchmarkVerdictReceipt, } from '@loopwright/hardware-runner'; import { computeNsga2Ranking } from './pareto.js'; import { canonicalizeJson, - parseBucketMetricsJson, parseDispatchManifestV1, - parseHardwareDiagnosticsJson, - parseHardwareProvenanceJson, parseNullProtoJson, type NullProtoJson, } from './schema.js'; @@ -44,6 +38,35 @@ import { type EvolutionExportFormat, type IndividualRecord, } from './types.js'; +import { + DEFAULT_MAX_BLOB_BYTES, + DEFAULT_SECRET_SCRUBBER, + PRINTABLE_ASCII_RE, + SAFE_FILENAME_ID_RE, + SAFE_ID_RE, + SHA256_HEX_RE, + assertCleanSecretText, + assertIndividualArtifactsBoundToReceipt, + assertNoSymlinkPath, + compareUtf16, + createNullRecord, + decodeUtf8Strict, + ensureDirectoryChainNoSymlink, + expectRecord, + makeDigest, + parseAndVerifyReceiptBytes, + parseDigestValue, + publishStagingDirectoryAtomically, + readVerifiedCasBlob, + readVerifiedRegularFileNoFollow, + sha256Hex, + validateAbsoluteFilesystemPath, + verifyNonSymlinkDirectoryFd, + writeNewFileNoFollow, + type ParsedReceiptBundle, + type ReceiptSignatureVerifier, +} from './bundle-fs.js'; +export type { ReceiptSignatureVerifier } from './bundle-fs.js'; export const EVOLUTION_BUNDLE_KIND = 'EvolutionBundle' as const; export const EVOLUTION_BUNDLE_VERSION = 1 as const; @@ -57,21 +80,11 @@ export const EVOLUTION_DISPATCH_MANIFEST_MEDIA_TYPE = 'application/vnd.loopwrigh export const EVOLUTION_RECEIPT_MEDIA_TYPE = 'application/vnd.loopwright.benchmark-verdict.v1+json' as const; export const EVOLUTION_BLOB_DEFAULT_MEDIA_TYPE = 'application/octet-stream' as const; -const DEFAULT_SECRET_SCRUBBER = new SecretScrubber(); -const DEFAULT_MAX_BLOB_BYTES = 67_108_864; // 64 MiB const DEFAULT_ENTRYPOINT_SYMBOL = 'loopwright_entrypoint' as const; const MAX_BUNDLE_MANIFEST_BYTES = 1_048_576; const MAX_OCI_DOC_BYTES = 1_048_576; -const SHA256_HEX_RE = /^[0-9a-f]{64}$/; -const SAFE_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/; -const SAFE_FILENAME_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/; -const BUCKET_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]*$/; const DTYPE_TOKEN_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,31}$/; -const PRINTABLE_ASCII_RE = /^[\x20-\x7E]+$/; -const LONE_SURROGATE_RE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(? = new Set(['__proto__', 'constructor', 'prototype']); -const DARWIN_ROOT_SYMLINKS: ReadonlySet = new Set(['/var', '/tmp', '/etc']); const BINARY_ARTIFACT_EXTENSIONS: readonly string[] = Object.freeze([ '.cubin', @@ -94,54 +107,6 @@ const TEXT_ARTIFACT_EXTENSIONS: readonly string[] = Object.freeze([ '.cfg', ]); -const RECEIPT_ALLOWED_KEYS: ReadonlySet = new Set([ - 'version', - 'kind', - 'storeId', - 'runId', - 'lockHash', - 'operationId', - 'dispatchId', - 'dispatchGeneration', - 'gateId', - 'checkId', - 'candidateDigest', - 'status', - 'reason', - 'expiresAtMs', - 'preemptionCount', - 'retryablePreemption', - 'detail', - 'metrics', - 'findings', - 'hardwareProvenance', - 'outputArtifacts', - 'bucketMetrics', - 'hardwareDiagnostics', - 'heldOutWorkloadId', - 'signature', -]); - -const RECEIPT_REQUIRED_KEYS: readonly string[] = Object.freeze([ - 'version', - 'kind', - 'storeId', - 'runId', - 'lockHash', - 'operationId', - 'dispatchId', - 'dispatchGeneration', - 'gateId', - 'checkId', - 'candidateDigest', - 'status', - 'reason', - 'expiresAtMs', - 'preemptionCount', - 'signature', -]); - -const ARTIFACT_ENTRY_KEYS: ReadonlySet = new Set(['name', 'digest', 'byteLength', 'mediaType']); const BUNDLE_MANIFEST_KEYS: ReadonlySet = new Set([ 'kind', 'version', @@ -178,18 +143,13 @@ const PARETO_ENTRY_KEYS: ReadonlySet = new Set([ 'hardwareDiagnostics', ]); -export type ReceiptSignatureVerifier = ( - receipt: SignedBenchmarkVerdictReceipt, - rawReceiptBytes: Uint8Array, - individualId: string, -) => boolean | Promise; - export interface ExportEvolutionBundleOptions { readonly store: EvolutionCampaignStore; readonly campaignId: string; readonly outputDir: string; readonly format?: EvolutionExportFormat; readonly allowSyntheticProbe?: boolean; + readonly allowHostAttested?: boolean; readonly allowUnverifiedSignature?: boolean; readonly individualIds?: readonly string[]; readonly dispatchManifest?: DispatchManifestV1 | string | Uint8Array; @@ -218,6 +178,7 @@ export interface ExportEvolutionBundleResult { export interface VerifyEvolutionBundleOptions { readonly bundleDir: string; readonly allowSyntheticProbe?: boolean; + readonly allowHostAttested?: boolean; readonly allowUnverifiedSignature?: boolean; readonly receiptSigningSecret?: string; readonly verifyReceiptSignature?: ReceiptSignatureVerifier; @@ -237,17 +198,6 @@ export interface VerifyEvolutionBundleResult { readonly blobCount: number; } -interface ParsedReceiptBundle { - readonly receipt: SignedBenchmarkVerdictReceipt; - readonly rawBytes: Buffer; - readonly rawDigest: Digest; - readonly provenance: HardwareProvenance; - readonly outputArtifacts: readonly BenchmarkOutputArtifact[]; - readonly bucketMetrics?: readonly BucketMetricEntry[]; - readonly hardwareDiagnostics?: HardwareDiagnostics; - readonly heldOutWorkloadId?: string; -} - interface VerifiedStageABlob { readonly digest: Digest; readonly byteLength: number; @@ -256,431 +206,6 @@ interface VerifiedStageABlob { textChecked: boolean; } -function createNullRecord>(): T { - return Object.create(null) as T; -} - -function compareUtf16(a: string, b: string): number { - return a < b ? -1 : a > b ? 1 : 0; -} - -function sha256Hex(bytes: Uint8Array | string): string { - return createHash('sha256').update(bytes).digest('hex'); -} - -function makeDigest(hex: string): Digest { - if (!SHA256_HEX_RE.test(hex)) { - throw new EvolutionError('ARTIFACT_INVALID', `invalid sha256 digest hex "${hex}"`); - } - const out = createNullRecord<{ algorithm: 'sha256'; hex: string }>(); - out.algorithm = 'sha256'; - out.hex = hex; - return out; -} - -function isAllowedOsRootSymlink(targetPath: string): boolean { - return process.platform === 'darwin' && DARWIN_ROOT_SYMLINKS.has(targetPath); -} - -function decodeUtf8Strict(bytes: Uint8Array, diagPath: string): string { - try { - return new TextDecoder('utf-8', { fatal: true }).decode(bytes); - } catch { - throw new EvolutionError('ARTIFACT_INVALID', 'payload bytes are not valid UTF-8', diagPath); - } -} - -function assertCleanSecretText(text: string, scrubber: SecretScrubber, diagPath: string): void { - if (scrubber.containsSecret(text)) { - throw new EvolutionError('SECRET_LEAK_DETECTED', `secret material detected at ${diagPath}`, diagPath); - } -} - -function validateAbsoluteFilesystemPath(rawPath: string, label: string): string { - if ( - typeof rawPath !== 'string' - || rawPath.length === 0 - || rawPath.length > 4_096 - || /[\0\r\n]/.test(rawPath) - || LONE_SURROGATE_RE.test(rawPath) - ) { - throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', `${label} must be a clean non-empty path`, `/${label}`); - } - const resolved = resolve(rawPath); - if (!isAbsolute(resolved)) { - throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', `${label} must resolve to an absolute path`, `/${label}`); - } - return resolved; -} - -async function assertNoSymlinkPath( - targetPath: string, - options: { readonly checkLeaf?: boolean; readonly diagPath?: string } = {}, -): Promise { - const diagPath = options.diagPath ?? targetPath; - const normalized = validateAbsoluteFilesystemPath(targetPath, 'path'); - let cursor = options.checkLeaf === false ? dirname(normalized) : normalized; - let depth = 0; - - while (true) { - if (++depth > 128) { - throw new EvolutionError('ARTIFACT_INVALID', `path exceeds maximum directory depth: ${normalized}`, diagPath); - } - const st = await lstat(cursor).catch((err: NodeJS.ErrnoException) => { - if (err.code === 'ENOENT') return null; - if (err.code === 'ELOOP') { - throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `symlink forbidden along ${normalized}`, diagPath); - } - throw err; - }); - - if (st !== null) { - if (st.isSymbolicLink() && !isAllowedOsRootSymlink(cursor)) { - throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `symlink forbidden at ${cursor}`, diagPath); - } - const isCheckedLeaf = options.checkLeaf !== false && cursor === normalized; - if (!isCheckedLeaf && !st.isDirectory() && !isAllowedOsRootSymlink(cursor)) { - throw new EvolutionError('ARTIFACT_INVALID', `ancestor component is not a directory: ${cursor}`, diagPath); - } - } - - const parent = dirname(cursor); - if (parent === cursor) break; - cursor = parent; - } -} - -async function ensureDirectoryChainNoSymlink(targetDir: string, mode = 0o755): Promise { - const normalized = resolve(targetDir); - await assertNoSymlinkPath(normalized, { checkLeaf: true, diagPath: normalized }); - - const missing: string[] = []; - let cursor = normalized; - while (true) { - const st = await lstat(cursor).catch((err: NodeJS.ErrnoException) => { - if (err.code === 'ENOENT') return null; - if (err.code === 'ELOOP') { - throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `symlink forbidden along ${cursor}`, cursor); - } - throw err; - }); - if (st !== null) { - if (st.isSymbolicLink() && !isAllowedOsRootSymlink(cursor)) { - throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `directory cannot be a symlink: ${cursor}`, cursor); - } - if (!st.isDirectory() && !isAllowedOsRootSymlink(cursor)) { - throw new EvolutionError('ARTIFACT_INVALID', `expected directory at ${cursor}`, cursor); - } - break; - } - missing.push(cursor); - const parent = dirname(cursor); - if (parent === cursor) break; - cursor = parent; - } - - for (let i = missing.length - 1; i >= 0; i--) { - const dirToMake = missing[i]!; - await mkdir(dirToMake, { mode, recursive: false }).catch((err: NodeJS.ErrnoException) => { - if (err.code !== 'EEXIST') throw err; - }); - const created = await lstat(dirToMake); - if (created.isSymbolicLink() || !created.isDirectory()) { - throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `created path is not a regular directory: ${dirToMake}`, dirToMake); - } - } -} - -async function verifyNonSymlinkDirectoryFd(dirPath: string): Promise { - const st = await lstat(dirPath).catch((err: NodeJS.ErrnoException) => { - if (err.code === 'ENOENT') { - throw new EvolutionError('ARTIFACT_MISSING', `directory not found: ${dirPath}`, dirPath); - } - if (err.code === 'ELOOP') { - throw new EvolutionError('ARTIFACT_INVALID', `symlink forbidden along directory: ${dirPath}`, dirPath); - } - throw err; - }); - if (st.isSymbolicLink()) { - throw new EvolutionError('ARTIFACT_INVALID', `directory cannot be a symlink: ${dirPath}`, dirPath); - } - if (!st.isDirectory()) { - throw new EvolutionError('ARTIFACT_INVALID', `expected directory at ${dirPath}`, dirPath); - } - const noFollow = 'O_NOFOLLOW' in fsConstants ? fsConstants.O_NOFOLLOW : 0; - const dirFlag = 'O_DIRECTORY' in fsConstants ? fsConstants.O_DIRECTORY : 0; - const handle = await open(dirPath, fsConstants.O_RDONLY | noFollow | dirFlag).catch((err: NodeJS.ErrnoException) => { - if (err.code === 'ELOOP' || err.code === 'EFTYPE') { - throw new EvolutionError('ARTIFACT_INVALID', `symlink directory forbidden: ${dirPath}`, dirPath); - } - throw err; - }); - try { - const fdStat = await handle.stat(); - if (!fdStat.isDirectory() || fdStat.dev !== st.dev || fdStat.ino !== st.ino) { - throw new EvolutionError('ARTIFACT_INVALID', `directory identity changed during open: ${dirPath}`, dirPath); - } - } finally { - await handle.close(); - } -} - -async function readVerifiedRegularFileNoFollow( - filePath: string, - options: { - readonly expectedSha256Hex?: string; - readonly expectedByteLength?: number; - readonly maxBytes: number; - readonly missingCode?: 'ARTIFACT_MISSING' | 'ARTIFACT_INVALID'; - }, -): Promise { - const missingCode = options.missingCode ?? 'ARTIFACT_MISSING'; - const st = await lstat(filePath).catch((err: NodeJS.ErrnoException) => { - if (err.code === 'ENOENT') { - throw new EvolutionError(missingCode, `file not found: ${filePath}`, filePath); - } - if (err.code === 'ELOOP') { - throw new EvolutionError('ARTIFACT_INVALID', `symlink forbidden at ${filePath}`, filePath); - } - throw err; - }); - - if (st.isSymbolicLink()) { - throw new EvolutionError('ARTIFACT_INVALID', `symlink artifact is forbidden: ${filePath}`, filePath); - } - if (!st.isFile()) { - throw new EvolutionError('ARTIFACT_INVALID', `artifact must be a regular file: ${filePath}`, filePath); - } - if (st.nlink !== 1) { - throw new EvolutionError( - 'ARTIFACT_INVALID', - `artifact hardlink forbidden (nlink=${st.nlink}, expected 1): ${filePath}`, - filePath, - ); - } - if (st.size > options.maxBytes) { - throw new EvolutionError('ARTIFACT_INVALID', `artifact exceeds maximum size ${options.maxBytes}: ${filePath}`, filePath); - } - if (options.expectedByteLength !== undefined && st.size !== options.expectedByteLength) { - throw new EvolutionError( - 'ARTIFACT_INVALID', - `artifact byteLength mismatch (expected ${options.expectedByteLength}, observed ${st.size}): ${filePath}`, - filePath, - ); - } - - const noFollow = 'O_NOFOLLOW' in fsConstants ? fsConstants.O_NOFOLLOW : 0; - const handle = await open(filePath, fsConstants.O_RDONLY | noFollow).catch((err: NodeJS.ErrnoException) => { - if (err.code === 'ELOOP' || err.code === 'EFTYPE') { - throw new EvolutionError('ARTIFACT_INVALID', `symlink forbidden on open: ${filePath}`, filePath); - } - if (err.code === 'ENOENT') { - throw new EvolutionError(missingCode, `file not found: ${filePath}`, filePath); - } - throw err; - }); - - try { - const fdStat = await handle.stat(); - if ( - !fdStat.isFile() - || fdStat.nlink !== 1 - || fdStat.size !== st.size - || fdStat.dev !== st.dev - || fdStat.ino !== st.ino - || fdStat.size > options.maxBytes - ) { - throw new EvolutionError('ARTIFACT_INVALID', `artifact changed or failed fd stat verification: ${filePath}`, filePath); - } - if (options.expectedByteLength !== undefined && fdStat.size !== options.expectedByteLength) { - throw new EvolutionError( - 'ARTIFACT_INVALID', - `artifact byteLength mismatch on fd stat: ${filePath}`, - filePath, - ); - } - - const buf = Buffer.alloc(fdStat.size); - let offset = 0; - while (offset < fdStat.size) { - const res = await handle.read(buf, offset, fdStat.size - offset, offset); - if (res.bytesRead === 0) break; - offset += res.bytesRead; - } - if (offset !== fdStat.size) { - throw new EvolutionError('ARTIFACT_INVALID', `incomplete read for artifact: ${filePath}`, filePath); - } - if (options.expectedSha256Hex !== undefined) { - const observedHex = sha256Hex(buf); - if (observedHex !== options.expectedSha256Hex) { - throw new EvolutionError( - 'ARTIFACT_INVALID', - `artifact SHA-256 mismatch (expected ${options.expectedSha256Hex}, observed ${observedHex}): ${filePath}`, - filePath, - ); - } - } - return buf; - } finally { - await handle.close(); - } -} - -async function readVerifiedCasBlob( - campaignRoot: string, - digestHex: string, - options: { - readonly expectedByteLength?: number; - readonly maxBytes: number; - }, -): Promise { - if (!SHA256_HEX_RE.test(digestHex)) { - throw new EvolutionError('ARTIFACT_INVALID', `invalid CAS sha256 hex "${digestHex}"`); - } - await verifyNonSymlinkDirectoryFd(campaignRoot); - const casDir = join(campaignRoot, 'cas'); - const shaDir = join(casDir, 'sha256'); - await verifyNonSymlinkDirectoryFd(casDir); - await verifyNonSymlinkDirectoryFd(shaDir); - - const blobPath = join(shaDir, digestHex); - return readVerifiedRegularFileNoFollow(blobPath, { - expectedSha256Hex: digestHex, - ...(options.expectedByteLength !== undefined ? { expectedByteLength: options.expectedByteLength } : {}), - maxBytes: options.maxBytes, - missingCode: 'ARTIFACT_MISSING', - }); -} - -async function writeNewFileNoFollow(filePath: string, bytes: Uint8Array, mode = 0o644): Promise { - const noFollow = 'O_NOFOLLOW' in fsConstants ? fsConstants.O_NOFOLLOW : 0; - const handle = await open( - filePath, - fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_WRONLY | noFollow, - mode, - ); - try { - let written = 0; - while (written < bytes.byteLength) { - const res = await handle.write(bytes, written, bytes.byteLength - written, written); - if (res.bytesWritten <= 0) { - throw new EvolutionError('EVOLUTION_STORE_ERROR', `short write staging file ${filePath}`, filePath); - } - written += res.bytesWritten; - } - await handle.sync(); - } finally { - await handle.close(); - } -} - -function expectRecord( - value: NullProtoJson | undefined, - allowedKeys: ReadonlySet, - requiredKeys: readonly string[], - code: 'ARTIFACT_INVALID' | 'EXPORT_UNVERIFIED_FORBIDDEN', - diagPath: string, -): Record { - if (value === undefined || value === null || typeof value !== 'object' || Array.isArray(value)) { - throw new EvolutionError(code, 'expected object record', diagPath); - } - const obj = value as Record; - for (const key of Object.keys(obj)) { - if (!Object.hasOwn(obj, key)) continue; - if (FORBIDDEN_PROTOTYPE_KEYS.has(key) || !allowedKeys.has(key)) { - throw new EvolutionError(code, `unknown or forbidden field "${key}"`, `${diagPath}/${key}`); - } - } - for (const req of requiredKeys) { - if (!Object.hasOwn(obj, req) || obj[req] === undefined) { - throw new EvolutionError(code, `missing required field "${req}"`, `${diagPath}/${req}`); - } - } - return obj; -} - -function parseDigestValue( - value: NullProtoJson | undefined, - code: 'ARTIFACT_INVALID' | 'EXPORT_UNVERIFIED_FORBIDDEN', - diagPath: string, -): Digest { - const obj = expectRecord(value, new Set(['algorithm', 'hex']), ['algorithm', 'hex'], code, diagPath); - if (obj['algorithm'] !== 'sha256') { - throw new EvolutionError(code, 'digest algorithm must be "sha256"', `${diagPath}/algorithm`); - } - if (typeof obj['hex'] !== 'string' || !SHA256_HEX_RE.test(obj['hex'])) { - throw new EvolutionError(code, 'digest hex must be 64 lowercase hex characters', `${diagPath}/hex`); - } - return makeDigest(obj['hex']); -} - -function parseReceiptOutputArtifacts( - raw: NullProtoJson | undefined, - maxBlobBytes: number, - diagPath: string, -): readonly BenchmarkOutputArtifact[] { - if (raw === undefined) return []; - if (!Array.isArray(raw) || raw.length > LIMITS.manifest) { - throw new EvolutionError('ARTIFACT_INVALID', 'receipt outputArtifacts must be a bounded array', diagPath); - } - const seenNames = new Set(); - const out: BenchmarkOutputArtifact[] = []; - for (let i = 0; i < raw.length; i++) { - const itemPath = `${diagPath}/${i}`; - const obj = expectRecord(raw[i], ARTIFACT_ENTRY_KEYS, ['name', 'digest', 'byteLength'], 'ARTIFACT_INVALID', itemPath); - const rawName = obj['name']; - if (typeof rawName !== 'string' || rawName.length < 1 || rawName.length > LIMITS.path) { - throw new EvolutionError('ARTIFACT_INVALID', 'invalid artifact name', `${itemPath}/name`); - } - const validRel = validateRelativePath(rawName); - if (!validRel.ok) { - throw new EvolutionError('ARTIFACT_INVALID', `invalid artifact relative path "${rawName}"`, `${itemPath}/name`); - } - if (seenNames.has(validRel.value)) { - throw new EvolutionError('ARTIFACT_INVALID', `duplicate receipt outputArtifact "${validRel.value}"`, `${itemPath}/name`); - } - seenNames.add(validRel.value); - - const digest = parseDigestValue(obj['digest'], 'ARTIFACT_INVALID', `${itemPath}/digest`); - const byteLength = obj['byteLength']; - if ( - typeof byteLength !== 'number' - || !Number.isSafeInteger(byteLength) - || Object.is(byteLength, -0) - || byteLength < 0 - || byteLength > maxBlobBytes - ) { - throw new EvolutionError('ARTIFACT_INVALID', 'invalid artifact byteLength', `${itemPath}/byteLength`); - } - - const entry = createNullRecord<{ - name: string; - digest: Digest; - byteLength: number; - mediaType?: string | null; - }>(); - entry.name = validRel.value; - entry.digest = digest; - entry.byteLength = byteLength; - if (Object.hasOwn(obj, 'mediaType') && obj['mediaType'] !== undefined) { - if (obj['mediaType'] === null) { - entry.mediaType = null; - } else if ( - typeof obj['mediaType'] === 'string' - && obj['mediaType'].length >= 1 - && obj['mediaType'].length <= LIMITS.mediaType - && PRINTABLE_ASCII_RE.test(obj['mediaType']) - ) { - entry.mediaType = obj['mediaType']; - } else { - throw new EvolutionError('ARTIFACT_INVALID', 'invalid artifact mediaType', `${itemPath}/mediaType`); - } - } - out.push(entry as BenchmarkOutputArtifact); - } - return out; -} - function isTextualArtifact(name: string, mediaType: string | null | undefined): boolean { const lowerName = name.toLowerCase(); if (TEXT_ARTIFACT_EXTENSIONS.some(ext => lowerName.endsWith(ext))) { @@ -714,238 +239,6 @@ function inferBlobMediaType(name: string, declaredMediaType?: string | null): st return EVOLUTION_BLOB_DEFAULT_MEDIA_TYPE; } -async function parseAndVerifyReceiptBytes( - rawBytes: Buffer, - options: { - readonly individualId: string; - readonly expectedLockHash?: Digest; - readonly expectedTargetCellId?: string; - readonly allowSyntheticProbe: boolean; - readonly receiptSigningSecret?: string; - readonly verifyReceiptSignature?: ReceiptSignatureVerifier; - readonly scrubber: SecretScrubber; - readonly maxBlobBytes: number; - }, -): Promise { - const diagPath = `/receipts/${options.individualId}`; - if (rawBytes.byteLength === 0 || rawBytes.byteLength > MAX_RECEIPT_FILE_BYTES) { - throw new EvolutionError( - 'ARTIFACT_INVALID', - `receipt exceeds bounds (1..${MAX_RECEIPT_FILE_BYTES} bytes) for ${options.individualId}`, - diagPath, - ); - } - const text = decodeUtf8Strict(rawBytes, diagPath); - assertCleanSecretText(text, options.scrubber, diagPath); - - let parsedRaw: NullProtoJson; - try { - parsedRaw = parseNullProtoJson(text, MAX_RECEIPT_FILE_BYTES, diagPath); - } catch (err: unknown) { - if (err instanceof EvolutionError) { - throw new EvolutionError('ARTIFACT_INVALID', `malformed verdict receipt JSON: ${err.message}`, diagPath); - } - throw err; - } - - const obj = expectRecord( - parsedRaw, - RECEIPT_ALLOWED_KEYS, - RECEIPT_REQUIRED_KEYS, - 'ARTIFACT_INVALID', - diagPath, - ); - - if (obj['version'] !== 1 || obj['kind'] !== 'benchmark_verdict') { - throw new EvolutionError('ARTIFACT_INVALID', 'receipt must have version: 1 and kind: "benchmark_verdict"', diagPath); - } - if (typeof obj['storeId'] !== 'string' || !SAFE_ID_RE.test(obj['storeId'])) { - throw new EvolutionError('ARTIFACT_INVALID', 'invalid receipt storeId', `${diagPath}/storeId`); - } - if (typeof obj['runId'] !== 'string' || obj['runId'].length < 1 || obj['runId'].length > LIMITS.identifier) { - throw new EvolutionError('ARTIFACT_INVALID', 'invalid receipt runId', `${diagPath}/runId`); - } - if (typeof obj['operationId'] !== 'string' || !SAFE_FILENAME_ID_RE.test(obj['operationId'])) { - throw new EvolutionError('ARTIFACT_INVALID', 'invalid receipt operationId', `${diagPath}/operationId`); - } - if (typeof obj['dispatchId'] !== 'string' || !SAFE_ID_RE.test(obj['dispatchId'])) { - throw new EvolutionError('ARTIFACT_INVALID', 'invalid receipt dispatchId', `${diagPath}/dispatchId`); - } - if ( - typeof obj['dispatchGeneration'] !== 'number' - || !Number.isSafeInteger(obj['dispatchGeneration']) - || Object.is(obj['dispatchGeneration'], -0) - || obj['dispatchGeneration'] < 0 - ) { - throw new EvolutionError('ARTIFACT_INVALID', 'invalid receipt dispatchGeneration', `${diagPath}/dispatchGeneration`); - } - if (typeof obj['gateId'] !== 'string' || obj['gateId'].length < 1 || obj['gateId'].length > 128 || !PRINTABLE_ASCII_RE.test(obj['gateId'])) { - throw new EvolutionError('ARTIFACT_INVALID', 'invalid receipt gateId', `${diagPath}/gateId`); - } - if (typeof obj['checkId'] !== 'string' || obj['checkId'].length < 1 || obj['checkId'].length > LIMITS.identifier) { - throw new EvolutionError('ARTIFACT_INVALID', 'invalid receipt checkId', `${diagPath}/checkId`); - } - if (typeof obj['candidateDigest'] !== 'string' || !SHA256_HEX_RE.test(obj['candidateDigest'])) { - throw new EvolutionError('ARTIFACT_INVALID', 'invalid receipt candidateDigest', `${diagPath}/candidateDigest`); - } - if (typeof obj['expiresAtMs'] !== 'string' || !/^(?:0|[1-9][0-9]{0,17})$/.test(obj['expiresAtMs'])) { - throw new EvolutionError('ARTIFACT_INVALID', 'invalid receipt expiresAtMs', `${diagPath}/expiresAtMs`); - } - if ( - typeof obj['preemptionCount'] !== 'number' - || !Number.isSafeInteger(obj['preemptionCount']) - || Object.is(obj['preemptionCount'], -0) - || obj['preemptionCount'] < 0 - || obj['preemptionCount'] > 16 - ) { - throw new EvolutionError('ARTIFACT_INVALID', 'invalid receipt preemptionCount', `${diagPath}/preemptionCount`); - } - - const lockHash = parseDigestValue(obj['lockHash'], 'ARTIFACT_INVALID', `${diagPath}/lockHash`); - if (options.expectedLockHash !== undefined && lockHash.hex !== options.expectedLockHash.hex) { - throw new EvolutionError( - 'EXPORT_UNVERIFIED_FORBIDDEN', - `receipt lockHash mismatch for ${options.individualId}`, - `${diagPath}/lockHash`, - ); - } - - const signature = obj['signature']; - if (typeof signature !== 'string' || !SHA256_HEX_RE.test(signature)) { - throw new EvolutionError( - 'EXPORT_UNVERIFIED_FORBIDDEN', - `receipt missing valid HMAC signature for ${options.individualId}`, - `${diagPath}/signature`, - ); - } - - if (options.receiptSigningSecret !== undefined) { - const validHmac = verifyBenchmarkVerdictSignature( - options.receiptSigningSecret, - obj as Readonly>, - signature, - ); - if (!validHmac) { - throw new EvolutionError( - 'EXPORT_UNVERIFIED_FORBIDDEN', - `verdict receipt HMAC verification failed for ${options.individualId}`, - `${diagPath}/signature`, - ); - } - } - - if (options.verifyReceiptSignature !== undefined) { - const verifiedByCallback = await options.verifyReceiptSignature( - obj as unknown as SignedBenchmarkVerdictReceipt, - rawBytes, - options.individualId, - ); - if (!verifiedByCallback) { - throw new EvolutionError( - 'EXPORT_UNVERIFIED_FORBIDDEN', - `verdict receipt signature verifier rejected ${options.individualId}`, - `${diagPath}/signature`, - ); - } - } - - const status = obj['status']; - if (status !== 'approved') { - throw new EvolutionError( - 'EXPORT_UNVERIFIED_FORBIDDEN', - `verdict receipt status must be "approved" (got "${String(status)}") for ${options.individualId}`, - `${diagPath}/status`, - ); - } - if (obj['reason'] !== null) { - throw new EvolutionError( - 'EXPORT_UNVERIFIED_FORBIDDEN', - `approved verdict receipt must have null reason for ${options.individualId}`, - `${diagPath}/reason`, - ); - } - - if (!Object.hasOwn(obj, 'hardwareProvenance') || obj['hardwareProvenance'] === undefined) { - throw new EvolutionError( - 'EXPORT_UNVERIFIED_FORBIDDEN', - `verdict receipt missing hardwareProvenance for ${options.individualId}`, - `${diagPath}/hardwareProvenance`, - ); - } - - let provenance: HardwareProvenance; - try { - provenance = parseHardwareProvenanceJson( - obj['hardwareProvenance'] as unknown as HardwareProvenance, - `${diagPath}/hardwareProvenance`, - ); - } catch (err: unknown) { - throw new EvolutionError( - 'EXPORT_UNVERIFIED_FORBIDDEN', - `invalid hardwareProvenance on receipt for ${options.individualId}: ${err instanceof Error ? err.message : String(err)}`, - `${diagPath}/hardwareProvenance`, - ); - } - - if (options.expectedTargetCellId !== undefined && provenance.targetCellId !== options.expectedTargetCellId) { - throw new EvolutionError( - 'EXPORT_UNVERIFIED_FORBIDDEN', - `receipt targetCellId "${provenance.targetCellId}" does not match campaign targetCellId "${options.expectedTargetCellId}"`, - `${diagPath}/hardwareProvenance/targetCellId`, - ); - } - - if (provenance.probeKind !== 'physical' && !options.allowSyntheticProbe) { - throw new EvolutionError( - 'EXPORT_UNVERIFIED_FORBIDDEN', - `refusing to export "${provenance.probeKind}" hardware receipt for ${options.individualId} without allowSyntheticProbe: true`, - `${diagPath}/hardwareProvenance/probeKind`, - ); - } - - const outputArtifacts = parseReceiptOutputArtifacts( - obj['outputArtifacts'], - options.maxBlobBytes, - `${diagPath}/outputArtifacts`, - ); - - let bucketMetrics: readonly BucketMetricEntry[] | undefined; - if (Object.hasOwn(obj, 'bucketMetrics') && obj['bucketMetrics'] !== undefined) { - bucketMetrics = parseBucketMetricsJson( - obj['bucketMetrics'] as unknown as readonly BucketMetricEntry[], - options.scrubber, - ); - } - - let hardwareDiagnostics: HardwareDiagnostics | undefined; - if (Object.hasOwn(obj, 'hardwareDiagnostics') && obj['hardwareDiagnostics'] !== undefined) { - hardwareDiagnostics = parseHardwareDiagnosticsJson( - obj['hardwareDiagnostics'] as unknown as HardwareDiagnostics, - options.scrubber, - ); - } - - let heldOutWorkloadId: string | undefined; - if (Object.hasOwn(obj, 'heldOutWorkloadId') && obj['heldOutWorkloadId'] !== undefined) { - const rawWl = obj['heldOutWorkloadId']; - if (typeof rawWl !== 'string' || !BUCKET_ID_RE.test(rawWl) || rawWl.length > LIMITS.bucketId) { - throw new EvolutionError('ARTIFACT_INVALID', 'invalid heldOutWorkloadId on receipt', `${diagPath}/heldOutWorkloadId`); - } - heldOutWorkloadId = rawWl; - } - - return { - receipt: obj as unknown as SignedBenchmarkVerdictReceipt, - rawBytes, - rawDigest: makeDigest(sha256Hex(rawBytes)), - provenance, - outputArtifacts, - ...(bucketMetrics !== undefined ? { bucketMetrics } : {}), - ...(hardwareDiagnostics !== undefined ? { hardwareDiagnostics } : {}), - ...(heldOutWorkloadId !== undefined ? { heldOutWorkloadId } : {}), - }; -} - function assertCompatibleHardwareProvenance( base: HardwareProvenance, other: HardwareProvenance, @@ -973,26 +266,6 @@ function assertCompatibleHardwareProvenance( } } -function assertIndividualArtifactsBoundToReceipt( - individual: IndividualRecord, - receiptArtifacts: readonly BenchmarkOutputArtifact[], -): void { - if (individual.outputArtifacts.length === 0) return; - const byDigest = new Map(); - for (const art of receiptArtifacts) { - byDigest.set(art.digest.hex, art.byteLength); - } - for (const ref of individual.outputArtifacts) { - const expectedLen = byDigest.get(ref.digest.hex); - if (expectedLen === undefined || expectedLen !== ref.byteLength) { - throw new EvolutionError( - 'ARTIFACT_INVALID', - `individual "${individual.individualId}" outputArtifact "${ref.name}" does not match signed verdict receipt`, - ); - } - } -} - function comparePortfolioCandidateBetter(a: IndividualRecord, b: IndividualRecord): number { const rankA = a.paretoRank ?? Number.MAX_SAFE_INTEGER; const rankB = b.paretoRank ?? Number.MAX_SAFE_INTEGER; @@ -1519,48 +792,6 @@ function buildOciLayoutArtifacts(params: { }; } -async function publishStagingDirectoryAtomically( - stagingDir: string, - targetDir: string, - overwrite: boolean, -): Promise { - const existing = await lstat(targetDir).catch((err: NodeJS.ErrnoException) => { - if (err.code === 'ENOENT') return null; - if (err.code === 'ELOOP') { - throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `symlink forbidden at outputDir: ${targetDir}`, targetDir); - } - throw err; - }); - - if (existing === null) { - await rename(stagingDir, targetDir); - return; - } - - if (existing.isSymbolicLink()) { - throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `outputDir cannot be a symlink: ${targetDir}`, targetDir); - } - if (!existing.isDirectory()) { - throw new EvolutionError('ARTIFACT_INVALID', `outputDir exists and is not a directory: ${targetDir}`, targetDir); - } - if (!overwrite) { - throw new EvolutionError('EVOLUTION_CONFLICT', `outputDir already exists: ${targetDir}`, targetDir); - } - - const backupDir = join(dirname(targetDir), `.evolution-bundle-backup-${randomBytes(8).toString('hex')}`); - await rename(targetDir, backupDir); - try { - await rename(stagingDir, targetDir); - } catch (err) { - await rename(backupDir, targetDir).catch(() => undefined); - throw err; - } - await rm(backupDir, { recursive: true, force: true }).catch(async () => { - await chmod(backupDir, 0o700).catch(() => undefined); - await rm(backupDir, { recursive: true, force: true }).catch(() => undefined); - }); -} - /** * Deterministically export verified, compatibility-pinned `evolution-bundle.v1` artifacts * (`dir` or `oci-layout`) after enforcing fail-closed hardware provenance, HMAC receipt, @@ -1574,6 +805,7 @@ export async function exportEvolutionBundle( } const scrubber = options.scrubber ?? DEFAULT_SECRET_SCRUBBER; const allowSyntheticProbe = options.allowSyntheticProbe === true; + const allowHostAttested = options.allowHostAttested === true; const maxBlobBytes = options.maxBlobBytes ?? DEFAULT_MAX_BLOB_BYTES; const overwrite = options.overwrite !== false; const defaultEntrypoint = options.defaultEntrypoint ?? DEFAULT_ENTRYPOINT_SYMBOL; @@ -1656,6 +888,7 @@ export async function exportEvolutionBundle( individualId: ind.individualId, expectedTargetCellId: campaign.manifest.spec.targetCellId, allowSyntheticProbe, + allowHostAttested, ...(options.receiptSigningSecret !== undefined ? { receiptSigningSecret: options.receiptSigningSecret } : {}), ...(options.verifyReceiptSignature !== undefined ? { verifyReceiptSignature: options.verifyReceiptSignature } : {}), scrubber, @@ -2239,6 +1472,7 @@ export async function verifyEvolutionBundle( ): Promise { const scrubber = options.scrubber ?? DEFAULT_SECRET_SCRUBBER; const allowSyntheticProbe = options.allowSyntheticProbe === true; + const allowHostAttested = options.allowHostAttested === true; const maxBlobBytes = options.maxBlobBytes ?? DEFAULT_MAX_BLOB_BYTES; const hasReceiptVerifier = @@ -2319,6 +1553,7 @@ export async function verifyEvolutionBundle( const parsedReceipt = await parseAndVerifyReceiptBytes(receiptBytes, { individualId, allowSyntheticProbe, + allowHostAttested, ...(options.receiptSigningSecret !== undefined ? { receiptSigningSecret: options.receiptSigningSecret } : {}), ...(options.verifyReceiptSignature !== undefined ? { verifyReceiptSignature: options.verifyReceiptSignature } : {}), scrubber, diff --git a/packages/evolution/src/index.ts b/packages/evolution/src/index.ts index 70129910..cc4900ef 100644 --- a/packages/evolution/src/index.ts +++ b/packages/evolution/src/index.ts @@ -48,5 +48,6 @@ export * from './pareto.js'; export * from './sampler.js'; export * from './scratchpad.js'; export * from './bundle.js'; +export * from './snapshot.js'; export * from './team-supervisor.js'; export * from './campaign.js'; diff --git a/packages/evolution/src/schema.ts b/packages/evolution/src/schema.ts index a34e711b..69eee00a 100644 --- a/packages/evolution/src/schema.ts +++ b/packages/evolution/src/schema.ts @@ -1903,6 +1903,7 @@ const HARDWARE_PROVENANCE_KEYS = new Set([ 'topology', 'workloadDigest', 'clockLockMode', + 'isolation', ]); export function parseHardwareProvenanceJson(rawJson: string | HardwareProvenance, path = '/hardwareProvenance'): HardwareProvenance { @@ -1940,6 +1941,7 @@ export function parseHardwareProvenanceJson(rawJson: string | HardwareProvenance topology?: string; workloadDigest: Digest; clockLockMode: 'locked' | 'unlocked' | 'unknown'; + isolation?: 'docker' | 'host_attested'; }>(); prov.targetCellId = expectIdentifier(obj['targetCellId'], `${path}/targetCellId`); prov.probeKind = expectEnum(obj['probeKind'], ['physical', 'synthetic_fixture'] as const, `${path}/probeKind`); @@ -1955,6 +1957,9 @@ export function parseHardwareProvenanceJson(rawJson: string | HardwareProvenance } prov.workloadDigest = expectDigest(obj['workloadDigest'], `${path}/workloadDigest`); prov.clockLockMode = expectEnum(obj['clockLockMode'], ['locked', 'unlocked', 'unknown'] as const, `${path}/clockLockMode`); + if (Object.hasOwn(obj, 'isolation') && obj['isolation'] !== undefined) { + prov.isolation = expectEnum(obj['isolation'], ['docker', 'host_attested'] as const, `${path}/isolation`); + } return prov as HardwareProvenance; } diff --git a/packages/evolution/src/snapshot.ts b/packages/evolution/src/snapshot.ts new file mode 100644 index 00000000..26132682 --- /dev/null +++ b/packages/evolution/src/snapshot.ts @@ -0,0 +1,1391 @@ +import { randomBytes } from 'node:crypto'; +import { lstat, mkdir, readdir, rm } from 'node:fs/promises'; +import { dirname, join } from 'node:path'; +import { + SecretScrubber, + validateRelativePath, + type ArtifactRef, + type BucketMetricEntry, + type Digest, + type HardwareDiagnostics, + type HardwareProvenance, + type StructuredFinding, +} from '@loopwright/core'; +import { MAX_RECEIPT_FILE_BYTES } from '@loopwright/hardware-runner'; +import { EVOLUTION_BLOB_DEFAULT_MEDIA_TYPE, EVOLUTION_RECEIPT_MEDIA_TYPE } from './bundle.js'; +import { + DEFAULT_MAX_BLOB_BYTES, + DEFAULT_SECRET_SCRUBBER, + FORBIDDEN_PROTOTYPE_KEYS, + LONE_SURROGATE_RE, + PRINTABLE_ASCII_RE, + SAFE_FILENAME_ID_RE, + SAFE_ID_RE, + SHA256_HEX_RE, + assertCleanSecretText, + assertIndividualArtifactsBoundToReceipt, + assertNoSymlinkPath, + compareUtf16, + createNullRecord, + decodeUtf8Strict, + ensureDirectoryChainNoSymlink, + makeDigest, + parseAndVerifyReceiptBytes, + parseDigestValue, + publishStagingDirectoryAtomically, + readVerifiedCasBlob, + readVerifiedRegularFileNoFollow, + sha256Hex, + validateAbsoluteFilesystemPath, + verifyNonSymlinkDirectoryFd, + writeNewFileNoFollow, +} from './bundle-fs.js'; +import { + canonicalizeJson, + parseArtifactRefsJson, + parseBucketMetricsJson, + parseEvolutionCampaignDocument, + parseHardwareDiagnosticsJson, + parseHardwareProvenanceJson, + parseMetricsRecordJson, + parseNullProtoJson, + parseStructuredFindingsJson, + parseTeamDiagnosisValue, + type NullProtoJson, +} from './schema.js'; +import { CAMPAIGN_SQLITE_FILENAME, DEFAULT_CAMPAIGN_CLOCK, EvolutionCampaignStore } from './store.js'; +import { + SCRATCHPAD_MAX_BYTES, + EvolutionError, + type BundleMemberDigest, + type CampaignClockSource, + type CampaignRecord, + type CampaignStagePhase, + type CampaignStatus, + type EvolutionCampaignManifest, + type IndividualMutationKind, + type IndividualRecord, + type IndividualStatus, + type IslandRecord, + type LineageEdgeRecord, + type ModelBanditArmRecord, + type ScratchpadSnapshotRecord, + type TeamConfigRecord, + type TeamPatchDiagnosis, +} from './types.js'; + +export const CAMPAIGN_SNAPSHOT_KIND = 'CampaignSnapshot' as const; +export const CAMPAIGN_SNAPSHOT_VERSION = 1 as const; +export const CAMPAIGN_SNAPSHOT_NDJSON_MEDIA_TYPE = 'application/x-ndjson' as const; +export const CAMPAIGN_SNAPSHOT_JSON_MEDIA_TYPE = 'application/json' as const; +export const CAMPAIGN_SNAPSHOT_SCRATCHPAD_MEDIA_TYPE = 'text/markdown' as const; + +const MAX_SNAPSHOT_MANIFEST_BYTES = 1_048_576; +const MAX_SNAPSHOT_MEMBER_BYTES = 16_777_216; // 16 MiB per JSON / JSONL member +const MODEL_LABEL_RE = /^[\x21-\x7E]{1,128}$/; + +const CAMPAIGN_STATUSES = ['active', 'paused', 'completed', 'failed'] as const; +const STAGE_PHASES = ['single-target', 'specialist', 'portfolio'] as const; +const INDIVIDUAL_STATUSES = ['passed', 'soft_passed', 'failed', 'preempted'] as const; +const MUTATION_KINDS = ['baseline', 'diff_tune', 'full_rewrite', 'crossover', 'portfolio'] as const; +const LINEAGE_ROLES = ['primary', 'crossover_donor', 'inspiration', 'portfolio_member'] as const; +const TEAM_CONFIG_STATUSES = ['baseline', 'trial', 'promoted', 'rolled_back'] as const; + +const CAMPAIGN_MEMBER = 'campaign.json'; +const INDIVIDUALS_MEMBER = 'individuals.jsonl'; +const LINEAGE_MEMBER = 'lineage.jsonl'; +const ISLANDS_MEMBER = 'islands.json'; +const BANDIT_MEMBER = 'bandit.json'; +const SCRATCHPAD_INDEX_MEMBER = 'scratchpad.jsonl'; +const TEAM_CONFIGS_MEMBER = 'team_configs.jsonl'; +const REQUIRED_MEMBERS: readonly string[] = Object.freeze([ + CAMPAIGN_MEMBER, + INDIVIDUALS_MEMBER, + LINEAGE_MEMBER, + ISLANDS_MEMBER, + BANDIT_MEMBER, + SCRATCHPAD_INDEX_MEMBER, + TEAM_CONFIGS_MEMBER, +]); + +const MANIFEST_KEYS: ReadonlySet = new Set(['kind', 'version', 'campaignId', 'generations', 'parentDigest', 'members']); +const GENERATIONS_KEYS: ReadonlySet = new Set(['min', 'max']); +const MEMBER_KEYS: ReadonlySet = new Set(['path', 'digest', 'byteLength', 'mediaType']); +const CAMPAIGN_KEYS: ReadonlySet = new Set([ + 'campaignId', 'name', 'status', 'stagePhase', 'activeBucketId', 'manifest', 'manifestDigest', + 'baseRevision', 'lockHash', 'driverConstraint', 'currentGeneration', 'evaluationsUsed', 'preemptionsCount', +]); +const INDIVIDUAL_KEYS: ReadonlySet = new Set([ + 'individualId', 'campaignId', 'islandId', 'generation', 'bucketId', 'teamConfigId', 'modelId', 'trackId', + 'mutationKind', 'status', 'failureReason', 'nicheKey', 'paretoRank', 'crowdingDistance', 'crowdingIsBoundary', + 'scalarFitness', 'offspringCount', 'codeSliceCasDigest', 'evidenceDigest', 'receipt', 'outputArtifacts', + 'metrics', 'bucketMetrics', 'hardwareDiagnostics', 'hardwareProvenance', 'findings', +]); +const INDIVIDUAL_OPTIONAL_KEYS: readonly string[] = ['bucketMetrics', 'hardwareDiagnostics', 'hardwareProvenance', 'findings']; +const INDIVIDUAL_REQUIRED_KEYS: readonly string[] = [...INDIVIDUAL_KEYS].filter(k => !INDIVIDUAL_OPTIONAL_KEYS.includes(k)); +const ISLAND_KEYS: ReadonlySet = new Set([ + 'campaignId', 'islandId', 'activeTeamConfigId', 'currentGeneration', 'consecutiveNoGainGenerations', + 'consecutivePathologyRuns', 'lastHypervolume', 'bestRooflineHeadroom', +]); +const TEAM_CONFIG_KEYS: ReadonlySet = new Set([ + 'teamConfigId', 'campaignId', 'islandId', 'parentTeamConfigId', 'createdGeneration', 'status', + 'trialBudgetGenerations', 'trialUsedGenerations', 'diagnosis', 'patchCasDigest', 'paretoAdvances', 'nicheDiscoveries', +]); +const LINEAGE_KEYS: ReadonlySet = new Set([ + 'campaignId', 'childIndividualId', 'parentIndividualId', 'role', 'sourceIslandId', 'createdGeneration', +]); +const BANDIT_KEYS: ReadonlySet = new Set([ + 'campaignId', 'modelId', 'pullCount', 'totalReward', 'meanReward', 'lastPulledGeneration', +]); +const SCRATCHPAD_KEYS: ReadonlySet = new Set([ + 'snapshotId', 'campaignId', 'generation', 'casDigest', 'byteLength', 'topGainsCount', 'failurePatternsCount', +]); +const DIAGNOSIS_KEYS: ReadonlySet = new Set(['summary', 'plateauCategory', 'rationale']); + +export interface CampaignSnapshotManifestV1 { + readonly kind: typeof CAMPAIGN_SNAPSHOT_KIND; + readonly version: typeof CAMPAIGN_SNAPSHOT_VERSION; + readonly campaignId: string; + readonly generations: { readonly min: number; readonly max: number }; + readonly parentDigest?: Digest; + readonly members: readonly BundleMemberDigest[]; +} + +/** The `campaigns` row without its civil `createdAtWallMs` / `updatedAtWallMs` columns. */ +export type SnapshotCampaignRecordV1 = Omit; + +/** + * One `individuals` row. `crowdingIsBoundary` carries the `+Infinity` crowding distance, and `receipt` + * is the CAS digest of the approved verdict receipt or `null` when none exists. + */ +export interface SnapshotIndividualRecordV1 { + readonly individualId: string; + readonly campaignId: string; + readonly islandId: number; + readonly generation: number; + readonly bucketId: string | null; + readonly teamConfigId: string; + readonly modelId: string; + readonly trackId: string | null; + readonly mutationKind: IndividualMutationKind; + readonly status: IndividualStatus; + readonly failureReason: string | null; + readonly nicheKey: string | null; + readonly paretoRank: number | null; + readonly crowdingDistance: number | null; + readonly crowdingIsBoundary: boolean; + readonly scalarFitness: number | null; + readonly offspringCount: number; + readonly codeSliceCasDigest: Digest | null; + readonly evidenceDigest: Digest | null; + readonly receipt: Digest | null; + readonly outputArtifacts: readonly ArtifactRef[]; + readonly metrics: Readonly>; + readonly bucketMetrics?: readonly BucketMetricEntry[]; + readonly hardwareDiagnostics?: HardwareDiagnostics; + readonly hardwareProvenance?: HardwareProvenance; + readonly findings?: readonly StructuredFinding[]; +} + +/** One `scratchpad_snapshots` row; its content lives at `scratchpad/.md`. */ +export type SnapshotScratchpadRecordV1 = Omit; + +/** Options shared by snapshot write, verify, and import: receipt gates, scrubber, and blob bound. */ +export interface CampaignSnapshotCommonOptions { + readonly allowSyntheticProbe?: boolean; + readonly allowHostAttested?: boolean; + readonly receiptSigningSecret?: string; + readonly scrubber?: SecretScrubber; + readonly maxBlobBytes?: number; +} + +export interface WriteCampaignSnapshotOptions extends CampaignSnapshotCommonOptions { + readonly store: EvolutionCampaignStore; + readonly campaignId: string; + readonly outDir: string; + readonly parentDigest?: Digest; + readonly overwrite?: boolean; +} + +export interface WriteCampaignSnapshotResult { + readonly outDir: string; + readonly manifestDigest: Digest; + readonly parentDigest?: Digest; + readonly individualCount: number; + readonly receiptCount: number; + readonly blobCount: number; +} + +export interface VerifyCampaignSnapshotOptions extends CampaignSnapshotCommonOptions { + readonly bundleDir: string; +} + +export interface VerifyCampaignSnapshotResult { + readonly bundleDir: string; + readonly manifest: CampaignSnapshotManifestV1; + readonly manifestDigest: Digest; + readonly individualCount: number; + readonly receiptCount: number; + readonly blobCount: number; +} + +export interface ImportCampaignSnapshotOptions extends VerifyCampaignSnapshotOptions { + readonly stateDir: string; + readonly clock?: CampaignClockSource; +} + +export interface ImportCampaignSnapshotResult { + readonly stateDir: string; + readonly dbPath: string; + readonly campaignId: string; + readonly snapshotDigest: Digest; + readonly individualCount: number; + readonly receiptCount: number; + readonly blobCount: number; +} + +interface VerifiedCampaignSnapshot { + readonly bundleDir: string; + readonly manifest: CampaignSnapshotManifestV1; + readonly manifestDigest: Digest; + readonly campaign: SnapshotCampaignRecordV1; + readonly individuals: readonly SnapshotIndividualRecordV1[]; + readonly lineageEdges: readonly LineageEdgeRecord[]; + readonly islands: readonly IslandRecord[]; + readonly modelBanditArms: readonly ModelBanditArmRecord[]; + readonly teamConfigs: readonly TeamConfigRecord[]; + readonly scratchpadSnapshots: readonly SnapshotScratchpadRecordV1[]; + readonly scratchpadBytes: ReadonlyMap; + readonly receiptBytes: ReadonlyMap; + readonly blobByteLengths: ReadonlyMap; +} + +// --------------------------------------------------------------------------- +// Strict member parsers (untrusted input; every failure is ARTIFACT_INVALID) +// --------------------------------------------------------------------------- + +function invalid(message: string, path: string): never { + throw new EvolutionError('ARTIFACT_INVALID', message, path); +} + +function expectObject( + value: NullProtoJson | undefined, + allowedKeys: ReadonlySet, + requiredKeys: readonly string[], + path: string, +): Record { + if (value === undefined || value === null || typeof value !== 'object' || Array.isArray(value)) { + invalid('expected object record', path); + } + const obj = value as Record; + for (const key of Object.keys(obj)) { + if (!Object.hasOwn(obj, key)) continue; + if (FORBIDDEN_PROTOTYPE_KEYS.has(key) || !allowedKeys.has(key)) { + invalid(`unknown or forbidden field "${key}"`, `${path}/${key}`); + } + } + for (const req of requiredKeys) { + if (!Object.hasOwn(obj, req) || obj[req] === undefined) { + invalid(`missing required field "${req}"`, `${path}/${req}`); + } + } + return obj; +} + +function expectString(value: NullProtoJson | undefined, minLen: number, maxLen: number, path: string): string { + if (typeof value !== 'string') invalid('expected string', path); + if (value.length < minLen || value.length > maxLen || LONE_SURROGATE_RE.test(value)) { + invalid(`string length must be within ${minLen}..${maxLen}`, path); + } + return value; +} + +function expectNullableString(value: NullProtoJson | undefined, minLen: number, maxLen: number, path: string): string | null { + return value === null || value === undefined ? null : expectString(value, minLen, maxLen, path); +} + +function expectSafeId(value: NullProtoJson | undefined, path: string): string { + const s = expectString(value, 1, 128, path); + if (FORBIDDEN_PROTOTYPE_KEYS.has(s) || !SAFE_ID_RE.test(s)) invalid(`invalid id "${s}"`, path); + return s; +} + +function expectNullableSafeId(value: NullProtoJson | undefined, path: string): string | null { + return value === null || value === undefined ? null : expectSafeId(value, path); +} + +function expectInteger(value: NullProtoJson | undefined, min: number, max: number, path: string): number { + if (typeof value !== 'number' || !Number.isSafeInteger(value) || Object.is(value, -0) || value < min || value > max) { + invalid(`expected integer within ${min}..${max}`, path); + } + return value; +} + +function expectNullableInteger(value: NullProtoJson | undefined, min: number, max: number, path: string): number | null { + return value === null || value === undefined ? null : expectInteger(value, min, max, path); +} + +function expectFinite(value: NullProtoJson | undefined, path: string): number { + if (typeof value !== 'number' || !Number.isFinite(value) || Object.is(value, -0) || value < 0) { + invalid('expected finite non-negative number', path); + } + return value; +} + +function expectNullableFinite(value: NullProtoJson | undefined, path: string): number | null { + return value === null || value === undefined ? null : expectFinite(value, path); +} + +function expectBoolean(value: NullProtoJson | undefined, path: string): boolean { + if (typeof value !== 'boolean') invalid('expected boolean', path); + return value; +} + +function expectEnum(value: NullProtoJson | undefined, allowed: readonly T[], path: string): T { + if (typeof value !== 'string' || !(allowed as readonly string[]).includes(value)) { + invalid(`expected one of [${allowed.join(', ')}]`, path); + } + return value as T; +} + +function expectDigest(value: NullProtoJson | undefined, path: string): Digest { + return parseDigestValue(value, 'ARTIFACT_INVALID', path); +} + +function expectNullableDigest(value: NullProtoJson | undefined, path: string): Digest | null { + return value === null || value === undefined ? null : parseDigestValue(value, 'ARTIFACT_INVALID', path); +} + +function parseJsonMember(text: string, diagPath: string, maxBytes: number): NullProtoJson { + try { + return parseNullProtoJson(text, maxBytes, diagPath); + } catch (err: unknown) { + throw new EvolutionError( + 'ARTIFACT_INVALID', + `invalid ${diagPath}: ${err instanceof Error ? err.message : String(err)}`, + diagPath, + ); + } +} + +function parseJsonLines(text: string, relPath: string, maxLineBytes: number): readonly NullProtoJson[] { + const lines = text.split('\n'); + if (lines.length > 0 && lines[lines.length - 1] === '') lines.pop(); + return lines.map((line, index) => { + if (line.length === 0) invalid('blank line inside JSONL member', `${relPath}/${index}`); + return parseJsonMember(line, `${relPath}/${index}`, maxLineBytes); + }); +} + +function parseArrayMember(text: string, relPath: string): readonly NullProtoJson[] { + const parsed = parseJsonMember(text, `/${relPath}`, MAX_SNAPSHOT_MEMBER_BYTES); + if (!Array.isArray(parsed)) invalid(`${relPath} must be an array`, `/${relPath}`); + return parsed; +} + +function parseManifest(obj: Record, path: string): CampaignSnapshotManifestV1 { + if (obj['kind'] !== CAMPAIGN_SNAPSHOT_KIND || obj['version'] !== CAMPAIGN_SNAPSHOT_VERSION) { + invalid(`manifest.json must have kind: "${CAMPAIGN_SNAPSHOT_KIND}" and version: ${CAMPAIGN_SNAPSHOT_VERSION}`, path); + } + const campaignId = expectSafeId(obj['campaignId'], `${path}/campaignId`); + const genObj = expectObject(obj['generations'], GENERATIONS_KEYS, ['min', 'max'], `${path}/generations`); + const min = expectInteger(genObj['min'], 0, Number.MAX_SAFE_INTEGER, `${path}/generations/min`); + const max = expectInteger(genObj['max'], min, Number.MAX_SAFE_INTEGER, `${path}/generations/max`); + let parentDigest: Digest | undefined; + if (obj['parentDigest'] !== undefined) { + parentDigest = expectDigest(obj['parentDigest'], `${path}/parentDigest`); + } + if (!Array.isArray(obj['members']) || obj['members'].length === 0) { + invalid('members must be a non-empty array', `${path}/members`); + } + const seenPaths = new Set(); + const members: BundleMemberDigest[] = []; + for (let i = 0; i < obj['members'].length; i++) { + const mPath = `${path}/members/${i}`; + const mObj = expectObject(obj['members'][i], MEMBER_KEYS, ['path', 'digest', 'byteLength'], mPath); + const relPath = expectString(mObj['path'], 1, 512, `${mPath}/path`); + if (!validateRelativePath(relPath).ok || !isAllowedMemberPath(relPath)) { + invalid(`invalid snapshot member path "${relPath}"`, `${mPath}/path`); + } + if (seenPaths.has(relPath)) invalid(`duplicate member path "${relPath}"`, `${mPath}/path`); + seenPaths.add(relPath); + members.push({ + path: relPath, + digest: expectDigest(mObj['digest'], `${mPath}/digest`), + byteLength: expectInteger(mObj['byteLength'], 0, Number.MAX_SAFE_INTEGER, `${mPath}/byteLength`), + ...(mObj['mediaType'] === undefined + ? {} + : { mediaType: expectString(mObj['mediaType'], 1, 128, `${mPath}/mediaType`) }), + }); + } + for (const required of REQUIRED_MEMBERS) { + if (!seenPaths.has(required)) invalid(`manifest.json does not list required member "${required}"`, `${path}/members`); + } + const out = createNullRecord<{ + kind: typeof CAMPAIGN_SNAPSHOT_KIND; + version: typeof CAMPAIGN_SNAPSHOT_VERSION; + campaignId: string; + generations: { readonly min: number; readonly max: number }; + parentDigest?: Digest; + members: readonly BundleMemberDigest[]; + }>(); + out.kind = CAMPAIGN_SNAPSHOT_KIND; + out.version = CAMPAIGN_SNAPSHOT_VERSION; + out.campaignId = campaignId; + out.generations = Object.freeze({ min, max }); + if (parentDigest !== undefined) out.parentDigest = parentDigest; + out.members = Object.freeze(members.sort((a, b) => compareUtf16(a.path, b.path))); + return out as CampaignSnapshotManifestV1; +} + +function isAllowedMemberPath(relPath: string): boolean { + if (REQUIRED_MEMBERS.includes(relPath)) return true; + const blob = /^blobs\/sha256\/([0-9a-f]{64})$/.exec(relPath); + if (blob !== null) return true; + const scratchpad = /^scratchpad\/([0-9a-f]{64})\.md$/.exec(relPath); + if (scratchpad !== null) return true; + const receipt = /^receipts\/([A-Za-z0-9][A-Za-z0-9._-]{0,127})\.verdict\.json$/.exec(relPath); + return receipt !== null && receipt[1] !== '.' && receipt[1] !== '..'; +} + +function scratchpadPath(hex: string): string { + return `scratchpad/${hex}.md`; +} + +function parseCampaign(obj: Record, path: string): SnapshotCampaignRecordV1 { + const campaignId = expectSafeId(obj['campaignId'], `${path}/campaignId`); + const manifestValue = obj['manifest']; + if (manifestValue === null || typeof manifestValue !== 'object' || Array.isArray(manifestValue)) { + invalid('campaign manifest must be an object', `${path}/manifest`); + } + let manifest: EvolutionCampaignManifest; + try { + manifest = parseEvolutionCampaignDocument(manifestValue); + } catch (err: unknown) { + throw new EvolutionError( + 'ARTIFACT_INVALID', + `invalid ${path}/manifest: ${err instanceof Error ? err.message : String(err)}`, + `${path}/manifest`, + ); + } + const out = createNullRecord<{ + campaignId: string; + name: string; + status: CampaignStatus; + stagePhase: CampaignStagePhase; + activeBucketId: string | null; + manifest: EvolutionCampaignManifest; + manifestDigest: Digest; + baseRevision: string; + lockHash: Digest; + driverConstraint: string | null; + currentGeneration: number; + evaluationsUsed: number; + preemptionsCount: number; + }>(); + out.campaignId = campaignId; + out.name = expectString(obj['name'], 1, 128, `${path}/name`); + out.status = expectEnum(obj['status'], CAMPAIGN_STATUSES, `${path}/status`); + out.stagePhase = expectEnum(obj['stagePhase'], STAGE_PHASES, `${path}/stagePhase`); + out.activeBucketId = expectNullableString(obj['activeBucketId'], 1, 128, `${path}/activeBucketId`); + out.manifest = manifest; + out.manifestDigest = expectDigest(obj['manifestDigest'], `${path}/manifestDigest`); + out.baseRevision = expectString(obj['baseRevision'], 1, 128, `${path}/baseRevision`); + out.lockHash = expectDigest(obj['lockHash'], `${path}/lockHash`); + const driverConstraint = expectNullableString(obj['driverConstraint'], 1, 128, `${path}/driverConstraint`); + if (driverConstraint !== null && !PRINTABLE_ASCII_RE.test(driverConstraint)) { + invalid('driverConstraint must be printable ASCII', `${path}/driverConstraint`); + } + out.driverConstraint = driverConstraint; + out.currentGeneration = expectInteger(obj['currentGeneration'], 0, Number.MAX_SAFE_INTEGER, `${path}/currentGeneration`); + out.evaluationsUsed = expectInteger(obj['evaluationsUsed'], 0, Number.MAX_SAFE_INTEGER, `${path}/evaluationsUsed`); + out.preemptionsCount = expectInteger(obj['preemptionsCount'], 0, Number.MAX_SAFE_INTEGER, `${path}/preemptionsCount`); + return out as SnapshotCampaignRecordV1; +} + +function parseIndividual(obj: Record, path: string): SnapshotIndividualRecordV1 { + const out = createNullRecord>(); + out.individualId = expectSafeId(obj['individualId'], `${path}/individualId`); + out.campaignId = expectSafeId(obj['campaignId'], `${path}/campaignId`); + out.islandId = expectInteger(obj['islandId'], 0, 15, `${path}/islandId`); + out.generation = expectInteger(obj['generation'], 0, Number.MAX_SAFE_INTEGER, `${path}/generation`); + out.bucketId = expectNullableString(obj['bucketId'], 1, 128, `${path}/bucketId`); + out.teamConfigId = expectSafeId(obj['teamConfigId'], `${path}/teamConfigId`); + out.modelId = expectString(obj['modelId'], 1, 128, `${path}/modelId`); + if (!MODEL_LABEL_RE.test(out.modelId as string)) invalid('modelId must be printable ASCII', `${path}/modelId`); + out.trackId = expectNullableString(obj['trackId'], 1, 128, `${path}/trackId`); + out.mutationKind = expectEnum(obj['mutationKind'], MUTATION_KINDS, `${path}/mutationKind`); + out.status = expectEnum(obj['status'], INDIVIDUAL_STATUSES, `${path}/status`); + out.failureReason = expectNullableString(obj['failureReason'], 1, 256, `${path}/failureReason`); + out.nicheKey = expectNullableString(obj['nicheKey'], 1, 256, `${path}/nicheKey`); + out.paretoRank = expectNullableInteger(obj['paretoRank'], 1, Number.MAX_SAFE_INTEGER, `${path}/paretoRank`); + const crowdingIsBoundary = expectBoolean(obj['crowdingIsBoundary'], `${path}/crowdingIsBoundary`); + const crowdingDistance = expectNullableFinite(obj['crowdingDistance'], `${path}/crowdingDistance`); + if (crowdingIsBoundary && crowdingDistance !== null) { + invalid('crowdingDistance must be null when crowdingIsBoundary is true', `${path}/crowdingDistance`); + } + out.crowdingIsBoundary = crowdingIsBoundary; + out.crowdingDistance = crowdingDistance; + out.scalarFitness = expectNullableFinite(obj['scalarFitness'], `${path}/scalarFitness`); + out.offspringCount = expectInteger(obj['offspringCount'], 0, Number.MAX_SAFE_INTEGER, `${path}/offspringCount`); + out.codeSliceCasDigest = expectNullableDigest(obj['codeSliceCasDigest'], `${path}/codeSliceCasDigest`); + out.evidenceDigest = expectNullableDigest(obj['evidenceDigest'], `${path}/evidenceDigest`); + out.receipt = expectNullableDigest(obj['receipt'], `${path}/receipt`); + try { + out.outputArtifacts = parseArtifactRefsJson(obj['outputArtifacts'] as unknown as readonly ArtifactRef[], `${path}/outputArtifacts`); + out.metrics = parseMetricsRecordJson(obj['metrics'] as Readonly>, `${path}/metrics`); + if (obj['bucketMetrics'] !== undefined && obj['bucketMetrics'] !== null) { + out.bucketMetrics = parseBucketMetricsJson(obj['bucketMetrics'] as unknown as readonly BucketMetricEntry[]); + } + if (obj['hardwareDiagnostics'] !== undefined && obj['hardwareDiagnostics'] !== null) { + out.hardwareDiagnostics = parseHardwareDiagnosticsJson(obj['hardwareDiagnostics'] as unknown as HardwareDiagnostics); + } + if (obj['hardwareProvenance'] !== undefined && obj['hardwareProvenance'] !== null) { + out.hardwareProvenance = parseHardwareProvenanceJson(obj['hardwareProvenance'] as unknown as HardwareProvenance, `${path}/hardwareProvenance`); + } + if (obj['findings'] !== undefined && obj['findings'] !== null) { + out.findings = parseStructuredFindingsJson(obj['findings'] as unknown as readonly StructuredFinding[], `${path}/findings`); + } + } catch (err: unknown) { + if (err instanceof EvolutionError && err.code === 'SECRET_LEAK_DETECTED') throw err; + throw new EvolutionError( + 'ARTIFACT_INVALID', + `invalid individual record: ${err instanceof Error ? err.message : String(err)}`, + path, + ); + } + return out as unknown as SnapshotIndividualRecordV1; +} + +function parseIsland(obj: Record, path: string): IslandRecord { + const out = createNullRecord>(); + out.campaignId = expectSafeId(obj['campaignId'], `${path}/campaignId`); + out.islandId = expectInteger(obj['islandId'], 0, 15, `${path}/islandId`); + out.activeTeamConfigId = expectSafeId(obj['activeTeamConfigId'], `${path}/activeTeamConfigId`); + out.currentGeneration = expectInteger(obj['currentGeneration'], 0, Number.MAX_SAFE_INTEGER, `${path}/currentGeneration`); + out.consecutiveNoGainGenerations = expectInteger(obj['consecutiveNoGainGenerations'], 0, Number.MAX_SAFE_INTEGER, `${path}/consecutiveNoGainGenerations`); + out.consecutivePathologyRuns = expectInteger(obj['consecutivePathologyRuns'], 0, Number.MAX_SAFE_INTEGER, `${path}/consecutivePathologyRuns`); + out.lastHypervolume = expectFinite(obj['lastHypervolume'], `${path}/lastHypervolume`); + out.bestRooflineHeadroom = expectNullableFinite(obj['bestRooflineHeadroom'], `${path}/bestRooflineHeadroom`); + return out as unknown as IslandRecord; +} + +function parseTeamDiagnosis(value: NullProtoJson | undefined, path: string): TeamPatchDiagnosis | null { + if (value === null || value === undefined) return null; + const obj = expectObject(value, DIAGNOSIS_KEYS, ['summary', 'plateauCategory', 'rationale'], path); + try { + return parseTeamDiagnosisValue(obj, path); + } catch (err: unknown) { + throw new EvolutionError('ARTIFACT_INVALID', `invalid diagnosis: ${err instanceof Error ? err.message : String(err)}`, path); + } +} + +function parseTeamConfig(obj: Record, path: string): TeamConfigRecord { + const out = createNullRecord>(); + out.teamConfigId = expectSafeId(obj['teamConfigId'], `${path}/teamConfigId`); + out.campaignId = expectSafeId(obj['campaignId'], `${path}/campaignId`); + out.islandId = expectInteger(obj['islandId'], 0, 15, `${path}/islandId`); + out.parentTeamConfigId = expectNullableSafeId(obj['parentTeamConfigId'], `${path}/parentTeamConfigId`); + out.createdGeneration = expectInteger(obj['createdGeneration'], 0, Number.MAX_SAFE_INTEGER, `${path}/createdGeneration`); + out.status = expectEnum(obj['status'], TEAM_CONFIG_STATUSES, `${path}/status`); + out.trialBudgetGenerations = expectInteger(obj['trialBudgetGenerations'], 0, Number.MAX_SAFE_INTEGER, `${path}/trialBudgetGenerations`); + out.trialUsedGenerations = expectInteger(obj['trialUsedGenerations'], 0, Number.MAX_SAFE_INTEGER, `${path}/trialUsedGenerations`); + out.diagnosis = parseTeamDiagnosis(obj['diagnosis'], `${path}/diagnosis`); + out.patchCasDigest = expectNullableDigest(obj['patchCasDigest'], `${path}/patchCasDigest`); + out.paretoAdvances = expectInteger(obj['paretoAdvances'], 0, Number.MAX_SAFE_INTEGER, `${path}/paretoAdvances`); + out.nicheDiscoveries = expectInteger(obj['nicheDiscoveries'], 0, Number.MAX_SAFE_INTEGER, `${path}/nicheDiscoveries`); + return out as unknown as TeamConfigRecord; +} + +function parseLineageEdge(obj: Record, path: string): LineageEdgeRecord { + const out = createNullRecord>(); + out.campaignId = expectSafeId(obj['campaignId'], `${path}/campaignId`); + out.childIndividualId = expectSafeId(obj['childIndividualId'], `${path}/childIndividualId`); + out.parentIndividualId = expectSafeId(obj['parentIndividualId'], `${path}/parentIndividualId`); + if (out.childIndividualId === out.parentIndividualId) invalid('lineage edge cannot link an individual to itself', path); + out.role = expectEnum(obj['role'], LINEAGE_ROLES, `${path}/role`); + out.sourceIslandId = expectInteger(obj['sourceIslandId'], 0, 15, `${path}/sourceIslandId`); + out.createdGeneration = expectInteger(obj['createdGeneration'], 0, Number.MAX_SAFE_INTEGER, `${path}/createdGeneration`); + return out as unknown as LineageEdgeRecord; +} + +function parseBanditArm(obj: Record, path: string): ModelBanditArmRecord { + const out = createNullRecord>(); + out.campaignId = expectSafeId(obj['campaignId'], `${path}/campaignId`); + out.modelId = expectString(obj['modelId'], 1, 128, `${path}/modelId`); + out.pullCount = expectInteger(obj['pullCount'], 0, Number.MAX_SAFE_INTEGER, `${path}/pullCount`); + out.totalReward = expectFinite(obj['totalReward'], `${path}/totalReward`); + out.meanReward = expectFinite(obj['meanReward'], `${path}/meanReward`); + out.lastPulledGeneration = expectNullableInteger(obj['lastPulledGeneration'], 0, Number.MAX_SAFE_INTEGER, `${path}/lastPulledGeneration`); + return out as unknown as ModelBanditArmRecord; +} + +function parseScratchpad(obj: Record, path: string): SnapshotScratchpadRecordV1 { + const out = createNullRecord>(); + out.snapshotId = expectSafeId(obj['snapshotId'], `${path}/snapshotId`); + out.campaignId = expectSafeId(obj['campaignId'], `${path}/campaignId`); + out.generation = expectInteger(obj['generation'], 0, Number.MAX_SAFE_INTEGER, `${path}/generation`); + out.casDigest = expectDigest(obj['casDigest'], `${path}/casDigest`); + out.byteLength = expectInteger(obj['byteLength'], 0, SCRATCHPAD_MAX_BYTES, `${path}/byteLength`); + out.topGainsCount = expectInteger(obj['topGainsCount'], 0, Number.MAX_SAFE_INTEGER, `${path}/topGainsCount`); + out.failurePatternsCount = expectInteger(obj['failurePatternsCount'], 0, Number.MAX_SAFE_INTEGER, `${path}/failurePatternsCount`); + return out as unknown as SnapshotScratchpadRecordV1; +} + +// --------------------------------------------------------------------------- +// Serialization (deterministic canonical JSON; no timestamps) +// --------------------------------------------------------------------------- + +function serializeJsonl(records: readonly object[]): string { + return records.length === 0 ? '' : `${records.map(r => canonicalizeJson(r)).join('\n')}\n`; +} + +/** `crowdingDistance: +Infinity` becomes `crowdingIsBoundary: true`; `verdictReceiptCasDigest` becomes `receipt`. */ +function toIndividualV1(ind: IndividualRecord, receipt: Digest | null): SnapshotIndividualRecordV1 { + const isBoundary = ind.crowdingDistance === Number.POSITIVE_INFINITY; + return { + individualId: ind.individualId, + campaignId: ind.campaignId, + islandId: ind.islandId, + generation: ind.generation, + bucketId: ind.bucketId, + teamConfigId: ind.teamConfigId, + modelId: ind.modelId, + trackId: ind.trackId, + mutationKind: ind.mutationKind, + status: ind.status, + failureReason: ind.failureReason, + nicheKey: ind.nicheKey, + paretoRank: ind.paretoRank, + crowdingDistance: isBoundary ? null : ind.crowdingDistance, + crowdingIsBoundary: isBoundary, + scalarFitness: ind.scalarFitness, + offspringCount: ind.offspringCount, + codeSliceCasDigest: ind.codeSliceCasDigest, + evidenceDigest: ind.evidenceDigest, + receipt, + outputArtifacts: ind.outputArtifacts, + metrics: ind.metrics, + ...(ind.bucketMetrics !== undefined ? { bucketMetrics: ind.bucketMetrics } : {}), + ...(ind.hardwareDiagnostics !== undefined ? { hardwareDiagnostics: ind.hardwareDiagnostics } : {}), + ...(ind.hardwareProvenance !== undefined ? { hardwareProvenance: ind.hardwareProvenance } : {}), + ...(ind.findings !== undefined ? { findings: ind.findings } : {}), + }; +} + +function toScratchpadV1(snap: ScratchpadSnapshotRecord): SnapshotScratchpadRecordV1 { + return { + snapshotId: snap.snapshotId, + campaignId: snap.campaignId, + generation: snap.generation, + casDigest: snap.casDigest, + byteLength: snap.byteLength, + topGainsCount: snap.topGainsCount, + failurePatternsCount: snap.failurePatternsCount, + }; +} + +/** Read only the `status` field of a stored receipt so a signed non-approved verdict can be skipped. */ +function peekReceiptStatus(rawBytes: Uint8Array, individualId: string): string { + const diagPath = `/receipts/${individualId}`; + if (rawBytes.byteLength === 0 || rawBytes.byteLength > MAX_RECEIPT_FILE_BYTES) { + throw new EvolutionError('ARTIFACT_INVALID', `receipt exceeds bounds for ${individualId}`, diagPath); + } + let parsed: NullProtoJson; + try { + parsed = parseNullProtoJson(decodeUtf8Strict(rawBytes, diagPath), MAX_RECEIPT_FILE_BYTES, diagPath); + } catch (err: unknown) { + throw new EvolutionError('ARTIFACT_INVALID', `malformed verdict receipt JSON: ${err instanceof Error ? err.message : String(err)}`, diagPath); + } + const status = parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) + ? (parsed as Record)['status'] + : undefined; + if (typeof status !== 'string') { + throw new EvolutionError('ARTIFACT_INVALID', `receipt has no status for ${individualId}`, `${diagPath}/status`); + } + return status; +} + +async function readVerifiedCasBlobIfExists( + campaignRoot: string, + digestHex: string, + maxBlobBytes: number, +): Promise { + try { + const bytes = await readVerifiedCasBlob(campaignRoot, digestHex, { maxBytes: maxBlobBytes }); + return bytes.byteLength; + } catch (err: unknown) { + if (err instanceof EvolutionError && err.code === 'ARTIFACT_MISSING') return null; + throw err; + } +} + +function resolveOptions(options: CampaignSnapshotCommonOptions): { + readonly scrubber: SecretScrubber; + readonly allowSyntheticProbe: boolean; + readonly allowHostAttested: boolean; + readonly maxBlobBytes: number; + readonly receiptSigningSecret: string | undefined; +} { + if (!options || typeof options !== 'object') { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'campaign snapshot options must be an object'); + } + const maxBlobBytes = options.maxBlobBytes ?? DEFAULT_MAX_BLOB_BYTES; + if (!Number.isSafeInteger(maxBlobBytes) || maxBlobBytes < 1) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'maxBlobBytes must be a positive integer', '/maxBlobBytes'); + } + return { + scrubber: options.scrubber ?? DEFAULT_SECRET_SCRUBBER, + allowSyntheticProbe: options.allowSyntheticProbe === true, + allowHostAttested: options.allowHostAttested === true, + maxBlobBytes, + receiptSigningSecret: typeof options.receiptSigningSecret === 'string' && options.receiptSigningSecret.length > 0 + ? options.receiptSigningSecret + : undefined, + }; +} + +/** + * Deterministically write a `campaign-snapshot.v1` directory from `campaign.sqlite`: every evaluated + * individual, lineage, islands, bandit arms, team configs, scratchpads, the CAS blobs the campaign + * needs to continue, and every approved verdict receipt, verified fail-closed exactly as + * `exportEvolutionBundle` verifies receipts. Nothing here copies clock or fence state. + */ +export async function writeCampaignSnapshot(options: WriteCampaignSnapshotOptions): Promise { + const resolved = resolveOptions(options); + const overwrite = options.overwrite !== false; + const campaignRoot = options.store.campaignRoot; + + const outDir = validateAbsoluteFilesystemPath(options.outDir, 'outDir'); + await assertNoSymlinkPath(outDir, { checkLeaf: true, diagPath: outDir }); + const preOutStat = await lstat(outDir).catch((err: NodeJS.ErrnoException) => { + if (err.code === 'ENOENT') return null; + if (err.code === 'ELOOP') { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `symlink forbidden at outDir: ${outDir}`, outDir); + } + throw err; + }); + if (preOutStat !== null) { + if (preOutStat.isSymbolicLink()) { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `outDir cannot be a symlink: ${outDir}`, outDir); + } + if (!preOutStat.isDirectory()) { + throw new EvolutionError('ARTIFACT_INVALID', `outDir exists and is not a directory: ${outDir}`, outDir); + } + if (!overwrite) { + throw new EvolutionError('EVOLUTION_CONFLICT', `outDir already exists: ${outDir}`, outDir); + } + } + + const campaign = await options.store.getCampaign(options.campaignId); + if (!campaign) { + throw new EvolutionError('EVOLUTION_NOT_FOUND', `campaign "${options.campaignId}" not found`, '/campaignId'); + } + + let parentDigest: Digest | undefined; + const provenance = await options.store.getSnapshotProvenance(options.campaignId); + if (options.parentDigest !== undefined) { + if (options.parentDigest.algorithm !== 'sha256' || !SHA256_HEX_RE.test(options.parentDigest.hex)) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'invalid parentDigest', '/parentDigest'); + } + if (provenance !== null && provenance.snapshotDigest.hex !== options.parentDigest.hex) { + throw new EvolutionError( + 'EVOLUTION_CONFLICT', + `parentDigest ${options.parentDigest.hex} does not match the imported snapshot ${provenance.snapshotDigest.hex}`, + '/parentDigest', + ); + } + parentDigest = makeDigest(options.parentDigest.hex); + } else if (provenance !== null) { + parentDigest = makeDigest(provenance.snapshotDigest.hex); + } + + const individuals = await options.store.listIndividuals(options.campaignId); + const islands = await options.store.listIslands(options.campaignId); + const teamConfigs = await options.store.listTeamConfigs(options.campaignId); + const lineageEdges = await options.store.listLineageEdges(options.campaignId); + const banditArms = await options.store.listModelBanditArms(options.campaignId); + const scratchpads = await options.store.listScratchpadSnapshots(options.campaignId); + + // Receipts: only approved verdicts travel; every other stored verdict exports as receipt: null. + const receiptBytes = new Map(); + const blobByteLengths = new Map(); + const scratchpadByteLengths = new Map(); + const requireCasBlob = async (digest: Digest, memberPath: string): Promise => { + const byteLength = await readVerifiedCasBlobIfExists(campaignRoot, digest.hex, resolved.maxBlobBytes); + if (byteLength === null) { + throw new EvolutionError('ARTIFACT_MISSING', `CAS blob ${digest.hex} not found in campaign store`, memberPath); + } + return byteLength; + }; + const requireBlob = async (digest: Digest): Promise => { + blobByteLengths.set(digest.hex, await requireCasBlob(digest, `/blobs/sha256/${digest.hex}`)); + }; + + const individualDocs: SnapshotIndividualRecordV1[] = []; + let minGeneration = 0; + let maxGeneration = 0; + for (const ind of individuals) { + const { codeSliceCasDigest, verdictReceiptCasDigest } = ind; + if (codeSliceCasDigest !== null) await requireBlob(codeSliceCasDigest); + let receipt: Digest | null = null; + if (verdictReceiptCasDigest !== null) { + if (!SAFE_FILENAME_ID_RE.test(ind.individualId) || ind.individualId === '.' || ind.individualId === '..') { + throw new EvolutionError('ARTIFACT_INVALID', `unsafe individualId for receipt filename: "${ind.individualId}"`); + } + const rawBytes = await readVerifiedCasBlob(campaignRoot, verdictReceiptCasDigest.hex, { + maxBytes: MAX_RECEIPT_FILE_BYTES, + }); + if (peekReceiptStatus(rawBytes, ind.individualId) === 'approved') { + if (resolved.receiptSigningSecret === undefined) { + throw new EvolutionError( + 'EXPORT_UNVERIFIED_FORBIDDEN', + `receiptSigningSecret is required to verify the approved verdict receipt of ${ind.individualId}`, + '/receiptSigningSecret', + ); + } + const parsed = await parseAndVerifyReceiptBytes(rawBytes, { + individualId: ind.individualId, + expectedLockHash: campaign.lockHash, + expectedTargetCellId: campaign.manifest.spec.targetCellId, + allowSyntheticProbe: resolved.allowSyntheticProbe, + allowHostAttested: resolved.allowHostAttested, + receiptSigningSecret: resolved.receiptSigningSecret, + scrubber: resolved.scrubber, + maxBlobBytes: resolved.maxBlobBytes, + }); + if (parsed.receipt.runId.startsWith('ind-') && parsed.receipt.runId !== ind.individualId) { + throw new EvolutionError( + 'EXPORT_UNVERIFIED_FORBIDDEN', + `receipt runId "${parsed.receipt.runId}" does not match individual "${ind.individualId}"`, + `/receipts/${ind.individualId}/runId`, + ); + } + if (ind.hardwareProvenance !== undefined + && canonicalizeJson(ind.hardwareProvenance) !== canonicalizeJson(parsed.provenance)) { + throw new EvolutionError( + 'ARTIFACT_INVALID', + `individual "${ind.individualId}" persisted hardwareProvenance diverges from signed verdict receipt`, + ); + } + assertIndividualArtifactsBoundToReceipt(ind, parsed.outputArtifacts); + for (const art of parsed.outputArtifacts) await requireBlob(art.digest); + receiptBytes.set(ind.individualId, rawBytes); + receipt = makeDigest(verdictReceiptCasDigest.hex); + } + } + if (receipt === null) { + // Without a signed claim, artifact blobs travel only when the store still holds them. + for (const art of ind.outputArtifacts) { + const byteLength = await readVerifiedCasBlobIfExists(campaignRoot, art.digest.hex, resolved.maxBlobBytes); + if (byteLength !== null) blobByteLengths.set(art.digest.hex, byteLength); + } + } + individualDocs.push(toIndividualV1(ind, receipt)); + if (individualDocs.length === 1) { + minGeneration = ind.generation; + maxGeneration = ind.generation; + } else { + minGeneration = Math.min(minGeneration, ind.generation); + maxGeneration = Math.max(maxGeneration, ind.generation); + } + } + for (const tc of teamConfigs) { + const { patchCasDigest } = tc; + if (patchCasDigest !== null) await requireBlob(patchCasDigest); + } + for (const snap of scratchpads) { + scratchpadByteLengths.set(snap.casDigest.hex, await requireCasBlob(snap.casDigest, scratchpadPath(snap.casDigest.hex))); + } + + const campaignDoc: Record = {}; + for (const key of [ + 'campaignId', 'name', 'status', 'stagePhase', 'activeBucketId', 'manifest', 'manifestDigest', + 'baseRevision', 'lockHash', 'driverConstraint', 'currentGeneration', 'evaluationsUsed', 'preemptionsCount', + ] as const) { + campaignDoc[key] = campaign[key]; + } + + const members: BundleMemberDigest[] = []; + const stagedFiles: { readonly relPath: string; readonly bytes: Buffer; readonly mediaType: string }[] = []; + const pushText = (relPath: string, text: string, mediaType: string): void => { + assertCleanSecretText(text, resolved.scrubber, `/${relPath}`); + stagedFiles.push({ relPath, bytes: Buffer.from(text, 'utf8'), mediaType }); + }; + pushText(CAMPAIGN_MEMBER, canonicalizeJson(campaignDoc), CAMPAIGN_SNAPSHOT_JSON_MEDIA_TYPE); + pushText(INDIVIDUALS_MEMBER, serializeJsonl(individualDocs), CAMPAIGN_SNAPSHOT_NDJSON_MEDIA_TYPE); + pushText(LINEAGE_MEMBER, serializeJsonl(lineageEdges), CAMPAIGN_SNAPSHOT_NDJSON_MEDIA_TYPE); + pushText(ISLANDS_MEMBER, canonicalizeJson(islands), CAMPAIGN_SNAPSHOT_JSON_MEDIA_TYPE); + pushText(BANDIT_MEMBER, canonicalizeJson(banditArms), CAMPAIGN_SNAPSHOT_JSON_MEDIA_TYPE); + pushText(TEAM_CONFIGS_MEMBER, serializeJsonl(teamConfigs), CAMPAIGN_SNAPSHOT_NDJSON_MEDIA_TYPE); + pushText(SCRATCHPAD_INDEX_MEMBER, serializeJsonl(scratchpads.map(toScratchpadV1)), CAMPAIGN_SNAPSHOT_NDJSON_MEDIA_TYPE); + for (const rec of stagedFiles) { + members.push({ path: rec.relPath, digest: makeDigest(sha256Hex(rec.bytes)), byteLength: rec.bytes.byteLength, mediaType: rec.mediaType }); + } + + // Content blobs: re-read one verified CAS blob at a time so memory stays O(1) blob. + const scratchpadRelPaths = [...scratchpadByteLengths.keys()].sort(compareUtf16).map(scratchpadPath); + const blobRelPaths = [...blobByteLengths.keys()].sort(compareUtf16).map(hex => `blobs/sha256/${hex}`); + for (const relPath of scratchpadRelPaths) { + const hex = relPath.slice('scratchpad/'.length, -'.md'.length); + members.push({ + path: relPath, + digest: makeDigest(hex), + byteLength: scratchpadByteLengths.get(hex)!, + mediaType: CAMPAIGN_SNAPSHOT_SCRATCHPAD_MEDIA_TYPE, + }); + } + for (const relPath of blobRelPaths) { + const hex = relPath.slice('blobs/sha256/'.length); + members.push({ path: relPath, digest: makeDigest(hex), byteLength: blobByteLengths.get(hex)!, mediaType: EVOLUTION_BLOB_DEFAULT_MEDIA_TYPE }); + } + for (const id of [...receiptBytes.keys()].sort(compareUtf16)) { + const bytes = receiptBytes.get(id)!; + members.push({ + path: `receipts/${id}.verdict.json`, + digest: makeDigest(sha256Hex(bytes)), + byteLength: bytes.byteLength, + mediaType: EVOLUTION_RECEIPT_MEDIA_TYPE, + }); + } + members.sort((a, b) => compareUtf16(a.path, b.path)); + + const manifest = createNullRecord>(); + manifest.kind = CAMPAIGN_SNAPSHOT_KIND; + manifest.version = CAMPAIGN_SNAPSHOT_VERSION; + manifest.campaignId = campaign.campaignId; + manifest.generations = { min: minGeneration, max: maxGeneration }; + if (parentDigest !== undefined) manifest.parentDigest = parentDigest; + manifest.members = members; + const manifestText = canonicalizeJson(manifest); + assertCleanSecretText(manifestText, resolved.scrubber, '/manifest.json'); + const manifestBytes = Buffer.from(manifestText, 'utf8'); + const manifestDigest = makeDigest(sha256Hex(manifestBytes)); + + const parentDir = dirname(outDir); + await ensureDirectoryChainNoSymlink(parentDir, 0o755); + const stagingDir = join(parentDir, `.evolution-snapshot-stage-${randomBytes(8).toString('hex')}`); + let published = false; + try { + await mkdir(stagingDir, { mode: 0o755, recursive: false }); + for (const sub of ['blobs', join('blobs', 'sha256'), 'receipts', 'scratchpad']) { + await mkdir(join(stagingDir, sub), { mode: 0o755, recursive: false }); + } + await writeNewFileNoFollow(join(stagingDir, 'manifest.json'), manifestBytes, 0o644); + for (const rec of stagedFiles) await writeNewFileNoFollow(join(stagingDir, rec.relPath), rec.bytes, 0o644); + for (const relPath of scratchpadRelPaths) { + const hex = relPath.slice('scratchpad/'.length, -'.md'.length); + const bytes = await readVerifiedCasBlob(campaignRoot, hex, { maxBytes: resolved.maxBlobBytes }); + await writeNewFileNoFollow(join(stagingDir, relPath), bytes, 0o644); + } + for (const relPath of blobRelPaths) { + const bytes = await readVerifiedCasBlob(campaignRoot, relPath.slice('blobs/sha256/'.length), { maxBytes: resolved.maxBlobBytes }); + await writeNewFileNoFollow(join(stagingDir, relPath), bytes, 0o644); + } + for (const id of receiptBytes.keys()) { + await writeNewFileNoFollow(join(stagingDir, 'receipts', `${id}.verdict.json`), receiptBytes.get(id)!, 0o644); + } + await publishStagingDirectoryAtomically(stagingDir, outDir, overwrite); + published = true; + } finally { + if (!published) { + await rm(stagingDir, { recursive: true, force: true }).catch(() => undefined); + } + } + + const result = createNullRecord>(); + result.outDir = outDir; + result.manifestDigest = manifestDigest; + if (parentDigest !== undefined) result.parentDigest = parentDigest; + result.individualCount = individuals.length; + result.receiptCount = receiptBytes.size; + result.blobCount = blobByteLengths.size; + return result as unknown as WriteCampaignSnapshotResult; +} + +/** + * Verify a `campaign-snapshot.v1` directory offline: `manifest.json`, every member digest and + * length under `O_NOFOLLOW`, every member's strict schema and cross-references, and every approved + * verdict receipt's HMAC and hardware provenance gates. + */ +export async function verifyCampaignSnapshot(options: VerifyCampaignSnapshotOptions): Promise { + const verified = await loadAndVerifySnapshot(options); + const result = createNullRecord>(); + result.bundleDir = verified.bundleDir; + result.manifest = verified.manifest; + result.manifestDigest = verified.manifestDigest; + result.individualCount = verified.individuals.length; + result.receiptCount = verified.receiptBytes.size; + result.blobCount = verified.blobByteLengths.size; + return result as unknown as VerifyCampaignSnapshotResult; +} + +async function loadAndVerifySnapshot(options: VerifyCampaignSnapshotOptions): Promise { + const resolved = resolveOptions(options); + const bundleDir = validateAbsoluteFilesystemPath(options.bundleDir, 'bundleDir'); + await assertNoSymlinkPath(bundleDir, { checkLeaf: true, diagPath: bundleDir }); + await verifyNonSymlinkDirectoryFd(bundleDir); + + const manifestBytes = await readVerifiedRegularFileNoFollow(join(bundleDir, 'manifest.json'), { + maxBytes: MAX_SNAPSHOT_MANIFEST_BYTES, + missingCode: 'ARTIFACT_MISSING', + }); + const manifestDigest = makeDigest(sha256Hex(manifestBytes)); + const manifestObj = expectObject( + parseJsonMember(decodeUtf8Strict(manifestBytes, '/manifest.json'), '/manifest.json', MAX_SNAPSHOT_MANIFEST_BYTES), + MANIFEST_KEYS, + ['kind', 'version', 'campaignId', 'generations', 'members'], + '/manifest.json', + ); + const manifest = parseManifest(manifestObj, '/manifest.json'); + + // Verify every member digest and length; keep only the small text members in memory. + const memberBytes = new Map(); + const blobByteLengths = new Map(); + for (const member of manifest.members) { + const absPath = join(bundleDir, member.path); + await assertNoSymlinkPath(absPath, { checkLeaf: true, diagPath: absPath }); + const isBlob = member.path.startsWith('blobs/sha256/'); + const bytes = await readVerifiedRegularFileNoFollow(absPath, { + expectedSha256Hex: member.digest.hex, + expectedByteLength: member.byteLength, + maxBytes: isBlob ? resolved.maxBlobBytes : MAX_SNAPSHOT_MEMBER_BYTES, + missingCode: 'ARTIFACT_MISSING', + }); + if (isBlob) { + const hexFromPath = member.path.slice('blobs/sha256/'.length); + if (hexFromPath !== member.digest.hex) { + throw new EvolutionError('ARTIFACT_INVALID', `blob path "${member.path}" does not match digest ${member.digest.hex}`, member.path); + } + blobByteLengths.set(member.digest.hex, member.byteLength); + } else { + memberBytes.set(member.path, bytes); + } + } + + const member = (relPath: string): Buffer => { + const bytes = memberBytes.get(relPath); + if (bytes === undefined) { + throw new EvolutionError('ARTIFACT_MISSING', `manifest.json does not list ${relPath}`, `/${relPath}`); + } + return bytes; + }; + + const campaign = parseCampaign( + expectObject( + parseJsonMember(decodeUtf8Strict(member(CAMPAIGN_MEMBER), `/${CAMPAIGN_MEMBER}`), `/${CAMPAIGN_MEMBER}`, MAX_SNAPSHOT_MEMBER_BYTES), + CAMPAIGN_KEYS, + [...CAMPAIGN_KEYS], + `/${CAMPAIGN_MEMBER}`, + ), + `/${CAMPAIGN_MEMBER}`, + ); + if (campaign.campaignId !== manifest.campaignId) { + throw new EvolutionError('ARTIFACT_INVALID', `campaign.json campaignId "${campaign.campaignId}" does not match manifest "${manifest.campaignId}"`, `/${CAMPAIGN_MEMBER}/campaignId`); + } + + const assertCampaignId = (actual: string, path: string): void => { + if (actual !== manifest.campaignId) { + throw new EvolutionError('ARTIFACT_INVALID', `record campaignId "${actual}" does not match manifest "${manifest.campaignId}"`, path); + } + }; + + const individuals = parseJsonLines(decodeUtf8Strict(member(INDIVIDUALS_MEMBER), `/${INDIVIDUALS_MEMBER}`), INDIVIDUALS_MEMBER, MAX_SNAPSHOT_MEMBER_BYTES) + .map((line, i) => parseIndividual(expectObject(line, INDIVIDUAL_KEYS, INDIVIDUAL_REQUIRED_KEYS, `/${INDIVIDUALS_MEMBER}/${i}`), `/${INDIVIDUALS_MEMBER}/${i}`)); + const lineageEdges = parseJsonLines(decodeUtf8Strict(member(LINEAGE_MEMBER), `/${LINEAGE_MEMBER}`), LINEAGE_MEMBER, MAX_SNAPSHOT_MEMBER_BYTES) + .map((line, i) => parseLineageEdge(expectObject(line, LINEAGE_KEYS, [...LINEAGE_KEYS], `/${LINEAGE_MEMBER}/${i}`), `/${LINEAGE_MEMBER}/${i}`)); + const islands = parseArrayMember(decodeUtf8Strict(member(ISLANDS_MEMBER), `/${ISLANDS_MEMBER}`), ISLANDS_MEMBER) + .map((entry, i) => parseIsland(expectObject(entry, ISLAND_KEYS, [...ISLAND_KEYS], `/${ISLANDS_MEMBER}/${i}`), `/${ISLANDS_MEMBER}/${i}`)); + const banditArms = parseArrayMember(decodeUtf8Strict(member(BANDIT_MEMBER), `/${BANDIT_MEMBER}`), BANDIT_MEMBER) + .map((entry, i) => parseBanditArm(expectObject(entry, BANDIT_KEYS, [...BANDIT_KEYS], `/${BANDIT_MEMBER}/${i}`), `/${BANDIT_MEMBER}/${i}`)); + const teamConfigs = parseJsonLines(decodeUtf8Strict(member(TEAM_CONFIGS_MEMBER), `/${TEAM_CONFIGS_MEMBER}`), TEAM_CONFIGS_MEMBER, MAX_SNAPSHOT_MEMBER_BYTES) + .map((line, i) => parseTeamConfig(expectObject(line, TEAM_CONFIG_KEYS, [...TEAM_CONFIG_KEYS], `/${TEAM_CONFIGS_MEMBER}/${i}`), `/${TEAM_CONFIGS_MEMBER}/${i}`)); + const scratchpads = parseJsonLines(decodeUtf8Strict(member(SCRATCHPAD_INDEX_MEMBER), `/${SCRATCHPAD_INDEX_MEMBER}`), SCRATCHPAD_INDEX_MEMBER, MAX_SNAPSHOT_MEMBER_BYTES) + .map((line, i) => parseScratchpad(expectObject(line, SCRATCHPAD_KEYS, [...SCRATCHPAD_KEYS], `/${SCRATCHPAD_INDEX_MEMBER}/${i}`), `/${SCRATCHPAD_INDEX_MEMBER}/${i}`)); + + // Generations in the manifest must describe the individuals actually present. + let minGeneration = 0; + let maxGeneration = 0; + individuals.forEach((ind, index) => { + if (index === 0) { + minGeneration = ind.generation; + maxGeneration = ind.generation; + } else { + minGeneration = Math.min(minGeneration, ind.generation); + maxGeneration = Math.max(maxGeneration, ind.generation); + } + }); + if (manifest.generations.min !== minGeneration || manifest.generations.max !== maxGeneration) { + throw new EvolutionError('ARTIFACT_INVALID', 'manifest.json generations do not match individuals.jsonl', '/manifest.json/generations'); + } + + // Cross-references: unique keys, every campaignId, and every foreign reference resolvable. + const teamConfigIds = new Set(); + for (const tc of teamConfigs) { + assertCampaignId(tc.campaignId, `/${TEAM_CONFIGS_MEMBER}`); + if (teamConfigIds.has(tc.teamConfigId)) invalid(`duplicate teamConfigId "${tc.teamConfigId}"`, `/${TEAM_CONFIGS_MEMBER}`); + teamConfigIds.add(tc.teamConfigId); + if (tc.parentTeamConfigId !== null && !teamConfigIds.has(tc.parentTeamConfigId) && !teamConfigs.some(t => t.teamConfigId === tc.parentTeamConfigId)) { + invalid(`team_config "${tc.teamConfigId}" references unknown parent "${tc.parentTeamConfigId}"`, `/${TEAM_CONFIGS_MEMBER}`); + } + } + const islandIds = new Set(); + for (const island of islands) { + assertCampaignId(island.campaignId, `/${ISLANDS_MEMBER}`); + if (islandIds.has(island.islandId)) invalid(`duplicate island ${island.islandId}`, `/${ISLANDS_MEMBER}`); + islandIds.add(island.islandId); + if (!teamConfigIds.has(island.activeTeamConfigId)) { + invalid(`island ${island.islandId} references unknown team_config "${island.activeTeamConfigId}"`, `/${ISLANDS_MEMBER}`); + } + } + const individualIds = new Set(); + for (const ind of individuals) { + assertCampaignId(ind.campaignId, `/${INDIVIDUALS_MEMBER}`); + if (individualIds.has(ind.individualId)) invalid(`duplicate individualId "${ind.individualId}"`, `/${INDIVIDUALS_MEMBER}`); + individualIds.add(ind.individualId); + if (!teamConfigIds.has(ind.teamConfigId)) { + invalid(`individual "${ind.individualId}" references unknown team_config "${ind.teamConfigId}"`, `/${INDIVIDUALS_MEMBER}`); + } + if (!islandIds.has(ind.islandId)) { + invalid(`individual "${ind.individualId}" references unknown island ${ind.islandId}`, `/${INDIVIDUALS_MEMBER}`); + } + if (ind.codeSliceCasDigest !== null && !blobByteLengths.has(ind.codeSliceCasDigest.hex)) { + invalid(`individual "${ind.individualId}" code slice ${ind.codeSliceCasDigest.hex} is missing from blobs`, `/${INDIVIDUALS_MEMBER}`); + } + for (const art of ind.outputArtifacts) { + const present = blobByteLengths.get(art.digest.hex); + if (present !== undefined && present !== art.byteLength) { + invalid(`individual "${ind.individualId}" outputArtifact "${art.name}" byteLength does not match blob`, `/${INDIVIDUALS_MEMBER}`); + } + } + } + const lineageKeys = new Set(); + for (const edge of lineageEdges) { + assertCampaignId(edge.campaignId, `/${LINEAGE_MEMBER}`); + const key = `${edge.childIndividualId}|${edge.parentIndividualId}|${edge.role}`; + if (lineageKeys.has(key)) invalid(`duplicate lineage edge "${key}"`, `/${LINEAGE_MEMBER}`); + lineageKeys.add(key); + for (const id of [edge.childIndividualId, edge.parentIndividualId]) { + if (!individualIds.has(id)) invalid(`lineage edge references unknown individual "${id}"`, `/${LINEAGE_MEMBER}`); + } + } + const banditKeys = new Set(); + for (const arm of banditArms) { + assertCampaignId(arm.campaignId, `/${BANDIT_MEMBER}`); + if (banditKeys.has(arm.modelId)) invalid(`duplicate bandit arm "${arm.modelId}"`, `/${BANDIT_MEMBER}`); + banditKeys.add(arm.modelId); + } + for (const tc of teamConfigs) { + if (tc.patchCasDigest !== null && !blobByteLengths.has(tc.patchCasDigest.hex)) { + invalid(`team_config "${tc.teamConfigId}" patch ${tc.patchCasDigest.hex} is missing from blobs`, `/${TEAM_CONFIGS_MEMBER}`); + } + } + const scratchpadBytes = new Map(); + const snapshotIds = new Set(); + for (const snap of scratchpads) { + assertCampaignId(snap.campaignId, `/${SCRATCHPAD_INDEX_MEMBER}`); + if (snapshotIds.has(snap.snapshotId)) invalid(`duplicate snapshotId "${snap.snapshotId}"`, `/${SCRATCHPAD_INDEX_MEMBER}`); + snapshotIds.add(snap.snapshotId); + const relPath = scratchpadPath(snap.casDigest.hex); + const bytes = memberBytes.get(relPath); + if (bytes === undefined) invalid(`scratchpad "${snap.snapshotId}" content ${relPath} is missing`, `/${SCRATCHPAD_INDEX_MEMBER}`); + if (bytes.byteLength !== snap.byteLength || sha256Hex(bytes) !== snap.casDigest.hex) { + invalid(`scratchpad "${snap.snapshotId}" content does not match its CAS digest`, `/${SCRATCHPAD_INDEX_MEMBER}`); + } + scratchpadBytes.set(snap.casDigest.hex, bytes); + } + + // Receipts: every approved receipt is verified fail-closed exactly as bundle export verifies it. + const receiptBytes = new Map(); + for (const ind of individuals) { + if (ind.receipt === null) continue; + const relPath = `receipts/${ind.individualId}.verdict.json`; + const bytes = memberBytes.get(relPath); + if (bytes === undefined) invalid(`individual "${ind.individualId}" has a receipt digest but no receipt member`, `/${relPath}`); + const listed = manifest.members.find(m => m.path === relPath)!; + if (listed.digest.hex !== ind.receipt.hex) { + invalid(`receipt member "${relPath}" digest does not match individual "${ind.individualId}"`, `/${relPath}`); + } + if (resolved.receiptSigningSecret === undefined) { + throw new EvolutionError( + 'EXPORT_UNVERIFIED_FORBIDDEN', + `receiptSigningSecret is required to verify the approved verdict receipt of ${ind.individualId}`, + '/receiptSigningSecret', + ); + } + const parsed = await parseAndVerifyReceiptBytes(bytes, { + individualId: ind.individualId, + expectedLockHash: campaign.lockHash, + expectedTargetCellId: campaign.manifest.spec.targetCellId, + allowSyntheticProbe: resolved.allowSyntheticProbe, + allowHostAttested: resolved.allowHostAttested, + receiptSigningSecret: resolved.receiptSigningSecret, + scrubber: resolved.scrubber, + maxBlobBytes: resolved.maxBlobBytes, + }); + if (parsed.rawDigest.hex !== ind.receipt.hex) { + invalid(`receipt "${relPath}" does not match the receipt digest of individual "${ind.individualId}"`, `/${relPath}`); + } + if (parsed.receipt.runId.startsWith('ind-') && parsed.receipt.runId !== ind.individualId) { + throw new EvolutionError( + 'EXPORT_UNVERIFIED_FORBIDDEN', + `receipt runId "${parsed.receipt.runId}" does not match individual "${ind.individualId}"`, + `/${relPath}/runId`, + ); + } + if (ind.hardwareProvenance !== undefined && canonicalizeJson(ind.hardwareProvenance) !== canonicalizeJson(parsed.provenance)) { + invalid(`individual "${ind.individualId}" hardwareProvenance diverges from its signed verdict receipt`, `/${INDIVIDUALS_MEMBER}`); + } + assertIndividualArtifactsBoundToReceipt(ind, parsed.outputArtifacts); + for (const art of parsed.outputArtifacts) { + if (!blobByteLengths.has(art.digest.hex)) { + invalid(`receipt "${ind.individualId}" references blob ${art.digest.hex} missing from snapshot members`, `/${relPath}/outputArtifacts`); + } + } + receiptBytes.set(ind.individualId, bytes); + } + + const result = createNullRecord>(); + result.bundleDir = bundleDir; + result.manifest = manifest; + result.manifestDigest = manifestDigest; + result.campaign = campaign; + result.individuals = individuals; + result.lineageEdges = lineageEdges; + result.islands = islands; + result.modelBanditArms = banditArms; + result.teamConfigs = teamConfigs; + result.scratchpadSnapshots = scratchpads; + result.scratchpadBytes = scratchpadBytes; + result.receiptBytes = receiptBytes; + result.blobByteLengths = blobByteLengths; + return result as unknown as VerifiedCampaignSnapshot; +} + +async function removeImportedState(stateDir: string, createdStateDir: boolean): Promise { + if (createdStateDir) { + await rm(stateDir, { recursive: true, force: true }).catch(() => undefined); + return; + } + for (const name of [CAMPAIGN_SQLITE_FILENAME, `${CAMPAIGN_SQLITE_FILENAME}-journal`]) { + await rm(join(stateDir, name), { force: true }).catch(() => undefined); + } + await rm(join(stateDir, 'cas'), { recursive: true, force: true }).catch(() => undefined); +} + +/** + * Import a `campaign-snapshot.v1` into a fresh `campaign.sqlite` under `stateDir` with a fresh + * authority: a new `campaign_meta` (lease, fence epoch, clock basis), search state copied verbatim, + * CAS content restored, and the snapshot digest recorded in `snapshot_provenance`. The state + * directory must be empty or absent; nothing is written before the whole snapshot verifies. + */ +export async function importCampaignSnapshot(options: ImportCampaignSnapshotOptions): Promise { + const resolved = resolveOptions(options); + const stateDir = validateAbsoluteFilesystemPath(options.stateDir, 'stateDir'); + await assertNoSymlinkPath(stateDir, { checkLeaf: true, diagPath: stateDir }); + const existing = await lstat(stateDir).catch((err: NodeJS.ErrnoException) => { + if (err.code === 'ENOENT') return null; + if (err.code === 'ELOOP') { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `symlink forbidden at stateDir: ${stateDir}`, stateDir); + } + throw err; + }); + if (existing !== null) { + if (existing.isSymbolicLink()) { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `stateDir cannot be a symlink: ${stateDir}`, stateDir); + } + if (!existing.isDirectory()) { + throw new EvolutionError('EVOLUTION_STORE_ERROR', `stateDir exists and is not a directory: ${stateDir}`, stateDir); + } + const entries = await readdir(stateDir); + if (entries.length > 0) { + throw new EvolutionError( + 'EVOLUTION_CONFLICT', + `stateDir already holds state (${entries.length} entries); import requires an empty directory`, + '/stateDir', + ); + } + } + + const verified = await loadAndVerifySnapshot(options); + const createdStateDir = existing === null; + await ensureDirectoryChainNoSymlink(dirname(stateDir), 0o755); + + const store = await EvolutionCampaignStore.open({ + campaignRoot: stateDir, + clock: options.clock ?? DEFAULT_CAMPAIGN_CLOCK, + createIfMissing: true, + }); + try { + const lease = await store.acquireLease(`import-${randomBytes(6).toString('hex')}`); + + for (const hex of [...verified.blobByteLengths.keys()].sort(compareUtf16)) { + const bytes = await readVerifiedRegularFileNoFollow(join(verified.bundleDir, 'blobs', 'sha256', hex), { + expectedSha256Hex: hex, + expectedByteLength: verified.blobByteLengths.get(hex)!, + maxBytes: resolved.maxBlobBytes, + missingCode: 'ARTIFACT_MISSING', + }); + await store.writeCasBlob(bytes); + } + for (const id of [...verified.receiptBytes.keys()].sort(compareUtf16)) { + await store.writeCasBlob(verified.receiptBytes.get(id)!); + } + for (const hex of [...verified.scratchpadBytes.keys()].sort(compareUtf16)) { + await store.writeCasBlob(verified.scratchpadBytes.get(hex)!); + } + + await store.importCampaignState(lease, { + campaign: verified.campaign, + islands: verified.islands, + teamConfigs: verified.teamConfigs, + individuals: verified.individuals.map(ind => ({ + individualId: ind.individualId, + campaignId: ind.campaignId, + islandId: ind.islandId, + generation: ind.generation, + bucketId: ind.bucketId, + teamConfigId: ind.teamConfigId, + modelId: ind.modelId, + trackId: ind.trackId, + mutationKind: ind.mutationKind, + status: ind.status, + failureReason: ind.failureReason, + nicheKey: ind.nicheKey, + paretoRank: ind.paretoRank, + crowdingDistance: ind.crowdingIsBoundary ? Number.POSITIVE_INFINITY : ind.crowdingDistance, + scalarFitness: ind.scalarFitness, + offspringCount: ind.offspringCount, + codeSliceCasDigest: ind.codeSliceCasDigest, + evidenceDigest: ind.evidenceDigest, + verdictReceiptCasDigest: ind.receipt, + outputArtifacts: ind.outputArtifacts, + metrics: ind.metrics, + ...(ind.bucketMetrics !== undefined ? { bucketMetrics: ind.bucketMetrics } : {}), + ...(ind.hardwareDiagnostics !== undefined ? { hardwareDiagnostics: ind.hardwareDiagnostics } : {}), + ...(ind.hardwareProvenance !== undefined ? { hardwareProvenance: ind.hardwareProvenance } : {}), + ...(ind.findings !== undefined ? { findings: ind.findings } : {}), + })), + lineageEdges: verified.lineageEdges, + modelBanditArms: verified.modelBanditArms, + scratchpadSnapshots: verified.scratchpadSnapshots, + snapshotDigest: verified.manifestDigest, + }); + await store.releaseLease(lease); + } catch (err: unknown) { + await store.close().catch(() => undefined); + await removeImportedState(stateDir, createdStateDir); + throw err; + } + await store.close(); + + const result = createNullRecord>(); + result.stateDir = stateDir; + result.dbPath = join(stateDir, CAMPAIGN_SQLITE_FILENAME); + result.campaignId = verified.campaign.campaignId; + result.snapshotDigest = verified.manifestDigest; + result.individualCount = verified.individuals.length; + result.receiptCount = verified.receiptBytes.size; + result.blobCount = verified.blobByteLengths.size; + return result as unknown as ImportCampaignSnapshotResult; +} diff --git a/packages/evolution/src/store.ts b/packages/evolution/src/store.ts index dea00479..f05e4b08 100644 --- a/packages/evolution/src/store.ts +++ b/packages/evolution/src/store.ts @@ -205,6 +205,13 @@ CREATE INDEX IF NOT EXISTS idx_team_configs_island ON team_configs(campaign_id, island_id, status); CREATE INDEX IF NOT EXISTS idx_scratchpads_campaign_gen ON scratchpad_snapshots(campaign_id, generation DESC); + +CREATE TABLE IF NOT EXISTS snapshot_provenance ( + campaign_id TEXT PRIMARY KEY, + snapshot_digest_hex TEXT NOT NULL, + imported_wall_ms INTEGER NOT NULL CHECK (imported_wall_ms >= 0), + FOREIGN KEY (campaign_id) REFERENCES campaigns(campaign_id) ON DELETE RESTRICT +) STRICT; `; type SqlRow = Record; @@ -235,6 +242,15 @@ function assertDigest(digest: Digest, label: string): void { } } +function assertDriverConstraint(driverConstraint: string | null, path: string): void { + if ( + driverConstraint !== null + && (driverConstraint.length < 1 || driverConstraint.length > 128 || !/^[\x20-\x7E]+$/.test(driverConstraint)) + ) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'invalid driverConstraint', path); + } +} + async function ensureNonSymlinkDirectory(dirPath: string, createIfMissing: boolean): Promise { const existing = await lstat(dirPath).catch((err: NodeJS.ErrnoException) => { if (err.code === 'ENOENT') return null; @@ -478,6 +494,39 @@ export interface CampaignStorePragmasSnapshot { readonly tables: readonly string[]; } +interface ValidatedIndividualColumns { + readonly outputArtifactsJson: string; + readonly metricsJson: string; + readonly bucketMetricsJson: string | null; + readonly hardwareDiagnosticsJson: string | null; + readonly hardwareProvenanceJson: string | null; + readonly findingsJson: string | null; + readonly crowdingCol: number | null; + readonly crowdingBoundaryCol: number; +} + +/** The `snapshot_provenance` row that names the `campaign-snapshot.v1` a campaign was imported from. */ +export interface CampaignSnapshotProvenanceRecord { + readonly campaignId: string; + readonly snapshotDigest: Digest; + readonly importedWallMs: number; +} + +/** + * Search state of one campaign as `importCampaignState` writes it. Every record is copied verbatim + * except the civil `createdAtWallMs` / `updatedAtWallMs` columns, which the import re-stamps. + */ +export interface ImportCampaignStateInput { + readonly campaign: Omit; + readonly islands: readonly IslandRecord[]; + readonly teamConfigs: readonly TeamConfigRecord[]; + readonly individuals: readonly Omit[]; + readonly lineageEdges: readonly LineageEdgeRecord[]; + readonly modelBanditArms: readonly ModelBanditArmRecord[]; + readonly scratchpadSnapshots: readonly Omit[]; + readonly snapshotDigest: Digest; +} + /** * Single-writer fenced SQLite store for `@loopwright/evolution` (`/campaign.sqlite`), * completely isolated from per-run `@loopwright/state` `LocalRunStore`. @@ -600,6 +649,25 @@ export class EvolutionCampaignStore { throw err; } } + // Stores created before campaign snapshots have no provenance table; add it idempotently. + const tableRows = db + .prepare("SELECT name FROM pragma_table_list WHERE schema = 'main' AND name = 'snapshot_provenance';") + .all() as SqlRow[]; + if (tableRows.length === 0) { + db.exec('BEGIN IMMEDIATE;'); + try { + db.exec(`CREATE TABLE snapshot_provenance ( + campaign_id TEXT PRIMARY KEY, + snapshot_digest_hex TEXT NOT NULL, + imported_wall_ms INTEGER NOT NULL CHECK (imported_wall_ms >= 0), + FOREIGN KEY (campaign_id) REFERENCES campaigns(campaign_id) ON DELETE RESTRICT +) STRICT;`); + db.exec('COMMIT;'); + } catch (err) { + if (db.isTransaction) db.exec('ROLLBACK;'); + throw err; + } + } } return new EvolutionCampaignStore(campaignRoot, dbPath, db, clock, monoNow, wallNow, !freshFile); @@ -1004,12 +1072,7 @@ export class EvolutionCampaignStore { } const driverConstraint = input.driverConstraint ?? null; - if ( - driverConstraint !== null - && (driverConstraint.length < 1 || driverConstraint.length > 128 || !/^[\x20-\x7E]+$/.test(driverConstraint)) - ) { - throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'invalid driverConstraint', '/driverConstraint'); - } + assertDriverConstraint(driverConstraint, '/driverConstraint'); const manifestJson = canonicalizeJson(validatedManifest); this.#db @@ -1116,12 +1179,7 @@ export class EvolutionCampaignStore { : (existing['driver_constraint'] === null || existing['driver_constraint'] === undefined ? null : String(existing['driver_constraint'])); - if ( - nextDriverConstraint !== null - && (nextDriverConstraint.length < 1 || nextDriverConstraint.length > 128 || !/^[\x20-\x7E]+$/.test(nextDriverConstraint)) - ) { - throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'invalid driverConstraint', '/driverConstraint'); - } + assertDriverConstraint(nextDriverConstraint, '/driverConstraint'); const nextGen = input.currentGeneration ?? Number(existing['current_generation']); this.#db @@ -1390,46 +1448,110 @@ export class EvolutionCampaignStore { }); } - recordIndividual(lease: CampaignLease, input: RecordIndividualInput): Promise { - return this.enqueue(() => { - assertSafeId(input.individualId, 'individualId'); - assertSafeId(input.campaignId, 'campaignId'); - assertSafeId(input.teamConfigId, 'teamConfigId'); - if (input.codeSliceCasDigest !== null) assertDigest(input.codeSliceCasDigest, 'codeSliceCasDigest'); - if (input.evidenceDigest !== null) assertDigest(input.evidenceDigest, 'evidenceDigest'); - if (input.verdictReceiptCasDigest !== null) assertDigest(input.verdictReceiptCasDigest, 'verdictReceiptCasDigest'); - - const validatedMetrics = parseMetricsRecordJson(input.metrics, '/metrics'); - const validatedArtifacts = parseArtifactRefsJson(input.outputArtifacts, '/outputArtifacts'); - const validatedBuckets = input.bucketMetrics !== undefined - ? parseBucketMetricsJson(input.bucketMetrics) - : undefined; - const validatedDiagnostics = input.hardwareDiagnostics !== undefined - ? parseHardwareDiagnosticsJson(input.hardwareDiagnostics) - : undefined; - const validatedProvenance = input.hardwareProvenance !== undefined - ? parseHardwareProvenanceJson(input.hardwareProvenance) - : undefined; - const validatedFindings = input.findings !== undefined - ? parseStructuredFindingsJson(input.findings) - : undefined; - - let crowdingCol: number | null = null; - let crowdingBoundaryCol = 0; - if (input.crowdingDistance !== null) { - if (input.crowdingDistance === Number.POSITIVE_INFINITY) { - crowdingBoundaryCol = 1; - crowdingCol = null; - } else if (!Number.isFinite(input.crowdingDistance) || Object.is(input.crowdingDistance, -0) || input.crowdingDistance < 0) { - throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'crowdingDistance must be >= 0 or +Infinity'); - } else { - crowdingCol = input.crowdingDistance; - } + #validateIndividualColumns(input: RecordIndividualInput): ValidatedIndividualColumns { + assertSafeId(input.individualId, 'individualId'); + assertSafeId(input.campaignId, 'campaignId'); + assertSafeId(input.teamConfigId, 'teamConfigId'); + if (input.codeSliceCasDigest !== null) assertDigest(input.codeSliceCasDigest, 'codeSliceCasDigest'); + if (input.evidenceDigest !== null) assertDigest(input.evidenceDigest, 'evidenceDigest'); + if (input.verdictReceiptCasDigest !== null) assertDigest(input.verdictReceiptCasDigest, 'verdictReceiptCasDigest'); + + const validatedMetrics = parseMetricsRecordJson(input.metrics, '/metrics'); + const validatedArtifacts = parseArtifactRefsJson(input.outputArtifacts, '/outputArtifacts'); + const validatedBuckets = input.bucketMetrics !== undefined + ? parseBucketMetricsJson(input.bucketMetrics) + : undefined; + const validatedDiagnostics = input.hardwareDiagnostics !== undefined + ? parseHardwareDiagnosticsJson(input.hardwareDiagnostics) + : undefined; + const validatedProvenance = input.hardwareProvenance !== undefined + ? parseHardwareProvenanceJson(input.hardwareProvenance) + : undefined; + const validatedFindings = input.findings !== undefined + ? parseStructuredFindingsJson(input.findings) + : undefined; + + let crowdingCol: number | null = null; + let crowdingBoundaryCol = 0; + if (input.crowdingDistance !== null) { + if (input.crowdingDistance === Number.POSITIVE_INFINITY) { + crowdingBoundaryCol = 1; + crowdingCol = null; + } else if (!Number.isFinite(input.crowdingDistance) || Object.is(input.crowdingDistance, -0) || input.crowdingDistance < 0) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'crowdingDistance must be >= 0 or +Infinity'); + } else { + crowdingCol = input.crowdingDistance; } + } - if (input.scalarFitness !== null && (!Number.isFinite(input.scalarFitness) || Object.is(input.scalarFitness, -0))) { - throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'scalarFitness must be a finite non-negative-zero number'); - } + if (input.scalarFitness !== null && (!Number.isFinite(input.scalarFitness) || Object.is(input.scalarFitness, -0))) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'scalarFitness must be a finite non-negative-zero number'); + } + + return { + outputArtifactsJson: canonicalizeJson(validatedArtifacts), + metricsJson: canonicalizeJson(validatedMetrics), + bucketMetricsJson: validatedBuckets !== undefined ? canonicalizeJson(validatedBuckets) : null, + hardwareDiagnosticsJson: validatedDiagnostics !== undefined ? canonicalizeJson(validatedDiagnostics) : null, + hardwareProvenanceJson: validatedProvenance !== undefined ? canonicalizeJson(validatedProvenance) : null, + findingsJson: validatedFindings !== undefined ? canonicalizeJson(validatedFindings) : null, + crowdingCol, + crowdingBoundaryCol, + }; + } + + #insertIndividualSync( + input: RecordIndividualInput & { readonly offspringCount: number }, + columns: ValidatedIndividualColumns, + createdAtWallMs: number, + ): void { + this.#db + .prepare( + `INSERT INTO individuals ( + individual_id, campaign_id, island_id, generation, bucket_id, + team_config_id, model_id, track_id, mutation_kind, status, + failure_reason, niche_key, pareto_rank, crowding_distance, crowding_is_boundary, + scalar_fitness, offspring_count, code_slice_cas_digest_hex, + evidence_digest_hex, verdict_receipt_cas_digest_hex, + output_artifacts_json, metrics_json, bucket_metrics_json, + hardware_diagnostics_json, hardware_provenance_json, findings_json, + created_at_wall_ms + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);`, + ) + .run( + input.individualId, + input.campaignId, + input.islandId, + input.generation, + input.bucketId, + input.teamConfigId, + input.modelId, + input.trackId, + input.mutationKind, + input.status, + input.failureReason, + input.nicheKey, + input.paretoRank, + columns.crowdingCol, + columns.crowdingBoundaryCol, + input.scalarFitness, + input.offspringCount, + input.codeSliceCasDigest?.hex ?? null, + input.evidenceDigest?.hex ?? null, + input.verdictReceiptCasDigest?.hex ?? null, + columns.outputArtifactsJson, + columns.metricsJson, + columns.bucketMetricsJson, + columns.hardwareDiagnosticsJson, + columns.hardwareProvenanceJson, + columns.findingsJson, + createdAtWallMs, + ); + } + + recordIndividual(lease: CampaignLease, input: RecordIndividualInput): Promise { + return this.enqueue(() => { + const columns = this.#validateIndividualColumns(input); return this.#inWriteTransaction(lease, now => { const campaignRow = this.#db @@ -1466,48 +1588,7 @@ export class EvolutionCampaignStore { } } - this.#db - .prepare( - `INSERT INTO individuals ( - individual_id, campaign_id, island_id, generation, bucket_id, - team_config_id, model_id, track_id, mutation_kind, status, - failure_reason, niche_key, pareto_rank, crowding_distance, crowding_is_boundary, - scalar_fitness, offspring_count, code_slice_cas_digest_hex, - evidence_digest_hex, verdict_receipt_cas_digest_hex, - output_artifacts_json, metrics_json, bucket_metrics_json, - hardware_diagnostics_json, hardware_provenance_json, findings_json, - created_at_wall_ms - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);`, - ) - .run( - input.individualId, - input.campaignId, - input.islandId, - input.generation, - input.bucketId, - input.teamConfigId, - input.modelId, - input.trackId, - input.mutationKind, - input.status, - input.failureReason, - input.nicheKey, - input.paretoRank, - crowdingCol, - crowdingBoundaryCol, - input.scalarFitness, - input.offspringCount ?? 0, - input.codeSliceCasDigest?.hex ?? null, - input.evidenceDigest?.hex ?? null, - input.verdictReceiptCasDigest?.hex ?? null, - canonicalizeJson(validatedArtifacts), - canonicalizeJson(validatedMetrics), - validatedBuckets !== undefined ? canonicalizeJson(validatedBuckets) : null, - validatedDiagnostics !== undefined ? canonicalizeJson(validatedDiagnostics) : null, - validatedProvenance !== undefined ? canonicalizeJson(validatedProvenance) : null, - validatedFindings !== undefined ? canonicalizeJson(validatedFindings) : null, - now.wallMs, - ); + this.#insertIndividualSync({ ...input, offspringCount: input.offspringCount ?? 0 }, columns, now.wallMs); if (input.lineageEdges !== undefined && input.lineageEdges.length > 0) { this.#insertLineageEdgesSync(input.lineageEdges); @@ -2058,6 +2139,221 @@ export class EvolutionCampaignStore { }); } + getSnapshotProvenance(campaignId: string): Promise { + return this.enqueue(() => { + const row = this.#db + .prepare('SELECT * FROM snapshot_provenance WHERE campaign_id = ?;') + .get(campaignId) as SqlRow | undefined; + if (!row) return null; + const out = createNullRecord<{ + campaignId: string; + snapshotDigest: Digest; + importedWallMs: number; + }>(); + out.campaignId = String(row['campaign_id']); + out.snapshotDigest = digestFromHex(String(row['snapshot_digest_hex'])); + out.importedWallMs = Number(row['imported_wall_ms']); + return out; + }); + } + + /** + * Restore one campaign from a verified `campaign-snapshot.v1` in a single fenced transaction. + * Search state is written verbatim; this file's `campaign_meta` stays the authority, and every + * civil `created_at_wall_ms` / `updated_at_wall_ms` column is re-stamped from the import clock. + * Never copies lease, fence, or monotonic clock state. + */ + importCampaignState(lease: CampaignLease, input: ImportCampaignStateInput): Promise { + return this.enqueue(() => { + const campaign = input.campaign; + assertSafeId(campaign.campaignId, 'campaignId'); + assertDigest(campaign.manifestDigest, 'manifestDigest'); + assertDigest(campaign.lockHash, 'lockHash'); + assertDigest(input.snapshotDigest, 'snapshotDigest'); + assertDriverConstraint(campaign.driverConstraint, '/driverConstraint'); + const manifest = parseEvolutionCampaignDocument(campaign.manifest); + + const teamConfigRows = [...input.teamConfigs] + .sort((a, b) => a.createdGeneration - b.createdGeneration || (a.teamConfigId < b.teamConfigId ? -1 : 1)) + .map(tc => { + assertSafeId(tc.teamConfigId, 'teamConfigId'); + if (tc.parentTeamConfigId !== null) assertSafeId(tc.parentTeamConfigId, 'parentTeamConfigId'); + if (tc.patchCasDigest !== null) assertDigest(tc.patchCasDigest, 'patchCasDigest'); + const diagnosisJson = tc.diagnosis === null + ? null + : canonicalizeJson(parseTeamDiagnosisValue( + sanitizeUntrustedValue(tc.diagnosis, { maxBytes: 4_096, path: '/diagnosis' }), + '/diagnosis', + )); + return { tc, diagnosisJson }; + }); + + const individualRows = [...input.individuals] + .sort((a, b) => a.generation - b.generation || (a.individualId < b.individualId ? -1 : 1)) + .map(ind => ({ + ind: { ...ind, offspringCount: ind.offspringCount }, + columns: this.#validateIndividualColumns({ ...ind, offspringCount: ind.offspringCount }), + })); + + for (const edge of input.lineageEdges) { + assertSafeId(edge.childIndividualId, 'childIndividualId'); + assertSafeId(edge.parentIndividualId, 'parentIndividualId'); + } + + for (const arm of input.modelBanditArms) { + for (const [label, value] of [ + ['pullCount', arm.pullCount], + ['totalReward', arm.totalReward], + ['meanReward', arm.meanReward], + ] as const) { + if (!Number.isFinite(value) || Object.is(value, -0) || value < 0) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', `bandit ${label} must be finite >= 0`, `/${label}`); + } + } + } + + for (const snap of input.scratchpadSnapshots) { + assertSafeId(snap.snapshotId, 'snapshotId'); + assertDigest(snap.casDigest, 'casDigest'); + if (!Number.isSafeInteger(snap.byteLength) || snap.byteLength < 0 || snap.byteLength > 16_384) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'byteLength must be within 0..16384', '/byteLength'); + } + } + + return this.#inWriteTransaction(lease, now => { + const existing = this.#db.prepare('SELECT COUNT(*) AS n FROM campaigns;').get() as SqlRow; + if (Number(existing['n']) !== 0) { + throw new EvolutionError( + 'EVOLUTION_CONFLICT', + 'campaign store already holds a campaign; import requires an empty state directory', + '/stateDir', + ); + } + + this.#db + .prepare( + `INSERT INTO campaigns ( + campaign_id, name, status, stage_phase, active_bucket_id, + manifest_json, manifest_digest_hex, base_revision, lock_hash_hex, driver_constraint, + current_generation, evaluations_used, preemptions_count, + created_at_wall_ms, updated_at_wall_ms + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);`, + ) + .run( + campaign.campaignId, + manifest.metadata.name, + campaign.status, + campaign.stagePhase, + campaign.activeBucketId, + canonicalizeJson(manifest), + campaign.manifestDigest.hex, + campaign.baseRevision, + campaign.lockHash.hex, + campaign.driverConstraint, + campaign.currentGeneration, + campaign.evaluationsUsed, + campaign.preemptionsCount, + now.wallMs, + now.wallMs, + ); + + const islandStmt = this.#db.prepare( + `INSERT INTO islands ( + campaign_id, island_id, active_team_config_id, current_generation, + consecutive_no_gain_generations, consecutive_pathology_runs, + last_hypervolume, best_roofline_headroom + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?);`, + ); + for (const island of input.islands) { + islandStmt.run( + island.campaignId, + island.islandId, + island.activeTeamConfigId, + island.currentGeneration, + island.consecutiveNoGainGenerations, + island.consecutivePathologyRuns, + island.lastHypervolume, + island.bestRooflineHeadroom, + ); + } + + const teamStmt = this.#db.prepare( + `INSERT INTO team_configs ( + team_config_id, campaign_id, island_id, parent_team_config_id, + created_generation, status, trial_budget_generations, trial_used_generations, + diagnosis_json, patch_cas_digest_hex, pareto_advances, niche_discoveries + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);`, + ); + for (const { tc, diagnosisJson } of teamConfigRows) { + teamStmt.run( + tc.teamConfigId, + tc.campaignId, + tc.islandId, + tc.parentTeamConfigId, + tc.createdGeneration, + tc.status, + tc.trialBudgetGenerations, + tc.trialUsedGenerations, + diagnosisJson, + tc.patchCasDigest?.hex ?? null, + tc.paretoAdvances, + tc.nicheDiscoveries, + ); + } + + for (const { ind, columns } of individualRows) { + this.#insertIndividualSync(ind, columns, now.wallMs); + } + this.#insertLineageEdgesSync(input.lineageEdges); + + const banditStmt = this.#db.prepare( + `INSERT INTO model_bandit_arms ( + campaign_id, model_id, pull_count, total_reward, mean_reward, last_pulled_generation + ) VALUES (?, ?, ?, ?, ?, ?);`, + ); + for (const arm of input.modelBanditArms) { + banditStmt.run( + arm.campaignId, + arm.modelId, + arm.pullCount, + arm.totalReward, + arm.meanReward, + arm.lastPulledGeneration, + ); + } + + const scratchpadStmt = this.#db.prepare( + `INSERT INTO scratchpad_snapshots ( + snapshot_id, campaign_id, generation, cas_digest_hex, byte_length, + cas_rel_path, top_gains_count, failure_patterns_count, created_at_wall_ms + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);`, + ); + for (const snap of input.scratchpadSnapshots) { + scratchpadStmt.run( + snap.snapshotId, + snap.campaignId, + snap.generation, + snap.casDigest.hex, + snap.byteLength, + `cas/sha256/${snap.casDigest.hex}`, + snap.topGainsCount, + snap.failurePatternsCount, + now.wallMs, + ); + } + + this.#db + .prepare('INSERT INTO snapshot_provenance (campaign_id, snapshot_digest_hex, imported_wall_ms) VALUES (?, ?, ?);') + .run(campaign.campaignId, input.snapshotDigest.hex, now.wallMs); + + const row = this.#db + .prepare('SELECT * FROM campaigns WHERE campaign_id = ?;') + .get(campaign.campaignId) as SqlRow; + return this.#hydrateCampaignRow(row); + }); + }); + } + close(): Promise { const closing = this.#queue.then(() => { if (!this.#closed) { diff --git a/packages/evolution/test/snapshot.test.ts b/packages/evolution/test/snapshot.test.ts new file mode 100644 index 00000000..65f9534a --- /dev/null +++ b/packages/evolution/test/snapshot.test.ts @@ -0,0 +1,1056 @@ +import assert from 'node:assert/strict'; +import { createHash } from 'node:crypto'; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { DatabaseSync } from 'node:sqlite'; +import test from 'node:test'; +import { + API_VERSION, + validateDocument, + type BucketMetricEntry, + type Digest, + type HardwareDiagnostics, + type HardwareProvenance, +} from '@loopwright/core'; +import { + signBenchmarkVerdict, + type BenchmarkOutputArtifact, + type BenchmarkVerdict, + type SignedBenchmarkVerdictReceipt, +} from '@loopwright/hardware-runner'; +import { exportEvolutionBundle, verifyEvolutionBundle } from '../src/bundle.js'; +import { parseEvolutionCampaignDocument, parseHardwareProvenanceJson } from '../src/schema.js'; +import { + importCampaignSnapshot, + verifyCampaignSnapshot, + writeCampaignSnapshot, + type CampaignSnapshotManifestV1, + type VerifyCampaignSnapshotOptions, +} from '../src/snapshot.js'; +import { synthesizeCampaignScratchpad } from '../src/scratchpad.js'; +import { CAMPAIGN_SQLITE_FILENAME, EvolutionCampaignStore } from '../src/store.js'; +import { + EvolutionError, + type CampaignClockSource, + type EvolutionErrorCode, + type IndividualRecord, + type IslandRecord, + type LineageEdgeRecord, + type ModelBanditArmRecord, + type ScratchpadSnapshotRecord, + type TeamConfigRecord, +} from '../src/types.js'; + +const TEST_HMAC_SECRET = 'test-snapshot-hmac-signing-secret-2026'; +const HIGH_MONO_MS = 1_000_000_000; // exporter host: a long-lived monotonic clock +const LOW_MONO_MS = 5_000; // importer host: a freshly booted monotonic clock +const WALL_MS = 1_700_000_000_000; + +function sha256Hex(data: Uint8Array | string): string { + return createHash('sha256').update(data).digest('hex'); +} + +function makeDigest(seed: string): Digest { + return { algorithm: 'sha256', hex: sha256Hex(seed) }; +} + +async function assertEvolutionErrorAsync( + fn: () => Promise, + expectedCode: EvolutionErrorCode, +): Promise { + try { + await fn(); + } catch (err: unknown) { + assert.ok(err instanceof EvolutionError, `expected EvolutionError(${expectedCode}), got ${String(err)}`); + assert.equal(err.code, expectedCode, `expected code ${expectedCode}, got ${err.code}: ${err.message}`); + return err; + } + assert.fail(`expected EvolutionError(${expectedCode}) to be thrown`); +} + +function assertEvolutionErrorSync(fn: () => unknown, expectedCode: EvolutionErrorCode): void { + assert.throws(fn, (err: unknown) => { + assert.ok(err instanceof EvolutionError, `expected EvolutionError(${expectedCode}), got ${String(err)}`); + assert.equal(err.code, expectedCode, `expected code ${expectedCode}, got ${err.code}: ${err.message}`); + return true; + }); +} + +/** Deterministic clock: every sample advances monotonic and wall time by 1 ms, so the drift guard sees 0. */ +function makeSteppingClock(monoMs: number, wallMs: number = WALL_MS): CampaignClockSource { + let mono = monoMs; + let wall = wallMs; + return { + nowMonotonicMs: (): number => ++mono, + nowWallMs: (): number => ++wall, + }; +} + +function collectRelativeFilesRecursive(rootDir: string, prefix = ''): readonly string[] { + const entries = readdirSync(join(rootDir, prefix), { withFileTypes: true }) + .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)); + const out: string[] = []; + for (const entry of entries) { + const rel = prefix.length === 0 ? entry.name : `${prefix}/${entry.name}`; + if (entry.isDirectory()) { + out.push(...collectRelativeFilesRecursive(rootDir, rel)); + } else { + out.push(rel); + } + } + return out; +} + +const SINGLE_TARGET_CAMPAIGN_YAML = `apiVersion: loopwright.dev/v1alpha1 +kind: EvolutionCampaign +metadata: + name: flash-decode-sm90a +spec: + taskpack: .loopwright/taskpack.yaml + targetCellId: cuda-h100-whole + stages: + mode: single-target + heldOutWorkloadId: decode-h100-holdout + population: + islands: 2 + migrationIntervalGenerations: 4 + maxMigrationElites: 1 + nicheAxes: + - id: bound_pipeline + kind: enum + values: [hbm, l2, smem_lds_ub, tensor_cube] + sampling: + noveltyDecayLambda: 1.0 + mutationWeights: + diff_tune: 0.5 + full_rewrite: 0.3 + crossover: 0.2 + maxCrossoversPerPrompt: 2 + objectives: + - metric: latency_us_p50 + direction: minimize + - metric: goodput_rps + direction: maximize + budgets: + maxGenerations: 10 + maxEvaluations: 40 + maxConcurrentEvaluations: 2 + scratchpadIntervalGenerations: 5 +`; + +const KERNEL_CUBIN_BYTES = Buffer.from('\x7fELF\x02\x01\x01\x00FLASH_DECODE_SM90A_CUBIN_PAYLOAD_V1', 'binary'); +const PATCH_JSON_BYTES = Buffer.from('{"kind":"TeamPatch","schemaVersion":"team-patch.v1"}\n', 'utf8'); +const SCRATCHPAD_MD_BYTES = Buffer.from('# Campaign scratchpad gen 1\n\n- top gain: ind-win-2 over ind-win-1\n', 'utf8'); + +function makeProvenance(overrides?: Partial): HardwareProvenance { + return { + targetCellId: 'cuda-h100-whole', + probeKind: 'physical', + vendor: 'nvidia', + deviceModel: 'NVIDIA H100 80GB HBM3', + accelerator: 'sm_90a', + isolationMode: 'whole_device', + deviceCount: 1, + driverVersion: '560.35.03', + runtimeVersion: 'cuda-12.6', + topology: 'single_gpu', + workloadDigest: makeDigest('workload-default'), + clockLockMode: 'locked', + ...overrides, + }; +} + +interface ReceiptFixtureOptions { + readonly lockHash: Digest; + readonly operationId: string; + readonly status?: 'approved' | 'denied' | 'expired'; + readonly reason?: string | null; + readonly probeKind?: 'physical' | 'synthetic_fixture'; + readonly isolation?: 'docker' | 'host_attested'; + readonly outputArtifacts?: readonly BenchmarkOutputArtifact[]; + readonly metrics?: Readonly>; +} + +function makeSignedReceiptBytes(opts: ReceiptFixtureOptions): { + readonly rawBytes: Buffer; + readonly provenance: HardwareProvenance; +} { + const provenance = makeProvenance({ + ...(opts.probeKind !== undefined ? { probeKind: opts.probeKind } : {}), + ...(opts.isolation !== undefined ? { isolation: opts.isolation } : {}), + }); + const status = opts.status ?? 'approved'; + const verdictBase: Record = { + version: 1, + kind: 'benchmark_verdict', + storeId: 'store-evo-01', + runId: 'run-evo-01', + lockHash: opts.lockHash, + operationId: opts.operationId, + dispatchId: `disp-${opts.operationId}`, + dispatchGeneration: 1, + gateId: 'benchmark-gate', + checkId: 'hw-bench', + candidateDigest: sha256Hex(`cand-${opts.operationId}`), + status, + reason: opts.reason !== undefined ? opts.reason : (status === 'approved' ? null : 'METRIC_THRESHOLD_FAILED'), + expiresAtMs: '1900000000000', + preemptionCount: 0, + metrics: opts.metrics ?? { latency_us_p50: 42.5, goodput_rps: 2400 }, + hardwareProvenance: provenance, + ...(opts.outputArtifacts !== undefined ? { outputArtifacts: opts.outputArtifacts } : {}), + }; + const signature = signBenchmarkVerdict(TEST_HMAC_SECRET, verdictBase as unknown as BenchmarkVerdict); + const receipt = { ...verdictBase, signature } as unknown as SignedBenchmarkVerdictReceipt; + return { rawBytes: Buffer.from(`${JSON.stringify(receipt, null, 2)}\n`, 'utf8'), provenance }; +} + +function makeEvidenceDocument(provenance: object): Record { + return { + apiVersion: API_VERSION, + kind: 'Evidence', + metadata: { id: 'ev-snap-1' }, + spec: { + checkId: 'hw-bench', + observedStatus: 'passed', + producerId: 'benchmark-gate', + method: 'benchmark_gate', + level: 'hardware_execution', + subject: { + lockHash: makeDigest('lock-snap-1'), + contractHash: makeDigest('contract-snap-1'), + repository: 'team/repository', + baseRevision: 'base-1', + sourceRevision: 'source-1', + candidateDigest: makeDigest('candidate-snap-1'), + targetMatrixDigest: null, + }, + artifacts: [{ + name: '.loopwright-verifier/check.hw-bench/kernel.cubin', + digest: makeDigest('kernel-cubin'), + byteLength: 16, + }], + reason: null, + hardwareProvenance: provenance, + }, + }; +} + +interface SeededCampaign { + readonly store: EvolutionCampaignStore; + readonly campaignId: string; + readonly lockHash: Digest; + readonly cubinDigest: Digest; + readonly patchDigest: Digest; + readonly scratchpadDigest: Digest; + readonly receiptBytes: ReadonlyMap; + readonly source: { + readonly individuals: readonly IndividualRecord[]; + readonly islands: readonly IslandRecord[]; + readonly lineage: readonly LineageEdgeRecord[]; + readonly bandit: readonly ModelBanditArmRecord[]; + readonly teamConfigs: readonly TeamConfigRecord[]; + readonly scratchpads: readonly ScratchpadSnapshotRecord[]; + }; +} + +/** + * Seed a resumable two-island campaign: two passed individuals with signed receipts and CAS code + * slices, a failed and a preempted individual without receipts, a failed crossover individual whose + * stored receipt is a signed `denied` verdict, lineage, bandit rewards, a trial team with a CAS + * patch, and one scratchpad snapshot. + */ +async function seedSnapshotCampaign( + campaignRoot: string, + options: { + readonly clock: CampaignClockSource; + readonly winReceipt?: (individualId: string) => Omit; + }, +): Promise { + const store = await EvolutionCampaignStore.open({ campaignRoot, clock: options.clock }); + const lease = await store.acquireLease('snapshot-test-owner'); + const manifest = parseEvolutionCampaignDocument(SINGLE_TARGET_CAMPAIGN_YAML); + const lockHash = makeDigest('lock-snap-1'); + const campaignId = 'camp-snap-1'; + await store.createCampaign(lease, { + campaignId, + manifest, + manifestDigest: makeDigest(SINGLE_TARGET_CAMPAIGN_YAML), + baseRevision: 'b'.repeat(40), + lockHash, + modelIds: ['model-a', 'model-b'], + }); + const islands = await store.listIslands(campaignId); + const teamOf = (islandId: number): string => islands.find(i => i.islandId === islandId)!.activeTeamConfigId; + + const cubinCas = await store.writeCasBlob(KERNEL_CUBIN_BYTES); + const codeWin1 = await store.writeCasBlob('// ind-win-1 baseline\n'); + const codeWin2 = await store.writeCasBlob('// ind-win-2 diff_tune\n'); + const codeFail1 = await store.writeCasBlob('// ind-fail-1 full_rewrite\n'); + const codeFail2 = await store.writeCasBlob('// ind-fail-2 crossover\n'); + const codePre1 = await store.writeCasBlob('// ind-pre-1 diff_tune\n'); + + const outputArtifacts: readonly BenchmarkOutputArtifact[] = [{ + name: 'flash_decode_sm90a.cubin', + digest: cubinCas.digest, + byteLength: cubinCas.byteLength, + mediaType: 'application/x-nvidia-cubin', + }]; + const bucketMetrics: readonly BucketMetricEntry[] = [{ + bucketId: 'bs1-isl4k', + dimensions: { batch: 1, isl: 4096, dtype: 'bf16' }, + metrics: { latency_us_p50: 42.5, goodput_rps: 2400, max_ulp: 0.5 }, + }]; + const hardwareDiagnostics: HardwareDiagnostics = { + boundPipeline: 'tensor_cube', + rooflineHeadroom: 1.12, + achievedSolPct: 84.5, + occupancyPct: 75, + localSpillBytes: 0, + }; + + const receiptBytes = new Map(); + const recordWinner = async ( + individualId: 'ind-win-1' | 'ind-win-2', + metrics: Readonly>, + ): Promise => { + const fixture = options.winReceipt?.(individualId) ?? { operationId: `op-${individualId}` }; + const receipt = makeSignedReceiptBytes({ ...fixture, lockHash, outputArtifacts, metrics }); + receiptBytes.set(individualId, receipt.rawBytes); + const receiptCas = await store.writeCasBlob(receipt.rawBytes); + await store.recordIndividual(lease, { + individualId, + campaignId, + islandId: 0, + generation: individualId === 'ind-win-1' ? 0 : 1, + bucketId: null, + teamConfigId: teamOf(0), + modelId: individualId === 'ind-win-1' ? 'model-a' : 'model-b', + trackId: 'cute', + mutationKind: individualId === 'ind-win-1' ? 'baseline' : 'diff_tune', + status: 'passed', + failureReason: null, + nicheKey: individualId === 'ind-win-1' ? 'bound_pipeline=tensor_cube' : 'bound_pipeline=hbm', + paretoRank: 1, + crowdingDistance: individualId === 'ind-win-1' ? Number.POSITIVE_INFINITY : 0.5, + scalarFitness: individualId === 'ind-win-1' ? 0.9 : 0.8, + codeSliceCasDigest: individualId === 'ind-win-1' ? codeWin1.digest : codeWin2.digest, + evidenceDigest: makeDigest(`evidence-${individualId}`), + verdictReceiptCasDigest: receiptCas.digest, + outputArtifacts: outputArtifacts.map(a => ({ + name: `.loopwright-verifier/check.hw-bench/${a.name}`, + digest: a.digest, + byteLength: a.byteLength, + uri: `cas://sha256/${a.digest.hex}`, + mediaType: a.mediaType ?? null, + })), + metrics, + bucketMetrics, + hardwareDiagnostics, + hardwareProvenance: receipt.provenance, + ...(individualId === 'ind-win-2' + ? { + lineageEdges: [{ + campaignId, + childIndividualId: individualId, + parentIndividualId: 'ind-win-1', + role: 'primary' as const, + sourceIslandId: 0, + createdGeneration: 1, + }], + } + : {}), + }); + }; + await recordWinner('ind-win-1', { latency_us_p50: 50, goodput_rps: 2000 }); + await recordWinner('ind-win-2', { latency_us_p50: 42.5, goodput_rps: 2400 }); + + await store.recordIndividual(lease, { + individualId: 'ind-fail-1', + campaignId, + islandId: 1, + generation: 1, + bucketId: null, + teamConfigId: teamOf(1), + modelId: 'model-a', + trackId: 'cute', + mutationKind: 'full_rewrite', + status: 'failed', + failureReason: 'RUN_FAILED', + nicheKey: null, + paretoRank: null, + crowdingDistance: null, + scalarFitness: null, + codeSliceCasDigest: codeFail1.digest, + evidenceDigest: null, + verdictReceiptCasDigest: null, + outputArtifacts: [], + metrics: {}, + }); + await store.recordIndividual(lease, { + individualId: 'ind-pre-1', + campaignId, + islandId: 1, + generation: 1, + bucketId: null, + teamConfigId: teamOf(1), + modelId: 'model-b', + trackId: 'cute', + mutationKind: 'diff_tune', + status: 'preempted', + failureReason: 'BENCHMARK_PREEMPTED', + nicheKey: null, + paretoRank: null, + crowdingDistance: null, + scalarFitness: null, + codeSliceCasDigest: codePre1.digest, + evidenceDigest: null, + verdictReceiptCasDigest: null, + outputArtifacts: [], + metrics: {}, + }); + + const denied = makeSignedReceiptBytes({ lockHash, operationId: 'op-ind-fail-2', status: 'denied' }); + receiptBytes.set('ind-fail-2', denied.rawBytes); + const deniedCas = await store.writeCasBlob(denied.rawBytes); + await store.recordIndividual(lease, { + individualId: 'ind-fail-2', + campaignId, + islandId: 1, + generation: 1, + bucketId: null, + teamConfigId: teamOf(1), + modelId: 'model-b', + trackId: 'cute', + mutationKind: 'crossover', + status: 'failed', + failureReason: 'LOCAL_VERIFICATION_FAILED', + nicheKey: null, + paretoRank: null, + crowdingDistance: null, + scalarFitness: null, + codeSliceCasDigest: codeFail2.digest, + evidenceDigest: makeDigest('evidence-ind-fail-2'), + verdictReceiptCasDigest: deniedCas.digest, + outputArtifacts: [], + metrics: { latency_us_p50: 80, goodput_rps: 900 }, + lineageEdges: [ + { campaignId, childIndividualId: 'ind-fail-2', parentIndividualId: 'ind-win-1', role: 'primary', sourceIslandId: 0, createdGeneration: 1 }, + { campaignId, childIndividualId: 'ind-fail-2', parentIndividualId: 'ind-win-2', role: 'crossover_donor', sourceIslandId: 0, createdGeneration: 1 }, + ], + }); + + const patchCas = await store.writeCasBlob(PATCH_JSON_BYTES); + await store.createTrialTeamConfig(lease, { + teamConfigId: 'team-trial-1', + campaignId, + islandId: 1, + parentTeamConfigId: teamOf(1), + createdGeneration: 1, + trialBudgetGenerations: 2, + diagnosis: { + summary: 'Island 1 stalled on HBM bandwidth', + plateauCategory: 'resource_spill_trap', + rationale: 'Separate spill auditor from mutator', + }, + patchCasDigest: patchCas.digest, + }); + await store.recordTeamTrialGeneration(lease, { teamConfigId: 'team-trial-1', advancedPareto: false, discoveredNiche: true }); + await store.updateIslandProgress(lease, { + campaignId, + islandId: 0, + currentGeneration: 1, + consecutiveNoGainGenerations: 1, + lastHypervolume: 0.25, + bestRooflineHeadroom: 1.12, + }); + + await store.recordModelBanditReward(lease, { campaignId, modelId: 'model-a', reward: 0.8, generation: 0 }); + await store.recordModelBanditReward(lease, { campaignId, modelId: 'model-b', reward: 0.3, generation: 1 }); + + const scratchpadCas = await store.writeCasBlob(SCRATCHPAD_MD_BYTES); + await store.recordScratchpadSnapshot(lease, { + snapshotId: 'snap-gen-1', + campaignId, + generation: 1, + casDigest: scratchpadCas.digest, + byteLength: scratchpadCas.byteLength, + casRelPath: scratchpadCas.casRelPath, + topGainsCount: 1, + failurePatternsCount: 1, + }); + + await store.updateCampaignProgress(lease, { campaignId, status: 'paused', currentGeneration: 1 }); + await store.releaseLease(lease); + + return { + store, + campaignId, + lockHash, + cubinDigest: cubinCas.digest, + patchDigest: patchCas.digest, + scratchpadDigest: scratchpadCas.digest, + receiptBytes, + source: { + individuals: await store.listIndividuals(campaignId), + islands: await store.listIslands(campaignId), + lineage: await store.listLineageEdges(campaignId), + bandit: await store.listModelBanditArms(campaignId), + teamConfigs: await store.listTeamConfigs(campaignId), + scratchpads: await store.listScratchpadSnapshots(campaignId), + }, + }; +} + +function omit(value: T, key: K): Omit { + const out: Partial = { ...value }; + delete out[key]; + return out as Omit; +} + +function readJsonlMember(bundleDir: string, relPath: string): readonly Record[] { + return readFileSync(join(bundleDir, relPath), 'utf8').split('\n').filter(Boolean) + .map(line => JSON.parse(line) as Record); +} + +// --------------------------------------------------------------------------- +// isolation: optional HardwareProvenance field (landed first; T11 produces it) +// --------------------------------------------------------------------------- + +test('isolation: parseHardwareProvenanceJson accepts the optional key, both values, and refuses others', () => { + const base = makeProvenance(); + const absent = parseHardwareProvenanceJson(JSON.stringify(base)); + assert.equal(Object.hasOwn(absent, 'isolation'), false); + + for (const value of ['docker', 'host_attested'] as const) { + const parsed = parseHardwareProvenanceJson(JSON.stringify({ ...base, isolation: value })); + assert.equal(parsed.isolation, value); + assert.equal(Object.getPrototypeOf(parsed), null); + } + + assertEvolutionErrorSync( + () => parseHardwareProvenanceJson(JSON.stringify({ ...base, isolation: 'vm' })), + 'EVOLUTION_SCHEMA_INVALID', + ); + assertEvolutionErrorSync( + () => parseHardwareProvenanceJson(JSON.stringify({ ...base, isolation: null })), + 'EVOLUTION_SCHEMA_INVALID', + ); +}); + +test('isolation: core Evidence schema accepts the optional key and refuses unknown values', () => { + const base = makeProvenance(); + for (const value of ['docker', 'host_attested'] as const) { + const parsed = validateDocument(makeEvidenceDocument({ ...base, isolation: value }), 'Evidence'); + assert.equal(parsed.ok, true, `isolation: ${value} must parse`); + assert.equal(parsed.value.spec.hardwareProvenance?.isolation, value); + } + const absent = validateDocument(makeEvidenceDocument(base), 'Evidence'); + assert.equal(absent.ok, true); + assert.equal(Object.hasOwn(absent.value.spec.hardwareProvenance!, 'isolation'), false); + const refused = validateDocument(makeEvidenceDocument({ ...base, isolation: 'vm' }), 'Evidence'); + assert.equal(refused.ok, false); + assert.equal(refused.errors[0]?.code, 'VALUE_ENUM'); +}); + +test('isolation: exportEvolutionBundle refuses host_attested without the flag and accepts it with the flag', async () => { + const tempDir = mkdtempSync(join(tmpdir(), 'evo-snapshot-isolation-')); + try { + const attestedRoot = join(tempDir, 'campaign-attested'); + const attested = await seedSnapshotCampaign(attestedRoot, { + clock: makeSteppingClock(HIGH_MONO_MS), + winReceipt: individualId => ({ operationId: `op-${individualId}`, isolation: 'host_attested' }), + }); + try { + const refused = await assertEvolutionErrorAsync( + () => exportEvolutionBundle({ + store: attested.store, + campaignId: attested.campaignId, + outputDir: join(tempDir, 'out-refused'), + receiptSigningSecret: TEST_HMAC_SECRET, + }), + 'EXPORT_UNVERIFIED_FORBIDDEN', + ); + assert.match(refused.message, /host_attested/); + assert.equal(existsSync(join(tempDir, 'out-refused')), false); + + const exported = await exportEvolutionBundle({ + store: attested.store, + campaignId: attested.campaignId, + outputDir: join(tempDir, 'out-attested'), + allowHostAttested: true, + receiptSigningSecret: TEST_HMAC_SECRET, + }); + assert.deepEqual(exported.exportedIndividualIds, ['ind-win-1', 'ind-win-2']); + await assertEvolutionErrorAsync( + () => verifyEvolutionBundle({ bundleDir: exported.outputDir, receiptSigningSecret: TEST_HMAC_SECRET }), + 'EXPORT_UNVERIFIED_FORBIDDEN', + ); + const verified = await verifyEvolutionBundle({ + bundleDir: exported.outputDir, + allowHostAttested: true, + receiptSigningSecret: TEST_HMAC_SECRET, + }); + assert.equal(verified.receiptCount, 2); + } finally { + await attested.store.close(); + } + + // isolation: 'docker' is the enforced-isolation declaration and passes without any flag + const dockerRoot = join(tempDir, 'campaign-docker'); + const docker = await seedSnapshotCampaign(dockerRoot, { + clock: makeSteppingClock(HIGH_MONO_MS), + winReceipt: individualId => ({ operationId: `op-${individualId}`, isolation: 'docker' }), + }); + try { + const exported = await exportEvolutionBundle({ + store: docker.store, + campaignId: docker.campaignId, + outputDir: join(tempDir, 'out-docker'), + receiptSigningSecret: TEST_HMAC_SECRET, + }); + const verified = await verifyEvolutionBundle({ bundleDir: exported.outputDir, receiptSigningSecret: TEST_HMAC_SECRET }); + assert.equal(verified.manifestDigest.hex, exported.manifestDigest.hex); + } finally { + await docker.store.close(); + } + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } +}); + +// --------------------------------------------------------------------------- +// campaign-snapshot.v1 +// --------------------------------------------------------------------------- + +test('snapshot: export, verify, import on a lower-clock host, and continue the campaign', async () => { + const tempDir = mkdtempSync(join(tmpdir(), 'evo-snapshot-roundtrip-')); + try { + const campaignRoot = join(tempDir, 'campaign'); + const seeded = await seedSnapshotCampaign(campaignRoot, { clock: makeSteppingClock(HIGH_MONO_MS) }); + const outDir = join(tempDir, 'snapshot'); + let firstDigestHex = ''; + try { + const written = await writeCampaignSnapshot({ + store: seeded.store, + campaignId: seeded.campaignId, + outDir, + receiptSigningSecret: TEST_HMAC_SECRET, + }); + firstDigestHex = written.manifestDigest.hex; + assert.equal(Object.hasOwn(written, 'parentDigest'), false); + assert.equal(written.individualCount, 5); + assert.equal(written.receiptCount, 2); + assert.equal(written.blobCount, 7); // five code slices, the shared cubin, the team patch + + const manifestBytes = readFileSync(join(outDir, 'manifest.json')); + assert.equal(sha256Hex(manifestBytes), firstDigestHex); + const manifest = JSON.parse(manifestBytes.toString('utf8')) as CampaignSnapshotManifestV1; + assert.equal(manifest.kind, 'CampaignSnapshot'); + assert.equal(manifest.version, 1); + assert.equal(manifest.campaignId, seeded.campaignId); + assert.deepEqual(manifest.generations, { min: 0, max: 1 }); + assert.equal(Object.hasOwn(manifest, 'parentDigest'), false); + + const files = collectRelativeFilesRecursive(outDir); + assert.deepEqual( + manifest.members.map(m => m.path).sort(), + files.filter(f => f !== 'manifest.json').sort(), + ); + for (const required of [ + 'campaign.json', + 'individuals.jsonl', + 'lineage.jsonl', + 'islands.json', + 'bandit.json', + 'scratchpad.jsonl', + 'team_configs.jsonl', + `scratchpad/${seeded.scratchpadDigest.hex}.md`, + `blobs/sha256/${seeded.cubinDigest.hex}`, + `blobs/sha256/${seeded.patchDigest.hex}`, + 'receipts/ind-win-1.verdict.json', + 'receipts/ind-win-2.verdict.json', + ]) { + assert.ok(files.includes(required), `snapshot must contain ${required}`); + } + assert.equal(files.some(f => f.startsWith('receipts/ind-fail-2')), false, 'a denied receipt is not exported'); + for (const member of manifest.members) { + assert.equal(sha256Hex(readFileSync(join(outDir, member.path))), member.digest.hex, member.path); + } + assert.deepEqual(readFileSync(join(outDir, 'receipts/ind-win-1.verdict.json')), seeded.receiptBytes.get('ind-win-1')); + assert.deepEqual(readFileSync(join(outDir, `blobs/sha256/${seeded.cubinDigest.hex}`)), KERNEL_CUBIN_BYTES); + assert.deepEqual(readFileSync(join(outDir, `scratchpad/${seeded.scratchpadDigest.hex}.md`)), SCRATCHPAD_MD_BYTES); + + const campaignDoc = JSON.parse(readFileSync(join(outDir, 'campaign.json'), 'utf8')) as Record; + assert.equal(campaignDoc['status'], 'paused'); + assert.equal(campaignDoc['evaluationsUsed'], 4); + assert.equal(campaignDoc['preemptionsCount'], 1); + + const individuals = readJsonlMember(outDir, 'individuals.jsonl'); + assert.deepEqual( + individuals.map(r => r['individualId']), + ['ind-win-1', 'ind-fail-1', 'ind-fail-2', 'ind-pre-1', 'ind-win-2'], + ); + const byId = new Map(individuals.map(r => [r['individualId'], r])); + assert.deepEqual(byId.get('ind-win-1')!['receipt'], { algorithm: 'sha256', hex: sha256Hex(seeded.receiptBytes.get('ind-win-1')!) }); + assert.equal(byId.get('ind-win-1')!['crowdingIsBoundary'], true); + assert.equal(byId.get('ind-win-1')!['crowdingDistance'], null); + assert.equal(byId.get('ind-win-2')!['crowdingIsBoundary'], false); + assert.equal(byId.get('ind-win-2')!['crowdingDistance'], 0.5); + for (const id of ['ind-fail-1', 'ind-pre-1', 'ind-fail-2']) { + assert.equal(byId.get(id)!['receipt'], null, `${id} must carry receipt: null`); + } + assert.equal(byId.get('ind-fail-1')!['status'], 'failed'); + assert.equal(byId.get('ind-pre-1')!['status'], 'preempted'); + assert.equal(individuals.some(r => Object.hasOwn(r, 'createdAtWallMs')), false); + + // Re-export is byte-identical + const outAgain = join(tempDir, 'snapshot-again'); + const writtenAgain = await writeCampaignSnapshot({ + store: seeded.store, + campaignId: seeded.campaignId, + outDir: outAgain, + receiptSigningSecret: TEST_HMAC_SECRET, + }); + assert.equal(writtenAgain.manifestDigest.hex, firstDigestHex); + for (const rel of files) { + assert.deepEqual(readFileSync(join(outDir, rel)), readFileSync(join(outAgain, rel)), rel); + } + + const verified = await verifyCampaignSnapshot({ bundleDir: outDir, receiptSigningSecret: TEST_HMAC_SECRET }); + assert.equal(verified.manifestDigest.hex, firstDigestHex); + assert.equal(verified.individualCount, 5); + assert.equal(verified.receiptCount, 2); + assert.equal(verified.blobCount, 7); + } finally { + await seeded.store.close(); + } + + // Import onto a host whose monotonic clock is far below the exporter's + const stateDir = join(tempDir, 'state'); + const importClock = makeSteppingClock(LOW_MONO_MS); + const imported = await importCampaignSnapshot({ + bundleDir: outDir, + stateDir, + receiptSigningSecret: TEST_HMAC_SECRET, + clock: importClock, + }); + assert.equal(imported.campaignId, seeded.campaignId); + assert.equal(imported.snapshotDigest.hex, firstDigestHex); + assert.equal(imported.individualCount, 5); + assert.equal(imported.receiptCount, 2); + assert.deepEqual(readdirSync(stateDir).sort(), [CAMPAIGN_SQLITE_FILENAME, 'cas']); + + const resumed = await EvolutionCampaignStore.open({ campaignRoot: stateDir, createIfMissing: false, clock: importClock }); + try { + const meta = await resumed.getMeta(); + assert.equal(meta.fenceEpoch, 1); + assert.equal(meta.leaseId, null); + assert.ok(meta.createdMonotonicMs > LOW_MONO_MS && meta.createdMonotonicMs < LOW_MONO_MS + 1_000, 'fresh clock basis from this host'); + const provenance = await resumed.getSnapshotProvenance(seeded.campaignId); + assert.equal(provenance?.snapshotDigest.hex, firstDigestHex); + + const individuals = await resumed.listIndividuals(seeded.campaignId); + assert.equal(individuals.length, 5); + for (const source of seeded.source.individuals) { + const copy = individuals.find(i => i.individualId === source.individualId)!; + const sourceRest = omit(omit(source, 'createdAtWallMs'), 'verdictReceiptCasDigest'); + const copyRest = omit(omit(copy, 'createdAtWallMs'), 'verdictReceiptCasDigest'); + assert.deepEqual(copyRest, sourceRest, source.individualId); + // Only approved receipts travel: the stored denied verdict of ind-fail-2 imports as null. + const expectedReceipt = source.individualId === 'ind-fail-2' ? null : source.verdictReceiptCasDigest?.hex ?? null; + assert.equal(copy.verdictReceiptCasDigest?.hex ?? null, expectedReceipt, source.individualId); + } + assert.deepEqual(await resumed.listIslands(seeded.campaignId), seeded.source.islands); + assert.deepEqual(await resumed.listLineageEdges(seeded.campaignId), seeded.source.lineage); + assert.deepEqual(await resumed.listModelBanditArms(seeded.campaignId), seeded.source.bandit); + assert.deepEqual(await resumed.listTeamConfigs(seeded.campaignId), seeded.source.teamConfigs); + const scratchpads = await resumed.listScratchpadSnapshots(seeded.campaignId); + assert.deepEqual(scratchpads.map(s => omit(s, 'createdAtWallMs')), seeded.source.scratchpads.map(s => omit(s, 'createdAtWallMs'))); + const campaign = await resumed.getCampaign(seeded.campaignId); + assert.equal(campaign?.status, 'paused'); + assert.equal(campaign?.evaluationsUsed, 4); + assert.equal(campaign?.preemptionsCount, 1); + assert.equal(campaign?.currentGeneration, 1); + assert.equal(campaign?.manifestDigest.hex, makeDigest(SINGLE_TARGET_CAMPAIGN_YAML).hex); + assert.equal((await resumed.getIslandNicheElites(seeded.campaignId, 0)).size, 2); + + // CAS content needed to continue and to export a bundle again + assert.deepEqual(await resumed.readCasBlob(seeded.cubinDigest.hex), KERNEL_CUBIN_BYTES); + assert.deepEqual(await resumed.readCasBlob(seeded.patchDigest.hex), PATCH_JSON_BYTES); + assert.deepEqual(await resumed.readCasBlob(seeded.scratchpadDigest.hex), SCRATCHPAD_MD_BYTES); + assert.deepEqual(await resumed.readCasBlob(sha256Hex(seeded.receiptBytes.get('ind-win-1')!)), seeded.receiptBytes.get('ind-win-1')); + // The restored CAS supports a bundle export whose manifest names the imported individuals + const bundle = await exportEvolutionBundle({ + store: resumed, + campaignId: seeded.campaignId, + outputDir: join(tempDir, 'bundle-after-import'), + receiptSigningSecret: TEST_HMAC_SECRET, + }); + assert.deepEqual(bundle.exportedIndividualIds, ['ind-win-1', 'ind-win-2']); + + // Continue the campaign under a new lease: no EVOLUTION_CLOCK_DRIFT. + // shortcut: continuation is proven at store level plus a bundle export from the restored CAS; the + // real `evolve run` continuation needs a repository and taskpack and is asserted by T10's CLI test. + // Revisit here only if the store-level proof stops covering a path `evolve run` depends on. + const lease = await resumed.acquireLease('resume-owner'); + assert.equal(lease.fenceEpoch, 2); + await resumed.recordIndividual(lease, { + individualId: 'ind-win-3', + campaignId: seeded.campaignId, + islandId: 0, + generation: 2, + bucketId: null, + teamConfigId: individuals.find(i => i.individualId === 'ind-win-2')!.teamConfigId, + modelId: 'model-b', + trackId: 'cute', + mutationKind: 'diff_tune', + status: 'passed', + failureReason: null, + nicheKey: 'bound_pipeline=l2', + paretoRank: 1, + crowdingDistance: 0.25, + scalarFitness: 0.95, + codeSliceCasDigest: (await resumed.writeCasBlob('// ind-win-3\n')).digest, + evidenceDigest: null, + verdictReceiptCasDigest: null, + outputArtifacts: [], + metrics: { latency_us_p50: 40, goodput_rps: 2600 }, + lineageEdges: [{ campaignId: seeded.campaignId, childIndividualId: 'ind-win-3', parentIndividualId: 'ind-win-2', role: 'primary', sourceIslandId: 0, createdGeneration: 2 }], + }); + await resumed.updateParetoRanks(lease, seeded.campaignId, [{ individualId: 'ind-win-3', paretoRank: 1, crowdingDistance: 0.25 }]); + await resumed.recordModelBanditReward(lease, { campaignId: seeded.campaignId, modelId: 'model-b', reward: 0.9, generation: 2 }); + const synth = await synthesizeCampaignScratchpad({ store: resumed, lease, campaignId: seeded.campaignId, generation: 2 }); + assert.ok(synth.content.length > 0); + await resumed.releaseLease(lease); + assert.equal((await resumed.getCampaign(seeded.campaignId))?.evaluationsUsed, 5); + + // A re-export names the imported snapshot as parentDigest + const reexported = await writeCampaignSnapshot({ + store: resumed, + campaignId: seeded.campaignId, + outDir: join(tempDir, 'snapshot-2'), + receiptSigningSecret: TEST_HMAC_SECRET, + }); + assert.equal(reexported.parentDigest?.hex, firstDigestHex); + const manifest2 = JSON.parse(readFileSync(join(tempDir, 'snapshot-2', 'manifest.json'), 'utf8')) as CampaignSnapshotManifestV1; + assert.equal(manifest2.parentDigest?.hex, firstDigestHex); + assert.deepEqual(manifest2.generations, { min: 0, max: 2 }); + assert.equal(manifest2.members.some(m => m.path === 'receipts/ind-win-3.verdict.json'), false); + const verified2 = await verifyCampaignSnapshot({ bundleDir: join(tempDir, 'snapshot-2'), receiptSigningSecret: TEST_HMAC_SECRET }); + assert.equal(verified2.individualCount, 6); + + // A caller-supplied parentDigest must agree with the store's snapshot_provenance + await assertEvolutionErrorAsync( + () => writeCampaignSnapshot({ + store: resumed, + campaignId: seeded.campaignId, + outDir: join(tempDir, 'snapshot-conflict'), + parentDigest: makeDigest('other'), + receiptSigningSecret: TEST_HMAC_SECRET, + }), + 'EVOLUTION_CONFLICT', + ); + assert.equal(existsSync(join(tempDir, 'snapshot-conflict')), false); + } finally { + await resumed.close(); + } + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } +}); + +test('snapshot: a tampered receipt or member fails verification and import', async () => { + const tempDir = mkdtempSync(join(tmpdir(), 'evo-snapshot-tamper-')); + try { + const campaignRoot = join(tempDir, 'campaign'); + const seeded = await seedSnapshotCampaign(campaignRoot, { clock: makeSteppingClock(HIGH_MONO_MS) }); + const snapshotDir = join(tempDir, 'snapshot'); + let firstDigestHex = ''; + try { + const written = await writeCampaignSnapshot({ + store: seeded.store, + campaignId: seeded.campaignId, + outDir: snapshotDir, + receiptSigningSecret: TEST_HMAC_SECRET, + }); + firstDigestHex = written.manifestDigest.hex; + } finally { + await seeded.store.close(); + } + const verifyOptions: VerifyCampaignSnapshotOptions = { bundleDir: snapshotDir, receiptSigningSecret: TEST_HMAC_SECRET }; + + // Tampered receipt (same length, still valid JSON): member digest mismatch + const receiptPath = join(snapshotDir, 'receipts', 'ind-win-1.verdict.json'); + const originalReceipt = readFileSync(receiptPath); + const tamperedReceipt = Buffer.from(originalReceipt.toString('utf8').replace('NVIDIA H100', 'NVIDIA H1O0'), 'utf8'); + assert.equal(tamperedReceipt.byteLength, originalReceipt.byteLength); + writeFileSync(receiptPath, tamperedReceipt); + await assertEvolutionErrorAsync(() => verifyCampaignSnapshot(verifyOptions), 'ARTIFACT_INVALID'); + await assertEvolutionErrorAsync( + () => importCampaignSnapshot({ ...verifyOptions, stateDir: join(tempDir, 'state-a'), clock: makeSteppingClock(LOW_MONO_MS) }), + 'ARTIFACT_INVALID', + ); + assert.equal(existsSync(join(tempDir, 'state-a')), false, 'a failed import leaves no state directory behind'); + + // Tampered receipt with every digest that names it updated to match: only the HMAC can refuse it + const manifestPath = join(snapshotDir, 'manifest.json'); + const originalManifest = readFileSync(manifestPath); + const individualsPath = join(snapshotDir, 'individuals.jsonl'); + const originalIndividuals = readFileSync(individualsPath, 'utf8'); + const originalReceiptHex = sha256Hex(originalReceipt); + assert.ok(originalIndividuals.includes(`"receipt":{"algorithm":"sha256","hex":"${originalReceiptHex}"}`)); + const tamperedIndividuals = originalIndividuals.replace(originalReceiptHex, sha256Hex(tamperedReceipt)); + writeFileSync(individualsPath, tamperedIndividuals); + const manifest = JSON.parse(originalManifest.toString('utf8')) as { members: { path: string; digest: Digest }[] }; + manifest.members.find(m => m.path === 'receipts/ind-win-1.verdict.json')!.digest = { algorithm: 'sha256', hex: sha256Hex(tamperedReceipt) }; + manifest.members.find(m => m.path === 'individuals.jsonl')!.digest = { algorithm: 'sha256', hex: sha256Hex(tamperedIndividuals) }; + writeFileSync(manifestPath, JSON.stringify(manifest)); + const hmacFailure = await assertEvolutionErrorAsync(() => verifyCampaignSnapshot(verifyOptions), 'EXPORT_UNVERIFIED_FORBIDDEN'); + assert.match(hmacFailure.message, /ind-win-1/); + await assertEvolutionErrorAsync( + () => importCampaignSnapshot({ ...verifyOptions, stateDir: join(tempDir, 'state-hmac'), clock: makeSteppingClock(LOW_MONO_MS) }), + 'EXPORT_UNVERIFIED_FORBIDDEN', + ); + + // Restore the receipt, individuals, and manifest, then tamper a search-state member + writeFileSync(receiptPath, originalReceipt); + writeFileSync(manifestPath, originalManifest); + writeFileSync(individualsPath, originalIndividuals); + assert.ok(originalIndividuals.includes('"status":"passed"')); + writeFileSync(individualsPath, originalIndividuals.replace('"status":"passed"', '"status":"failed"')); + await assertEvolutionErrorAsync(() => verifyCampaignSnapshot(verifyOptions), 'ARTIFACT_INVALID'); + await assertEvolutionErrorAsync( + () => importCampaignSnapshot({ ...verifyOptions, stateDir: join(tempDir, 'state-b'), clock: makeSteppingClock(LOW_MONO_MS) }), + 'ARTIFACT_INVALID', + ); + + // Restore everything: the snapshot verifies again, so the failures above were the only defects + writeFileSync(individualsPath, originalIndividuals); + const restored = await verifyCampaignSnapshot(verifyOptions); + assert.equal(restored.manifestDigest.hex, firstDigestHex); + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } +}); + +test('snapshot: synthetic_fixture receipts need the flag, receipts need a secret, and a conflicting parentDigest is refused', async () => { + const tempDir = mkdtempSync(join(tmpdir(), 'evo-snapshot-gates-')); + try { + const campaignRoot = join(tempDir, 'campaign'); + const seeded = await seedSnapshotCampaign(campaignRoot, { + clock: makeSteppingClock(HIGH_MONO_MS), + winReceipt: individualId => ({ operationId: `op-${individualId}`, probeKind: 'synthetic_fixture' }), + }); + try { + const base = { store: seeded.store, campaignId: seeded.campaignId, outDir: join(tempDir, 'snapshot') }; + const synthetic = await assertEvolutionErrorAsync( + () => writeCampaignSnapshot({ ...base, receiptSigningSecret: TEST_HMAC_SECRET }), + 'EXPORT_UNVERIFIED_FORBIDDEN', + ); + assert.match(synthetic.message, /synthetic_fixture/); + assert.equal(existsSync(base.outDir), false); + await writeCampaignSnapshot({ ...base, allowSyntheticProbe: true, receiptSigningSecret: TEST_HMAC_SECRET }); + await assertEvolutionErrorAsync( + () => verifyCampaignSnapshot({ bundleDir: base.outDir, receiptSigningSecret: TEST_HMAC_SECRET }), + 'EXPORT_UNVERIFIED_FORBIDDEN', + ); + const verified = await verifyCampaignSnapshot({ bundleDir: base.outDir, allowSyntheticProbe: true, receiptSigningSecret: TEST_HMAC_SECRET }); + assert.equal(verified.receiptCount, 2); + + // A receipt-bearing snapshot cannot be written or verified without a signing secret + await assertEvolutionErrorAsync( + () => writeCampaignSnapshot({ ...base, outDir: join(tempDir, 'snapshot-nosecret'), allowSyntheticProbe: true }), + 'EXPORT_UNVERIFIED_FORBIDDEN', + ); + assert.equal(existsSync(join(tempDir, 'snapshot-nosecret')), false); + await assertEvolutionErrorAsync( + () => verifyCampaignSnapshot({ bundleDir: base.outDir, allowSyntheticProbe: true }), + 'EXPORT_UNVERIFIED_FORBIDDEN', + ); + + } finally { + await seeded.store.close(); + } + + // An explicit parentDigest is recorded when the store has no provenance yet + const parentDigest = makeDigest('parent-snapshot'); + const firstRoot = join(tempDir, 'campaign-parent'); + const first = await seedSnapshotCampaign(firstRoot, { clock: makeSteppingClock(HIGH_MONO_MS) }); + try { + const written = await writeCampaignSnapshot({ + store: first.store, + campaignId: first.campaignId, + outDir: join(tempDir, 'snapshot-parent'), + parentDigest, + receiptSigningSecret: TEST_HMAC_SECRET, + }); + assert.equal(written.parentDigest?.hex, parentDigest.hex); + const manifest = JSON.parse(readFileSync(join(tempDir, 'snapshot-parent', 'manifest.json'), 'utf8')) as CampaignSnapshotManifestV1; + assert.equal(manifest.parentDigest?.hex, parentDigest.hex); + assert.equal((await first.store.getSnapshotProvenance(first.campaignId)) ?? null, null, 'exporting does not record provenance'); + } finally { + await first.store.close(); + } + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } +}); + +test('snapshot: import refuses a non-empty state directory without touching it and accepts an empty one', async () => { + const tempDir = mkdtempSync(join(tmpdir(), 'evo-snapshot-nonempty-')); + try { + const campaignRoot = join(tempDir, 'campaign'); + const seeded = await seedSnapshotCampaign(campaignRoot, { clock: makeSteppingClock(HIGH_MONO_MS) }); + try { + await writeCampaignSnapshot({ + store: seeded.store, + campaignId: seeded.campaignId, + outDir: join(tempDir, 'snapshot'), + receiptSigningSecret: TEST_HMAC_SECRET, + }); + } finally { + await seeded.store.close(); + } + const bundleDir = join(tempDir, 'snapshot'); + const importOptions = { bundleDir, receiptSigningSecret: TEST_HMAC_SECRET, clock: makeSteppingClock(LOW_MONO_MS) }; + + const occupied = join(tempDir, 'state-occupied'); + mkdirSync(occupied); + writeFileSync(join(occupied, 'notes.txt'), 'keep me'); + await assertEvolutionErrorAsync(() => importCampaignSnapshot({ ...importOptions, stateDir: occupied }), 'EVOLUTION_CONFLICT'); + assert.deepEqual(readdirSync(occupied), ['notes.txt']); + + const existing = join(tempDir, 'state-existing'); + const existingStore = await EvolutionCampaignStore.open({ campaignRoot: existing, clock: makeSteppingClock(LOW_MONO_MS) }); + await existingStore.close(); + await assertEvolutionErrorAsync(() => importCampaignSnapshot({ ...importOptions, stateDir: existing }), 'EVOLUTION_CONFLICT'); + assert.deepEqual(readdirSync(existing).sort(), [CAMPAIGN_SQLITE_FILENAME, 'cas']); + + const empty = join(tempDir, 'state-empty'); + mkdirSync(empty); + const imported = await importCampaignSnapshot({ ...importOptions, stateDir: empty }); + assert.equal(imported.stateDir, empty); + assert.deepEqual(readdirSync(empty).sort(), [CAMPAIGN_SQLITE_FILENAME, 'cas']); + + // A store created before campaign snapshots existed gains snapshot_provenance on reopen + const legacyRoot = join(tempDir, 'legacy'); + const legacy = await EvolutionCampaignStore.open({ campaignRoot: legacyRoot, clock: makeSteppingClock(LOW_MONO_MS) }); + const campaign = await legacy.getCampaign('camp-snap-1'); + await legacy.close(); + assert.equal(campaign, null); + const raw = new DatabaseSync(join(legacyRoot, CAMPAIGN_SQLITE_FILENAME)); + raw.exec('DROP TABLE snapshot_provenance;'); + raw.close(); + const migrated = await EvolutionCampaignStore.open({ campaignRoot: legacyRoot, createIfMissing: false, clock: makeSteppingClock(LOW_MONO_MS) }); + try { + assert.ok((await migrated.inspectPragmas()).tables.includes('snapshot_provenance')); + assert.equal(await migrated.getSnapshotProvenance('camp-snap-1'), null); + } finally { + await migrated.close(); + } + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } +}); diff --git a/specs/2026-11-30-managed-controller-in-process-execution.md b/specs/2026-11-30-managed-controller-in-process-execution.md index bb83c4e8..6dac4fed 100644 --- a/specs/2026-11-30-managed-controller-in-process-execution.md +++ b/specs/2026-11-30-managed-controller-in-process-execution.md @@ -1,6 +1,6 @@ # Spec: Managed Controller in-process execution: `command.v1` checks, exec roles, and portable campaign state -Status: Planned +Status: Building Type: Feature ## Summary @@ -284,7 +284,8 @@ controller's own environment on a host whose isolation the registry attests. `campaign-snapshot.v1`: `manifest.json` (`campaignId`, generation range, `parentDigest` when the campaign was imported, member digests and lengths), `individuals.jsonl` (one record per evaluated candidate, passed or not, with CAS digests for code and evidence and the receipt - digest when one exists), `lineage.jsonl`, `islands.json`, `bandit.json`, `scratchpad/`, + digest when one exists), `campaign.json` (the campaign row without its civil timestamps), + `lineage.jsonl`, `islands.json`, `bandit.json`, `scratchpad.jsonl` (the scratchpad index), `scratchpad/`, `team_configs.jsonl`, `blobs/sha256/`, and `receipts/.verdict.json` for every individual that has an approved receipt. A receipt is verified fail-closed as [bundle.ts](../packages/evolution/src/bundle.ts) verifies it; `synthetic_fixture` receipts are @@ -324,6 +325,11 @@ controller's own environment on a host whose isolation the registry attests. - `loopwright runner inline --config worker.yaml` serves the relay and one worker in one process on loopback, for a controller whose `gateEndpoints` entry points at it. The two-stage isolation (Stage A without held-out workloads, Stage B read-only with them) is unchanged. + The relay keeps its HMAC and bearer authentication unchanged; the worker configuration gains an + optional `relay:` block and the inline runner prints the bound loopback URL. No in-process + identity shortcut exists (Open Question 3, resolved). When the bwrap probe fails, sandbox + negotiation falls back to `linux-landlock` today; this version does not route `deviceOwnership: + host` through that fallback, so a negative probe stops the feature. - Acceptance: a loopback end-to-end test runs `benchmark-gate.v1` through the inline runner on `synthetic_fixture`; the receipt records `isolation`; `evolve export` refuses a `host_attested` receipt without the flag; the closure row stays `blocked_external` until a @@ -566,20 +572,20 @@ and T11 have disjoint `Owns:` and start together; T5 follows T2. Owns: `packages/cli/src/closure.ts`, `packages/cli/src/failure-matrix.ts`, `packages/cli/test/closure-and-failure-matrix.test.ts`, `docs/contribute/closure-matrix.md`, `docs/configuration/controller-and-registry.md`, `docs/operations/cli.md`, `docs/operations/coding-agents.md`, `docs/configuration/task-contract.md`, `docs/walkthroughs/managed-controller-in-isolated-host.md`, `docs/contribute/adr/0003-linux-sqlite-profiles.md`, `docs/README.md`, `site/data/navigation.yaml`, `scripts/check-docs.mjs` Acceptance: the ledger has 26 rows (two `closed_local`, one `blocked_external`) with the tests named; `closure` reports the split and `--verify-failures` passes; ADR 0003 supersedes the profile sentence of ADR 0001 with the CI evidence and the Linux `fullfsync` semantics; the handler table, the registry fields, the role profiles, the credential consumers, the evidence level, the CLI pages, the ADR table, the new walkthrough, and this spec are linked from `docs/README.md`; the walkthrough is in the site navigation and the public site paths. Verify: `npm run lint:docs && npm run site && node packages/cli/dist/main.js closure --verify-failures` -- [ ] **T9 · Campaign snapshot module (phase 2)** +- [x] **T9 · Campaign snapshot module (phase 2)** Blocked by: None - Owns: `packages/evolution/src/snapshot.ts`, `packages/evolution/src/index.ts`, `packages/evolution/src/store.ts`, `packages/evolution/src/bundle.ts`, `packages/evolution/src/schema.ts`, `packages/core/src/evidence.ts`, `packages/evolution/test/snapshot.test.ts` + Owns: `packages/evolution/src/snapshot.ts`, `packages/evolution/src/index.ts`, `packages/evolution/src/store.ts`, `packages/evolution/src/bundle.ts`, `packages/evolution/src/schema.ts`, `packages/evolution/src/bundle-fs.ts`, `packages/core/src/evidence.ts`, `packages/evolution/test/snapshot.test.ts` Gate: review Acceptance: `writeCampaignSnapshot(store, outDir, { parentDigest })` writes the F4 members, includes every individual with its status and `receipt: null` when no approved receipt exists, verifies receipts fail-closed, and refuses `synthetic_fixture` without the flag; `verifyCampaignSnapshot(bundleDir, { receiptSecret })` validates offline; `importCampaignSnapshot(bundleDir, stateDir, { receiptSecret })` refuses a non-empty state directory, creates a fresh `campaign_meta` and a `snapshot_provenance` row, copies the search tables verbatim, and never copies clock or fence columns. `HardwareProvenance` gains the optional `isolation` field in core and in the evolution parser; `exportEvolutionBundle` refuses `host_attested` receipts without the flag and accepts them with it. Land that field edit first: T11 produces it. Verify: `node scripts/run-tests.mjs --pkg evolution --concurrency 1` - [ ] **T10 · Snapshot CLI and documentation (phase 2)** Blocked by: T8, T9 - Owns: `packages/cli/src/evolve.ts`, `packages/cli/src/main.ts`, `packages/cli/src/arguments.ts`, `packages/cli/test/evolve-snapshot.test.ts`, `docs/configuration/campaign-snapshots.md`, `docs/operations/cli.md`, `docs/README.md`, `site/data/navigation.yaml` - Acceptance: `evolve export --snapshot`, `evolve check --bundle`, and `evolve import` exist with `--receipt-secret-env` and exit codes consistent with the other `evolve` commands; `docs/README.md` and the site navigation index the new page; `lint:docs` and `site` pass. + Owns: `packages/cli/src/evolve.ts`, `packages/cli/src/main.ts`, `packages/cli/src/arguments.ts`, `packages/cli/test/evolve-snapshot.test.ts`, `docs/configuration/campaign-snapshots.md`, `docs/contribute/internals.md`, `docs/operations/cli.md`, `docs/README.md`, `site/data/navigation.yaml` + Acceptance: `evolve export --snapshot`, `evolve check --bundle`, and `evolve import` exist with `--receipt-secret-env`, `--allow-synthetic-probe`, and `--allow-host-attested`, and exit codes consistent with the other `evolve` commands; `evolve-snapshot.test.ts` asserts the real `evolve run` continuation on a host with a lower monotonic clock; `docs/contribute/internals.md` lists the `snapshot_provenance` table; `docs/README.md` and the site navigation index the new page; `lint:docs` and `site` pass. Verify: `node scripts/run-tests.mjs --pkg cli && npm run lint:docs && npm run site` - [ ] **T11 · In-process benchmark gate, feasibility first (phase 2)** Blocked by: None - Owns: `packages/hardware-runner/src/config.ts`, `packages/hardware-runner/src/worker.ts`, `packages/hardware-runner/src/evaluator.ts`, `packages/hardware-runner/src/provenance.ts`, `packages/hardware-runner/src/relay-server.ts`, `packages/hardware-runner/src/index.ts`, `packages/hardware-runner/test/**`, `packages/cli/src/main.ts`, `packages/cli/src/arguments.ts`, `packages/cli/test/runner-inline.test.ts` + Owns: `packages/hardware-runner/src/config.ts`, `packages/hardware-runner/src/worker.ts`, `packages/hardware-runner/src/evaluator.ts`, `packages/hardware-runner/src/provenance.ts`, `packages/hardware-runner/src/relay-server.ts`, `packages/hardware-runner/src/index.ts`, `packages/hardware-runner/src/types.ts`, `packages/controller/src/benchmark-gate.ts`, `packages/hardware-runner/test/**`, `packages/cli/src/main.ts`, `packages/cli/src/arguments.ts`, `packages/cli/test/runner-inline.test.ts`, `packages/cli/test/runner-cli.test.ts` Gate: review Acceptance: first, a recorded probe decides whether `native_os` can create its namespaces under the target Pod profile (RuntimeDefault seccomp, all capabilities dropped); if it cannot, the task reports that and stops before any feature code. Then `deviceOwnership: host` permits `sandboxBackend: native_os` with `probeMode: physical`, `hardwareProvenance.isolation` (the optional T9 field) records `docker` or `host_attested`, and `loopwright runner inline --config worker.yaml` serves relay and worker in one process on loopback; a loopback end-to-end test runs `benchmark-gate.v1` through the inline runner on `synthetic_fixture`; the physical evidence row stays `blocked_external`. Verify: `node scripts/run-tests.mjs --pkg hardware-runner && node scripts/run-tests.mjs --pkg cli` @@ -688,6 +694,9 @@ with the exact error code asserted. the fence (ADR 0001). Portable snapshots give cross-host continuity without a service. - **A `docker` backend for Managed Controller checks.** Useful on shared hosts; not needed by the first consumer. Deferred; the `runtimeProfiles` docker settings are the natural home. +- **Binding controller and worker identities in-process for the inline runner, without HMAC.** + Rejected: a second trust path that exists in one mode only. The relay's HMAC and bearer + authentication stay unchanged. ## Open Questions @@ -696,7 +705,7 @@ with the exact error code asserted. 2. Is the usage file the right shape for `exec` token accounting, or should `exec` report usage on stdout as a trailing JSON line? 3. Does the inline runner (F5) need its own relay authentication, or may it bind the controller - and worker identities in-process without HMAC? + and worker identities in-process without HMAC? Resolved: unchanged HMAC and bearer, see F5. 4. Can `native_os` create its namespaces under the target Pod profile at all? T11's probe answers this before any feature code. 5. Which analytics export format (Parquet or JSONL) would operators read, and is it worth a From d8731e98910c9b5516df7800106afef5f3bd3851 Mon Sep 17 00:00:00 2001 From: thxCode Date: Mon, 30 Nov 2026 23:55:54 +0800 Subject: [PATCH 06/26] feat(controller): validate command.v1 handlers, host.localChecks, and exec profiles - registry accepts command.v1 check handler and exec role profile - config refuses missing direct attestation and unfit timeouts - host_execution evidence level and capability; RoleAdapterKind gains exec - named limits for captureBytes, exec command entries, localChecks timeout - T2 spec check-off; T3/T4 Owns notes for exports, handlers, errors Task 2 of managed-controller-in-process-execution. Signed-off-by: thxCode --- packages/controller/src/config.ts | 15 + packages/controller/src/registry.ts | 116 ++++++- packages/controller/src/types.ts | 35 +- .../test/config-local-checks.test.ts | 135 ++++++++ packages/controller/test/exec-profile.test.ts | 302 ++++++++++++++++++ .../test/registry-command-v1.test.ts | 193 +++++++++++ packages/core/src/contracts.ts | 5 +- packages/core/src/limits.ts | 16 + packages/core/test/contracts.test.ts | 40 +++ ...managed-controller-in-process-execution.md | 8 +- 10 files changed, 846 insertions(+), 19 deletions(-) create mode 100644 packages/controller/test/config-local-checks.test.ts create mode 100644 packages/controller/test/exec-profile.test.ts create mode 100644 packages/controller/test/registry-command-v1.test.ts diff --git a/packages/controller/src/config.ts b/packages/controller/src/config.ts index feef0383..b74c0872 100644 --- a/packages/controller/src/config.ts +++ b/packages/controller/src/config.ts @@ -148,6 +148,9 @@ export function loadConfiguration(unowned: LoadConfigurationInput, ports: Config const registryBytes = await readBoundedFile(registryPath, DOCUMENT_BYTES, true), registryDigest = hash(registryBytes); if (registryDigest.hex !== registrySha256) refuse('REGISTRY_UNTRUSTED', '/registry'); const registry = validateRegistry(parseDocumentBytes(registryBytes, format(registryPath))); + if (registry.spec.handlers.some(handler => handler.implementation === 'command.v1') && registry.spec.host?.localChecks?.backend !== 'direct') { + refuse('CONFIG_SCHEMA', '/registry/spec/host/localChecks'); + } const source = await readBoundedFile(configPath, DOCUMENT_BYTES, false), raw = parseDocumentBytes(source, format(configPath)); const shape = authoring(raw), registryBinding = shape.spec.registry; if (!same(registryBinding, { name: registry.metadata.name, digest: registryDigest })) refuse('CONFIG_REFERENCE', '/spec/registry'); @@ -199,6 +202,18 @@ export function loadConfiguration(unowned: LoadConfigurationInput, ports: Config checked.spec.task = finalTask; const configuration = safe as unknown as ControllerConfiguration; if (configuration.spec.controls.drainReserveMs >= finalTask.spec.budgets.wallTimeMs) refuse('CONFIG_SCHEMA', '/spec/controls/drainReserveMs'); + for (const handler of registry.spec.handlers) { + if (handler.implementation !== 'command.v1') continue; + if (configuration.spec.controls.drainReserveMs + (handler.parameters.timeoutMs as number) > finalTask.spec.budgets.wallTimeMs) { + refuse('CONFIG_SCHEMA', '/registry/spec/handlers'); + } + } + for (const profile of registry.spec.roleProfiles) { + if (profile.adapter !== 'exec' || profile.exec === undefined) continue; + if (configuration.spec.controls.drainReserveMs + profile.exec.timeoutMs > finalTask.spec.budgets.wallTimeMs) { + refuse('CONFIG_SCHEMA', '/registry/spec/roleProfiles'); + } + } const resources = []; let resourceBytes = 0; for (const requested of finalTask.spec.trustedContext.resources) { const resource = registry.spec.resources.find(item => item.id === requested.id); diff --git a/packages/controller/src/registry.ts b/packages/controller/src/registry.ts index 8dd95db9..105cd588 100644 --- a/packages/controller/src/registry.ts +++ b/packages/controller/src/registry.ts @@ -3,7 +3,7 @@ import { isIP } from 'node:net'; import { digestArtifact } from '@loopwright/core'; import { validateSelection } from '@loopwright/agent-pi/catalog'; import { isExternalMcpToolName } from '@loopwright/agent-pi/mcp'; -import { CONTROLLER_API_VERSION, type TrustedRegistry, type RoleProfile, type Handler, type Implementation, type GateEndpoint, type PublicationEndpoint } from './types.js'; +import { CONTROLLER_API_VERSION, type TrustedRegistry, type RoleProfile, type Handler, type Implementation, type GateEndpoint, type PublicationEndpoint, type ExecProfileCommand } from './types.js'; import { digestValue, id, integer, isRecord, list, record, same, text, type Scalar } from './schema.js'; import { template } from './interpolation.js'; import { refuse, type ControllerDiagnostic } from './errors.js'; @@ -13,7 +13,7 @@ import { isValidEvolveBlockId, isValidEvolveGuardPath, } from './verifier-protocol.js'; -const implementations = ['pi.agent.v1', 'pi.compact.v1', 'scope.v1', 'json-artifact.v1', 'json-keys-guard.v1', 'line-section-guard.v1', 'evolve-block-guard.v1', 'no-change.v1', 'gate.v1', 'benchmark-gate.v1']; +const implementations = ['pi.agent.v1', 'pi.compact.v1', 'scope.v1', 'json-artifact.v1', 'json-keys-guard.v1', 'line-section-guard.v1', 'evolve-block-guard.v1', 'no-change.v1', 'gate.v1', 'benchmark-gate.v1', 'command.v1']; function unique(value: readonly { readonly id: string }[], path: string): void { if (new Set(value.map(item => item.id)).size !== value.length) refuse('CONFIG_SCHEMA', path); } function enumValue(value: unknown, values: readonly string[], path: string): void { if (typeof value !== 'string' || !values.includes(value)) refuse('CONFIG_SCHEMA', path); } export function labelValue(value: unknown, path: string): string { @@ -41,6 +41,7 @@ export function validateHandler(raw: unknown, path: string): Handler { ? implementation === 'pi.compact.v1' ? ['pi', 'compaction'] : ['pi'] : implementation === 'gate.v1' ? ['external_service', 'read_only'] : implementation === 'benchmark-gate.v1' ? ['hardware_execution', 'read_only'] + : implementation === 'command.v1' ? ['host_execution'] : ['inert_bytes', 'read_only']; if (!same(capabilities, expected)) refuse('CAPABILITY_UNSUPPORTED', path + '/capabilities'); if (implementation === 'pi.agent.v1') { @@ -65,6 +66,24 @@ export function validateHandler(raw: unknown, path: string): Handler { } id(parameters.heldOutWorkloadId, path + '/parameters/heldOutWorkloadId'); if (hasMaxPreemptions) integer(parameters.maxPreemptions, 0, 16, path + '/parameters/maxPreemptions'); + } else if (implementation === 'command.v1') { + const parameters = record(value.parameters, ['checkId', 'script', 'args', 'env', 'toolchainPaths', 'timeoutMs'], path + '/parameters'); + id(parameters.checkId, path + '/parameters/checkId'); + if (!digestArtifact(text(parameters.script, path + '/parameters/script', 1024), new Uint8Array()).ok) refuse('CONFIG_SCHEMA', path + '/parameters/script'); + list(parameters.args, path + '/parameters/args', 64).forEach((item, index) => text(item, `${path}/parameters/args/${index}`)); + if (!isRecord(parameters.env)) refuse('CONFIG_SCHEMA', path + '/parameters/env'); + const envEntries = Object.entries(parameters.env); + if (envEntries.length > 32) refuse('CONFIG_SCHEMA', path + '/parameters/env'); + for (const [name, raw] of envEntries) { + if (!/^[A-Z][A-Z0-9_]{0,63}$/.test(name) || name.startsWith('LOOPWRIGHT_') || typeof raw !== 'string' || raw.length > 16384) { + refuse('CONFIG_SCHEMA', `${path}/parameters/env/${name}`); + } + } + const toolchainPaths = list(parameters.toolchainPaths, path + '/parameters/toolchainPaths', 32); + toolchainPaths.forEach((item, index) => { + if (!digestArtifact(text(item, `${path}/parameters/toolchainPaths/${index}`, 1024), new Uint8Array()).ok) refuse('CONFIG_SCHEMA', `${path}/parameters/toolchainPaths/${index}`); + }); + integer(parameters.timeoutMs, 1000, 3600000, path + '/parameters/timeoutMs'); } else if (implementation === 'json-keys-guard.v1') { const parameters = record(value.parameters, ['checkId', 'path', 'allowedPointers'], path + '/parameters'); id(parameters.checkId, path + '/parameters/checkId'); @@ -201,14 +220,76 @@ const DEFAULT_DELEGATED_CONTEXT: RoleProfile['context'] = Object.freeze({ toolReserve: 16384, maxOutputTokens: 65536, }); +function execCommand(raw: unknown, path: string): ExecProfileCommand { + if (!raw || typeof raw !== 'object' || Array.isArray(raw)) refuse('CONFIG_SCHEMA', path); + const hasArgs = Object.hasOwn(raw, 'args'), hasEnv = Object.hasOwn(raw, 'env'), hasCredentialRefs = Object.hasOwn(raw, 'credentialRefs'), hasCaptureBytes = Object.hasOwn(raw, 'captureBytes'); + const value = record(raw, ['command', 'timeoutMs', ...(hasArgs ? ['args' as const] : []), ...(hasEnv ? ['env' as const] : []), ...(hasCredentialRefs ? ['credentialRefs' as const] : []), ...(hasCaptureBytes ? ['captureBytes' as const] : [])], path); + const command = list(value.command, path + '/command', 64); + if (command.length < 1) refuse('CONFIG_SCHEMA', path + '/command'); + const entries = command.map((item, index) => text(item, `${path}/command/${index}`, 4096)); + const program = entries[0]!; + if (!isAbsolute(program) || /[\0\r\n]/.test(program) || program.endsWith('/')) refuse('CONFIG_SCHEMA', `${path}/command/0`); + const args = hasArgs ? list(value.args, path + '/args', 64).map((item, index) => text(item, `${path}/args/${index}`, 4096)) : undefined; + let env: Readonly> | undefined; + if (hasEnv) { + if (!isRecord(value.env)) refuse('CONFIG_SCHEMA', path + '/env'); + const rawEnv = Object.entries(value.env); + if (rawEnv.length > 32) refuse('CONFIG_SCHEMA', path + '/env'); + const checkedEnv: Record = Object.create(null) as Record; + for (const [name, rawValue] of rawEnv) { + if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) || name.length > 64) refuse('CONFIG_SCHEMA', `${path}/env/${name}`); + checkedEnv[name] = text(rawValue, `${path}/env/${name}`); + } + env = checkedEnv; + } + const credentialRefs = hasCredentialRefs ? list(value.credentialRefs, path + '/credentialRefs', 16).map((item, index) => id(item, `${path}/credentialRefs/${index}`)) : undefined; + if (credentialRefs !== undefined && new Set(credentialRefs).size !== credentialRefs.length) refuse('CONFIG_SCHEMA', path + '/credentialRefs'); + const timeoutMs = integer(value.timeoutMs, 1, Number.MAX_SAFE_INTEGER, path + '/timeoutMs'); + const captureBytes = hasCaptureBytes ? integer(value.captureBytes, 1024, 1048576, path + '/captureBytes') : undefined; + return { + command: entries, + ...(args !== undefined ? { args } : {}), + ...(env !== undefined ? { env } : {}), + ...(credentialRefs !== undefined ? { credentialRefs } : {}), + timeoutMs, + ...(captureBytes !== undefined ? { captureBytes } : {}), + }; +} function role(raw: unknown, path: string): RoleProfile { if (!raw || typeof raw !== 'object' || Array.isArray(raw)) refuse('CONFIG_SCHEMA', path); - const hasAdapter = Object.hasOwn(raw, 'adapter'), hasContext = Object.hasOwn(raw, 'context'), hasLimits = Object.hasOwn(raw, 'limits'); - const keys = ['id', ...(hasAdapter ? ['adapter' as const] : []), 'selection', 'tools', ...(hasContext ? ['context' as const] : []), 'runtimeRef', 'providerCredentialRef', 'mcp', ...(hasLimits ? ['limits' as const] : [])]; + const hasAdapter = Object.hasOwn(raw, 'adapter'), hasContext = Object.hasOwn(raw, 'context'), hasLimits = Object.hasOwn(raw, 'limits'), hasExec = Object.hasOwn(raw, 'exec'); + const keys = ['id', ...(hasAdapter ? ['adapter' as const] : []), 'selection', 'tools', ...(hasContext ? ['context' as const] : []), 'runtimeRef', 'providerCredentialRef', 'mcp', ...(hasLimits ? ['limits' as const] : []), ...(hasExec ? ['exec' as const] : [])]; const value = record(raw, keys, path); const adapterRaw = hasAdapter ? value.adapter : 'pi'; - if (adapterRaw !== 'pi' && adapterRaw !== 'delegated') refuse('CONFIG_SCHEMA', path + '/adapter'); + if (adapterRaw !== 'pi' && adapterRaw !== 'delegated' && adapterRaw !== 'exec') refuse('CONFIG_SCHEMA', path + '/adapter'); const checkedLimits = hasLimits ? roleLimits(value.limits, path + '/limits') : undefined; + if (adapterRaw === 'exec') { + if (!hasExec) refuse('CONFIG_SCHEMA', path + '/exec'); + id(value.id, path + '/id'); + if (value.runtimeRef !== null) refuse('CONFIG_SCHEMA', path + '/runtimeRef'); + if (value.providerCredentialRef !== null) refuse('CONFIG_SCHEMA', path + '/providerCredentialRef'); + if (value.mcp !== null) refuse('CONFIG_SCHEMA', path + '/mcp'); + const sel = record(value.selection, ['provider', 'model', 'thinking'], path + '/selection'); + const provider = labelValue(sel.provider, path + '/selection/provider'); + const model = labelValue(sel.model, path + '/selection/model'); + const thinking = labelValue(sel.thinking, path + '/selection/thinking'); + const tools = list(value.tools, path + '/tools', 8).map(item => text(item, path + '/tools', 128)); + if (new Set(tools).size !== tools.length || tools.some(name => !['read', 'bash', 'write', 'edit', 'delete'].includes(name))) refuse('CAPABILITY_UNSUPPORTED', path + '/tools'); + // Shape parity only: `context` is neither required nor read for exec roles. + const checkedContext = hasContext && value.context !== undefined ? context(value.context, path + '/context') : DEFAULT_DELEGATED_CONTEXT; + return { + id: value.id as string, + adapter: 'exec', + selection: { provider, model, thinking }, + tools, + context: checkedContext, + runtimeRef: null, + providerCredentialRef: null, + mcp: null, + exec: execCommand(value.exec, path + '/exec'), + ...(checkedLimits !== undefined ? { limits: checkedLimits } : {}), + }; + } if (adapterRaw === 'delegated') { id(value.id, path + '/id'); if (value.runtimeRef !== null) id(value.runtimeRef, path + '/runtimeRef'); @@ -277,10 +358,15 @@ export function validateRegistry(raw: unknown): TrustedRegistry { const top = record(raw, ['apiVersion', 'kind', 'metadata', 'spec'], '/registry'); if (top.apiVersion !== CONTROLLER_API_VERSION || top.kind !== 'TrustedRegistry') refuse('CONFIG_SCHEMA', '/registry'); id(record(top.metadata, ['name'], '/registry/metadata').name, '/registry/metadata/name'); - const spec = top.spec as Record, hasGate = Object.hasOwn(spec, 'gateEndpoints'), hasPublication = Object.hasOwn(spec, 'publicationEndpoints'); + const spec = top.spec as Record, hasGate = Object.hasOwn(spec, 'gateEndpoints'), hasPublication = Object.hasOwn(spec, 'publicationEndpoints'), hasHost = Object.hasOwn(spec, 'host'); const value = record(top.spec, ['version', 'resourceVersion', 'handlers', 'roleProfiles', 'resources', 'runtimeProfiles', 'credentialBindings', 'environmentBindings', - ...(hasGate ? ['gateEndpoints' as const] : []), ...(hasPublication ? ['publicationEndpoints' as const] : [])], '/registry/spec'); + ...(hasHost ? ['host' as const] : []), ...(hasGate ? ['gateEndpoints' as const] : []), ...(hasPublication ? ['publicationEndpoints' as const] : [])], '/registry/spec'); integer(value.version, 1, 1, '/registry/spec/version'); text(value.resourceVersion, '/registry/spec/resourceVersion', 128); + if (hasHost) { + const host = record(value.host, ['localChecks'], '/registry/spec/host'); + const localChecks = record(host.localChecks, ['backend'], '/registry/spec/host/localChecks'); + if (localChecks.backend !== 'direct') refuse('CONFIG_SCHEMA', '/registry/spec/host/localChecks/backend'); + } const handlers = list(value.handlers).map((item, i) => validateHandler(item, '/registry/spec/handlers/' + i)); unique(handlers, '/registry/spec/handlers'); const roles = list(value.roleProfiles).map((item, i) => role(item, '/registry/spec/roleProfiles/' + i)); unique(roles, '/registry/spec/roleProfiles'); for (const item of list(value.runtimeProfiles)) { @@ -296,14 +382,22 @@ export function validateRegistry(raw: unknown): TrustedRegistry { if (!digestArtifact(text(resource.path, '/registry/spec/resources', 1024), new Uint8Array()).ok) refuse('CONFIG_SCHEMA', '/registry/spec/resources'); } unique(value.resources as readonly { id: string }[], '/registry/spec/resources'); - for (const item of list(value.credentialBindings)) { + const bindings = list(value.credentialBindings).map(item => { const binding = record(item, ['id', 'consumer', 'destinationRef', 'environmentNames', 'template'], '/registry/spec/credentialBindings'); - id(binding.id); id(binding.destinationRef); enumValue(binding.consumer, ['provider', 'mcp', 'gate', 'publisher'], '/registry/spec/credentialBindings'); + id(binding.id); id(binding.destinationRef); enumValue(binding.consumer, ['provider', 'mcp', 'gate', 'publisher', 'exec'], '/registry/spec/credentialBindings'); const names = list(binding.environmentNames).map(name => text(name)); if (new Set(names).size !== names.length || names.some(name => !/^[A-Za-z_][A-Za-z0-9_]*$/.test(name))) refuse('CONFIG_SCHEMA', '/registry/spec/credentialBindings'); const parts = template(text(binding.template), '/registry/spec/credentialBindings'), used = parts.flatMap(part => part.name === null ? [] : [part.name]); if (!used.length || used.some(name => !names.includes(name))) refuse('CONFIG_SCHEMA', '/registry/spec/credentialBindings'); - } - unique(value.credentialBindings as readonly { id: string }[], '/registry/spec/credentialBindings'); + return binding; + }); + unique(bindings as unknown as readonly { id: string }[], '/registry/spec/credentialBindings'); + roles.forEach((profile, index) => { + if (profile.adapter !== 'exec' || profile.exec?.credentialRefs === undefined) return; + for (const ref of profile.exec.credentialRefs) { + const binding = bindings.find(item => item.id === ref); + if (!binding || binding.consumer !== 'exec') refuse('CONFIG_REFERENCE', `/registry/spec/roleProfiles/${index}/exec/credentialRefs`); + } + }); const environment = list(value.environmentBindings).map(item => { const binding = record(item, ['name', 'classification', 'paths'], '/registry/spec/environmentBindings'); if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(text(binding.name))) refuse('CONFIG_SCHEMA', '/registry/spec/environmentBindings'); diff --git a/packages/controller/src/types.ts b/packages/controller/src/types.ts index 1c586b90..015a66a0 100644 --- a/packages/controller/src/types.ts +++ b/packages/controller/src/types.ts @@ -48,8 +48,9 @@ export type Implementation = | 'evolve-block-guard.v1' | 'no-change.v1' | 'gate.v1' - | 'benchmark-gate.v1'; -export type RoleAdapterKind = 'pi' | 'delegated'; + | 'benchmark-gate.v1' + | 'command.v1'; +export type RoleAdapterKind = 'pi' | 'delegated' | 'exec'; export type ControllerPolicyProfile = 'local' | 'github'; export interface PersistedHostPolicy { readonly policyProfile: ControllerPolicyProfile; @@ -218,10 +219,30 @@ export interface RoleProfile { readonly id: string; readonly adapter?: RoleAdapterKind; readonly selection: AdapterPolicy['selection'] | DelegatedSelection; readonly tools: readonly string[]; readonly context: AdapterPolicy['context']; readonly runtimeRef: string | null; readonly providerCredentialRef: string | null; readonly mcp: AdapterPolicyV2['mcp'] | null; readonly limits?: Partial | undefined; + /** Present iff `adapter: 'exec'`: the local command the controller spawns for each agent step. */ + readonly exec?: ExecProfileCommand | undefined; +} +/** The `exec` block of a role profile: the local command the controller spawns for each agent step. */ +export interface ExecProfileCommand { + readonly command: readonly string[]; + readonly args?: readonly string[]; + readonly env?: Readonly>; + readonly credentialRefs?: readonly string[]; + readonly timeoutMs: number; + readonly captureBytes?: number; +} +/** Role profile with `adapter: 'exec'`: a local command, no runtime profile, no provider credential, no MCP server. `context` is shape parity only; exec roles never read it. */ +export interface ExecRoleProfile extends RoleProfile { + readonly adapter: 'exec'; + readonly selection: DelegatedSelection; + readonly runtimeRef: null; + readonly providerCredentialRef: null; + readonly mcp: null; + readonly exec: ExecProfileCommand; } export interface RegistryResource { readonly id: string; readonly kind: 'instruction' | 'skill' | 'document'; readonly path: string; readonly digest: Digest } export interface RuntimeProfile { readonly id: string; readonly identity: RuntimeIdentity; readonly dockerExecutable: string; readonly dockerSocket: string } -export interface CredentialBinding { readonly id: string; readonly consumer: 'provider' | 'mcp' | 'gate' | 'publisher'; readonly destinationRef: string; readonly environmentNames: readonly string[]; readonly template: string } +export interface CredentialBinding { readonly id: string; readonly consumer: 'provider' | 'mcp' | 'gate' | 'publisher' | 'exec'; readonly destinationRef: string; readonly environmentNames: readonly string[]; readonly template: string } export interface EnvironmentBinding { readonly name: string; readonly classification: 'nonsecret' | 'credential'; readonly paths: readonly string[] } export interface GateEndpoint { readonly id: string; readonly url: string; readonly signingCredentialRef: string; readonly authCredentialRef: string | null; @@ -237,6 +258,8 @@ export interface TrustedRegistry { readonly spec: { readonly version: 1; readonly resourceVersion: string; readonly handlers: readonly Handler[]; readonly roleProfiles: readonly RoleProfile[]; readonly resources: readonly RegistryResource[]; readonly runtimeProfiles: readonly RuntimeProfile[]; readonly credentialBindings: readonly CredentialBinding[]; readonly environmentBindings: readonly EnvironmentBinding[]; + /** Attests that `command.v1` handlers run in the controller's own environment; required whenever the registry holds one. */ + readonly host?: { readonly localChecks: { readonly backend: 'direct' } }; readonly gateEndpoints: readonly GateEndpoint[]; readonly publicationEndpoints: readonly PublicationEndpoint[] }; } export interface Controls { @@ -265,6 +288,12 @@ export interface CheckpointCapacity { readonly A: number; readonly N: number; re readonly publication: boolean; readonly additionalRefs: 4; readonly requiredRefs: 6; readonly checkpointBytes: 40960 } export interface VerifierSlot { readonly id: string; readonly checkId: string; readonly implicit: 'scope' | 'no_change' | null; readonly handler: Handler } export interface PlannedRole { readonly roleId: string; readonly adapter: RoleAdapterKind; readonly profileRef: string; readonly providerCredentialRef: string | null; readonly runtime: RuntimeProfile; readonly policy: AdapterPolicyV2 } +/** Planned role for `adapter: 'exec'`: carries the validated command that the exec runner spawns. */ +export interface ExecPlannedRole extends PlannedRole { + readonly adapter: 'exec'; + readonly providerCredentialRef: null; + readonly exec: ExecProfileCommand; +} export interface PlannedNode { readonly id: string; readonly kind: 'agent' | 'check'; diff --git a/packages/controller/test/config-local-checks.test.ts b/packages/controller/test/config-local-checks.test.ts new file mode 100644 index 00000000..5cf5a4e0 --- /dev/null +++ b/packages/controller/test/config-local-checks.test.ts @@ -0,0 +1,135 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { configurationFixture } from './config-fixtures.js'; +import { hash } from '../src/schema.js'; +import type { ControllerResult } from '../src/errors.js'; +import type { LoadedConfiguration } from '../src/types.js'; + +const COMMAND_DIGEST = hash('loopwright.dev/controller/handler/v1\0command.v1-local-checks'); +/** The fixture task carries `wallTimeMs: 600000` and the controller `drainReserveMs: 120000`. */ +const DRAIN_RESERVE_MS = 120000; +const WALL_TIME_MS = 600000; + +function good(result: ControllerResult): T { + assert.equal(result.ok, true, result.ok ? '' : JSON.stringify(result.error)); + if (!result.ok) throw new Error('expected success'); + return result.value; +} + +function set(value: unknown, path: readonly (string | number)[], replacement: unknown): void { + let parent = value as Record; + for (const key of path.slice(0, -1)) parent = parent[key] as Record; + parent[path.at(-1)!] = replacement; +} + +function commandHandler(timeoutMs = WALL_TIME_MS - DRAIN_RESERVE_MS): Record { + return { + id: 'forge-evaluate', + version: 1, + kind: 'check', + implementation: 'command.v1', + digest: { algorithm: 'sha256', hex: COMMAND_DIGEST.hex }, + parameters: { + checkId: 'forge-evaluate', + script: 'scripts/forge-evaluate.sh', + args: [], + env: {}, + toolchainPaths: [], + timeoutMs, + }, + capabilities: ['host_execution'], + }; +} + +function execProfile(timeoutMs = WALL_TIME_MS - DRAIN_RESERVE_MS): Record { + return { + id: 'author', + adapter: 'exec', + selection: { provider: 'openai', model: 'gpt-5', thinking: 'medium' }, + tools: ['read', 'write', 'edit'], + runtimeRef: null, + providerCredentialRef: null, + mcp: null, + exec: { + command: ['/usr/local/bin/forgevo-author'], + timeoutMs, + }, + }; +} + +async function withLocalChecksFixture(mutate: (fixture: Awaited>) => Promise | void): Promise> { + const f = await configurationFixture(); + try { + set(f.registry, ['spec', 'host'], { localChecks: { backend: 'direct' } }); + set(f.registry, ['spec', 'handlers'], [...f.registry.spec.handlers, commandHandler()]); + set(f.registry, ['spec', 'roleProfiles'], [...f.registry.spec.roleProfiles, execProfile()]); + await mutate(f); + await f.save(); + return await f.load(); + } finally { + await f.cleanup(); + } +} + +test('loadConfiguration accepts a command.v1 handler and an exec profile under host.localChecks direct', async () => { + const loaded = good(await withLocalChecksFixture(() => undefined)); + assert.equal(loaded.registry.spec.host?.localChecks?.backend, 'direct'); + assert.ok(loaded.registry.spec.handlers.some(handler => handler.implementation === 'command.v1')); + const profile = loaded.registry.spec.roleProfiles.find(item => item.id === 'author')!; + assert.equal(profile.adapter, 'exec'); + assert.deepEqual(profile.exec, { command: ['/usr/local/bin/forgevo-author'], timeoutMs: WALL_TIME_MS - DRAIN_RESERVE_MS }); + assert.equal(profile.runtimeRef, null); + assert.equal(profile.providerCredentialRef, null); + assert.equal(profile.mcp, null); +}); + +test('loadConfiguration accepts the registry without host.localChecks when no command.v1 handler exists', async () => { + const f = await configurationFixture(); + try { + set(f.registry, ['spec', 'roleProfiles'], [...f.registry.spec.roleProfiles, execProfile()]); + await f.save(); + good(await f.load()); + } finally { + await f.cleanup(); + } +}); + +test('loadConfiguration refuses a command.v1 handler without host.localChecks or with another backend', async () => { + const cases: readonly { readonly name: string; readonly mutate: (fixture: Awaited>) => void }[] = [ + { name: 'missing host block', mutate: f => delete (f.registry.spec as Record).host }, + { name: 'missing localChecks', mutate: f => set(f.registry, ['spec', 'host'], { attested: true }) }, + { name: 'docker backend', mutate: f => set(f.registry, ['spec', 'host', 'localChecks', 'backend'], 'docker') }, + { name: 'null backend', mutate: f => set(f.registry, ['spec', 'host', 'localChecks', 'backend'], null) }, + ]; + for (const item of cases) { + const loaded = await withLocalChecksFixture(item.mutate); + assert.equal(loaded.ok, false, item.name); + if (!loaded.ok) assert.equal(loaded.error.code, 'CONFIG_SCHEMA', item.name); + } +}); + +test('loadConfiguration refuses a command.v1 timeoutMs that cannot fit between drainReserveMs and wallTimeMs', async () => { + for (const timeoutMs of [WALL_TIME_MS - DRAIN_RESERVE_MS + 1, WALL_TIME_MS, WALL_TIME_MS + 1]) { + const loaded = await withLocalChecksFixture(f => set(f.registry, ['spec', 'handlers', 4, 'parameters', 'timeoutMs'], timeoutMs)); + assert.equal(loaded.ok, false, String(timeoutMs)); + if (!loaded.ok) assert.equal(loaded.error.code, 'CONFIG_SCHEMA', String(timeoutMs)); + } + const atTheLimit = good(await withLocalChecksFixture(f => set(f.registry, ['spec', 'handlers', 4, 'parameters', 'timeoutMs'], WALL_TIME_MS - DRAIN_RESERVE_MS))); + assert.equal(atTheLimit.registry.spec.handlers.find(handler => handler.implementation === 'command.v1')?.parameters.timeoutMs, WALL_TIME_MS - DRAIN_RESERVE_MS); +}); + +test('loadConfiguration refuses an exec timeoutMs that cannot fit between drainReserveMs and wallTimeMs', async () => { + for (const timeoutMs of [WALL_TIME_MS - DRAIN_RESERVE_MS + 1, WALL_TIME_MS]) { + const loaded = await withLocalChecksFixture(f => set(f.registry, ['spec', 'roleProfiles', 1, 'exec', 'timeoutMs'], timeoutMs)); + assert.equal(loaded.ok, false, String(timeoutMs)); + if (!loaded.ok) assert.equal(loaded.error.code, 'CONFIG_SCHEMA', String(timeoutMs)); + } + const atTheLimit = good(await withLocalChecksFixture(f => set(f.registry, ['spec', 'roleProfiles', 1, 'exec', 'timeoutMs'], WALL_TIME_MS - DRAIN_RESERVE_MS))); + assert.equal(atTheLimit.registry.spec.roleProfiles.find(item => item.id === 'author')?.exec?.timeoutMs, WALL_TIME_MS - DRAIN_RESERVE_MS); +}); + +test('loadConfiguration refuses a command.v1 handler whose schema is invalid before the budget check', async () => { + const loaded = await withLocalChecksFixture(f => set(f.registry, ['spec', 'handlers', 4, 'parameters', 'env'], { LOOPWRIGHT_RUN_ID: 'run-1' })); + assert.equal(loaded.ok, false); + if (!loaded.ok) assert.equal(loaded.error.code, 'CONFIG_SCHEMA'); +}); diff --git a/packages/controller/test/exec-profile.test.ts b/packages/controller/test/exec-profile.test.ts new file mode 100644 index 00000000..473ec36e --- /dev/null +++ b/packages/controller/test/exec-profile.test.ts @@ -0,0 +1,302 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { stringify } from 'yaml'; +import { validateRegistry } from '../src/registry.js'; +import { parseDocumentBytes } from '../src/parser.js'; +import { hash } from '../src/schema.js'; +import { ControllerFailure } from '../src/errors.js'; +import type { + ExecPlannedRole, + ExecProfileCommand, + ExecRoleProfile, + Handler, + PlannedRole, + RoleAdapterKind, + RoleProfile, + TrustedRegistry, +} from '../src/types.js'; + +const PI_DIGEST = hash('loopwright.dev/controller/handler/v1\0pi.agent.v1-test'); + +function piAgentHandler(): Record { + return { + id: 'package.patch', + version: 1, + kind: 'agent', + implementation: 'pi.agent.v1', + digest: { algorithm: 'sha256', hex: PI_DIGEST.hex }, + parameters: { prompt: 'Produce one structured submission for the frozen candidate.', purpose: 'task' }, + capabilities: ['pi'], + }; +} + +function execProfile(exec: Record = {}): Record { + return { + id: 'author', + adapter: 'exec', + selection: { provider: 'openai', model: 'gpt-5', thinking: 'medium' }, + tools: ['read', 'write', 'edit'], + runtimeRef: null, + providerCredentialRef: null, + mcp: null, + exec: { + command: ['/usr/local/bin/forgevo-author'], + env: { FORGEVO_LLM_BASE_URL: 'https://api.example.com/v1' }, + credentialRefs: ['llm-token'], + timeoutMs: 600000, + ...exec, + }, + }; +} + +function execRegistry(profile: Record = execProfile()): Record { + return { + apiVersion: 'loopwright.dev/v1alpha1', + kind: 'TrustedRegistry', + metadata: { name: 'operator' }, + spec: { + version: 1, + resourceVersion: 'context-1', + handlers: [piAgentHandler()], + roleProfiles: [structuredClone(profile)], + resources: [], + runtimeProfiles: [], + credentialBindings: [{ + id: 'llm-token', + consumer: 'exec', + destinationRef: 'openai', + environmentNames: ['LLM_TOKEN'], + template: '${LLM_TOKEN}', + }], + environmentBindings: [], + }, + }; +} + +function set(value: unknown, path: readonly (string | number)[], replacement: unknown): void { + let parent = value as Record; + for (const key of path.slice(0, -1)) parent = parent[key] as Record; + parent[path.at(-1)!] = replacement; +} + +function refusal(mutate: (registry: Record) => void): string { + const registry = execRegistry(); + mutate(registry); + try { + validateRegistry(registry); + } catch (error) { + if (error instanceof ControllerFailure) return error.diagnostic.code; + throw error; + } + return 'accepted'; +} + +/** The normalized exec env is a null-prototype record, like every `record()` output. */ +function pojoExec(exec: ExecProfileCommand | undefined): Record { + return exec === undefined ? {} : { ...exec, ...(exec.env !== undefined ? { env: { ...exec.env } } : {}) }; +} + +test('types export RoleAdapterKind exec, ExecProfileCommand, ExecRoleProfile, and ExecPlannedRole', () => { + const adapterKind: RoleAdapterKind = 'exec'; + assert.equal(adapterKind, 'exec'); + const command: ExecProfileCommand = { + command: ['/usr/local/bin/forgevo-author'], + args: ['--strict'], + env: { FORGEVO_LLM_BASE_URL: 'https://api.example.com/v1' }, + credentialRefs: ['llm-token'], + timeoutMs: 600000, + captureBytes: 65536, + }; + const profile: ExecRoleProfile = { + id: 'author', + adapter: 'exec', + selection: { provider: 'openai', model: 'gpt-5', thinking: 'medium' }, + tools: ['read', 'write', 'edit'], + context: { + mode: 'estimated_guard', + estimator: 'lw-pi-final-json-bytes-v1', + proofId: null, + version: 1, + evidence: 'estimated', + workingWindowCeiling: 200000, + maxRequestBytes: 524288, + serviceMargin: 32768, + toolReserve: 16384, + maxOutputTokens: 65536, + }, + runtimeRef: null, + providerCredentialRef: null, + mcp: null, + exec: command, + }; + const widenProfile: (value: ExecRoleProfile) => RoleProfile = value => value; + const widenPlanned: (value: ExecPlannedRole) => PlannedRole = value => value; + assert.equal(widenProfile(profile).adapter, 'exec'); + assert.equal(widenProfile(profile).exec, command); + assert.ok(widenPlanned); + const plannedShape: Pick = { + adapter: 'exec', + providerCredentialRef: null, + exec: command, + }; + assert.equal(plannedShape.exec.timeoutMs, 600000); +}); + +test('validateRegistry accepts an exec role profile beside a pi.agent.v1 handler with consumer: exec bindings', () => { + const validated = validateRegistry(execRegistry()) as TrustedRegistry; + const handler = validated.spec.handlers[0]! as Handler; + assert.equal(handler.implementation, 'pi.agent.v1'); + const profile = validated.spec.roleProfiles[0]!; + assert.equal(profile.id, 'author'); + assert.equal(profile.adapter, 'exec'); + assert.deepEqual(profile.selection, { provider: 'openai', model: 'gpt-5', thinking: 'medium' }); + assert.deepEqual(profile.tools, ['read', 'write', 'edit']); + assert.equal(profile.runtimeRef, null); + assert.equal(profile.providerCredentialRef, null); + assert.equal(profile.mcp, null); + assert.deepEqual(pojoExec(profile.exec), { + command: ['/usr/local/bin/forgevo-author'], + env: { FORGEVO_LLM_BASE_URL: 'https://api.example.com/v1' }, + credentialRefs: ['llm-token'], + timeoutMs: 600000, + }); + assert.deepEqual(profile.context, { + mode: 'estimated_guard', + estimator: 'lw-pi-final-json-bytes-v1', + proofId: null, + version: 1, + evidence: 'estimated', + workingWindowCeiling: 200000, + maxRequestBytes: 524288, + serviceMargin: 32768, + toolReserve: 16384, + maxOutputTokens: 65536, + }); + assert.equal(validated.spec.credentialBindings[0]!.consumer, 'exec'); + + const roundTrippedJson = validateRegistry(JSON.parse(JSON.stringify(validated))); + assert.deepEqual(roundTrippedJson, validated); + const roundTrippedYaml = validateRegistry(parseDocumentBytes(Buffer.from(stringify(validated), 'utf8'), 'yaml')); + assert.deepEqual(roundTrippedYaml, validated); +}); + +test('exec profiles validate optional keys: context stays optional and unreferenced, args and captureBytes accepted', () => { + const withEverything = execRegistry(execProfile({ + command: ['/usr/local/bin/forgevo-author', '--mode', 'json'], + args: ['--attempt', '2'], + captureBytes: 1048576, + })); + const validated = validateRegistry(withEverything) as TrustedRegistry; + assert.deepEqual(pojoExec(validated.spec.roleProfiles[0]!.exec), { + command: ['/usr/local/bin/forgevo-author', '--mode', 'json'], + env: { FORGEVO_LLM_BASE_URL: 'https://api.example.com/v1' }, + credentialRefs: ['llm-token'], + timeoutMs: 600000, + captureBytes: 1048576, + args: ['--attempt', '2'], + }); + + const withoutEnvOrCredentialRefs = execRegistry(); + delete (withoutEnvOrCredentialRefs.spec as { roleProfiles: { exec: Record }[] }).roleProfiles[0]!.exec.env; + delete (withoutEnvOrCredentialRefs.spec as { roleProfiles: { exec: Record }[] }).roleProfiles[0]!.exec.credentialRefs; + const lean = validateRegistry(withoutEnvOrCredentialRefs) as TrustedRegistry; + assert.deepEqual(pojoExec(lean.spec.roleProfiles[0]!.exec), { command: ['/usr/local/bin/forgevo-author'], timeoutMs: 600000 }); + + const withContext = execRegistry(); + set(withContext, ['spec', 'roleProfiles', 0, 'context'], { + mode: 'estimated_guard', estimator: 'lw-pi-final-json-bytes-v1', proofId: null, version: 1, evidence: 'estimated', + workingWindowCeiling: 100000, maxRequestBytes: 524288, serviceMargin: 32768, toolReserve: 16384, maxOutputTokens: 4096, + }); + const withContextValidated = validateRegistry(withContext) as TrustedRegistry; + assert.equal(withContextValidated.spec.roleProfiles[0]!.context?.maxOutputTokens, 4096); +}); + +test('exec profiles refuse a missing exec block, non-null runtime and credential fields, and unknown keys', () => { + const cases: readonly { readonly name: string; readonly mutate: (registry: Record) => void }[] = [ + { name: 'missing exec block', mutate: registry => delete (registry.spec as { roleProfiles: Record[] }).roleProfiles[0]!.exec }, + { name: 'non-null runtimeRef', mutate: registry => set(registry, ['spec', 'roleProfiles', 0, 'runtimeRef'], 'docker') }, + { name: 'non-null providerCredentialRef', mutate: registry => set(registry, ['spec', 'roleProfiles', 0, 'providerCredentialRef'], 'copilot') }, + { name: 'non-null mcp', mutate: registry => set(registry, ['spec', 'roleProfiles', 0, 'mcp'], {}) }, + { name: 'unknown profile key', mutate: registry => set(registry, ['spec', 'roleProfiles', 0, 'runtime'], { hours: 1 }) }, + { name: 'unknown exec key', mutate: registry => set(registry, ['spec', 'roleProfiles', 0, 'exec', 'cwd'], '/') }, + { name: 'missing timeoutMs', mutate: registry => delete (registry.spec as { roleProfiles: { exec: Record }[] }).roleProfiles[0]!.exec.timeoutMs }, + { name: 'zero timeoutMs', mutate: registry => set(registry, ['spec', 'roleProfiles', 0, 'exec', 'timeoutMs'], 0) }, + { name: 'fractional timeoutMs', mutate: registry => set(registry, ['spec', 'roleProfiles', 0, 'exec', 'timeoutMs'], 1.5) }, + { name: 'missing command', mutate: registry => delete (registry.spec as { roleProfiles: { exec: Record }[] }).roleProfiles[0]!.exec.command }, + { name: 'empty command', mutate: registry => set(registry, ['spec', 'roleProfiles', 0, 'exec', 'command'], []) }, + { name: 'null exec', mutate: registry => set(registry, ['spec', 'roleProfiles', 0, 'exec'], null) }, + ]; + for (const item of cases) { + assert.equal(refusal(item.mutate), 'CONFIG_SCHEMA', item.name); + } +}); + +test('exec command[0] refuses relative paths, trailing slashes, NUL, and newline; entries after it may be flags', () => { + const cases: readonly { readonly name: string; readonly command: unknown }[] = [ + { name: 'relative program', command: ['forgevo-author'] }, + { name: 'relative nested program', command: ['bin/forgevo-author'] }, + { name: 'trailing slash', command: ['/usr/local/bin/forgevo-author/'] }, + { name: 'NUL in program', command: ['/usr/local/bin/forgevo\0author'] }, + { name: 'newline in program', command: ['/usr/local/bin/forgevo-author\n'] }, + { name: 'dot-relative program', command: ['./forgevo-author'] }, + { name: 'empty program entry', command: [''] }, + { name: 'sixty-five entries', command: ['/usr/local/bin/forgevo-author', ...Array.from({ length: 64 }, (_, i) => 'arg-' + i)] }, + { name: 'non-string entry', command: ['/usr/local/bin/forgevo-author', 3] }, + ]; + for (const item of cases) { + assert.equal(refusal(registry => set(registry, ['spec', 'roleProfiles', 0, 'exec', 'command'], item.command)), 'CONFIG_SCHEMA', item.name); + } + assert.equal(refusal(registry => set(registry, ['spec', 'roleProfiles', 0, 'exec', 'command'], ['/usr/local/bin/forgevo-author', '--mode', 'json'])), 'accepted'); +}); + +test('exec captureBytes refuses out-of-bounds values and accepts the F2 limits', () => { + for (const captureBytes of [1023, 1048577, 0, 65536.5]) { + assert.equal(refusal(registry => set(registry, ['spec', 'roleProfiles', 0, 'exec', 'captureBytes'], captureBytes)), 'CONFIG_SCHEMA', String(captureBytes)); + } + for (const captureBytes of [1024, 65536, 1048576]) { + assert.equal(refusal(registry => set(registry, ['spec', 'roleProfiles', 0, 'exec', 'captureBytes'], captureBytes)), 'accepted', String(captureBytes)); + } +}); + +test('exec env refuses malformed names and non-string values', () => { + const envCases: readonly { readonly name: string; readonly env: unknown }[] = [ + { name: 'empty name', env: { '': 'x' } }, + { name: 'digit-leading name', env: { '1FORGE': 'x' } }, + { name: 'space in name', env: { 'FORGE VO': 'x' } }, + { name: 'dash in name', env: { 'FORGE-VO': 'x' } }, + { name: 'null value', env: { FORGEVO_LLM_BASE_URL: null } }, + { name: 'numeric value', env: { FORGEVO_LLM_BASE_URL: 1 } }, + { name: 'array env', env: [] }, + ]; + for (const item of envCases) { + assert.equal(refusal(registry => set(registry, ['spec', 'roleProfiles', 0, 'exec', 'env'], item.env)), 'CONFIG_SCHEMA', item.name); + } +}); + +test('exec tools follow the delegated vocabulary without codemode or MCP tools', () => { + for (const tools of [['read', 'fly'], ['codemode'], ['mcp__workspace__read_file'], ['read', 'read']]) { + assert.equal(refusal(registry => set(registry, ['spec', 'roleProfiles', 0, 'tools'], tools)), 'CAPABILITY_UNSUPPORTED', JSON.stringify(tools)); + } + for (const tools of [['read'], ['read', 'bash', 'write', 'edit', 'delete']]) { + assert.equal(refusal(registry => set(registry, ['spec', 'roleProfiles', 0, 'tools'], tools)), 'accepted', JSON.stringify(tools)); + } +}); + +test('exec credentialRefs refuse unknown bindings and bindings that are not consumer: exec', () => { + assert.equal(refusal(registry => set(registry, ['spec', 'roleProfiles', 0, 'exec', 'credentialRefs'], ['missing'])), 'CONFIG_REFERENCE'); + assert.equal(refusal(registry => set(registry, ['spec', 'credentialBindings', 0, 'consumer'], 'provider')), 'CONFIG_REFERENCE'); + assert.equal(refusal(registry => set(registry, ['spec', 'credentialBindings', 0, 'consumer'], 'mcp')), 'CONFIG_REFERENCE'); + assert.equal(refusal(() => undefined), 'accepted'); +}); + +test('exec selection and profile ids validate like delegated profiles', () => { + const cases: readonly { readonly name: string; readonly mutate: (registry: Record) => void }[] = [ + { name: 'missing selection', mutate: registry => delete (registry.spec as { roleProfiles: Record[] }).roleProfiles[0]!.selection }, + { name: 'unknown selection key', mutate: registry => set(registry, ['spec', 'roleProfiles', 0, 'selection', 'api'], 'openai-responses') }, + { name: 'whitespace in provider', mutate: registry => set(registry, ['spec', 'roleProfiles', 0, 'selection', 'provider'], 'open ai') }, + { name: 'invalid profile id', mutate: registry => set(registry, ['spec', 'roleProfiles', 0, 'id'], 'Author') }, + ]; + for (const item of cases) { + assert.equal(refusal(item.mutate), 'CONFIG_SCHEMA', item.name); + } +}); diff --git a/packages/controller/test/registry-command-v1.test.ts b/packages/controller/test/registry-command-v1.test.ts new file mode 100644 index 00000000..8f28a180 --- /dev/null +++ b/packages/controller/test/registry-command-v1.test.ts @@ -0,0 +1,193 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { stringify } from 'yaml'; +import { validateRegistry } from '../src/registry.js'; +import { parseDocumentBytes } from '../src/parser.js'; +import { hash } from '../src/schema.js'; +import { ControllerFailure } from '../src/errors.js'; +import type { Handler, TrustedRegistry } from '../src/types.js'; + +const COMMAND_DIGEST = hash('loopwright.dev/controller/handler/v1\0command.v1-test'); + +function commandHandler(parameters: Record = {}): Record { + return { + id: 'forge-evaluate', + version: 1, + kind: 'check', + implementation: 'command.v1', + digest: { algorithm: 'sha256', hex: COMMAND_DIGEST.hex }, + parameters: { + checkId: 'forge-evaluate', + script: 'scripts/forge-evaluate.sh', + args: [], + env: {}, + toolchainPaths: [], + timeoutMs: 600000, + ...parameters, + }, + capabilities: ['host_execution'], + }; +} + +function registryFixture(handlers: readonly unknown[] = [commandHandler()]): Record { + return { + apiVersion: 'loopwright.dev/v1alpha1', + kind: 'TrustedRegistry', + metadata: { name: 'operator' }, + spec: { + version: 1, + resourceVersion: 'context-1', + handlers: structuredClone(handlers), + roleProfiles: [], + resources: [], + runtimeProfiles: [], + credentialBindings: [], + environmentBindings: [], + host: { localChecks: { backend: 'direct' } }, + }, + }; +} + +function set(value: unknown, path: readonly (string | number)[], replacement: unknown): void { + let parent = value as Record; + for (const key of path.slice(0, -1)) parent = parent[key] as Record; + parent[path.at(-1)!] = replacement; +} + +function refusal(mutate: (registry: Record) => void): string { + const registry = registryFixture(); + mutate(registry); + try { + validateRegistry(registry); + } catch (error) { + if (error instanceof ControllerFailure) return error.diagnostic.code; + throw error; + } + return 'accepted'; +} + +test('validateRegistry accepts a command.v1 check handler with the F1 parameters under host.localChecks direct', () => { + const registry = registryFixture([commandHandler({ + args: ['--json', 'kernel=rmsnorm'], + env: { FORGEVO_KERNEL_ID: 'rmsnorm_0123456789abcdef' }, + toolchainPaths: ['toolchains/cuda/bin'], + timeoutMs: 600000, + })]); + const validated = validateRegistry(registry) as TrustedRegistry; + const handler = validated.spec.handlers[0]! as Handler; + assert.equal(handler.implementation, 'command.v1'); + assert.equal(handler.kind, 'check'); + assert.deepEqual(handler.capabilities, ['host_execution']); + assert.equal(handler.parameters.checkId, 'forge-evaluate'); + assert.equal(handler.parameters.script, 'scripts/forge-evaluate.sh'); + assert.deepEqual(handler.parameters.args, ['--json', 'kernel=rmsnorm']); + assert.deepEqual(handler.parameters.env, { FORGEVO_KERNEL_ID: 'rmsnorm_0123456789abcdef' }); + assert.deepEqual(handler.parameters.toolchainPaths, ['toolchains/cuda/bin']); + assert.equal(handler.parameters.timeoutMs, 600000); + + const roundTrippedJson = validateRegistry(JSON.parse(JSON.stringify(validated))); + assert.deepEqual(roundTrippedJson, validated); + const roundTrippedYaml = validateRegistry(parseDocumentBytes(Buffer.from(stringify(validated), 'utf8'), 'yaml')); + assert.deepEqual(roundTrippedYaml, validated); +}); + +test('command.v1 parameters refuse unknown or missing keys with CONFIG_SCHEMA', () => { + const cases: readonly { readonly name: string; readonly mutate: (registry: Record) => void }[] = [ + { name: 'unknown parameter key', mutate: registry => set(registry, ['spec', 'handlers', 0, 'parameters', 'networkMode'], 'host') }, + { name: 'missing checkId', mutate: registry => delete (registry.spec as { handlers: { parameters: Record }[] }).handlers[0]!.parameters.checkId }, + { name: 'missing timeoutMs', mutate: registry => delete (registry.spec as { handlers: { parameters: Record }[] }).handlers[0]!.parameters.timeoutMs }, + { name: 'missing script', mutate: registry => delete (registry.spec as { handlers: { parameters: Record }[] }).handlers[0]!.parameters.script }, + ]; + for (const item of cases) { + assert.equal(refusal(item.mutate), 'CONFIG_SCHEMA', item.name); + } +}); + +test('command.v1 env refuses reserved names, malformed names, non-strings, and too many entries', () => { + const envCases: readonly { readonly name: string; readonly env: unknown }[] = [ + { name: 'reserved LOOPWRIGHT_RUN_ID', env: { LOOPWRIGHT_RUN_ID: 'run-1' } }, + { name: 'reserved LOOPWRIGHT_ prefix', env: { LOOPWRIGHT_STEP_ID: 'build' } }, + { name: 'lowercase name', env: { forgevo_kernel_id: 'x' } }, + { name: 'digit-leading name', env: { '1FORGE': 'x' } }, + { name: 'lowercase letter in tail', env: { FORGEVO_kernel: 'x' } }, + { name: 'overlong name', env: { ['A'.repeat(65)]: 'x' } }, + { name: 'non-string value', env: { FORGEVO_KERNEL_ID: 3 } }, + { name: 'null value', env: { FORGEVO_KERNEL_ID: null } }, + { name: 'thirty-three entries', env: Object.fromEntries(Array.from({ length: 33 }, (_, i) => ['FORGEVO_' + i, String(i)])) }, + { name: 'array env', env: [] }, + { name: 'null env', env: null }, + ]; + for (const item of envCases) { + assert.equal(refusal(registry => set(registry, ['spec', 'handlers', 0, 'parameters', 'env'], item.env)), 'CONFIG_SCHEMA', item.name); + } +}); + +test('command.v1 args, toolchainPaths, script, and timeoutMs refuse out-of-bounds values', () => { + const cases: readonly { readonly name: string; readonly mutate: (registry: Record) => void }[] = [ + { name: 'sixty-five args', mutate: registry => set(registry, ['spec', 'handlers', 0, 'parameters', 'args'], Array.from({ length: 65 }, (_, i) => 'arg-' + i)) }, + { name: 'non-string arg', mutate: registry => set(registry, ['spec', 'handlers', 0, 'parameters', 'args'], [3]) }, + { name: 'thirty-three toolchainPaths', mutate: registry => set(registry, ['spec', 'handlers', 0, 'parameters', 'toolchainPaths'], Array.from({ length: 33 }, (_, i) => 'toolchains/' + i)) }, + { name: 'absolute script', mutate: registry => set(registry, ['spec', 'handlers', 0, 'parameters', 'script'], '/etc/passwd') }, + { name: 'escaping script', mutate: registry => set(registry, ['spec', 'handlers', 0, 'parameters', 'script'], '../forge-evaluate.sh') }, + { name: 'empty script', mutate: registry => set(registry, ['spec', 'handlers', 0, 'parameters', 'script'], '') }, + { name: 'timeout below range', mutate: registry => set(registry, ['spec', 'handlers', 0, 'parameters', 'timeoutMs'], 999) }, + { name: 'timeout above range', mutate: registry => set(registry, ['spec', 'handlers', 0, 'parameters', 'timeoutMs'], 3600001) }, + { name: 'timeout not an integer', mutate: registry => set(registry, ['spec', 'handlers', 0, 'parameters', 'timeoutMs'], 600000.5) }, + { name: 'wrong kind', mutate: registry => set(registry, ['spec', 'handlers', 0, 'kind'], 'agent') }, + ]; + for (const item of cases) { + assert.equal(refusal(item.mutate), 'CONFIG_SCHEMA', item.name); + } +}); + +test('command.v1 capabilities refuse anything other than host_execution with CAPABILITY_UNSUPPORTED', () => { + const cases: readonly { readonly name: string; readonly capabilities: unknown }[] = [ + { name: 'host_execution with read_only', capabilities: ['host_execution', 'read_only'] }, + { name: 'inert capabilities', capabilities: ['inert_bytes', 'read_only'] }, + { name: 'hardware capabilities', capabilities: ['hardware_execution', 'read_only'] }, + { name: 'empty capabilities', capabilities: [] }, + { name: 'single wrong capability', capabilities: ['host_execution_'] }, + ]; + for (const item of cases) { + assert.equal(refusal(registry => set(registry, ['spec', 'handlers', 0, 'capabilities'], item.capabilities)), 'CAPABILITY_UNSUPPORTED', item.name); + } + assert.equal(refusal(registry => set(registry, ['spec', 'handlers', 0, 'id'], 'forge-evaluate2')), 'accepted'); +}); + +test('command.v1 parameter bounds accept the limits and refuse one past them', () => { + const atLimit = registryFixture([commandHandler({ + args: Array.from({ length: 64 }, (_, i) => 'arg-' + i), + env: Object.fromEntries(Array.from({ length: 32 }, (_, i) => ['FORGEVO_' + i, String(i)])), + toolchainPaths: Array.from({ length: 32 }, (_, i) => 'toolchains/' + i), + timeoutMs: 3600000, + })]); + assert.ok(validateRegistry(atLimit)); + const minTimeout = registryFixture([commandHandler({ timeoutMs: 1000 })]); + assert.ok(validateRegistry(minTimeout)); +}); + +test('host.localChecks accepts backend direct and refuses other backends or unknown keys', () => { + assert.equal(refusal(() => undefined), 'accepted'); + const backendCases: readonly { readonly name: string; readonly host: unknown }[] = [ + { name: 'docker backend', host: { localChecks: { backend: 'docker' } } }, + { name: 'empty backend', host: { localChecks: { backend: '' } } }, + { name: 'null backend', host: { localChecks: { backend: null } } }, + { name: 'unknown localChecks key', host: { localChecks: { backend: 'direct', runtime: 'container' } } }, + { name: 'missing localChecks', host: { attested: true } }, + { name: 'null host', host: null }, + ]; + for (const item of backendCases) { + assert.equal(refusal(registry => set(registry, ['spec', 'host'], item.host)), 'CONFIG_SCHEMA', item.name); + } +}); + +test('validateRegistry alone accepts a command.v1 handler without host; loadConfiguration owns that cross-check', () => { + const registry = registryFixture(); + delete (registry.spec as Record).host; + const validated = validateRegistry(registry) as TrustedRegistry; + assert.equal(validated.spec.host, undefined); +}); + +test('command.v1 handler ids stay unique with other check handlers', () => { + assert.equal(refusal(registry => set(registry, ['spec', 'handlers', 1], commandHandler())), 'CONFIG_SCHEMA'); +}); diff --git a/packages/core/src/contracts.ts b/packages/core/src/contracts.ts index fc9a9615..06a9e4b2 100644 --- a/packages/core/src/contracts.ts +++ b/packages/core/src/contracts.ts @@ -568,8 +568,11 @@ export function configDocument(kind: K, spec: Schema< return shape(value, path); }; } -export const evidenceLevel = enumeration('static_inspection', 'synthetic_fixture', 'local_execution', 'external_service', 'hardware_execution'); +export const evidenceLevel = enumeration('static_inspection', 'synthetic_fixture', 'local_execution', 'external_service', 'hardware_execution', 'host_execution'); export type EvidenceLevel = Infer; +/** Capability strings a TrustedRegistry handler may declare. `host_execution` marks code that ran in the controller's own environment on a host the registry attests. */ +export const handlerCapability = enumeration('pi', 'compaction', 'inert_bytes', 'read_only', 'external_service', 'hardware_execution', 'host_execution'); +export type HandlerCapability = Infer; export const checkStatus = enumeration('passed', 'failed', 'blocked', 'not_run'); export type CheckStatus = Infer; const overlaySchema = record({ diff --git a/packages/core/src/limits.ts b/packages/core/src/limits.ts index 0ddb2fc2..b953d4ad 100644 --- a/packages/core/src/limits.ts +++ b/packages/core/src/limits.ts @@ -41,6 +41,22 @@ export const VERIFIER_ARTIFACT_LIMITS = Object.freeze({ maxTotalBytes: OVERLAY_LIMITS.maxMaxBytes, }); +/** Bounds for Managed Controller `command.v1` checks under the `direct` backend. */ +export const LOCAL_CHECK_LIMITS = Object.freeze({ + timeoutMsMin: 1_000, + timeoutMsMax: 3_600_000, + checkOutBytes: 65_536, +}); + +/** Bounds for `exec` role profiles. */ +export const EXEC_LIMITS = Object.freeze({ + captureBytesMin: 1_024, + captureBytesDefault: 65_536, + captureBytesMax: 1_048_576, + commandEntriesMin: 1, + commandEntriesMax: 64, +}); + export const LIMITS = Object.freeze({ inputBytes: 1_048_576, depth: 64, string: 16_384, nodes: 65_536, properties: 128, collection: 1_024, identifier: 64, toolName: 128, diff --git a/packages/core/test/contracts.test.ts b/packages/core/test/contracts.test.ts index d5960afc..0810cb2a 100644 --- a/packages/core/test/contracts.test.ts +++ b/packages/core/test/contracts.test.ts @@ -1,6 +1,8 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import { admitTask, resolveOverlayLimits, validateDocument, LIMITS, OVERLAY_LIMITS } from '../src/index.js'; +import { handlerCapability } from '../src/contracts.js'; +import { EXEC_LIMITS, LOCAL_CHECK_LIMITS } from '../src/limits.js'; import { contract, code, value } from './fixtures.js'; test('contract accepts exact builtin/MCP tools without weakening identifiers', () => { @@ -171,6 +173,44 @@ test('contract supports at least 16 roles and 16 steps', () => { assert.equal(validateDocument(input, 'TaskContract').ok, true); }); +test('host_execution is an accepted evidence level for acceptance checks', () => { + const alone = contract(); + alone.spec.acceptance.checks[0]!.allowedEvidenceLevels = ['host_execution']; + assert.deepEqual(value(validateDocument(alone, 'TaskContract')).spec.acceptance.checks[0]!.allowedEvidenceLevels, ['host_execution']); + + const mixed = contract(); + mixed.spec.acceptance.checks[0]!.allowedEvidenceLevels = ['host_execution', 'local_execution']; + assert.deepEqual(value(validateDocument(mixed, 'TaskContract')).spec.acceptance.checks[0]!.allowedEvidenceLevels, ['host_execution', 'local_execution']); + + const unknown = contract(); + unknown.spec.acceptance.checks[0]!.allowedEvidenceLevels = ['host_executions']; + assert.equal(code(validateDocument(unknown, 'TaskContract')), 'VALUE_ENUM'); +}); + +test('handlerCapability accepts host_execution beside the existing handler capability vocabulary', () => { + for (const capability of ['pi', 'compaction', 'inert_bytes', 'read_only', 'external_service', 'hardware_execution', 'host_execution']) { + assert.equal(handlerCapability(capability, '/capabilities'), capability); + } + for (const capability of ['network', 'host_execution_', '', 'HOST_EXECUTION']) { + assert.throws( + () => handlerCapability(capability, '/capabilities'), + (err: unknown) => err instanceof Error && err.message === 'VALUE_ENUM', + capability, + ); + } +}); + +test('limits carry the command.v1 and exec bounds named by the spec', () => { + assert.equal(LOCAL_CHECK_LIMITS.timeoutMsMin, 1000); + assert.equal(LOCAL_CHECK_LIMITS.timeoutMsMax, 3600000); + assert.equal(LOCAL_CHECK_LIMITS.checkOutBytes, 65536); + assert.equal(EXEC_LIMITS.captureBytesMin, 1024); + assert.equal(EXEC_LIMITS.captureBytesMax, 1048576); + assert.equal(EXEC_LIMITS.captureBytesDefault, 65536); + assert.equal(EXEC_LIMITS.commandEntriesMin, 1); + assert.equal(EXEC_LIMITS.commandEntriesMax, 64); +}); + test('OVERLAY_LIMITS and resolveOverlayLimits validate configurable overlay ceilings', () => { assert.equal(OVERLAY_LIMITS.defaultMaxFiles, 128); assert.equal(OVERLAY_LIMITS.defaultMaxBytes, 4_194_304); diff --git a/specs/2026-11-30-managed-controller-in-process-execution.md b/specs/2026-11-30-managed-controller-in-process-execution.md index 6dac4fed..8dcc08f6 100644 --- a/specs/2026-11-30-managed-controller-in-process-execution.md +++ b/specs/2026-11-30-managed-controller-in-process-execution.md @@ -533,7 +533,7 @@ and T11 have disjoint `Owns:` and start together; T5 follows T2. Gate: review Acceptance: `materializeAttemptWorkspace` and `scanCandidateDirectory` move verbatim into `candidate-workspace.ts` with exported signatures; `step.ts` imports them; the step tests change only their imports. Verify: `node scripts/run-tests.mjs --pkg controller` -- [ ] **T2 · Schema tracer: `command.v1`, `host.localChecks`, `exec` profiles, `consumer: exec`, `host_execution`** +- [x] **T2 · Schema tracer: `command.v1`, `host.localChecks`, `exec` profiles, `consumer: exec`, `host_execution`** Blocked by: None Owns: `packages/core/src/contracts.ts`, `packages/core/src/limits.ts`, `packages/controller/src/types.ts`, `packages/controller/src/registry.ts`, `packages/controller/src/config.ts`, `packages/controller/test/registry-command-v1.test.ts`, `packages/controller/test/exec-profile.test.ts`, `packages/controller/test/config-local-checks.test.ts`, `packages/core/test/contracts.test.ts` Acceptance: `validateRegistry` accepts a `command.v1` handler with the F1 parameters and `host.localChecks.backend: direct`, and an `exec` profile with the F2 keys beside a `pi.agent.v1` agent handler; it refuses the F1 and F2 refusal cases with the codes named there. `loadConfiguration` refuses a registry with a `command.v1` handler but no `host.localChecks`, any backend other than `direct`, and a `command.v1` or `exec` `timeoutMs` that cannot fit between `drainReserveMs` and `wallTimeMs`. `host_execution` is accepted as an evidence level and a capability, and `RoleAdapterKind` includes `'exec'`. @@ -542,13 +542,13 @@ and T11 have disjoint `Owns:` and start together; T5 follows T2. Blocked by: T1, T2 Owns: `packages/core/src/local-check-contract.ts`, `packages/core/src/index.ts`, `packages/core/test/local-check-contract.test.ts`, `packages/controller/src/local-check.ts`, `packages/controller/test/local-check.test.ts`, `packages/controller/test/local-check-fixtures.ts` Gate: review - Acceptance: the contract module exports the environment names, the env name rule, and the `$LOOPWRIGHT_CHECK_OUT` parser (64 KiB, `passed` and `summary` refused, metric and finding bounds). `LocalCheck.run(job, signal)` follows `Gate.run` and executes the script in its own process group with the binding marker written first: candidate materialized through the T1 helpers into a disposable directory, the F1 environment, `timeoutMs` with process-group kill, exit-code mapping, output artifact bound to `candidateDigest`, scrubbed stderr tail, receipt with `method: 'direct_script'` and the script and registry digests. The captured overlay is byte-identical before and after; an operation without a proof marker settles `blocked` with `EVIDENCE_UNAVAILABLE` and is not re-dispatched. + Acceptance: the contract module exports the environment names, the env name rule, and the `$LOOPWRIGHT_CHECK_OUT` parser (64 KiB, `passed` and `summary` refused, metric and finding bounds); `packages/core/src/index.ts` also exports the T2 limits (`LOCAL_CHECK_LIMITS`, `EXEC_LIMITS`) and `handlerCapability`. `LocalCheck.run(job, signal)` follows `Gate.run` and executes the script in its own process group with the binding marker written first: candidate materialized through the T1 helpers into a disposable directory, the F1 environment, `timeoutMs` with process-group kill, exit-code mapping, output artifact bound to `candidateDigest`, scrubbed stderr tail, receipt with `method: 'direct_script'` and the script and registry digests. The captured overlay is byte-identical before and after; an operation without a proof marker settles `blocked` with `EVIDENCE_UNAVAILABLE` and is not re-dispatched. Verify: `node scripts/run-tests.mjs --pkg core && node scripts/run-tests.mjs --pkg controller` - [ ] **T4 · `command.v1` controller integration** Blocked by: T3 - Owns: `packages/controller/src/compile.ts`, `packages/controller/src/controller.ts`, `packages/controller/src/recovery.ts`, `packages/controller/test/compile.test.ts`, `packages/controller/test/rework.test.ts`, `packages/controller/test/local-check-integration.test.ts`, `packages/controller/test/recovery-cycle.test.ts` + Owns: `packages/controller/src/compile.ts`, `packages/controller/src/controller.ts`, `packages/controller/src/recovery.ts`, `packages/controller/src/handlers.ts`, `packages/controller/src/errors.ts`, `packages/controller/test/compile.test.ts`, `packages/controller/test/rework.test.ts`, `packages/controller/test/local-check-integration.test.ts`, `packages/controller/test/recovery-cycle.test.ts` Gate: review - Acceptance: admission resolves the script and `toolchainPaths` at `target.sourceRevision` from the baseline tree, requires the executable bit and a fully protected script directory, and records the directory digest in the compiled slot; `check` validates schema and budget only; the controller dispatches `command.v1` slots to `LocalCheck`, extracts `detail` for them in the rework summary, and exports the receipt through `inspect`; recovery settles a `command.v1` operation without a proof marker as `blocked`. A controller cycle test with the deterministic fake adapter as author and the T3 stub scripts settles `completed` for a passing script and reworks with `detail` for a failing one. + Acceptance: admission resolves the script and `toolchainPaths` at `target.sourceRevision` from the baseline tree, requires the executable bit and a fully protected script directory, and records the directory digest in the compiled slot; `check` validates schema and budget only; the controller dispatches `command.v1` slots to `LocalCheck`, extracts `detail` for them in the rework summary, and exports the receipt through `inspect`; recovery settles a `command.v1` operation without a proof marker as `blocked`. A controller cycle test with the deterministic fake adapter as author and the T3 stub scripts settles `completed` for a passing script and reworks with `detail` for a failing one. `installedHandlerDigests()` in `handlers.ts` lists `command.v1`, and the `safePath` segment whitelist in `errors.ts` covers the new refusal paths (`host`, `localChecks`, `backend`, `command`, `script`, `env`, `toolchainPaths`, `exec`, `captureBytes`, `credentialRefs`). Verify: `node scripts/run-tests.mjs --pkg controller` - [ ] **T5 · `exec` runner module** Blocked by: T2 From 3e3fc0ec8ac7adc449dac6ad9f7316833c474506 Mon Sep 17 00:00:00 2001 From: thxCode Date: Tue, 1 Dec 2026 00:07:42 +0800 Subject: [PATCH 07/26] feat(core): export exec and local-check limits from the package root - export EXEC_LIMITS and LOCAL_CHECK_LIMITS for the exec runner - export handlerCapability for registry consumers - unblocks T5; satisfies the T3 index.ts export item Task 5 of managed-controller-in-process-execution. Signed-off-by: thxCode --- packages/core/src/index.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index d14c2562..aa97e195 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -1,6 +1,6 @@ export { API_VERSION } from './boundary.js'; export { - LIMITS, OVERLAY_LIMITS, HANDOFF_LIMITS, VERIFIER_ARTIFACT_LIMITS, + LIMITS, OVERLAY_LIMITS, HANDOFF_LIMITS, VERIFIER_ARTIFACT_LIMITS, EXEC_LIMITS, LOCAL_CHECK_LIMITS, type OverlayLimits, type OverlayLimitsInput, type OverlayLimitOptions, } from './limits.js'; export { @@ -12,7 +12,7 @@ export { isVerifierNamespacePath, parseVerifierArtifactPath, type VerifierArtifactPath, } from './scope.js'; export { - isWritablePath, resolveOverlayLimits, matchesDriverConstraint, + isWritablePath, resolveOverlayLimits, matchesDriverConstraint, handlerCapability, type TaskContract, type ReworkPolicy, type Digest, type ArtifactRef, type EvidenceLevel, type CheckStatus, type MetricValue, type MetricsMap, type FindingSeverity, type StructuredFinding, type StepHandoffSource, type StepHandoffSelect, type StepHandoffSelector, From 1711a2e18fddd42cbabd4871f9ec2dc4c9cd0e47 Mon Sep 17 00:00:00 2001 From: thxCode Date: Tue, 1 Dec 2026 00:37:54 +0800 Subject: [PATCH 08/26] refactor(controller): move candidate workspace helpers into candidate-workspace.ts - move materializeAttemptWorkspace and scanCandidateDirectory verbatim - step.ts imports them; export two helpers the moved bodies call - prune imports only the moved bodies used; document the module cycle - T1 spec check-off Task 1 of managed-controller-in-process-execution. Signed-off-by: thxCode --- .../controller/src/candidate-workspace.ts | 552 ++++++++++++++++++ packages/controller/src/step.ts | 539 +---------------- ...managed-controller-in-process-execution.md | 2 +- 3 files changed, 563 insertions(+), 530 deletions(-) create mode 100644 packages/controller/src/candidate-workspace.ts diff --git a/packages/controller/src/candidate-workspace.ts b/packages/controller/src/candidate-workspace.ts new file mode 100644 index 00000000..a1a9278d --- /dev/null +++ b/packages/controller/src/candidate-workspace.ts @@ -0,0 +1,552 @@ +/** + * Candidate attempt workspace helpers shared by `step.ts` and the local-check executor. + * This module imports `isWritableCandidateFile` and `resolveCurrentFileModes` from `./step.js`, + * and `step.ts` imports the two functions below, so the two modules form a cycle. LIMITED: only + * hoisted `function` declarations may cross this cycle. Never add a module-level `const`, `class`, + * or evaluated call that reads the other module's bindings at init time; it throws a TDZ error. + * The controller suite exercises every caller. + */ +import { constants } from 'node:fs'; +import { chmod, lstat, mkdir, open, readdir, rename, rm } from 'node:fs/promises'; +import { dirname, join, relative, resolve } from 'node:path'; +import { createHash } from 'node:crypto'; +import { digestArtifact, digestArtifactFromMetadata, identifyManifest, isWritablePath, type ArtifactManifest, type ArtifactRef, type Digest, type TaskContract } from '@loopwright/core'; +import { type DelegatedCaptureOverlayEntryV2 } from './capture.js'; +import { approvedState } from './config.js'; +import { roleResourcesFor, Cycle } from './controller.js'; +import { refuse, type ControllerDiagnostic } from './errors.js'; +import { copyVerifiedFileReadOnly, STREAM_CHUNK_BYTES } from './files.js'; +import { materializeContextFilesDir } from './handoff.js'; +import { hash, same } from './schema.js'; +import { + attachVerifiedCasSeal, + canonicalizeCandidateManifest, + compareUtf16, + isHostProtectedPath, + materializeBaseline, + overlayManifestBounds, + type FrozenSource, + type HostPathProtectionOptions, +} from './source.js'; +import { ArtifactStore, privateDirectory, resolveCanonicalCasBlobPath } from './storage.js'; +import { + type AttemptHandoffExtract, + type CasCandidateFile, + type CompiledPlan, + type ControllerAttempt, + type PlannedRole, +} from './types.js'; +import { isWritableCandidateFile, resolveCurrentFileModes } from './step.js'; + +export async function materializeAttemptWorkspace( + cycle: Cycle, + runRoot: string, + attemptId: string, + role: PlannedRole, + repair: ControllerAttempt['repair'], + hostProtection: HostPathProtectionOptions, + activeResources?: ReturnType, + handoffExtracts: readonly AttemptHandoffExtract[] = [], + phase: ControllerDiagnostic['phase'] = 'execution', +): Promise<{ readonly candidateDir: string; readonly contextFiles: readonly string[] }> { + const { context } = cycle; + const { plan, loaded, source, owner, artifacts } = context; + const state = approvedState(loaded); + const excluded = [context.descriptor.repository, ...state.input.untrustedRoots]; + const workspacesRoot = join(resolve(runRoot), 'workspaces'); + const runWorkspaceDir = join(workspacesRoot, context.lock.spec.runId); + const attemptWorkspaceDir = join(runWorkspaceDir, attemptId); + const stagingWorkspaceDir = join(runWorkspaceDir, `.stage-${attemptId}`); + const stagingCandidateDir = join(stagingWorkspaceDir, 'candidate'); + const stagingContextDir = join(stagingWorkspaceDir, 'context'); + const candidateDir = join(attemptWorkspaceDir, 'candidate'); + const contextDir = join(attemptWorkspaceDir, 'context'); + + await privateDirectory(workspacesRoot, excluded); + await privateDirectory(runWorkspaceDir, excluded); + await rm(stagingWorkspaceDir, { recursive: true, force: true }); + await privateDirectory(stagingWorkspaceDir, excluded); + await privateDirectory(stagingCandidateDir, excluded); + await privateDirectory(stagingContextDir, excluded); + + try { + const effectiveTools = repair === 'format' ? [] : role.policy.tools; + const readOnlyRole = repair === 'format' || !effectiveTools.some(tool => tool === 'write' || tool === 'edit' || tool === 'delete' || tool === 'bash'); + const modes = await resolveCurrentFileModes(context, cycle.head, cycle.candidate.files); + + if (source.version === 2) { + await materializeBaseline(source, stagingCandidateDir, owner, cycle.deadline); + await chmod(stagingCandidateDir, 0o700); + const deletedSet = new Set(cycle.candidate.manifest.spec.deleted ?? []); + for (const delPath of deletedSet) { + await rm(join(stagingCandidateDir, delPath), { force: true }); + } + for (const item of cycle.candidate.files) { + const targetPath = join(stagingCandidateDir, item.name); + await mkdir(dirname(targetPath), { recursive: true, mode: 0o700 }); + await rm(targetPath, { recursive: true, force: true }); + if ('bytes' in item) { + const file = await open(targetPath, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600); + try { + await file.writeFile(item.bytes); + await file.sync(); + } finally { + await file.close(); + } + } else { + const canonicalBlobPath = await resolveCanonicalCasBlobPath(artifacts.directory, item.digest.hex, item.blobPath, 'execution'); + await copyVerifiedFileReadOnly(canonicalBlobPath, targetPath, { + expectedBytes: item.byteLength, + expectedSha256: item.digest.hex, + mode: 0o600, + ownedSource: true, + requireReadOnlySource: true, + verifyCanonicalSource: true, + path: item.name, + phase: 'execution', + }); + } + } + const allPaths = new Set(); + for (const entry of source.baselineEntries ?? []) { + if (!deletedSet.has(entry.name)) allPaths.add(entry.name); + } + for (const file of cycle.candidate.files) allPaths.add(file.name); + for (const relPath of allPaths) { + const gitMode = modes.get(relPath) ?? '100644'; + const writable = !readOnlyRole && isWritableCandidateFile(relPath, plan.scope, hostProtection); + const perm = gitMode === '100755' ? (writable ? 0o700 : 0o500) : (writable ? 0o600 : 0o400); + await chmod(join(stagingCandidateDir, relPath), perm); + } + } else { + for (const item of cycle.candidate.files) { + const targetPath = join(stagingCandidateDir, item.name); + await mkdir(dirname(targetPath), { recursive: true, mode: 0o700 }); + const gitMode = modes.get(item.name) ?? '100644'; + const writable = !readOnlyRole && isWritableCandidateFile(item.name, plan.scope, hostProtection); + const perm = gitMode === '100755' ? (writable ? 0o700 : 0o500) : (writable ? 0o600 : 0o400); + if ('bytes' in item) { + const file = await open(targetPath, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, perm); + try { + await file.writeFile(item.bytes); + await file.chmod(perm); + await file.sync(); + } finally { + await file.close(); + } + } else { + const canonicalBlobPath = await resolveCanonicalCasBlobPath(artifacts.directory, item.digest.hex, item.blobPath, 'execution'); + await copyVerifiedFileReadOnly(canonicalBlobPath, targetPath, { + expectedBytes: item.byteLength, + expectedSha256: item.digest.hex, + mode: perm, + ownedSource: true, + requireReadOnlySource: true, + verifyCanonicalSource: true, + path: item.name, + phase: 'execution', + }); + } + } + } + + const effectiveResources = activeResources ?? roleResourcesFor(loaded, plan, role.roleId); + const stagedContextFiles = await materializeContextFilesDir( + stagingContextDir, + effectiveResources, + handoffExtracts, + artifacts.directory, + phase, + ); + + const backupWorkspaceDir = join(runWorkspaceDir, `.prev-${attemptId}`); + await rm(backupWorkspaceDir, { recursive: true, force: true }); + let movedPriorAside = false; + if (await lstat(attemptWorkspaceDir).then(() => true, () => false)) { + await rename(attemptWorkspaceDir, backupWorkspaceDir); + movedPriorAside = true; + } + try { + await rename(stagingWorkspaceDir, attemptWorkspaceDir); + } catch (renameError) { + if (movedPriorAside) { + await rename(backupWorkspaceDir, attemptWorkspaceDir).catch(() => undefined); + } + throw renameError; + } + if (movedPriorAside) { + await rm(backupWorkspaceDir, { recursive: true, force: true }).catch(() => undefined); + } + const contextFiles = stagedContextFiles.map(filePath => join(contextDir, relative(stagingContextDir, filePath))); + return { candidateDir, contextFiles }; + } catch (error) { + await rm(stagingWorkspaceDir, { recursive: true, force: true }).catch(() => undefined); + throw error; + } +} + +export async function scanCandidateDirectory( + candidateDir: string, + source: FrozenSource, + task: TaskContract, + previousDigest: Digest, + previousModes: ReadonlyMap, + disallowMutations: boolean, + overlayConfig: CompiledPlan['budgets']['overlay'], + artifacts: ArtifactStore, + hostProtection: HostPathProtectionOptions, +): Promise<{ + readonly manifest: ArtifactManifest; + readonly files: readonly CasCandidateFile[]; + readonly overlay: readonly DelegatedCaptureOverlayEntryV2[]; + readonly deleted: readonly string[]; +}> { + const bounds = overlayManifestBounds(overlayConfig); + const v2BaseTree = source.version === 2 ? source.manifest.spec.baseTree! : undefined; + const v2BaselineByPath = + source.version === 2 + ? new Map((source.baselineEntries ?? []).map(entry => [entry.name, entry])) + : undefined; + const v1BaselineByPath = + source.version === 1 + ? new Map( + source.artifacts.map(artifact => [ + artifact.name, + { byteLength: artifact.bytes.byteLength, mode: artifact.mode ?? ('100644' as const) }, + ]), + ) + : undefined; + let rootStat; + try { + rootStat = await lstat(candidateDir); + } catch { + refuse('ARTIFACT_INVALID', '', 'execution'); + } + if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) refuse('ARTIFACT_INVALID', '', 'execution'); + + interface ScannedRegularEntry { + readonly absPath: string; + readonly name: string; + readonly mode: '100644' | '100755'; + readonly byteLength: number; + readonly sha256: string; + readonly gitOid?: string | undefined; + } + + const scannedFiles: ScannedRegularEntry[] = []; + const seenPaths = new Set(); + const streamChunk = Buffer.allocUnsafe(STREAM_CHUNK_BYTES); + const probeByte = Buffer.allocUnsafe(1); + let entriesSeen = 0; + let knownOverlayFiles = 0; + let knownOverlayBytes = 0; + let knownClassicFiles = 0; + let knownClassicBytes = 0; + + const visit = async (absDir: string, relPrefix: string, depth: number): Promise => { + if (depth > 32) refuse('ARTIFACT_INVALID', '', 'execution'); + const dirEntries = await readdir(absDir, { withFileTypes: true }); + entriesSeen += dirEntries.length; + if (entriesSeen > 131_072) refuse('OUTPUT_LIMIT', '', 'execution'); + dirEntries.sort((a, b) => compareUtf16(a.name, b.name)); + for (const d of dirEntries) { + if (d.name.toLowerCase() === '.git' || Buffer.byteLength(d.name, 'utf8') > 255) refuse('ARTIFACT_INVALID', '', 'execution'); + const absPath = join(absDir, d.name); + const relPath = relPrefix ? `${relPrefix}/${d.name}` : d.name; + const st = await lstat(absPath); + if (st.isSymbolicLink()) refuse('ARTIFACT_INVALID', '', 'execution'); + if (st.isDirectory()) { + await visit(absPath, relPath, depth + 1); + continue; + } + if (!st.isFile() || st.nlink !== 1) refuse('ARTIFACT_INVALID', '', 'execution'); + if (!digestArtifact(relPath, new Uint8Array()).ok) refuse('ARTIFACT_INVALID', '', 'execution'); + + const fh = await open(absPath, constants.O_RDONLY | constants.O_NOFOLLOW); + let byteLength: number; + let mode: '100644' | '100755'; + let sha256: string; + let gitOid: string | undefined; + let sizeChangedOrAdded = false; + try { + const fst = await fh.stat(); + if (fst.dev !== st.dev || fst.ino !== st.ino || fst.nlink !== 1 || !fst.isFile() || fst.size !== st.size) { + refuse('ARTIFACT_INVALID', '', 'execution'); + } + if (source.version === 2) { + const baseEntry = v2BaselineByPath!.get(relPath); + sizeChangedOrAdded = baseEntry === undefined || baseEntry.byteLength !== fst.size; + if (sizeChangedOrAdded) { + if (isHostProtectedPath(relPath, hostProtection)) { + refuse('ARTIFACT_INVALID', '', 'execution'); + } + if ( + fst.size > bounds.perFileMaxBytes || + knownOverlayFiles + 1 > bounds.maxFiles || + knownOverlayBytes + fst.size > bounds.maxBytes + ) { + refuse('OUTPUT_LIMIT', '', 'execution'); + } + knownOverlayFiles += 1; + knownOverlayBytes += fst.size; + } + } else { + const baseEntry = v1BaselineByPath!.get(relPath); + const observedMode: '100644' | '100755' = (fst.mode & 0o111) !== 0 ? '100755' : '100644'; + if ( + (baseEntry === undefined || baseEntry.byteLength !== fst.size || baseEntry.mode !== observedMode) + && isHostProtectedPath(relPath, hostProtection) + ) { + refuse('ARTIFACT_INVALID', '', 'execution'); + } + if ( + fst.size > bounds.perFileMaxBytes || + knownClassicFiles + 1 > bounds.maxFiles || + knownClassicBytes + fst.size > bounds.maxBytes + ) { + refuse('OUTPUT_LIMIT', '', 'execution'); + } + knownClassicFiles += 1; + knownClassicBytes += fst.size; + } + const shaHasher = createHash('sha256'); + const gitHasher = + v2BaseTree !== undefined + ? createHash(v2BaseTree.objectFormat === 'sha256' ? 'sha256' : 'sha1').update(`blob ${fst.size}\0`, 'utf8') + : null; + let offset = 0; + while (offset < fst.size) { + const toRead = Math.min(streamChunk.length, fst.size - offset); + const { bytesRead } = await fh.read(streamChunk, 0, toRead, offset); + if (bytesRead <= 0) break; + const slice = streamChunk.subarray(0, bytesRead); + shaHasher.update(slice); + gitHasher?.update(slice); + offset += bytesRead; + } + const { bytesRead: extraBytes } = await fh.read(probeByte, 0, 1, offset); + const after = await fh.stat(); + if ( + extraBytes !== 0 || + offset !== fst.size || + after.dev !== fst.dev || + after.ino !== fst.ino || + after.nlink !== 1 || + !after.isFile() || + after.size !== fst.size || + after.mtimeMs !== fst.mtimeMs || + after.ctimeMs !== fst.ctimeMs + ) { + refuse('ARTIFACT_INVALID', '', 'execution'); + } + byteLength = fst.size; + mode = (fst.mode & 0o111) !== 0 ? '100755' : '100644'; + sha256 = shaHasher.digest('hex'); + gitOid = gitHasher?.digest('hex'); + } finally { + await fh.close(); + } + if (source.version === 2 && !sizeChangedOrAdded) { + const baseEntry = v2BaselineByPath!.get(relPath); + if (baseEntry !== undefined && gitOid !== baseEntry.oid) { + if (isHostProtectedPath(relPath, hostProtection)) { + refuse('ARTIFACT_INVALID', '', 'execution'); + } + if ( + byteLength > bounds.perFileMaxBytes || + knownOverlayFiles + 1 > bounds.maxFiles || + knownOverlayBytes + byteLength > bounds.maxBytes + ) { + refuse('OUTPUT_LIMIT', '', 'execution'); + } + knownOverlayFiles += 1; + knownOverlayBytes += byteLength; + } + } + seenPaths.add(relPath); + scannedFiles.push({ absPath, name: relPath, mode, byteLength, sha256, gitOid }); + } + }; + + await visit(candidateDir, '', 1); + scannedFiles.sort((a, b) => compareUtf16(a.name, b.name)); + + if (source.version === 2) { + const baseTree = v2BaseTree!; + const baselineByPath = v2BaselineByPath!; + const deleted: string[] = []; + for (const baseEntry of source.baselineEntries ?? []) { + if (!seenPaths.has(baseEntry.name)) { + if (isHostProtectedPath(baseEntry.name, hostProtection)) refuse('ARTIFACT_INVALID', '', 'execution'); + deleted.push(baseEntry.name); + } + } + deleted.sort(compareUtf16); + const overlay: DelegatedCaptureOverlayEntryV2[] = []; + const files: CasCandidateFile[] = []; + const manifestEntries: ArtifactRef[] = []; + let totalOverlayBytes = 0; + for (const file of scannedFiles) { + const baseEntry = baselineByPath.get(file.name); + const expectedMode = previousModes.get(file.name) ?? baseEntry?.mode ?? '100644'; + if (baseEntry && file.gitOid === baseEntry.oid) { + if (file.mode !== expectedMode) { + refuse('ARTIFACT_INVALID', '', 'execution'); + } + continue; + } + if (disallowMutations && file.mode !== expectedMode) { + refuse('ARTIFACT_INVALID', '', 'execution'); + } + const effectiveMode = disallowMutations ? expectedMode : file.mode; + if (isHostProtectedPath(file.name, hostProtection)) refuse('ARTIFACT_INVALID', '', 'execution'); + if ( + file.byteLength > bounds.perFileMaxBytes || + overlay.length >= bounds.maxFiles || + (totalOverlayBytes += file.byteLength) > bounds.maxBytes + ) { + refuse('OUTPUT_LIMIT', '', 'execution'); + } + const pointer = await artifacts.putCasBlobFromFile(file.name, file.absPath, bounds.perFileMaxBytes, { + gitObjectFormat: baseTree.objectFormat, + }); + if ( + pointer.sha256 !== file.sha256 + || pointer.byteLength !== file.byteLength + || (pointer.verifiedSeal !== undefined && file.gitOid !== undefined && pointer.verifiedSeal.gitOid !== file.gitOid) + ) { + refuse('ARTIFACT_INVALID', '', 'execution'); + } + const ref = digestArtifactFromMetadata(file.name, { + digest: { algorithm: 'sha256', hex: pointer.sha256 }, + byteLength: pointer.byteLength, + }); + if (!ref.ok) refuse('ARTIFACT_INVALID', '', 'execution'); + overlay.push({ + name: file.name, + mode: effectiveMode, + sha256: pointer.sha256, + byteLength: pointer.byteLength, + blobRef: pointer.blobRef, + }); + const casFile: CasCandidateFile = { + name: file.name, + byteLength: pointer.byteLength, + digest: ref.value.digest, + blobPath: pointer.path, + mode: effectiveMode, + }; + if (pointer.verifiedSeal !== undefined) { + attachVerifiedCasSeal(casFile, pointer.verifiedSeal); + } + files.push(casFile); + manifestEntries.push(ref.value); + } + const identified = identifyManifest( + canonicalizeCandidateManifest({ + apiVersion: 'loopwright.dev/v1alpha1', + kind: 'ArtifactManifest', + metadata: { id: 'candidate' }, + spec: { baseTree, entries: manifestEntries, deleted }, + }), + bounds.options, + ); + if (!identified.ok) refuse('ARTIFACT_INVALID', '', 'execution'); + if (disallowMutations && !same(identified.value.digest, previousDigest)) { + refuse('ARTIFACT_INVALID', '', 'execution'); + } + return { manifest: identified.value.manifest, files, overlay, deleted }; + } + + // source.version === 1 (classic mode) + if (scannedFiles.length > bounds.maxFiles) refuse('OUTPUT_LIMIT', '', 'execution'); + let totalBytes = 0; + const baselineByPath = new Map( + source.artifacts.map(item => [ + item.name, + { byteLength: item.bytes.byteLength, sha256: hash(item.bytes).hex, mode: item.mode ?? ('100644' as const) }, + ]), + ); + const scannedNames = new Set(scannedFiles.map(item => item.name)); + const deleted: string[] = []; + for (const baseName of baselineByPath.keys()) { + if (!scannedNames.has(baseName)) { + if (isHostProtectedPath(baseName, hostProtection)) refuse('ARTIFACT_INVALID', '', 'execution'); + deleted.push(baseName); + } + } + deleted.sort(compareUtf16); + const overlay: DelegatedCaptureOverlayEntryV2[] = []; + const files: CasCandidateFile[] = []; + const manifestEntries: ArtifactRef[] = []; + for (const file of scannedFiles) { + const baseInfo = baselineByPath.get(file.name); + const expectedMode = previousModes.get(file.name) ?? baseInfo?.mode ?? '100644'; + if (disallowMutations && file.mode !== expectedMode) { + refuse('ARTIFACT_INVALID', '', 'execution'); + } + const effectiveMode = disallowMutations ? expectedMode : file.mode; + const modeChangedFromBaseline = baseInfo !== undefined && baseInfo.mode !== effectiveMode; + const modifiedOrAdded = + baseInfo === undefined + || baseInfo.byteLength !== file.byteLength + || baseInfo.sha256 !== file.sha256 + || modeChangedFromBaseline; + if (modifiedOrAdded && isHostProtectedPath(file.name, hostProtection)) { + refuse('ARTIFACT_INVALID', '', 'execution'); + } + if (modeChangedFromBaseline) { + if (baseInfo.byteLength === file.byteLength && baseInfo.sha256 === file.sha256) { + refuse('ARTIFACT_INVALID', '', 'execution'); + } + const writable = isWritablePath(task, file.name); + if (!writable.ok || !writable.value) { + refuse('ARTIFACT_INVALID', '', 'execution'); + } + } + if (file.byteLength > bounds.perFileMaxBytes || (totalBytes += file.byteLength) > bounds.maxBytes) { + refuse('OUTPUT_LIMIT', '', 'execution'); + } + const pointer = !modifiedOrAdded + ? (await artifacts.tryReuseCasBlob(file.name, file.sha256, file.byteLength)) + ?? await artifacts.putCasBlobFromFile(file.name, file.absPath, bounds.perFileMaxBytes) + : await artifacts.putCasBlobFromFile(file.name, file.absPath, bounds.perFileMaxBytes); + if (pointer.sha256 !== file.sha256 || pointer.byteLength !== file.byteLength) { + refuse('ARTIFACT_INVALID', '', 'execution'); + } + const ref = digestArtifactFromMetadata(file.name, { + digest: { algorithm: 'sha256', hex: pointer.sha256 }, + byteLength: pointer.byteLength, + }); + if (!ref.ok) refuse('ARTIFACT_INVALID', '', 'execution'); + overlay.push({ + name: file.name, + mode: effectiveMode, + sha256: pointer.sha256, + byteLength: pointer.byteLength, + blobRef: pointer.blobRef, + }); + files.push({ + name: file.name, + byteLength: pointer.byteLength, + digest: ref.value.digest, + blobPath: pointer.path, + mode: effectiveMode, + }); + manifestEntries.push(ref.value); + } + const identified = identifyManifest( + canonicalizeCandidateManifest({ + apiVersion: 'loopwright.dev/v1alpha1', + kind: 'ArtifactManifest', + metadata: { id: 'candidate' }, + spec: { entries: manifestEntries }, + }), + bounds.options, + ); + if (!identified.ok) refuse('ARTIFACT_INVALID', '', 'execution'); + if (disallowMutations && !same(identified.value.digest, previousDigest)) { + refuse('ARTIFACT_INVALID', '', 'execution'); + } + return { manifest: identified.value.manifest, files, overlay, deleted }; +} diff --git a/packages/controller/src/step.ts b/packages/controller/src/step.ts index c64a9d7c..fc83df06 100644 --- a/packages/controller/src/step.ts +++ b/packages/controller/src/step.ts @@ -1,16 +1,17 @@ import { constants } from 'node:fs'; -import { chmod, lstat, mkdir, open, readdir, realpath, rename, rm, unlink } from 'node:fs/promises'; -import { basename, dirname, join, relative, resolve } from 'node:path'; -import { createHash, randomBytes, timingSafeEqual } from 'node:crypto'; -import { LIMITS, bindSubject, digestArtifact, digestArtifactFromMetadata, identifyManifest, isWritablePath, type ArtifactManifest, type ArtifactRef, type Digest, type TaskContract } from '@loopwright/core'; +import { lstat, open, readdir, realpath, rename, rm, unlink } from 'node:fs/promises'; +import { basename, dirname, join, resolve } from 'node:path'; +import { randomBytes, timingSafeEqual } from 'node:crypto'; +import { LIMITS, bindSubject, identifyManifest } from '@loopwright/core'; import { reopenLocalRun, type Authority, type LocalRunStore } from '@loopwright/state'; import { approvedState } from './config.js'; +import { materializeAttemptWorkspace, scanCandidateDirectory } from './candidate-workspace.js'; import { compilePlan } from './compile.js'; import { ControllerFailure, refuse, result, safeDiagnostic, type ControllerDiagnostic } from './errors.js'; -import { copyVerifiedFileReadOnly, inside, readBoundedFile, STREAM_CHUNK_BYTES } from './files.js'; +import { inside, readBoundedFile } from './files.js'; import { parsePrivateJson } from './parser.js'; import { canonical, freeze, hash, id, integer, isRecord, list, record, same, text } from './schema.js'; -import { ArtifactStore, privateDirectory, resolveCanonicalCasBlobPath, stateValue } from './storage.js'; +import { ArtifactStore, privateDirectory, stateValue } from './storage.js'; import { ControllerOwner } from './ownership.js'; import { admitRetainedRun, @@ -28,20 +29,15 @@ import { adoptDelegatedCapture, captureDelegatedRole, nativeSessionId, - type DelegatedCaptureOverlayEntryV2, type DelegatedCapturePayloadV2, } from './capture.js'; import { assertCanonicalMinimalOverlay, - attachVerifiedCasSeal, canonicalizeCandidateManifest, - compareUtf16, isHostProtectedPath, matchesScopePattern, - materializeBaseline, overlayManifestBounds, restoreSource, - type FrozenSource, type HostPathProtectionOptions, } from './source.js'; import { isVerdictStep, normalizeSubmission, validateStepVerdictObject, type RetainedSubmission, type Submission } from './submission.js'; @@ -55,12 +51,10 @@ import { formatPolicy, reworkPrompt } from './repair.js'; import { countDelegatedBudgets, observeParentExhaustion, storeFactsCertain, refuseFromRoleOutcome } from './budget-observations.js'; import { validateGateUrlOverrides } from './gate.js'; import { appendHandoffPromptBlock, materializeContextFilesDir } from './handoff.js'; -import { createCycle, Cycle, normalizeWatchedPaths, roleResourcesFor, type ControllerPorts, type CycleContext } from './controller.js'; +import { createCycle, Cycle, normalizeWatchedPaths, type ControllerPorts, type CycleContext } from './controller.js'; import { incident, type ControllerIncident } from './finalize.js'; import { CONTROLLER_LIMITS, - type AttemptHandoffExtract, - type CasCandidateFile, type CompiledPlan, type ControllerAttempt, type ControllerPolicyProfile, @@ -131,7 +125,7 @@ interface StepLeaseRecord { readonly contextFiles: readonly string[]; } -function isWritableCandidateFile( +export function isWritableCandidateFile( name: string, scope: CompiledPlan['scope'], hostProtection: HostPathProtectionOptions, @@ -330,7 +324,7 @@ async function cleanupRunWorkspaces( } } -async function resolveCurrentFileModes( +export async function resolveCurrentFileModes( context: CycleContext, head: ProgressHead | null, candidateFiles?: readonly { readonly name: string; readonly mode?: '100644' | '100755' | undefined }[], @@ -384,153 +378,6 @@ async function resolveCurrentFileModes( return modes; } -async function materializeAttemptWorkspace( - cycle: Cycle, - runRoot: string, - attemptId: string, - role: PlannedRole, - repair: ControllerAttempt['repair'], - hostProtection: HostPathProtectionOptions, - activeResources?: ReturnType, - handoffExtracts: readonly AttemptHandoffExtract[] = [], - phase: ControllerDiagnostic['phase'] = 'execution', -): Promise<{ readonly candidateDir: string; readonly contextFiles: readonly string[] }> { - const { context } = cycle; - const { plan, loaded, source, owner, artifacts } = context; - const state = approvedState(loaded); - const excluded = [context.descriptor.repository, ...state.input.untrustedRoots]; - const workspacesRoot = join(resolve(runRoot), 'workspaces'); - const runWorkspaceDir = join(workspacesRoot, context.lock.spec.runId); - const attemptWorkspaceDir = join(runWorkspaceDir, attemptId); - const stagingWorkspaceDir = join(runWorkspaceDir, `.stage-${attemptId}`); - const stagingCandidateDir = join(stagingWorkspaceDir, 'candidate'); - const stagingContextDir = join(stagingWorkspaceDir, 'context'); - const candidateDir = join(attemptWorkspaceDir, 'candidate'); - const contextDir = join(attemptWorkspaceDir, 'context'); - - await privateDirectory(workspacesRoot, excluded); - await privateDirectory(runWorkspaceDir, excluded); - await rm(stagingWorkspaceDir, { recursive: true, force: true }); - await privateDirectory(stagingWorkspaceDir, excluded); - await privateDirectory(stagingCandidateDir, excluded); - await privateDirectory(stagingContextDir, excluded); - - try { - const effectiveTools = repair === 'format' ? [] : role.policy.tools; - const readOnlyRole = repair === 'format' || !effectiveTools.some(tool => tool === 'write' || tool === 'edit' || tool === 'delete' || tool === 'bash'); - const modes = await resolveCurrentFileModes(context, cycle.head, cycle.candidate.files); - - if (source.version === 2) { - await materializeBaseline(source, stagingCandidateDir, owner, cycle.deadline); - await chmod(stagingCandidateDir, 0o700); - const deletedSet = new Set(cycle.candidate.manifest.spec.deleted ?? []); - for (const delPath of deletedSet) { - await rm(join(stagingCandidateDir, delPath), { force: true }); - } - for (const item of cycle.candidate.files) { - const targetPath = join(stagingCandidateDir, item.name); - await mkdir(dirname(targetPath), { recursive: true, mode: 0o700 }); - await rm(targetPath, { recursive: true, force: true }); - if ('bytes' in item) { - const file = await open(targetPath, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600); - try { - await file.writeFile(item.bytes); - await file.sync(); - } finally { - await file.close(); - } - } else { - const canonicalBlobPath = await resolveCanonicalCasBlobPath(artifacts.directory, item.digest.hex, item.blobPath, 'execution'); - await copyVerifiedFileReadOnly(canonicalBlobPath, targetPath, { - expectedBytes: item.byteLength, - expectedSha256: item.digest.hex, - mode: 0o600, - ownedSource: true, - requireReadOnlySource: true, - verifyCanonicalSource: true, - path: item.name, - phase: 'execution', - }); - } - } - const allPaths = new Set(); - for (const entry of source.baselineEntries ?? []) { - if (!deletedSet.has(entry.name)) allPaths.add(entry.name); - } - for (const file of cycle.candidate.files) allPaths.add(file.name); - for (const relPath of allPaths) { - const gitMode = modes.get(relPath) ?? '100644'; - const writable = !readOnlyRole && isWritableCandidateFile(relPath, plan.scope, hostProtection); - const perm = gitMode === '100755' ? (writable ? 0o700 : 0o500) : (writable ? 0o600 : 0o400); - await chmod(join(stagingCandidateDir, relPath), perm); - } - } else { - for (const item of cycle.candidate.files) { - const targetPath = join(stagingCandidateDir, item.name); - await mkdir(dirname(targetPath), { recursive: true, mode: 0o700 }); - const gitMode = modes.get(item.name) ?? '100644'; - const writable = !readOnlyRole && isWritableCandidateFile(item.name, plan.scope, hostProtection); - const perm = gitMode === '100755' ? (writable ? 0o700 : 0o500) : (writable ? 0o600 : 0o400); - if ('bytes' in item) { - const file = await open(targetPath, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, perm); - try { - await file.writeFile(item.bytes); - await file.chmod(perm); - await file.sync(); - } finally { - await file.close(); - } - } else { - const canonicalBlobPath = await resolveCanonicalCasBlobPath(artifacts.directory, item.digest.hex, item.blobPath, 'execution'); - await copyVerifiedFileReadOnly(canonicalBlobPath, targetPath, { - expectedBytes: item.byteLength, - expectedSha256: item.digest.hex, - mode: perm, - ownedSource: true, - requireReadOnlySource: true, - verifyCanonicalSource: true, - path: item.name, - phase: 'execution', - }); - } - } - } - - const effectiveResources = activeResources ?? roleResourcesFor(loaded, plan, role.roleId); - const stagedContextFiles = await materializeContextFilesDir( - stagingContextDir, - effectiveResources, - handoffExtracts, - artifacts.directory, - phase, - ); - - const backupWorkspaceDir = join(runWorkspaceDir, `.prev-${attemptId}`); - await rm(backupWorkspaceDir, { recursive: true, force: true }); - let movedPriorAside = false; - if (await lstat(attemptWorkspaceDir).then(() => true, () => false)) { - await rename(attemptWorkspaceDir, backupWorkspaceDir); - movedPriorAside = true; - } - try { - await rename(stagingWorkspaceDir, attemptWorkspaceDir); - } catch (renameError) { - if (movedPriorAside) { - await rename(backupWorkspaceDir, attemptWorkspaceDir).catch(() => undefined); - } - throw renameError; - } - if (movedPriorAside) { - await rm(backupWorkspaceDir, { recursive: true, force: true }).catch(() => undefined); - } - const contextFiles = stagedContextFiles.map(filePath => join(contextDir, relative(stagingContextDir, filePath))); - return { candidateDir, contextFiles }; - } catch (error) { - await rm(stagingWorkspaceDir, { recursive: true, force: true }).catch(() => undefined); - throw error; - } -} - async function buildStepYield( cycle: Cycle, runRoot: string, @@ -1245,372 +1092,6 @@ async function settleForcedStepRun( return settled; } -async function scanCandidateDirectory( - candidateDir: string, - source: FrozenSource, - task: TaskContract, - previousDigest: Digest, - previousModes: ReadonlyMap, - disallowMutations: boolean, - overlayConfig: CompiledPlan['budgets']['overlay'], - artifacts: ArtifactStore, - hostProtection: HostPathProtectionOptions, -): Promise<{ - readonly manifest: ArtifactManifest; - readonly files: readonly CasCandidateFile[]; - readonly overlay: readonly DelegatedCaptureOverlayEntryV2[]; - readonly deleted: readonly string[]; -}> { - const bounds = overlayManifestBounds(overlayConfig); - const v2BaseTree = source.version === 2 ? source.manifest.spec.baseTree! : undefined; - const v2BaselineByPath = - source.version === 2 - ? new Map((source.baselineEntries ?? []).map(entry => [entry.name, entry])) - : undefined; - const v1BaselineByPath = - source.version === 1 - ? new Map( - source.artifacts.map(artifact => [ - artifact.name, - { byteLength: artifact.bytes.byteLength, mode: artifact.mode ?? ('100644' as const) }, - ]), - ) - : undefined; - let rootStat; - try { - rootStat = await lstat(candidateDir); - } catch { - refuse('ARTIFACT_INVALID', '', 'execution'); - } - if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) refuse('ARTIFACT_INVALID', '', 'execution'); - - interface ScannedRegularEntry { - readonly absPath: string; - readonly name: string; - readonly mode: '100644' | '100755'; - readonly byteLength: number; - readonly sha256: string; - readonly gitOid?: string | undefined; - } - - const scannedFiles: ScannedRegularEntry[] = []; - const seenPaths = new Set(); - const streamChunk = Buffer.allocUnsafe(STREAM_CHUNK_BYTES); - const probeByte = Buffer.allocUnsafe(1); - let entriesSeen = 0; - let knownOverlayFiles = 0; - let knownOverlayBytes = 0; - let knownClassicFiles = 0; - let knownClassicBytes = 0; - - const visit = async (absDir: string, relPrefix: string, depth: number): Promise => { - if (depth > 32) refuse('ARTIFACT_INVALID', '', 'execution'); - const dirEntries = await readdir(absDir, { withFileTypes: true }); - entriesSeen += dirEntries.length; - if (entriesSeen > 131_072) refuse('OUTPUT_LIMIT', '', 'execution'); - dirEntries.sort((a, b) => compareUtf16(a.name, b.name)); - for (const d of dirEntries) { - if (d.name.toLowerCase() === '.git' || Buffer.byteLength(d.name, 'utf8') > 255) refuse('ARTIFACT_INVALID', '', 'execution'); - const absPath = join(absDir, d.name); - const relPath = relPrefix ? `${relPrefix}/${d.name}` : d.name; - const st = await lstat(absPath); - if (st.isSymbolicLink()) refuse('ARTIFACT_INVALID', '', 'execution'); - if (st.isDirectory()) { - await visit(absPath, relPath, depth + 1); - continue; - } - if (!st.isFile() || st.nlink !== 1) refuse('ARTIFACT_INVALID', '', 'execution'); - if (!digestArtifact(relPath, new Uint8Array()).ok) refuse('ARTIFACT_INVALID', '', 'execution'); - - const fh = await open(absPath, constants.O_RDONLY | constants.O_NOFOLLOW); - let byteLength: number; - let mode: '100644' | '100755'; - let sha256: string; - let gitOid: string | undefined; - let sizeChangedOrAdded = false; - try { - const fst = await fh.stat(); - if (fst.dev !== st.dev || fst.ino !== st.ino || fst.nlink !== 1 || !fst.isFile() || fst.size !== st.size) { - refuse('ARTIFACT_INVALID', '', 'execution'); - } - if (source.version === 2) { - const baseEntry = v2BaselineByPath!.get(relPath); - sizeChangedOrAdded = baseEntry === undefined || baseEntry.byteLength !== fst.size; - if (sizeChangedOrAdded) { - if (isHostProtectedPath(relPath, hostProtection)) { - refuse('ARTIFACT_INVALID', '', 'execution'); - } - if ( - fst.size > bounds.perFileMaxBytes || - knownOverlayFiles + 1 > bounds.maxFiles || - knownOverlayBytes + fst.size > bounds.maxBytes - ) { - refuse('OUTPUT_LIMIT', '', 'execution'); - } - knownOverlayFiles += 1; - knownOverlayBytes += fst.size; - } - } else { - const baseEntry = v1BaselineByPath!.get(relPath); - const observedMode: '100644' | '100755' = (fst.mode & 0o111) !== 0 ? '100755' : '100644'; - if ( - (baseEntry === undefined || baseEntry.byteLength !== fst.size || baseEntry.mode !== observedMode) - && isHostProtectedPath(relPath, hostProtection) - ) { - refuse('ARTIFACT_INVALID', '', 'execution'); - } - if ( - fst.size > bounds.perFileMaxBytes || - knownClassicFiles + 1 > bounds.maxFiles || - knownClassicBytes + fst.size > bounds.maxBytes - ) { - refuse('OUTPUT_LIMIT', '', 'execution'); - } - knownClassicFiles += 1; - knownClassicBytes += fst.size; - } - const shaHasher = createHash('sha256'); - const gitHasher = - v2BaseTree !== undefined - ? createHash(v2BaseTree.objectFormat === 'sha256' ? 'sha256' : 'sha1').update(`blob ${fst.size}\0`, 'utf8') - : null; - let offset = 0; - while (offset < fst.size) { - const toRead = Math.min(streamChunk.length, fst.size - offset); - const { bytesRead } = await fh.read(streamChunk, 0, toRead, offset); - if (bytesRead <= 0) break; - const slice = streamChunk.subarray(0, bytesRead); - shaHasher.update(slice); - gitHasher?.update(slice); - offset += bytesRead; - } - const { bytesRead: extraBytes } = await fh.read(probeByte, 0, 1, offset); - const after = await fh.stat(); - if ( - extraBytes !== 0 || - offset !== fst.size || - after.dev !== fst.dev || - after.ino !== fst.ino || - after.nlink !== 1 || - !after.isFile() || - after.size !== fst.size || - after.mtimeMs !== fst.mtimeMs || - after.ctimeMs !== fst.ctimeMs - ) { - refuse('ARTIFACT_INVALID', '', 'execution'); - } - byteLength = fst.size; - mode = (fst.mode & 0o111) !== 0 ? '100755' : '100644'; - sha256 = shaHasher.digest('hex'); - gitOid = gitHasher?.digest('hex'); - } finally { - await fh.close(); - } - if (source.version === 2 && !sizeChangedOrAdded) { - const baseEntry = v2BaselineByPath!.get(relPath); - if (baseEntry !== undefined && gitOid !== baseEntry.oid) { - if (isHostProtectedPath(relPath, hostProtection)) { - refuse('ARTIFACT_INVALID', '', 'execution'); - } - if ( - byteLength > bounds.perFileMaxBytes || - knownOverlayFiles + 1 > bounds.maxFiles || - knownOverlayBytes + byteLength > bounds.maxBytes - ) { - refuse('OUTPUT_LIMIT', '', 'execution'); - } - knownOverlayFiles += 1; - knownOverlayBytes += byteLength; - } - } - seenPaths.add(relPath); - scannedFiles.push({ absPath, name: relPath, mode, byteLength, sha256, gitOid }); - } - }; - - await visit(candidateDir, '', 1); - scannedFiles.sort((a, b) => compareUtf16(a.name, b.name)); - - if (source.version === 2) { - const baseTree = v2BaseTree!; - const baselineByPath = v2BaselineByPath!; - const deleted: string[] = []; - for (const baseEntry of source.baselineEntries ?? []) { - if (!seenPaths.has(baseEntry.name)) { - if (isHostProtectedPath(baseEntry.name, hostProtection)) refuse('ARTIFACT_INVALID', '', 'execution'); - deleted.push(baseEntry.name); - } - } - deleted.sort(compareUtf16); - const overlay: DelegatedCaptureOverlayEntryV2[] = []; - const files: CasCandidateFile[] = []; - const manifestEntries: ArtifactRef[] = []; - let totalOverlayBytes = 0; - for (const file of scannedFiles) { - const baseEntry = baselineByPath.get(file.name); - const expectedMode = previousModes.get(file.name) ?? baseEntry?.mode ?? '100644'; - if (baseEntry && file.gitOid === baseEntry.oid) { - if (file.mode !== expectedMode) { - refuse('ARTIFACT_INVALID', '', 'execution'); - } - continue; - } - if (disallowMutations && file.mode !== expectedMode) { - refuse('ARTIFACT_INVALID', '', 'execution'); - } - const effectiveMode = disallowMutations ? expectedMode : file.mode; - if (isHostProtectedPath(file.name, hostProtection)) refuse('ARTIFACT_INVALID', '', 'execution'); - if ( - file.byteLength > bounds.perFileMaxBytes || - overlay.length >= bounds.maxFiles || - (totalOverlayBytes += file.byteLength) > bounds.maxBytes - ) { - refuse('OUTPUT_LIMIT', '', 'execution'); - } - const pointer = await artifacts.putCasBlobFromFile(file.name, file.absPath, bounds.perFileMaxBytes, { - gitObjectFormat: baseTree.objectFormat, - }); - if ( - pointer.sha256 !== file.sha256 - || pointer.byteLength !== file.byteLength - || (pointer.verifiedSeal !== undefined && file.gitOid !== undefined && pointer.verifiedSeal.gitOid !== file.gitOid) - ) { - refuse('ARTIFACT_INVALID', '', 'execution'); - } - const ref = digestArtifactFromMetadata(file.name, { - digest: { algorithm: 'sha256', hex: pointer.sha256 }, - byteLength: pointer.byteLength, - }); - if (!ref.ok) refuse('ARTIFACT_INVALID', '', 'execution'); - overlay.push({ - name: file.name, - mode: effectiveMode, - sha256: pointer.sha256, - byteLength: pointer.byteLength, - blobRef: pointer.blobRef, - }); - const casFile: CasCandidateFile = { - name: file.name, - byteLength: pointer.byteLength, - digest: ref.value.digest, - blobPath: pointer.path, - mode: effectiveMode, - }; - if (pointer.verifiedSeal !== undefined) { - attachVerifiedCasSeal(casFile, pointer.verifiedSeal); - } - files.push(casFile); - manifestEntries.push(ref.value); - } - const identified = identifyManifest( - canonicalizeCandidateManifest({ - apiVersion: 'loopwright.dev/v1alpha1', - kind: 'ArtifactManifest', - metadata: { id: 'candidate' }, - spec: { baseTree, entries: manifestEntries, deleted }, - }), - bounds.options, - ); - if (!identified.ok) refuse('ARTIFACT_INVALID', '', 'execution'); - if (disallowMutations && !same(identified.value.digest, previousDigest)) { - refuse('ARTIFACT_INVALID', '', 'execution'); - } - return { manifest: identified.value.manifest, files, overlay, deleted }; - } - - // source.version === 1 (classic mode) - if (scannedFiles.length > bounds.maxFiles) refuse('OUTPUT_LIMIT', '', 'execution'); - let totalBytes = 0; - const baselineByPath = new Map( - source.artifacts.map(item => [ - item.name, - { byteLength: item.bytes.byteLength, sha256: hash(item.bytes).hex, mode: item.mode ?? ('100644' as const) }, - ]), - ); - const scannedNames = new Set(scannedFiles.map(item => item.name)); - const deleted: string[] = []; - for (const baseName of baselineByPath.keys()) { - if (!scannedNames.has(baseName)) { - if (isHostProtectedPath(baseName, hostProtection)) refuse('ARTIFACT_INVALID', '', 'execution'); - deleted.push(baseName); - } - } - deleted.sort(compareUtf16); - const overlay: DelegatedCaptureOverlayEntryV2[] = []; - const files: CasCandidateFile[] = []; - const manifestEntries: ArtifactRef[] = []; - for (const file of scannedFiles) { - const baseInfo = baselineByPath.get(file.name); - const expectedMode = previousModes.get(file.name) ?? baseInfo?.mode ?? '100644'; - if (disallowMutations && file.mode !== expectedMode) { - refuse('ARTIFACT_INVALID', '', 'execution'); - } - const effectiveMode = disallowMutations ? expectedMode : file.mode; - const modeChangedFromBaseline = baseInfo !== undefined && baseInfo.mode !== effectiveMode; - const modifiedOrAdded = - baseInfo === undefined - || baseInfo.byteLength !== file.byteLength - || baseInfo.sha256 !== file.sha256 - || modeChangedFromBaseline; - if (modifiedOrAdded && isHostProtectedPath(file.name, hostProtection)) { - refuse('ARTIFACT_INVALID', '', 'execution'); - } - if (modeChangedFromBaseline) { - if (baseInfo.byteLength === file.byteLength && baseInfo.sha256 === file.sha256) { - refuse('ARTIFACT_INVALID', '', 'execution'); - } - const writable = isWritablePath(task, file.name); - if (!writable.ok || !writable.value) { - refuse('ARTIFACT_INVALID', '', 'execution'); - } - } - if (file.byteLength > bounds.perFileMaxBytes || (totalBytes += file.byteLength) > bounds.maxBytes) { - refuse('OUTPUT_LIMIT', '', 'execution'); - } - const pointer = !modifiedOrAdded - ? (await artifacts.tryReuseCasBlob(file.name, file.sha256, file.byteLength)) - ?? await artifacts.putCasBlobFromFile(file.name, file.absPath, bounds.perFileMaxBytes) - : await artifacts.putCasBlobFromFile(file.name, file.absPath, bounds.perFileMaxBytes); - if (pointer.sha256 !== file.sha256 || pointer.byteLength !== file.byteLength) { - refuse('ARTIFACT_INVALID', '', 'execution'); - } - const ref = digestArtifactFromMetadata(file.name, { - digest: { algorithm: 'sha256', hex: pointer.sha256 }, - byteLength: pointer.byteLength, - }); - if (!ref.ok) refuse('ARTIFACT_INVALID', '', 'execution'); - overlay.push({ - name: file.name, - mode: effectiveMode, - sha256: pointer.sha256, - byteLength: pointer.byteLength, - blobRef: pointer.blobRef, - }); - files.push({ - name: file.name, - byteLength: pointer.byteLength, - digest: ref.value.digest, - blobPath: pointer.path, - mode: effectiveMode, - }); - manifestEntries.push(ref.value); - } - const identified = identifyManifest( - canonicalizeCandidateManifest({ - apiVersion: 'loopwright.dev/v1alpha1', - kind: 'ArtifactManifest', - metadata: { id: 'candidate' }, - spec: { entries: manifestEntries }, - }), - bounds.options, - ); - if (!identified.ok) refuse('ARTIFACT_INVALID', '', 'execution'); - if (disallowMutations && !same(identified.value.digest, previousDigest)) { - refuse('ARTIFACT_INVALID', '', 'execution'); - } - return { manifest: identified.value.manifest, files, overlay, deleted }; -} - async function readExplicitSubmissionFile(path: string): Promise { const rawTarget = resolve(text(path, '/submissionFile', 4096)); let target: string; diff --git a/specs/2026-11-30-managed-controller-in-process-execution.md b/specs/2026-11-30-managed-controller-in-process-execution.md index 8dcc08f6..5a2118ab 100644 --- a/specs/2026-11-30-managed-controller-in-process-execution.md +++ b/specs/2026-11-30-managed-controller-in-process-execution.md @@ -527,7 +527,7 @@ export interface LocalCheckOutcome { Phase 1 is T1 to T8 and ships what the first consumer needs. Phase 2 is T9 to T12. T1, T2, T9, and T11 have disjoint `Owns:` and start together; T5 follows T2. -- [ ] **T1 · Prefactor: shared candidate workspace helpers** +- [x] **T1 · Prefactor: shared candidate workspace helpers** Blocked by: None Owns: `packages/controller/src/candidate-workspace.ts`, `packages/controller/src/step.ts`, `packages/controller/test/step-engine.test.ts` Gate: review From b5d4ff16c8102257a16bbff0c813c1e9275e4619 Mon Sep 17 00:00:00 2001 From: thxCode Date: Tue, 1 Dec 2026 08:29:57 +0800 Subject: [PATCH 09/26] feat(controller): add the exec role runner with an allowlisted child environment - runExecRole spawns the command in its own process group - allowlist-only environment; credentials via SecretResolver, never process.env - bounded scrubbed capture; exit 0/3/other/timeout/cancel mapping with group kill - optional usage file parse with exact refusal codes - T5 spec check-off; F2 list separators recorded Task 5 of managed-controller-in-process-execution. Signed-off-by: thxCode --- packages/controller/src/exec-role.ts | 277 ++++++++++++++++++ .../controller/test/exec-role-fixtures.ts | 50 ++++ packages/controller/test/exec-role.test.ts | 184 ++++++++++++ ...managed-controller-in-process-execution.md | 4 +- 4 files changed, 513 insertions(+), 2 deletions(-) create mode 100644 packages/controller/src/exec-role.ts create mode 100644 packages/controller/test/exec-role-fixtures.ts create mode 100644 packages/controller/test/exec-role.test.ts diff --git a/packages/controller/src/exec-role.ts b/packages/controller/src/exec-role.ts new file mode 100644 index 00000000..5626afa2 --- /dev/null +++ b/packages/controller/src/exec-role.ts @@ -0,0 +1,277 @@ +import { spawn } from 'node:child_process'; +import { constants } from 'node:fs'; +import { lstat, open } from 'node:fs/promises'; +import { isAbsolute } from 'node:path'; +import { EXEC_LIMITS, LIMITS, SecretScrubber } from '@loopwright/core'; +import { ControllerFailure, refuse, type ControllerDiagnostic } from './errors.js'; +import { inside } from './files.js'; +import { parseDocumentBytes } from './parser.js'; +import { id, integer, list, record } from './schema.js'; +import type { CredentialBinding, ExecProfileCommand } from './types.js'; + +/** The two vault operations the exec runner needs. The controller's `process.env` is never read or passed. */ +export interface SecretResolver { + /** Expanded template value of the `consumer: exec` binding `ref`; refuses when `ref` names no such binding. */ + readonly resolveExecCredential: (ref: string) => string; + /** Vault assertion over every captured byte: refuses with `CONFIG_CREDENTIAL_INVALID` when any vault secret appears. */ + readonly assertClean: (value: Uint8Array | string | object) => void; +} + +/** One agent step handed to the exec runner: the validated profile `exec` block, the role's tools, and the bound credentials. */ +export interface ExecRoleSpec { + readonly exec: ExecProfileCommand; + /** Advisory for the child (`LOOPWRIGHT_ALLOWED_TOOLS`); the controller re-validates the overlay. */ + readonly tools: readonly string[]; + /** The `credentialRefs` of `exec`, resolved to their registry bindings. */ + readonly credentials: readonly CredentialBinding[]; +} + +export interface ExecRoleContext { + readonly runId: string; + readonly stepId: string; + readonly roleId: string; + readonly attemptId: string; + /** `scope.writable` globs, exported colon-separated as `LOOPWRIGHT_SCOPE_WRITABLE`. */ + readonly scopeWritable: readonly string[]; + /** Absolute paths of the attempt's read-only context files, exported colon-separated as `LOOPWRIGHT_CONTEXT_FILES`. */ + readonly contextFiles: readonly string[]; + /** The attempt scratch directory: `HOME`, `TMPDIR`, and the parent of `usageOut`. */ + readonly scratchDir: string; + /** Absolute path of the prompt file: argv[len-2]. */ + readonly promptFile: string; + /** Absolute path of the attempt candidate directory: `cwd` and argv[len-1]. */ + readonly candidateDir: string; + /** Absolute path of the usage file (`LOOPWRIGHT_USAGE_OUT`); must lie inside `scratchDir`. */ + readonly usageOut: string; + readonly secrets: SecretResolver; + /** Abort kills the process group and refuses `CANCELLED`. */ + readonly signal: AbortSignal; + /** Called with the child's process group right after the spawn, so the controller records it before execution proceeds; when it throws, the group is killed and the error rethrown. */ + readonly onSpawned?: ((pgid: number) => Promise) | undefined; +} + +/** One request from the usage file; T7 wraps it as `RequestUsage` with `provenance: 'reported'`. */ +export interface ExecUsageRequest { + readonly requestId: string; + readonly inputTokens: number; + readonly outputTokens: number; + readonly costMicrousd: number; +} + +export interface ExecRoleOutcome { + readonly status: 'completed' | 'blocked' | 'failed'; + /** `null` for `completed`; for `blocked` the last non-empty stderr line (or `exec_blocked`); otherwise `exec_exit_`, `exec_signal_`, or `exec_timeout`. */ + readonly reason: string | null; + readonly exitCode: number | null; + readonly exitSignal: NodeJS.Signals | null; + readonly timedOut: boolean; + /** The child's process group id (`detached: true`: equals the child pid). */ + readonly pgid: number; + /** Scrubbed, then asserted clean against the vault. */ + readonly stdout: string; + readonly stderr: string; + readonly stdoutTruncated: boolean; + readonly stderrTruncated: boolean; + /** Empty when the child was killed: a half-written usage file is not read. */ + readonly usage: readonly ExecUsageRequest[]; +} + +const ALLOWLIST = Object.freeze({ PATH: '/usr/local/bin:/usr/bin:/bin', LANG: 'C.UTF-8', LC_ALL: 'C.UTF-8', TERM: 'dumb' } as const); +const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/; +const ENV_ENTRIES_MAX = 32; +/** Above the largest legitimate file (1024 requests × ≈150 bytes) and far below `DOCUMENT_BYTES`. */ +const USAGE_FILE_MAX_BYTES = 262_144; +/** `reason()` in submission.ts bounds the synthesized submission's reason. */ +const REASON_MAX_CHARS = 4_096; +const GROUP_EXIT_WAIT_MS = 2_000; +const GROUP_POLL_MS = 15; + +function refusing(code: ControllerDiagnostic['code'], path: string, work: () => T): T { + try { return work(); } catch (error) { if (error instanceof ControllerFailure) refuse(code, path, 'execution'); throw error; } +} +function bounded(value: unknown, min: number, max: number, path: string): number { + if (!Number.isSafeInteger(value) || Object.is(value, -0) || (value as number) < min || (value as number) > max) refuse('CONFIG_SCHEMA', path, 'execution'); + return value as number; +} +function absolutePath(value: string, path: string): string { + if (!isAbsolute(value) || /[\0\r\n]/.test(value)) refuse('CONFIG_SCHEMA', path, 'execution'); + return value; +} + +/** The allowlisted environment: fixed entries, the scratch directory, the configured `env`, one variable per bound credential name, then the contract. */ +function environment(spec: ExecRoleSpec, context: ExecRoleContext, scrubber: SecretScrubber): Record { + const env: Record = Object.create(null) as Record; + const claimed = new Set(); + for (const [name, value] of Object.entries(ALLOWLIST)) { claimed.add(name); env[name] = value; } + claimed.add('HOME'); claimed.add('TMPDIR'); env['HOME'] = context.scratchDir; env['TMPDIR'] = context.scratchDir; + // User-supplied names never shadow an allowlisted entry, a contract entry, or each other. + const claim = (name: string, path: string): void => { + if (!ENV_NAME.test(name) || name.length > 64 || claimed.has(name) || name.startsWith('LOOPWRIGHT_')) refuse('CONFIG_SCHEMA', path, 'execution'); + claimed.add(name); + }; + const configured = spec.exec.env ?? {}; + if (Object.keys(configured).length > ENV_ENTRIES_MAX) refuse('CONFIG_SCHEMA', '/exec/env', 'execution'); + for (const [name, value] of Object.entries(configured)) { claim(name, '/exec/env'); env[name] = value; } + // Every binding and name is validated before the first secret is resolved: a refused spec never touches the vault. + for (const binding of spec.credentials) { + if (binding.consumer !== 'exec') refuse('CONFIG_REFERENCE', '/exec/credentialRefs', 'execution'); + for (const name of binding.environmentNames) claim(name, '/exec/credentialRefs'); + } + for (const binding of spec.credentials) { + const value = context.secrets.resolveExecCredential(binding.id); + scrubber.register(value); + for (const name of binding.environmentNames) env[name] = value; + } + env['LOOPWRIGHT_RUN_ID'] = context.runId; env['LOOPWRIGHT_STEP_ID'] = context.stepId; env['LOOPWRIGHT_ROLE_ID'] = context.roleId; env['LOOPWRIGHT_ATTEMPT_ID'] = context.attemptId; + env['LOOPWRIGHT_SCOPE_WRITABLE'] = context.scopeWritable.join(':'); + env['LOOPWRIGHT_ALLOWED_TOOLS'] = spec.tools.join(','); + env['LOOPWRIGHT_CONTEXT_FILES'] = context.contextFiles.join(':'); + env['LOOPWRIGHT_USAGE_OUT'] = context.usageOut; + // A NUL in any value would be rejected by the spawn or silently end the variable for the child. + for (const value of Object.values(env)) if (/\0/.test(value)) refuse('CONFIG_SCHEMA', '', 'execution'); + return env; +} + +/** Bounded capture of one stream: bytes past the limit are dropped and only flagged. */ +function capture(maxBytes: number): { push: (chunk: Buffer) => void; text: () => string; readonly truncated: boolean } { + const chunks: Buffer[] = []; let bytes = 0, truncated = false; + return { + push: chunk => { + if (chunk.byteLength === 0) return; + if (bytes >= maxBytes) { truncated = true; return; } + const keep = Math.min(chunk.byteLength, maxBytes - bytes); + if (keep < chunk.byteLength) truncated = true; + chunks.push(chunk.subarray(0, keep)); bytes += keep; + }, + text: () => Buffer.concat(chunks).toString('utf8'), + get truncated() { return truncated; }, + }; +} + +function groupAlive(pgid: number): boolean { + try { process.kill(-pgid, 0); return true; } catch (error) { return (error as NodeJS.ErrnoException).code === 'EPERM'; } +} +function killGroup(pgid: number): void { + try { process.kill(-pgid, 'SIGKILL'); } catch { /* already gone */ } +} +/** `ESRCH` on the group is the only proof of exit; the poll is bounded so a survivor fails closed. */ +async function confirmGroupGone(pgid: number): Promise { + const deadline = performance.now() + GROUP_EXIT_WAIT_MS; + while (groupAlive(pgid)) { + if (performance.now() >= deadline) refuse('CLEANUP_FAILED', '', 'execution'); + killGroup(pgid); + await new Promise(resolve => { setTimeout(resolve, GROUP_POLL_MS); }); + } +} + +/** The submission `reason()` printable rule: C0, DEL, and C1 controls become spaces. */ +function printable(value: string): string { + let result = ''; + for (let index = 0; index < value.length; index++) { const code = value.charCodeAt(index); result += code <= 31 || (code >= 127 && code <= 159) ? ' ' : value.charAt(index); } + return result; +} + +/** The last non-empty stderr line as a submission reason: printable and bounded, like `reason()` in submission.ts requires. */ +function blockedReason(stderr: string): string { + const lines = stderr.split('\n').map(line => printable(line).trim()).filter(line => line.length > 0); + return lines.at(-1)?.slice(0, REASON_MAX_CHARS) ?? 'exec_blocked'; +} + +function parseUsage(bytes: Buffer): readonly ExecUsageRequest[] { + const value = record(parseDocumentBytes(bytes, 'json'), ['requests'], '/usageOut'); + const requests = list(value['requests'], '/usageOut/requests', LIMITS.requests).map((item, index) => { + const path = `/usageOut/requests/${index}`; + const entry = record(item, ['requestId', 'inputTokens', 'outputTokens', 'costMicrousd'], path); + return { + requestId: id(entry['requestId'], path), + inputTokens: integer(entry['inputTokens'], 0, Number.MAX_SAFE_INTEGER, path), + outputTokens: integer(entry['outputTokens'], 0, Number.MAX_SAFE_INTEGER, path), + costMicrousd: integer(entry['costMicrousd'], 0, Number.MAX_SAFE_INTEGER, path), + }; + }); + // The ledger refuses duplicate request ids; the record is refused here rather than at booking time. + if (new Set(requests.map(request => request.requestId)).size !== requests.length) refuse('CONFIG_SCHEMA', '/usageOut', 'execution'); + return requests; +} + +/** Reads `$LOOPWRIGHT_USAGE_OUT` after the child exited on its own; a missing file is no records, anything malformed is refused. */ +async function readUsage(path: string, secrets: SecretResolver): Promise { + let stats: Awaited>; + try { stats = await lstat(path); } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return []; throw error; } + if (!stats.isFile() || stats.nlink !== 1) refuse('ARTIFACT_INVALID', '/usageOut', 'execution'); + if (stats.size > USAGE_FILE_MAX_BYTES) refuse('OUTPUT_LIMIT', '/usageOut', 'execution'); + const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW); + try { + const bytes = Buffer.alloc(Math.min(stats.size, USAGE_FILE_MAX_BYTES) + 1); let size = 0; + while (size < bytes.length) { const { bytesRead } = await file.read(bytes, size, bytes.length - size, size); if (!bytesRead) break; size += bytesRead; } + const content = bytes.subarray(0, size); + if (size > USAGE_FILE_MAX_BYTES) refuse('OUTPUT_LIMIT', '/usageOut', 'execution'); + // A record that reaches the ledger verbatim is refused on a secret, not scrubbed. + secrets.assertClean(content); + return refusing('SUBMISSION_INVALID', '/usageOut', () => parseUsage(content)); + } finally { await file.close(); } +} + +export async function runExecRole(spec: ExecRoleSpec, context: ExecRoleContext): Promise { + if (context.signal.aborted) refuse('CANCELLED', '', 'execution'); + const promptFile = absolutePath(context.promptFile, '/promptFile'), candidateDir = absolutePath(context.candidateDir, '/candidateDir'); + const scratchDir = absolutePath(context.scratchDir, '/scratchDir'), usageOut = absolutePath(context.usageOut, '/usageOut'); + if (!inside(usageOut, scratchDir)) refuse('CONFIG_SCHEMA', '/usageOut', 'execution'); + for (const file of context.contextFiles) absolutePath(file, '/contextFiles'); + const [program, ...prefix] = spec.exec.command; + if (program === undefined || !isAbsolute(program) || /[\0\r\n]/.test(program) || program.endsWith('/')) refuse('CONFIG_SCHEMA', '/exec/command/0', 'execution'); + const argv = [...prefix, ...(spec.exec.args ?? []), promptFile, candidateDir]; + for (const entry of argv) if (/\0/.test(entry)) refuse('CONFIG_SCHEMA', '/exec/command', 'execution'); + const timeoutMs = bounded(spec.exec.timeoutMs, 1, Number.MAX_SAFE_INTEGER, '/exec/timeoutMs'); + const captureBytes = spec.exec.captureBytes === undefined ? EXEC_LIMITS.captureBytesDefault : bounded(spec.exec.captureBytes, EXEC_LIMITS.captureBytesMin, EXEC_LIMITS.captureBytesMax, '/exec/captureBytes'); + const scrubber = new SecretScrubber(); + const env = environment(spec, context, scrubber); + if (context.signal.aborted) refuse('CANCELLED', '', 'execution'); + + // `detached: true` puts the child at the head of its own process group; stdin is `/dev/null`, so the child reads EOF. + const child = spawn(program, argv, { cwd: candidateDir, env, stdio: ['ignore', 'pipe', 'pipe'], detached: true }); + const stdout = capture(captureBytes), stderr = capture(captureBytes); + child.stdout!.on('data', (part: Buffer) => stdout.push(part)); child.stderr!.on('data', (part: Buffer) => stderr.push(part)); + child.stdout!.on('error', () => undefined); child.stderr!.on('error', () => undefined); + const pgid = child.pid ?? 0; + let timedOut = false, killed = false, grace: ReturnType | undefined; + // Idempotent: the group is signalled once, then the pipes are dropped if a `setsid` escapee still holds them past the grace. + const stop = (): void => { + if (killed) return; + killed = true; + if (pgid <= 0) return; + killGroup(pgid); + grace = setTimeout(() => { child.stdout?.destroy(); child.stderr?.destroy(); }, GROUP_EXIT_WAIT_MS); + }; + const exited = new Promise<{ readonly code: number | null; readonly signal: NodeJS.Signals | null }>((resolve, reject) => { + child.once('close', (code, signal) => resolve({ code, signal })); + child.once('error', reject); + }); + const timer = setTimeout(() => { timedOut = true; stop(); }, timeoutMs); + context.signal.addEventListener('abort', stop, { once: true }); + if (context.signal.aborted) stop(); + try { + if (pgid > 0 && context.onSpawned) await context.onSpawned(pgid); + const exit = await exited; + if (killed && pgid > 0) await confirmGroupGone(pgid); + if (context.signal.aborted) refuse('CANCELLED', '', 'execution'); + const clean = (captured: string): string => { const scrubbed = scrubber.scrub(captured); context.secrets.assertClean(scrubbed); return scrubbed; }; + // shortcut: truncation may cut a secret longer than `captureBytes`; scrubber and assertion see only the captured bytes, as `artifacts.put` would. + const out = clean(stdout.text()), err = clean(stderr.text()); + const usage = timedOut ? [] : await readUsage(usageOut, context.secrets); + const status = exit.code === 0 ? 'completed' : exit.code === 3 ? 'blocked' : 'failed'; + const reason = timedOut ? 'exec_timeout' + : status === 'completed' ? null + : status === 'blocked' ? blockedReason(err) + : exit.code === null ? `exec_signal_${exit.signal}` : `exec_exit_${exit.code}`; + return { status, reason, exitCode: exit.code, exitSignal: exit.signal, timedOut, pgid, stdout: out, stderr: err, stdoutTruncated: stdout.truncated, stderrTruncated: stderr.truncated, usage }; + } catch (error) { + stop(); await exited.catch(() => undefined); + if (pgid > 0) await confirmGroupGone(pgid); + if (error instanceof ControllerFailure || pgid > 0) throw error; + refuse('CONFIG_REFERENCE', '/exec/command/0', 'execution'); + } finally { + clearTimeout(timer); clearTimeout(grace); + context.signal.removeEventListener('abort', stop); + } +} diff --git a/packages/controller/test/exec-role-fixtures.ts b/packages/controller/test/exec-role-fixtures.ts new file mode 100644 index 00000000..1b9a9207 --- /dev/null +++ b/packages/controller/test/exec-role-fixtures.ts @@ -0,0 +1,50 @@ +import { spawn } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { readFileSync, writeFileSync } from 'node:fs'; + +// Deterministic POSIX stub for the exec runner tests: `node exec-role-fixtures.js `. +// The environment arrives only through the runner's allowlist, so the stub prints what it was given and nothing else. +const [mode, promptFile, candidateDir] = process.argv.slice(2); +if (mode === undefined || promptFile === undefined || candidateDir === undefined || process.argv.length !== 5) { + process.stderr.write('usage: exec-role-fixtures.js \n'); + process.exit(64); +} +const env = process.env as Record; +switch (mode) { + case 'print-env': + process.stdout.write(JSON.stringify({ env: process.env, argv: process.argv.slice(2), cwd: process.cwd(), stdin: readFileSync(0).toString() }) + '\n'); + break; + case 'print-secret': + // The digest proves which value reached the child without putting the value itself on a pipe. + process.stdout.write(`token=${env['LLM_TOKEN']}\nsha256=${createHash('sha256').update(env['LLM_TOKEN'] ?? '').digest('hex')}\n`); + process.stderr.write(`token=${env['LLM_TOKEN']}\n`); + break; + case 'sleep': + setInterval(() => {}, 1000); + break; + case 'fork-and-sleep': { + // The grandchild inherits both pipes and stays in the process group: only a group kill closes them. + const grandchild = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { stdio: ['ignore', 'inherit', 'inherit'] }); + grandchild.once('spawn', () => { process.stdout.write(JSON.stringify({ child: grandchild.pid }) + '\n'); }); + setInterval(() => {}, 1000); + break; + } + case 'flood': + process.stdout.write('0123456789abcdef'.repeat(256) + '\n'); + process.stderr.write('0123456789abcdef'.repeat(256) + '\n'); + break; + case 'write-usage': + writeFileSync(env['LOOPWRIGHT_USAGE_OUT']!, JSON.stringify({ requests: [{ requestId: 'req_1', inputTokens: 120, outputTokens: 45, costMicrousd: 1500 }] })); + break; + case 'write-malformed-usage': + writeFileSync(env['LOOPWRIGHT_USAGE_OUT']!, '{"requests":[{"requestId":"req 1","inputTokens":-1}]}'); + break; + default: + if (mode.startsWith('exit-')) { + process.stderr.write('first line\n\n blocked: need a human decision \n\n'); + process.exitCode = Number(mode.slice('exit-'.length)); + break; + } + process.stderr.write(`unknown mode: ${mode}\n`); + process.exitCode = 65; +} diff --git a/packages/controller/test/exec-role.test.ts b/packages/controller/test/exec-role.test.ts new file mode 100644 index 00000000..9a554175 --- /dev/null +++ b/packages/controller/test/exec-role.test.ts @@ -0,0 +1,184 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { createHash } from 'node:crypto'; +import { mkdir, mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { EXEC_LIMITS } from '@loopwright/core'; +import { ControllerFailure } from '../src/errors.js'; +import { runExecRole, type ExecRoleContext, type ExecRoleSpec, type SecretResolver } from '../src/exec-role.js'; +import type { CredentialBinding } from '../src/types.js'; + +const STUB = fileURLToPath(new URL('./exec-role-fixtures.js', import.meta.url)); +const SECRET = 'sk-exec-canary-Zx91Yy82Ww73Qq64'; +const SECRET_DIGEST = createHash('sha256').update(SECRET).digest('hex'); +const FLOOD = '0123456789abcdef'.repeat(256) + '\n'; +const BINDING: CredentialBinding = { id: 'llm-token', consumer: 'exec', destinationRef: 'openai', environmentNames: ['LLM_TOKEN'], template: '${LLM_TOKEN}' }; + +interface Attempt { readonly root: string; readonly candidateDir: string; readonly scratchDir: string; readonly promptFile: string; readonly usageOut: string } +interface SpecOptions { readonly mode?: string; readonly command?: readonly string[]; readonly env?: Readonly>; readonly captureBytes?: number; readonly timeoutMs?: number; readonly credentials?: readonly CredentialBinding[] } +interface ContextOptions { readonly signal?: AbortSignal; readonly secrets?: SecretResolver; readonly usageOut?: string; readonly onSpawned?: (pgid: number) => Promise } + +async function attempt(): Promise { + const root = await realpath(await mkdtemp(join(await realpath(tmpdir()), 'lw-exec-role-'))); + const candidateDir = join(root, 'candidate'), scratchDir = join(root, 'scratch'), promptFile = join(root, 'prompt.md'), usageOut = join(scratchDir, 'usage.json'); + await mkdir(candidateDir, { mode: 0o700 }); await mkdir(scratchDir, { mode: 0o700 }); await writeFile(promptFile, 'Produce one structured submission.\n'); + return { root, candidateDir, scratchDir, promptFile, usageOut }; +} + +function spec(options: SpecOptions = {}): ExecRoleSpec { + const { mode = 'print-env', command = [process.execPath, STUB], env, captureBytes, timeoutMs = 20_000, credentials = [] } = options; + return { exec: { command, args: [mode], timeoutMs, ...(env !== undefined ? { env } : {}), ...(captureBytes !== undefined ? { captureBytes } : {}) }, tools: ['read', 'write'], credentials }; +} + +/** The two vault operations the runner needs; `asserted` records every value the runner asserted. */ +function fakeVault(): { readonly secrets: SecretResolver; readonly asserted: string[] } { + const asserted: string[] = []; + return { + asserted, + secrets: { + resolveExecCredential: ref => { if (ref !== BINDING.id) assert.fail(`unexpected credential ref ${ref}`); return SECRET; }, + assertClean: value => { const text = typeof value === 'string' ? value : Buffer.from(value as Uint8Array).toString('utf8'); asserted.push(text); if (text.includes(SECRET)) assert.fail('secret reached the vault assertion'); }, + }, + }; +} + +const forbiddenVault: SecretResolver = { + resolveExecCredential: () => assert.fail('no secret may be resolved before the spec is validated'), + assertClean: () => assert.fail('nothing may be asserted before the spec is validated'), +}; + +function context(attempt: Attempt, options: ContextOptions = {}): ExecRoleContext { + return { + runId: 'run-1', stepId: 'build', roleId: 'author', attemptId: 'attempt-1', + scopeWritable: ['src/**', 'tests/**'], contextFiles: [join(attempt.root, 'context', 'a.md')], + scratchDir: attempt.scratchDir, promptFile: attempt.promptFile, candidateDir: attempt.candidateDir, usageOut: options.usageOut ?? attempt.usageOut, + secrets: options.secrets ?? fakeVault().secrets, signal: options.signal ?? new AbortController().signal, + ...(options.onSpawned !== undefined ? { onSpawned: options.onSpawned } : {}), + }; +} + +function refusal(code: string): (error: unknown) => boolean { + return error => error instanceof ControllerFailure && error.diagnostic.code === code && error.diagnostic.phase === 'execution'; +} + +function gone(pgid: number): void { assert.throws(() => process.kill(-pgid, 0), { code: 'ESRCH' }); } + +async function withAttempt(work: (attempt: Attempt) => Promise): Promise { + const current = await attempt(); + try { await work(current); } finally { await rm(current.root, { recursive: true, force: true }); } +} + +interface StubReport { readonly env: Record; readonly argv: string[]; readonly cwd: string; readonly stdin: string } + +test('exec role maps exit 0 to completed and hands promptFile and candidateDir over as the last argv with cwd = candidateDir and a closed stdin', () => withAttempt(async current => { + const outcome = await runExecRole(spec(), context(current)); + assert.equal(outcome.status, 'completed'); assert.equal(outcome.reason, null); assert.equal(outcome.exitCode, 0); assert.equal(outcome.exitSignal, null); assert.equal(outcome.timedOut, false); + assert.deepEqual(outcome.usage, []); assert.equal(outcome.stderr, ''); + const report = JSON.parse(outcome.stdout) as StubReport; + assert.deepEqual(report.argv.slice(-2), [current.promptFile, current.candidateDir]); + assert.equal(report.cwd, current.candidateDir); + assert.equal(report.stdin, ''); + assert.ok(outcome.pgid > 1); + gone(outcome.pgid); +})); + +test('exec role environment equals the allowlist plus the configured env, the bound credential, and the LOOPWRIGHT_* contract; nothing else is inherited', async () => { + process.env['LOOPWRIGHT_T5_SENTINEL'] = 'must-not-leak'; + try { + await withAttempt(async current => { + const outcome = await runExecRole(spec({ env: { FORGEVO_LLM_BASE_URL: 'https://api.example.com/v1' }, credentials: [BINDING] }), context(current)); + const { env } = JSON.parse(outcome.stdout) as StubReport; + // Measured on darwin: a `node` process started with an empty environment still reports `__CF_USER_TEXT_ENCODING`, + // because CoreFoundation's initializer sets it inside the observing process. The runner never passes it. + delete env['__CF_USER_TEXT_ENCODING']; + const expected = { + PATH: '/usr/local/bin:/usr/bin:/bin', HOME: current.scratchDir, TMPDIR: current.scratchDir, LANG: 'C.UTF-8', LC_ALL: 'C.UTF-8', TERM: 'dumb', + FORGEVO_LLM_BASE_URL: 'https://api.example.com/v1', LLM_TOKEN: '[scrubbed]', + LOOPWRIGHT_RUN_ID: 'run-1', LOOPWRIGHT_STEP_ID: 'build', LOOPWRIGHT_ROLE_ID: 'author', LOOPWRIGHT_ATTEMPT_ID: 'attempt-1', + LOOPWRIGHT_SCOPE_WRITABLE: 'src/**:tests/**', LOOPWRIGHT_ALLOWED_TOOLS: 'read,write', LOOPWRIGHT_CONTEXT_FILES: join(current.root, 'context', 'a.md'), LOOPWRIGHT_USAGE_OUT: current.usageOut, + }; + const sorted = (entries: Record) => Object.entries(entries).sort(([left], [right]) => left.localeCompare(right)); + assert.deepEqual(sorted(env), sorted(expected)); + }); + } finally { delete process.env['LOOPWRIGHT_T5_SENTINEL']; } +}); + +test('exec role passes a bound credential to the child through its environmentNames and scrubs it from every captured byte', () => withAttempt(async current => { + const { secrets, asserted } = fakeVault(); + const outcome = await runExecRole(spec({ mode: 'print-secret', credentials: [BINDING] }), context(current, { secrets })); + assert.equal(outcome.status, 'completed'); + assert.equal(outcome.stdout, `token=[scrubbed]\nsha256=${SECRET_DIGEST}\n`); + assert.equal(outcome.stderr, 'token=[scrubbed]\n'); + assert.ok(asserted.includes(outcome.stdout) && asserted.includes(outcome.stderr)); +})); + +test('exec role maps exit 3 to blocked with the last non-empty stderr line as the reason and any other exit to failed', () => withAttempt(async current => { + const blocked = await runExecRole(spec({ mode: 'exit-3' }), context(current)); + assert.equal(blocked.status, 'blocked'); assert.equal(blocked.reason, 'blocked: need a human decision'); assert.equal(blocked.exitCode, 3); + const failed = await runExecRole(spec({ mode: 'exit-7' }), context(current)); + assert.equal(failed.status, 'failed'); assert.equal(failed.reason, 'exec_exit_7'); assert.equal(failed.exitCode, 7); +})); + +test('exec role times out into failed exec_timeout and kills the whole process group, including a forked grandchild holding the pipes', { timeout: 30_000 }, () => withAttempt(async current => { + const outcome = await runExecRole(spec({ mode: 'fork-and-sleep', timeoutMs: 1_500 }), context(current)); + assert.equal(outcome.status, 'failed'); assert.equal(outcome.reason, 'exec_timeout'); assert.equal(outcome.timedOut, true); assert.equal(outcome.exitCode, null); + assert.deepEqual(outcome.usage, []); + const { child } = JSON.parse(outcome.stdout.trim()) as { readonly child: number }; + assert.ok(child > 0); + gone(outcome.pgid); + assert.throws(() => process.kill(child, 0), { code: 'ESRCH' }); +})); + +test('exec role cancel kills the process group and refuses CANCELLED', { timeout: 30_000 }, () => withAttempt(async current => { + const controller = new AbortController(); let pgid = 0; + const timer = setTimeout(() => controller.abort(), 300); + try { + await assert.rejects(runExecRole(spec({ mode: 'sleep' }), context(current, { signal: controller.signal, onSpawned: async id => { pgid = id; } })), refusal('CANCELLED')); + } finally { clearTimeout(timer); } + assert.ok(pgid > 1); + gone(pgid); +})); + +test('exec role captures each stream up to captureBytes and reports truncation', () => withAttempt(async current => { + const truncated = await runExecRole(spec({ mode: 'flood', captureBytes: EXEC_LIMITS.captureBytesMin }), context(current)); + assert.equal(truncated.stdout.length, EXEC_LIMITS.captureBytesMin); assert.equal(truncated.stderr.length, EXEC_LIMITS.captureBytesMin); + assert.equal(truncated.stdoutTruncated, true); assert.equal(truncated.stderrTruncated, true); + const full = await runExecRole(spec({ mode: 'flood' }), context(current)); + assert.equal(full.stdout, FLOOD); assert.equal(full.stderr, FLOOD); assert.equal(full.stdoutTruncated, false); assert.equal(full.stderrTruncated, false); +})); + +test('exec role reads the usage file after exit into request records and yields none when the file is missing', () => withAttempt(async current => { + const written = await runExecRole(spec({ mode: 'write-usage' }), context(current)); + assert.deepEqual(written.usage, [{ requestId: 'req_1', inputTokens: 120, outputTokens: 45, costMicrousd: 1500 }]); + const missing = await runExecRole(spec(), context(current, { usageOut: join(current.scratchDir, 'absent.json') })); + assert.deepEqual(missing.usage, []); +})); + +test('exec role refuses a malformed usage file with SUBMISSION_INVALID after the child is gone', () => withAttempt(async current => { + let pgid = 0; + await assert.rejects(runExecRole(spec({ mode: 'write-malformed-usage' }), context(current, { onSpawned: async id => { pgid = id; } })), refusal('SUBMISSION_INVALID')); + assert.equal(await readFile(current.usageOut, 'utf8'), '{"requests":[{"requestId":"req 1","inputTokens":-1}]}'); + gone(pgid); +})); + +test('exec role refuses an invalid command[0], colliding env names, non-exec bindings, out-of-bounds numbers, and a usage file outside the scratch directory before resolving any secret', () => withAttempt(async current => { + const cases: readonly (readonly [ExecRoleSpec, string])[] = [ + [spec({ command: ['relative/stub'] }), 'CONFIG_SCHEMA'], + [spec({ command: [join(current.root, 'stub\0')] }), 'CONFIG_SCHEMA'], + [spec({ command: [join(current.root, 'stub\n')] }), 'CONFIG_SCHEMA'], + [spec({ command: [STUB + '/'] }), 'CONFIG_SCHEMA'], + [spec({ env: { PATH: '/tmp' } }), 'CONFIG_SCHEMA'], + [spec({ env: { LOOPWRIGHT_RUN_ID: 'other' } }), 'CONFIG_SCHEMA'], + [spec({ credentials: [{ ...BINDING, environmentNames: ['HOME'] }] }), 'CONFIG_SCHEMA'], + [spec({ credentials: [{ ...BINDING, consumer: 'provider' }] }), 'CONFIG_REFERENCE'], + [spec({ captureBytes: EXEC_LIMITS.captureBytesMin - 1 }), 'CONFIG_SCHEMA'], + [spec({ captureBytes: EXEC_LIMITS.captureBytesMax + 1 }), 'CONFIG_SCHEMA'], + [spec({ timeoutMs: 0 }), 'CONFIG_SCHEMA'], + ]; + for (const [input, code] of cases) await assert.rejects(runExecRole(input, context(current, { secrets: forbiddenVault })), refusal(code)); + await assert.rejects(runExecRole(spec(), context(current, { secrets: forbiddenVault, usageOut: join(current.root, 'usage.json') })), refusal('CONFIG_SCHEMA')); + const aborted = new AbortController(); aborted.abort(); + await assert.rejects(runExecRole(spec(), context(current, { secrets: forbiddenVault, signal: aborted.signal })), refusal('CANCELLED')); +})); diff --git a/specs/2026-11-30-managed-controller-in-process-execution.md b/specs/2026-11-30-managed-controller-in-process-execution.md index 5a2118ab..8090dc52 100644 --- a/specs/2026-11-30-managed-controller-in-process-execution.md +++ b/specs/2026-11-30-managed-controller-in-process-execution.md @@ -199,7 +199,7 @@ controller's own environment on a host whose isolation the registry attests. `TMPDIR` (the attempt scratch directory), `LANG`, `TERM`, the configured `env`, the bound credentials, and `LOOPWRIGHT_RUN_ID`, `LOOPWRIGHT_STEP_ID`, `LOOPWRIGHT_ROLE_ID`, `LOOPWRIGHT_ATTEMPT_ID`, `LOOPWRIGHT_SCOPE_WRITABLE` (colon-separated globs), - `LOOPWRIGHT_ALLOWED_TOOLS`, `LOOPWRIGHT_CONTEXT_FILES`, and `LOOPWRIGHT_USAGE_OUT` (a file + `LOOPWRIGHT_ALLOWED_TOOLS` (comma-separated tool names), `LOOPWRIGHT_CONTEXT_FILES` (colon-separated paths), and `LOOPWRIGHT_USAGE_OUT` (a file path inside the attempt scratch directory; the controller sets it because the command cannot know that path, reads the file after exit, and scrubs it). The controller never passes its own `process.env`. @@ -550,7 +550,7 @@ and T11 have disjoint `Owns:` and start together; T5 follows T2. Gate: review Acceptance: admission resolves the script and `toolchainPaths` at `target.sourceRevision` from the baseline tree, requires the executable bit and a fully protected script directory, and records the directory digest in the compiled slot; `check` validates schema and budget only; the controller dispatches `command.v1` slots to `LocalCheck`, extracts `detail` for them in the rework summary, and exports the receipt through `inspect`; recovery settles a `command.v1` operation without a proof marker as `blocked`. A controller cycle test with the deterministic fake adapter as author and the T3 stub scripts settles `completed` for a passing script and reworks with `detail` for a failing one. `installedHandlerDigests()` in `handlers.ts` lists `command.v1`, and the `safePath` segment whitelist in `errors.ts` covers the new refusal paths (`host`, `localChecks`, `backend`, `command`, `script`, `env`, `toolchainPaths`, `exec`, `captureBytes`, `credentialRefs`). Verify: `node scripts/run-tests.mjs --pkg controller` -- [ ] **T5 · `exec` runner module** +- [x] **T5 · `exec` runner module** Blocked by: T2 Owns: `packages/controller/src/exec-role.ts`, `packages/controller/test/exec-role.test.ts`, `packages/controller/test/exec-role-fixtures.ts` Gate: review From 8cfd55b3de10a33f22628074898724b6d5936b23 Mon Sep 17 00:00:00 2001 From: thxCode Date: Tue, 1 Dec 2026 08:46:18 +0800 Subject: [PATCH 10/26] test(hardware-runner): record the native_os namespace feasibility probe - probe script and restricted-profile Pod manifest for bubblewrap namespaces - recorded verdict namespaces_blocked on kind/containerd 2.3 with PSA restricted - seccomp versus AppArmor differential recorded; no Landlock ABI on the node - no feature code: F5 stays behind the probe; spec records blocked_external Task 11 of managed-controller-in-process-execution. Signed-off-by: thxCode --- .../test/bwrap-namespace-probe.test.ts | 245 ++++++++++++ .../fixtures/bwrap-namespace-probe/pod.yaml | 94 +++++ .../fixtures/bwrap-namespace-probe/probe.sh | 369 ++++++++++++++++++ ...managed-controller-in-process-execution.md | 11 +- 4 files changed, 715 insertions(+), 4 deletions(-) create mode 100644 packages/hardware-runner/test/bwrap-namespace-probe.test.ts create mode 100644 packages/hardware-runner/test/fixtures/bwrap-namespace-probe/pod.yaml create mode 100755 packages/hardware-runner/test/fixtures/bwrap-namespace-probe/probe.sh diff --git a/packages/hardware-runner/test/bwrap-namespace-probe.test.ts b/packages/hardware-runner/test/bwrap-namespace-probe.test.ts new file mode 100644 index 00000000..bac43c9f --- /dev/null +++ b/packages/hardware-runner/test/bwrap-namespace-probe.test.ts @@ -0,0 +1,245 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; +import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { parseYamlDocument } from '@loopwright/taskpack'; +import { compileStrictSocketDenySeccompBpf } from '../src/evaluator.js'; + +/** + * T11 feasibility probe for `native_os` under `deviceOwnership: host`. The fixture is the + * deliverable: probe.sh (JSON lines) and pod.yaml (the target Pod profile). This file proves the + * probe's own fidelity, holds the measured cluster outcome, and runs the probe locally on Linux + * hosts that have bubblewrap as local evidence only. The cluster run is the qualification. + */ +const PROBE_DIR = fileURLToPath(new URL('./fixtures/bwrap-namespace-probe/', import.meta.url)).replace('/.test-build/', '/'); +const PROBE_SCRIPT = join(PROBE_DIR, 'probe.sh'); +const PROBE_POD = join(PROBE_DIR, 'pod.yaml'); +const SH = '/bin/sh'; + +export const PROBE_VERDICTS = [ + 'namespaces_ok', + 'namespaces_blocked', + 'netns_blocked', + 'other_ns_blocked', + 'seccomp_blocked', + 'partial', + 'bwrap_unavailable', +] as const; +export type ProbeVerdict = typeof PROBE_VERDICTS[number]; + +export interface ProbeAttemptLine { + readonly attempt: string; + readonly ok: boolean; + readonly exit: number; + readonly errno: string; + readonly message: string; +} + +/** + * Measured result under the target Pod profile. Recorded from the operator's run of pod.yaml; + * see probe.sh's header for what each verdict means for the feature. `differential` holds the + * diagnostics that are not part of the verdict (a second namespace without PodSecurity admission). + */ +export const RECORDED_PROBE_OUTCOME: Readonly<{ + readonly status: 'pending' | 'recorded'; + readonly verdict?: ProbeVerdict; + readonly measuredAt?: string; + readonly environment?: Readonly>; + readonly firstFailingAttempt?: Pick; + readonly failingAttempts?: readonly string[]; + readonly differential?: readonly string[]; + readonly caveat?: string; + readonly evidence?: readonly string[]; +}> = Object.freeze({ + status: 'recorded', + verdict: 'namespaces_blocked', + measuredAt: '2026-12-01', + environment: Object.freeze({ + cluster: 'kind v0.33.0 cluster lw-t11-probe on a developer Linux host (not the production GPU node)', + hostKernel: '6.17.0-23-generic (Ubuntu-family sysctls: kernel.unprivileged_userns_clone=1, kernel.apparmor_restrict_unprivileged_userns=1)', + kubernetes: 'v1.37.0', + containerRuntime: 'containerd 2.3.4 (kind node image Debian 13)', + podSecurityAdmission: 'namespace lw-t11-probe enforces pod-security.kubernetes.io/enforce=restricted (+audit, +warn, version latest); pod.yaml admitted unchanged', + pod: 'phase Succeeded, probe exit 0, 13 JSON lines', + containerContext: 'uid/gid 65532, x86_64, CapEff=0 CapBnd=0, NoNewPrivs=1, Seccomp=2 (1 filter), apparmor_profile=unconfined, user.max_user_namespaces=124231, landlock abi absent, bwrap 0.8.0 via the apt bootstrap', + }), + firstFailingAttempt: Object.freeze({ + attempt: 'negotiate-probe', + errno: 'EPERM', + message: 'bwrap: No permissions to create new namespace, likely because the kernel does not allow non-privileged user namespaces. See or .', + }), + failingAttempts: Object.freeze([ + 'negotiate-probe', 'unshare-all-share-net', 'userns-mount-proc-dev', 'seccomp-fd3-allowall', + 'seccomp-fd3-strict', 'stage-a-exact-shape', 'stage-b-exact-shape', + ]), + differential: Object.freeze([ + 'Variant A, same manifest with seccompProfile Unconfined (pod + container) in a namespace without PodSecurity enforcement: namespace creation proceeds; bwrap then fails at "loopback: Failed RTM_NEWADDR: Operation not permitted" (negotiate-probe and every seccomp/stage attempt, EPERM) and "setting up uid map: Permission denied" (unshare-all-share-net and userns-mount-proc-dev, EACCES); summary still namespaces_blocked.', + 'Variant B, A plus container appArmorProfile.type Unconfined: identical to A, so the host AppArmor unprivileged-userns restriction is not what blocks the restricted run.', + 'The restricted namespace refused variant A (PodSecurity restricted:latest forbids seccompProfile.type Unconfined), so a restricted Pod cannot relax seccomp.', + 'Conclusion: RuntimeDefault seccomp is the first barrier; without it the drop-ALL bounding set (CapBnd=0, inherited into any user namespace the process creates) still stops bwrap at uid mapping. native_os cannot run under the restricted profile; stage 2 (deviceOwnership, relay block, runner inline, isolation producer) is not implemented.', + ]), + caveat: 'Measured on a kind cluster on a developer Linux host; the production GPU node was not measured.', + evidence: Object.freeze([ + '.claude/handoffs/2026-11-30-t11-probe-output.jsonl', + '.claude/handoffs/2026-11-30-t11-probe-diag-a-seccomp-unconfined.jsonl', + '.claude/handoffs/2026-11-30-t11-probe-diag-b-seccomp-apparmor-unconfined.jsonl', + ]), +}); + +function runProbe(env: Readonly>): readonly ProbeAttemptLine[] { + const res = spawnSync(SH, [PROBE_SCRIPT], { + encoding: 'buffer', + env: { PATH: process.env.PATH ?? '/usr/bin:/bin', TMPDIR: process.env.TMPDIR, ...env }, + timeout: 180_000, + maxBuffer: 1_048_576, + }); + const stdout = res.stdout.toString('utf8'); + assert.equal(res.status, 0, `probe exited ${res.status}: ${res.stderr.toString('utf8').slice(0, 500)}`); + const logPath = join(env.PROBE_OUT_DIR!, 'bwrap-probe.jsonl'); + assert.equal(readFileSync(logPath, 'utf8'), stdout, 'probe.sh must mirror stdout into its emptyDir log'); + return stdout.split('\n').filter(line => line.length > 0).map(line => JSON.parse(line) as ProbeAttemptLine); +} + +function summaryOf(lines: readonly ProbeAttemptLine[]): ProbeAttemptLine { + const summary = lines.find(line => line.attempt === 'summary'); + assert.ok(summary, 'probe must end with a summary line'); + return summary; +} + +function verdictOf(summary: ProbeAttemptLine): ProbeVerdict { + const match = /^verdict=(\S+) feature=(\S+)(?::|\s*$)/.exec(summary.message); + assert.ok(match, `summary message must be verdict= feature=: ${summary.message}`); + assert.ok((PROBE_VERDICTS as readonly string[]).includes(match[1]!), `unknown verdict ${match[1]}`); + return match[1] as ProbeVerdict; +} + +test('probe fixture: --emit-seccomp-bpf is byte-identical to compileStrictSocketDenySeccompBpf on x64 and arm64', () => { + for (const arch of ['x64', 'arm64'] as const) { + const res = spawnSync(SH, [PROBE_SCRIPT, '--emit-seccomp-bpf', arch], { encoding: 'buffer' }); + assert.equal(res.status, 0, `${arch}: ${res.stderr.toString('utf8')}`); + assert.equal(res.stderr.byteLength, 0, `${arch}: unexpected stderr`); + assert.ok( + res.stdout.equals(compileStrictSocketDenySeccompBpf(arch)), + `${arch}: the fd-3 program the probe hands to bwrap differs from the evaluator's`, + ); + } + const unsupported = spawnSync(SH, [PROBE_SCRIPT, '--emit-seccomp-bpf', 'riscv64'], { encoding: 'utf8' }); + assert.notEqual(unsupported.status, 0); +}); + +test('probe fixture: pod.yaml applies the target profile and nothing that would change the namespace answer', () => { + const pod = parseYamlDocument(readFileSync(PROBE_POD, 'utf8')) as unknown as { + metadata: { name: string; labels: Record }; + spec: { + automountServiceAccountToken: boolean; + hostNetwork: boolean; + hostIPC: boolean; + hostPID: boolean; + securityContext: Record; + containers: readonly { + name: string; + command: readonly string[]; + env: readonly { name: string; value: string }[]; + securityContext: Record; + volumeMounts: readonly { name: string; mountPath: string; readOnly?: boolean }[]; + }[]; + volumes: readonly Record[]; + }; + }; + assert.equal(pod.metadata.name, 't11-bwrap-probe'); + assert.equal(pod.metadata.labels['pod-security.kubernetes.io/enforce'], 'restricted'); + const spec = pod.spec; + assert.equal(spec.automountServiceAccountToken, false); + assert.equal(spec.hostNetwork, false); + assert.equal(spec.hostIPC, false); + assert.equal(spec.hostPID, false); + for (const context of [spec.securityContext, ...spec.containers.map(c => c.securityContext)]) { + assert.equal(context.runAsNonRoot, true); + assert.equal(context.seccompProfile && (context.seccompProfile as { type: string }).type, 'RuntimeDefault'); + } + for (const container of spec.containers) { + assert.equal(container.securityContext.allowPrivilegeEscalation, false); + assert.deepEqual(container.securityContext.capabilities, { drop: ['ALL'] }); + assert.ok(typeof container.securityContext.runAsUser === 'number' && container.securityContext.runAsUser !== 0); + } + const container = spec.containers[0]!; + assert.deepEqual([...container.command], ['/bin/sh', '/probe/probe.sh']); + assert.equal(spec.volumes.length, container.volumeMounts.length); + for (const volume of spec.volumes) { + const keys = Object.keys(volume).filter(key => key !== 'name'); + assert.equal(keys.length, 1, `volume ${volume.name} must have exactly one source`); + assert.ok(keys[0] === 'emptyDir' || keys[0] === 'configMap', `volume ${volume.name} must not be a host path (${keys[0]})`); + } + for (const mount of container.volumeMounts) { + if (mount.mountPath === '/probe') assert.equal(mount.readOnly, true); + else assert.ok(mount.mountPath === '/probe-out' || mount.mountPath === '/tmp', `unexpected mount ${mount.mountPath}`); + } +}); + +test('probe fixture: without an executable bwrap the probe records bwrap_unavailable as JSON lines only', () => { + const outDir = mkdtempSync(join(tmpdir(), 'lw-bwrap-probe-none-')); + try { + const lines = runProbe({ PROBE_OUT_DIR: outDir, PROBE_BWRAP: join(outDir, 'missing-bwrap'), PROBE_SKIP_APT: '1' }); + const summary = summaryOf(lines); + assert.equal(verdictOf(summary), 'bwrap_unavailable'); + assert.equal(summary.ok, false); + const unavailable = lines.find(line => line.attempt === 'bwrap-unavailable'); + assert.ok(unavailable); + assert.equal(unavailable.ok, false); + assert.equal(unavailable.errno, 'ENOENT'); + assert.ok(lines.every(line => line.attempt !== 'negotiate-probe'), 'no namespace attempt may run without bwrap'); + } finally { + rmSync(outDir, { recursive: true, force: true }); + } +}); + +test('probe fixture: the recorded cluster outcome is consistent with the probe vocabulary and complete', t => { + if (RECORDED_PROBE_OUTCOME.status === 'pending') { + t.diagnostic('T11 probe not yet run in the target cluster: RECORDED_PROBE_OUTCOME.status is pending'); + assert.equal(RECORDED_PROBE_OUTCOME.verdict, undefined); + return; + } + const { verdict, firstFailingAttempt, failingAttempts, differential, environment, caveat, measuredAt, evidence } = RECORDED_PROBE_OUTCOME; + assert.ok(verdict && (PROBE_VERDICTS as readonly string[]).includes(verdict)); + assert.match(measuredAt ?? '', /^\d{4}-\d{2}-\d{2}$/); + assert.ok(environment && Object.keys(environment).length > 0, 'the measurement environment must be recorded'); + assert.ok(evidence && evidence.length > 0, 'the evidence files must be named'); + if (verdict === 'namespaces_ok') { + assert.equal(firstFailingAttempt, undefined); + return; + } + assert.ok(firstFailingAttempt, `${verdict} must record the first failing attempt`); + assert.ok(firstFailingAttempt.attempt.length > 0 && firstFailingAttempt.message.length > 0); + assert.ok(failingAttempts?.includes(firstFailingAttempt.attempt), 'the first failing attempt must be one of the failing attempts'); + if (verdict === 'namespaces_blocked') { + assert.ok(failingAttempts?.includes('userns-mount-proc-dev'), 'userns-mount-proc-dev is the smallest namespace set bwrap attempts'); + assert.equal(firstFailingAttempt.errno, 'EPERM'); + assert.ok(differential?.length && differential.length > 0, 'the seccomp-versus-appArmor differential must be recorded'); + assert.ok(caveat?.includes('not measured'), 'the caveat must say what was not measured'); + } + t.diagnostic(`T11 probe verdict=${verdict} at ${firstFailingAttempt.attempt} (${firstFailingAttempt.errno}): ${firstFailingAttempt.message}`); +}); + +test('probe fixture: local Linux run with bubblewrap is local evidence only (cluster run is the qualification)', { + skip: process.platform !== 'linux' || !existsSync('/usr/bin/bwrap'), +}, t => { + const outDir = mkdtempSync(join(tmpdir(), 'lw-bwrap-probe-local-')); + try { + const lines = runProbe({ PROBE_OUT_DIR: outDir, PROBE_BWRAP: '/usr/bin/bwrap', PROBE_SKIP_APT: '1' }); + const summary = summaryOf(lines); + const verdict = verdictOf(summary); + const context = lines.find(line => line.attempt === 'context'); + assert.ok(context, 'context line first'); + assert.equal(lines[0]?.attempt, 'context'); + for (const name of ['negotiate-probe', 'userns-mount-proc-dev', 'seccomp-fd3-strict', 'stage-a-exact-shape', 'stage-b-exact-shape']) { + assert.ok(lines.some(line => line.attempt === name), `${name} must be recorded`); + } + assert.equal(summary.ok, verdict === 'namespaces_ok'); + t.diagnostic(`local probe verdict=${verdict} (local host, not the target Pod profile)`); + } finally { + rmSync(outDir, { recursive: true, force: true }); + } +}); diff --git a/packages/hardware-runner/test/fixtures/bwrap-namespace-probe/pod.yaml b/packages/hardware-runner/test/fixtures/bwrap-namespace-probe/pod.yaml new file mode 100644 index 00000000..6d38bae8 --- /dev/null +++ b/packages/hardware-runner/test/fixtures/bwrap-namespace-probe/pod.yaml @@ -0,0 +1,94 @@ +# T11 feasibility probe Pod: runs probe.sh under the TARGET profile, exactly. +# +# Profile (the F5 "host profile" from the spec Notes): non-root, ALL capabilities dropped, +# allowPrivilegeEscalation: false, RuntimeDefault seccomp, no service account token, no host paths +# (only an emptyDir and a read-only ConfigMap projection), read-only root filesystem (so that +# "writes nothing outside its own emptyDir" is enforced by the kubelet, not promised by the script; +# a positive result transfers to a writable root, bwrap itself never writes to the root filesystem). +# The pod-security.kubernetes.io/enforce=restricted labels make a wrong namespace refuse the Pod +# instead of silently weakening it. +# +# No host paths. The probe writes only to the emptyDir mounted at /probe-out (and /tmp). +# The script comes from a ConfigMap created with --from-file so it is not duplicated here: +# +# NS= +# kubectl -n "$NS" create configmap t11-bwrap-probe-script \ +# --from-file=probe.sh=packages/hardware-runner/test/fixtures/bwrap-namespace-probe/probe.sh \ +# --dry-run=client -o yaml | kubectl apply -f - +# kubectl -n "$NS" apply -f packages/hardware-runner/test/fixtures/bwrap-namespace-probe/pod.yaml +# kubectl -n "$NS" wait --for=jsonpath='{.status.phase}'=Succeeded pod/t11-bwrap-probe --timeout=15m \ +# || kubectl -n "$NS" wait --for=jsonpath='{.status.phase}'=Failed pod/t11-bwrap-probe --timeout=15m +# kubectl -n "$NS" logs pod/t11-bwrap-probe > t11-bwrap-probe.jsonl +# +# The image ships no bubblewrap, so probe.sh fetches a user-space copy of bubblewrap and libcap2 +# into /probe-out with apt-get download (non-root, redirected apt state). That needs egress to +# deb.debian.org. If the namespace denies that egress, use any image that ships /usr/bin/bwrap and +# set PROBE_SKIP_APT=1, for example: +# sed -e 's|debian:bookworm-slim||' pod.yaml | kubectl -n "$NS" apply -f - +# Exit code 0 with verdict=bwrap_unavailable means inconclusive, not "blocked". +apiVersion: v1 +kind: Pod +metadata: + name: t11-bwrap-probe + labels: + app.kubernetes.io/name: t11-bwrap-probe + pod-security.kubernetes.io/enforce: restricted + pod-security.kubernetes.io/enforce-version: latest + pod-security.kubernetes.io/audit: restricted + pod-security.kubernetes.io/audit-version: latest + pod-security.kubernetes.io/warn: restricted + pod-security.kubernetes.io/warn-version: latest +spec: + restartPolicy: Never + automountServiceAccountToken: false + hostNetwork: false + hostIPC: false + hostPID: false + securityContext: + runAsNonRoot: true + runAsUser: 65532 + runAsGroup: 65532 + fsGroup: 65532 + fsGroupChangePolicy: OnRootMismatch + seccompProfile: + type: RuntimeDefault + containers: + - name: probe + image: docker.io/library/debian:bookworm-slim + command: ["/bin/sh", "/probe/probe.sh"] + env: + - name: PROBE_OUT_DIR + value: /probe-out + securityContext: + runAsNonRoot: true + runAsUser: 65532 + runAsGroup: 65532 + allowPrivilegeEscalation: false + capabilities: + drop: ["ALL"] + seccompProfile: + type: RuntimeDefault + readOnlyRootFilesystem: true + resources: + requests: + cpu: 100m + memory: 128Mi + limits: + memory: 512Mi + volumeMounts: + - name: script + mountPath: /probe + readOnly: true + - name: out + mountPath: /probe-out + - name: tmp + mountPath: /tmp + volumes: + - name: script + configMap: + name: t11-bwrap-probe-script + defaultMode: 0555 + - name: out + emptyDir: {} + - name: tmp + emptyDir: {} diff --git a/packages/hardware-runner/test/fixtures/bwrap-namespace-probe/probe.sh b/packages/hardware-runner/test/fixtures/bwrap-namespace-probe/probe.sh new file mode 100755 index 00000000..6515a3ba --- /dev/null +++ b/packages/hardware-runner/test/fixtures/bwrap-namespace-probe/probe.sh @@ -0,0 +1,369 @@ +#!/bin/sh +# bwrap-namespace-probe: feasibility probe for T11 / F5 (`native_os` under `deviceOwnership: host`). +# +# What it measures: whether bubblewrap can create the user, pid, mount, and network namespaces, +# mount --proc / --dev, bind --ro-bind / --bind paths, chdir, and install the Stage B socket-denial +# seccomp filter through `--seccomp ` under the TARGET Pod profile: non-root, ALL capabilities +# dropped, allowPrivilegeEscalation=false, RuntimeDefault seccomp, no host paths, no service account +# token (see pod.yaml). The attempts mirror buildStrictLinuxBwrapArgs +# (packages/hardware-runner/src/evaluator.ts) flag family by flag family, and the BPF program is +# byte-identical to compileStrictSocketDenySeccompBpf(arch); bwrap-namespace-probe.test.ts proves it. +# +# Output: JSON lines on stdout and in $PROBE_OUT_DIR/bwrap-probe.jsonl. Each attempt is one line: +# {"attempt": NAME, "ok": true|false, "exit": N, "errno": "EPERM"|..., "message": "..."} +# The last line is {"attempt":"summary","ok":...,"verdict":...,"feature":...}. +# The script writes nothing outside $PROBE_OUT_DIR (an emptyDir) and $TMPDIR (an emptyDir too). +# +# Environment: PROBE_OUT_DIR (default /probe-out), PROBE_BWRAP (use this bwrap instead of searching), +# PROBE_SKIP_APT=1 (never download bwrap; fail as bwrap_unavailable when it is not installed), +# PROBE_ATTEMPT_TIMEOUT_S (default 20). `probe.sh --emit-seccomp-bpf x64|arm64` prints the raw +# classic-BPF program and exits; it is the fidelity hook the unit test uses. +# +# Outcome (verdict) and what it means for the feature: +# namespaces_ok Every attempt passed. bwrap runs the exact Stage A and Stage B shapes here. +# Stage 2 proceeds: deviceOwnership: host, sandboxBackend: native_os with +# probeMode: physical, hardwareProvenance.isolation: 'host_attested'. +# namespaces_blocked "userns-mount-proc-dev" failed: the kernel or the node's security policy +# (user.max_user_namespaces=0, unprivileged_userns_clone=0, AppArmor or +# SELinux) denies unprivileged user namespaces in this profile. native_os +# cannot run in the Pod. Stage 2 STOPS before any feature code; report blocked +# with this file as evidence. +# Measured (a kind cluster on a developer Linux host, not a GPU node): under +# this profile every attempt fails with EPERM before any namespace exists. +# RuntimeDefault seccomp is the first barrier; with seccomp Unconfined the +# drop-ALL bounding set (CapBnd=0, inherited into any user namespace the +# process creates) still stops bwrap (uid map EACCES, RTM_NEWADDR EPERM), and +# relaxing the host AppArmor userns rule changes nothing. A restricted Pod +# cannot relax seccomp (PodSecurity refuses type Unconfined). +# netns_blocked User and mount namespaces work but --unshare-net fails. buildStrictLinuxBwrapArgs +# always emits --unshare-all, so the feature is blocked unless the lead accepts +# a --share-net variant (a design change: seccomp socket denial would become +# the only network control). +# other_ns_blocked User, mount, and net namespaces work, but ipc, pid, uts, or cgroup namespace +# creation fails. Blocked; the lead decides whether any of them can be dropped. +# seccomp_blocked Namespaces work but --seccomp fails: a nested filter cannot be installed +# under RuntimeDefault, or fd 3 is not inherited. Blocked: Stage B socket denial +# is a REQUIRED part of the two-stage isolation. +# partial An exact-shape attempt failed for another reason (bind, chdir, proc, dev, +# held-out visibility, host-side persistence). Read its message; treat the +# feature as blocked until the cause is understood. +# bwrap_unavailable No bwrap on PATH and the user-space bootstrap was skipped or failed. +# Inconclusive: re-run with an image that ships /usr/bin/bwrap (see pod.yaml). +# +# Notes: +# - The real worker negotiates bwrap only from /usr/bin/bwrap, /bin/bwrap, or /usr/local/bin/bwrap +# (TRUSTED_BWRAP_PATHS) and runs `--unshare-all --ro-bind / / /bin/true` before every job; +# attempt "negotiate-probe" runs exactly that command. The bootstrap below fetches a user-space +# copy into the emptyDir so the probe measures the kernel, not the image; the controller image +# must still ship a root-owned /usr/bin/bwrap. +# - The strict filter returns SECCOMP_RET_KILL_PROCESS, so a socket() call inside the sandbox is +# expected to kill the calling process with SIGSYS ("Bad system call"), not to fail with EPERM. +# Both observations count as "socket denied"; ENETUNREACH or ECONNREFUSED do not. +# - bwrap always creates a mount namespace; "userns-mount-proc-dev" is therefore the smallest +# namespace set it can attempt. +set -u +umask 077 + +OUT="${PROBE_OUT_DIR:-/probe-out}" +BWRAP="${PROBE_BWRAP:-}" +SKIP_APT="${PROBE_SKIP_APT:-0}" +ATTEMPT_TIMEOUT="${PROBE_ATTEMPT_TIMEOUT_S:-20}" +export TMPDIR="${TMPDIR:-/tmp}" + +# ---------------------------------------------------------------- helpers (classic BPF) +bpf_byte() { printf "\\$(printf '%03o' "$1")"; } + +bpf_instr() { # code jt jf k -> 8 bytes, struct sock_filter little-endian (same words as evaluator.ts) + bpf_byte $(( $1 & 0xff )); bpf_byte $(( ($1 >> 8) & 0xff )) + bpf_byte $(( $2 & 0xff )); bpf_byte $(( $3 & 0xff )) + bpf_byte $(( $4 & 0xff )); bpf_byte $(( ($4 >> 8) & 0xff )) + bpf_byte $(( ($4 >> 16) & 0xff )); bpf_byte $(( ($4 >> 24) & 0xff )) +} + +emit_seccomp_bpf() { # arch -> compileStrictSocketDenySeccompBpf(arch) on stdout + case "$1" in + x64) audit_arch=0xc000003e; block_x32=1 + set -- 101 246 320 165 166 155 321 298 323 250 248 249 425 426 427 41 53 42 49 50 43 288 ;; + arm64) audit_arch=0xc00000b7; block_x32=0 + set -- 117 104 294 40 39 41 280 241 282 219 217 218 425 426 427 198 199 203 200 201 202 242 ;; + *) echo "unsupported arch: $1" >&2; return 2 ;; + esac + bpf_instr 0x20 0 0 4 + bpf_instr 0x15 1 0 "$audit_arch" + bpf_instr 0x06 0 0 0x00050001 + bpf_instr 0x20 0 0 0 + if [ "$block_x32" -eq 1 ]; then bpf_instr 0x35 $(( $# + 1 )) 0 0x40000000; fi + n=$#; i=0 + for nr in "$@"; do bpf_instr 0x15 $(( n - i )) 0 "$nr"; i=$(( i + 1 )); done + bpf_instr 0x06 0 0 0x7fff0000 + bpf_instr 0x06 0 0 0x00050001 +} + +if [ "${1:-}" = "--emit-seccomp-bpf" ]; then + emit_seccomp_bpf "${2:-}" + exit $? +fi + +# ---------------------------------------------------------------- setup +mkdir -p "$OUT" 2>/dev/null || true +LOG="$OUT/bwrap-probe.jsonl" +if ! : > "$LOG" 2>/dev/null; then + printf '{"attempt":"probe-setup","ok":false,"errno":"EACCES","message":"PROBE_OUT_DIR is not writable: %s"}\n' "$OUT" + exit 2 +fi +case "$OUT" in + *[[:space:]]*|*[\'\"]*) + printf '{"attempt":"probe-setup","ok":false,"errno":"EINVAL","message":"PROBE_OUT_DIR must not contain whitespace or quotes"}\n' | tee -a "$LOG" + exit 2 + ;; +esac + +# ---------------------------------------------------------------- helpers (JSON, errno) +json_escape() { + tr -d '\000-\037\177\200-\377' | sed -e 's/\\/\\\\/g' -e 's/"/\\"/g' | head -c 400 +} + +emit() { # attempt ok exit errno message + line=$(printf '{"attempt":"%s","ok":%s,"exit":%s,"errno":"%s","message":"%s"}' \ + "$1" "$2" "$3" "$4" "$(printf '%s' "$5" | json_escape)") + printf '%s\n' "$line" >> "$LOG" + printf '%s\n' "$line" +} + +errno_of() { # exit_code message + case "$2" in + *"Operation not permitted"*|*"No permissions to create"*|*"No permissions to creating"*) echo EPERM ;; + *"Permission denied"*) echo EACCES ;; + *"Read-only file system"*) echo EROFS ;; + *"No such file or directory"*) echo ENOENT ;; + *"Invalid argument"*) echo EINVAL ;; + *"No space left on device"*) echo ENOSPC ;; + *"Resource temporarily unavailable"*) echo EAGAIN ;; + *"Not supported"*|*"Operation not supported"*) echo EOPNOTSUPP ;; + *"Unexpected capabilities"*) echo ECAP ;; + *"Bad system call"*) echo EKILLED_SIGSYS ;; + *) if [ "$1" -eq 124 ]; then echo ETIMEOUT; else echo "EXIT$1"; fi ;; + esac +} + +status_field() { # /proc/self/status field name -> value (empty when absent) + [ -r /proc/self/status ] || return 0 + awk -v k="$1" '$1 == k ":" { print $2; exit }' /proc/self/status 2>/dev/null +} + +read_or_na() { [ -r "$1" ] && head -c 64 "$1" 2>/dev/null | tr -d '\n' || echo na; } + +# ---------------------------------------------------------------- helpers (attempts) +attempt_fd3="" +attempt_stdout_note="" + +run_attempt() { # name cmd args... (timeout-wrapped; fd 3 bound to $attempt_fd3 when set) + name="$1"; shift + if [ -n "$attempt_fd3" ] && [ ! -f "$attempt_fd3" ]; then + attempt_fd3="" + emit "$name" false 1 ENOENT "seccomp filter file missing: the strict filter was not compiled for this architecture" + return 1 + fi + if [ -n "$attempt_fd3" ]; then + timeout "$ATTEMPT_TIMEOUT" "$@" 3<"$attempt_fd3" >"$OUT/$name.stdout" 2>"$OUT/$name.stderr" + rc=$? + else + timeout "$ATTEMPT_TIMEOUT" "$@" >"$OUT/$name.stdout" 2>"$OUT/$name.stderr" + rc=$? + fi + attempt_fd3="" + err_note=$(head -c 300 "$OUT/$name.stderr" 2>/dev/null | tr '\n' ' ' | sed -e 's/ */ /g' -e 's/^ //' -e 's/ $//') + out_note=$(head -n 1 "$OUT/$name.stdout" 2>/dev/null | head -c 120) + msg="$err_note" + if [ -n "$out_note" ]; then + if [ -n "$msg" ]; then msg="$msg | $out_note"; else msg="$out_note"; fi + fi + if [ -n "$attempt_stdout_note" ]; then msg="$msg [$attempt_stdout_note]"; attempt_stdout_note=""; fi + if [ "$rc" -eq 0 ]; then ok=true; errno=-; else ok=false; errno=$(errno_of "$rc" "$err_note"); fi + emit "$name" "$ok" "$rc" "$errno" "$msg" + [ "$rc" -eq 0 ] +} + +attempt_ok() { grep -q "\"attempt\":\"$1\",\"ok\":true" "$LOG"; } + +bootstrap_apt() { # user-space bubblewrap + libcap2 into the emptyDir (needs egress to deb.debian.org) + APT="$OUT/apt"; ROOT="$OUT/root" + mkdir -p "$APT/lists/partial" "$APT/cache/archives/partial" "$APT/deb" "$ROOT" \ + || { emit bootstrap false 1 EIO "cannot create $APT or $ROOT"; return 1; } + HOME="$OUT"; export HOME + APT_OPTS="-o Dir::State::lists=$APT/lists -o Dir::Cache=$APT/cache -o Dir::Cache::pkgcache= -o Dir::Cache::srcpkgcache= -o Debug::NoLocking=1 -o APT::Get::List-Cleanup=0 -o Acquire::Retries=1" + if ! apt-get $APT_OPTS update >"$OUT/apt-update.log" 2>&1; then + emit bootstrap false 1 ENETUNREACH "apt-get update failed (egress to deb.debian.org is required, or re-run with an image that ships /usr/bin/bwrap); see apt-update.log" + return 1 + fi + if ! (cd "$APT/deb" && apt-get $APT_OPTS download bubblewrap libcap2 >"$OUT/apt-download.log" 2>&1); then + emit bootstrap false 1 ENETUNREACH "apt-get download failed; see apt-download.log" + return 1 + fi + for deb in "$APT/deb"/*.deb; do + [ -f "$deb" ] || continue + dpkg-deb -x "$deb" "$ROOT" || { emit bootstrap false 1 EIO "dpkg-deb -x failed for ${deb##*/}"; return 1; } + done + BWRAP="$ROOT/usr/bin/bwrap" + [ -x "$BWRAP" ] || { emit bootstrap false 1 ENOENT "bwrap missing after extraction"; return 1; } + libdir=$(dirname "$(find "$ROOT/usr/lib" -name 'libcap.so.2*' 2>/dev/null | head -n 1)") + if [ -n "$libdir" ] && [ -d "$libdir" ]; then + LD_LIBRARY_PATH="$libdir${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"; export LD_LIBRARY_PATH + fi + emit bootstrap true 0 - "fetched bubblewrap and libcap2 into the emptyDir (user-space copy; the controller image must ship a root-owned /usr/bin/bwrap)" +} + +# ---------------------------------------------------------------- context +ARCH="$(uname -m)"; KERNEL="$(uname -r)" +BWRAP_ARCH="" +case "$ARCH" in x86_64) BWRAP_ARCH=x64 ;; aarch64|arm64) BWRAP_ARCH=arm64 ;; esac +printf '{"attempt":"context","ok":true,"uid":%s,"gid":%s,"arch":"%s","kernel":"%s","bwrap_arch":"%s","cap_eff":"%s","cap_bnd":"%s","no_new_privs":"%s","seccomp":"%s","seccomp_filters":"%s","userns_max":"%s","unprivileged_userns_clone":"%s","apparmor_restrict_userns":"%s","apparmor_profile":"%s","lsm":"%s","selinuxfs":"%s","landlock_abi":"%s","bwrap":"%s","bwrap_version":"%s"}\n' \ + "$(id -u)" "$(id -g)" "$ARCH" "$KERNEL" "$BWRAP_ARCH" \ + "$(status_field CapEff)" "$(status_field CapBnd)" "$(status_field NoNewPrivs)" \ + "$(status_field Seccomp)" "$(status_field Seccomp_filters)" \ + "$(read_or_na /proc/sys/user/max_user_namespaces)" \ + "$(read_or_na /proc/sys/kernel/unprivileged_userns_clone)" \ + "$(read_or_na /proc/sys/kernel/apparmor_restrict_unprivileged_userns)" \ + "$(read_or_na /proc/self/attr/current)" \ + "$(read_or_na /sys/kernel/security/lsm)" \ + "$([ -d /sys/fs/selinux ] && echo present || echo absent)" \ + "$(read_or_na /sys/kernel/security/landlock/abi)" \ + "pending" "pending" | tee -a "$LOG" + +# ---------------------------------------------------------------- bwrap +if [ -z "$BWRAP" ]; then + if command -v bwrap >/dev/null 2>&1; then + BWRAP="$(command -v bwrap)" + elif [ "$SKIP_APT" = "1" ]; then + emit bwrap-unavailable false 1 ENOENT "no bwrap on PATH and PROBE_SKIP_APT=1" + emit summary false 0 ENOENT "verdict=bwrap_unavailable feature=inconclusive: re-run with an image that ships /usr/bin/bwrap (see pod.yaml)" + exit 0 + else + bootstrap_apt || { emit summary false 1 ENOENT "verdict=bwrap_unavailable feature=inconclusive: bootstrap failed; read the bootstrap line"; exit 0; } + fi +fi +if [ ! -x "$BWRAP" ]; then + emit bwrap-unavailable false 1 ENOENT "bwrap is not executable: $BWRAP" + emit summary false 1 ENOENT "verdict=bwrap_unavailable feature=inconclusive: install bubblewrap or point PROBE_BWRAP at it" + exit 0 +fi +BWRAP_VERSION="$("$BWRAP" --version 2>&1 | head -n 1)" +emit bwrap-found true 0 - "path=$BWRAP version=$BWRAP_VERSION" + +# ---------------------------------------------------------------- fixtures (all inside $OUT) +CAND="$OUT/candidate"; A_OUT="$OUT/stage-a-out"; SCR="$OUT/scratch"; WL="$OUT/workload"; TC="$OUT/toolchain" +mkdir -p "$CAND" "$A_OUT" "$SCR" "$WL" "$TC/bin" +printf '#!/bin/sh\necho stage-a\n' > "$CAND/build.sh"; chmod 0755 "$CAND/build.sh" +printf '// kernel\n' > "$CAND/kernel.cu" +printf 'GOLDEN\n' > "$WL/secret-golden.bin"; chmod 0400 "$WL/secret-golden.bin" +printf '#!/bin/sh\necho evaluate\n' > "$WL/evaluate.sh"; chmod 0555 "$WL/evaluate.sh" +printf '#!/bin/sh\n' > "$TC/bin/toolchain-stub"; chmod 0755 "$TC/bin/toolchain-stub" +CAND_BEFORE="$(sha256sum "$CAND/build.sh" "$CAND/kernel.cu" 2>/dev/null)" + +{ bpf_instr 0x06 0 0 0x7fff0000; } > "$OUT/seccomp-allowall.bpf" +if [ -n "$BWRAP_ARCH" ]; then + emit_seccomp_bpf "$BWRAP_ARCH" > "$OUT/seccomp-strict.bpf" || emit seccomp-bpf false 1 EINVAL "cannot compile the strict filter for $ARCH" +else + emit seccomp-bpf false 1 EINVAL "unsupported architecture $ARCH: the evaluator cannot run native_os here either" +fi + +# Same flag families as buildStrictLinuxBwrapArgs (narrow /usr subpaths and optional system ro-binds). +COMMON="--unshare-all --unshare-pid --die-with-parent --new-session --tmpfs / --proc /proc --dev /dev --tmpfs /tmp" +RO_BINDS="" +for p in /usr/bin /usr/sbin /usr/lib /usr/lib32 /usr/lib64 /usr/libexec /usr/include /usr/share \ + /usr/x86_64-linux-gnu /usr/aarch64-linux-gnu /usr/local/bin /usr/local/lib /usr/local/lib64 /usr/local/include \ + /bin /sbin /lib /lib32 /lib64 /etc/ld.so.cache /etc/ld.so.conf /etc/ld.so.conf.d /etc/alternatives \ + /etc/ssl/openssl.cnf /etc/ssl/certs /etc/ca-certificates /etc/pki/ca-trust /etc/pki/tls/certs \ + /etc/pki/tls/cacerts /etc/pki/tls/openssl.cnf; do + RO_BINDS="$RO_BINDS --ro-bind-try $p $p" +done +SETENV="--clearenv --setenv HOME $SCR --setenv TMPDIR $SCR --setenv PATH /usr/local/bin:/usr/bin:/bin --setenv LANG C.UTF-8 --setenv TERM dumb" + +INNER_SOCKET='s="$({ (exec 3<>/dev/tcp/127.0.0.1/9) 2>&1; echo "rc=$?"; } 2>&1 | tr "\n" " ")" +case "$s" in + *"not permitted"*) sock=EPERM ;; + *"Bad system call"*|*"rc=159"*) sock=SIGSYS ;; + *"Network is unreachable"*) sock=ENETUNREACH ;; + *"Connection refused"*) sock=ECONNREFUSED ;; + *) sock="other:${s:0:80}" ;; +esac +case "$sock" in + EPERM|SIGSYS) echo "ok socket_denied=$sock"; exit 0 ;; + *) echo "socket_not_denied=$sock"; exit 16 ;; +esac' +INNER_A='c="$1"; o="$2"; w="$3"; expect="$4" +[ -r "$c/build.sh" ] || { echo "cand_unreadable"; exit 10; } +[ -w "$o" ] || { echo "out_not_writable"; exit 11; } +echo probe > "$o/stage-a-write" 2>/dev/null || { echo "out_write_failed"; exit 11; } +[ -r /proc/self/status ] || { echo "proc_missing"; exit 12; } +[ -c /dev/null ] || { echo "dev_null_missing"; exit 13; } +[ "$(pwd)" = "$expect" ] || { echo "cwd_mismatch:$(pwd)"; exit 14; } +[ -e "$w/secret-golden.bin" ] && { echo "held_out_visible_in_stage_a"; exit 15; } +'"$INNER_SOCKET" +INNER_B='o="$1"; w="$2"; s="$3"; c="$4" +[ -r "$o/stage-a-write" ] || { echo "stage_a_out_unreadable"; exit 20; } +{ echo x > "$o/stage-b-write"; } 2>/dev/null && { echo "stage_a_out_writable"; exit 21; } +[ -r "$w/secret-golden.bin" ] || { echo "workload_unreadable"; exit 22; } +[ -w "$s" ] || { echo "scratch_not_writable"; exit 23; } +[ -e "$c/build.sh" ] && { echo "candidate_visible_in_stage_b"; exit 24; } +'"$INNER_SOCKET" + +# ---------------------------------------------------------------- attempts (each recorded separately) +# 1. Exactly what negotiateSandboxBackend runs before every native_os job. +run_attempt negotiate-probe "$BWRAP" --unshare-all --ro-bind / / /bin/true +# 2. Disambiguate: which member of --unshare-all fails, if any. +run_attempt unshare-all-share-net "$BWRAP" --unshare-all --share-net --ro-bind / / /bin/true +# 3. The smallest namespace set bwrap can attempt (it always creates a mount namespace). +run_attempt userns-mount-proc-dev "$BWRAP" --unshare-user --ro-bind / / --proc /proc --dev /dev /bin/true +# 4. fd 3 + nested seccomp mechanism with a one-instruction allow-all filter. +attempt_fd3="$OUT/seccomp-allowall.bpf" +run_attempt seccomp-fd3-allowall "$BWRAP" --unshare-all --ro-bind / / --seccomp 3 -- /bin/true +# 5. The strict Stage B socket-denial filter must at least load. +attempt_fd3="$OUT/seccomp-strict.bpf" +run_attempt seccomp-fd3-strict "$BWRAP" --unshare-all --ro-bind / / --seccomp 3 -- /bin/true +# 6. Stage A exact shape: candidate ro, stage-a-out rw, scratch rw, no held-out workload, sockets denied. +attempt_fd3="$OUT/seccomp-strict.bpf" +run_attempt stage-a-exact-shape "$BWRAP" $COMMON $RO_BINDS --ro-bind "$TC" "$TC" --ro-bind "$CAND" "$CAND" \ + --bind "$A_OUT" "$A_OUT" --bind "$SCR" "$SCR" --chdir "$CAND" $SETENV --seccomp 3 -- \ + /bin/bash -c "$INNER_A" bwrap-probe "$CAND" "$A_OUT" "$WL" "$CAND" +# 7. Stage B exact shape: stage-a-out ro, held-out snapshot ro, scratch rw, no candidate, sockets denied. +attempt_fd3="$OUT/seccomp-strict.bpf" +run_attempt stage-b-exact-shape "$BWRAP" $COMMON $RO_BINDS --ro-bind "$TC" "$TC" --ro-bind "$A_OUT" "$A_OUT" \ + --ro-bind "$WL" "$WL" --bind "$SCR" "$SCR" --chdir "$SCR" $SETENV --seccomp 3 -- \ + /bin/bash -c "$INNER_B" bwrap-probe "$A_OUT" "$WL" "$SCR" "$CAND" + +# Host-side facts the sandbox cannot report about itself. +a_ok=false +if [ -f "$A_OUT/stage-a-write" ] && [ "$(sha256sum "$CAND/build.sh" "$CAND/kernel.cu" 2>/dev/null)" = "$CAND_BEFORE" ] && [ ! -e "$CAND/stage-a-write" ]; then a_ok=true; fi +if [ "$a_ok" = true ]; then + emit stage-a-host-checks true 0 - "stage-a-out bind persisted the write; candidate tree unchanged" +else + emit stage-a-host-checks false 1 EINVAL "stage-a-out bind did not persist the write, or the candidate tree changed" +fi +b_ok=false +if [ ! -e "$A_OUT/stage-b-write" ] && [ -f "$A_OUT/stage-a-write" ] && [ ! -w "$WL/secret-golden.bin" ]; then b_ok=true; fi +if [ "$b_ok" = true ]; then + emit stage-b-host-checks true 0 - "stage-a-out stayed read-only under Stage B; workload snapshot untouched" +else + emit stage-b-host-checks false 1 EINVAL "Stage B wrote into stage-a-out or the workload snapshot changed" +fi + +# ---------------------------------------------------------------- summary +verdict=""; feature="stop" +if attempt_ok userns-mount-proc-dev; then + if attempt_ok negotiate-probe && attempt_ok seccomp-fd3-allowall && attempt_ok seccomp-fd3-strict \ + && attempt_ok stage-a-exact-shape && attempt_ok stage-a-host-checks \ + && attempt_ok stage-b-exact-shape && attempt_ok stage-b-host-checks; then + verdict="namespaces_ok"; feature="proceed" + elif ! attempt_ok negotiate-probe; then + if attempt_ok unshare-all-share-net; then verdict="netns_blocked"; feature="lead-decides"; else verdict="other_ns_blocked"; feature="lead-decides"; fi + elif ! attempt_ok seccomp-fd3-allowall || ! attempt_ok seccomp-fd3-strict; then + verdict="seccomp_blocked" + else + verdict="partial"; feature="lead-decides" + fi +else + verdict="namespaces_blocked" +fi +if [ "$feature" = proceed ]; then ok=true; else ok=false; fi +emit summary "$ok" 0 - "verdict=$verdict feature=$feature" diff --git a/specs/2026-11-30-managed-controller-in-process-execution.md b/specs/2026-11-30-managed-controller-in-process-execution.md index 8090dc52..0c29d26f 100644 --- a/specs/2026-11-30-managed-controller-in-process-execution.md +++ b/specs/2026-11-30-managed-controller-in-process-execution.md @@ -316,7 +316,8 @@ controller's own environment on a host whose isolation the registry attests. RuntimeDefault seccomp usually cannot create them, so the first task is a feasibility probe in the target Pod profile, and the feature stays behind it. - `hardwareProvenance` gains an optional `isolation: 'docker' | 'host_attested'`. Every receipt - the worker signs carries it. An absent `isolation` marks a receipt that predates the field; only + a worker running under `deviceOwnership: host` signs carries it; no worker sets it in this + version, because F5 is blocked (see T11). An absent `isolation` marks a receipt that predates the field; only the docker backend could produce such a receipt, because `native_os` refuses `probeMode: physical` today. The type and schema live in [evidence.ts](../packages/core/src/evidence.ts) and the parser in [schema.ts](../packages/evolution/src/schema.ts); T9 owns both. `evolve export` refuses @@ -393,7 +394,8 @@ controller's own environment on a host whose isolation the registry attests. - `node:sqlite` on Linux differs from darwin → CI already runs every suite on both Linux profiles; ADR 0003 records the qualified profiles and the `fullfsync` semantics. - `native_os` isolation is unavailable in a restricted Pod → F5 starts with a feasibility probe - and stays behind it; `host_attested` receipts never pass for enforced isolation. + and stays behind it; `host_attested` receipts never pass for enforced isolation. Measured + 2026-12-01: `namespaces_blocked` (see T11); F5 stays closed in this version. ## Design Details @@ -585,14 +587,15 @@ and T11 have disjoint `Owns:` and start together; T5 follows T2. Verify: `node scripts/run-tests.mjs --pkg cli && npm run lint:docs && npm run site` - [ ] **T11 · In-process benchmark gate, feasibility first (phase 2)** Blocked by: None - Owns: `packages/hardware-runner/src/config.ts`, `packages/hardware-runner/src/worker.ts`, `packages/hardware-runner/src/evaluator.ts`, `packages/hardware-runner/src/provenance.ts`, `packages/hardware-runner/src/relay-server.ts`, `packages/hardware-runner/src/index.ts`, `packages/hardware-runner/src/types.ts`, `packages/controller/src/benchmark-gate.ts`, `packages/hardware-runner/test/**`, `packages/cli/src/main.ts`, `packages/cli/src/arguments.ts`, `packages/cli/test/runner-inline.test.ts`, `packages/cli/test/runner-cli.test.ts` + Owns: `packages/hardware-runner/src/config.ts`, `packages/hardware-runner/src/worker.ts`, `packages/hardware-runner/src/evaluator.ts`, `packages/hardware-runner/src/provenance.ts`, `packages/hardware-runner/src/relay-server.ts`, `packages/hardware-runner/src/index.ts`, `packages/hardware-runner/test/**`, `packages/cli/src/main.ts`, `packages/cli/src/arguments.ts`, `packages/cli/test/runner-inline.test.ts` Gate: review + Status: blocked_external (2026-12-01). The probe ran under PSA `restricted` on kind v0.33 (Kubernetes 1.37, containerd 2.3.4, kernel 6.17) and settled `namespaces_blocked`: RuntimeDefault seccomp denies namespace creation, the drop-ALL bounding set stops bubblewrap at uid mapping even with seccomp relaxed (which `restricted` forbids), and the node has no Landlock ABI. Stage 1 is delivered (`packages/hardware-runner/test/bwrap-namespace-probe.test.ts` holds `RECORDED_PROBE_OUTCOME`); no feature code was written and the stage-2 `Owns:` widenings are void. Acceptance: first, a recorded probe decides whether `native_os` can create its namespaces under the target Pod profile (RuntimeDefault seccomp, all capabilities dropped); if it cannot, the task reports that and stops before any feature code. Then `deviceOwnership: host` permits `sandboxBackend: native_os` with `probeMode: physical`, `hardwareProvenance.isolation` (the optional T9 field) records `docker` or `host_attested`, and `loopwright runner inline --config worker.yaml` serves relay and worker in one process on loopback; a loopback end-to-end test runs `benchmark-gate.v1` through the inline runner on `synthetic_fixture`; the physical evidence row stays `blocked_external`. Verify: `node scripts/run-tests.mjs --pkg hardware-runner && node scripts/run-tests.mjs --pkg cli` - [ ] **T12 · In-process gate documentation (phase 2)** Blocked by: T8, T10, T11 Owns: `docs/operations/cli.md`, `docs/configuration/task-contract.md`, `docs/contribute/closure-matrix.md`, `docs/README.md` - Acceptance: `runner inline`, `deviceOwnership`, the `isolation` field, and the `blocked_external` row are documented and indexed. + Acceptance: the feasibility probe, its recorded `namespaces_blocked` verdict, the `isolation` field, and the `blocked_external` row are documented and indexed; `runner inline` and `deviceOwnership` are documented as not implemented in this version because the probe blocked them. Verify: `npm run lint:docs && npm run site` ### Test Plan From 079f66237849f0527a2c6806c1292b115a85f56c Mon Sep 17 00:00:00 2001 From: thxCode Date: Tue, 1 Dec 2026 09:26:41 +0800 Subject: [PATCH 11/26] feat(controller): run command.v1 checks in-process through LocalCheck - core contract: env names, env name rule, strict CHECK_OUT parser - LocalCheck mirrors Gate.run: intent, permit, binding with pgid, proof, receipt - candidate workspace via T1 helpers; F1 environment; process-group kill on timeout - host_execution evidence; restore settles blocked/EVIDENCE_UNAVAILABLE, never re-dispatches - T3 spec check-off; T4 Owns widened with retained.ts and acceptance.ts Task 3 of managed-controller-in-process-execution. Signed-off-by: thxCode --- .../controller/src/candidate-workspace.ts | 17 +- packages/controller/src/local-check.ts | 500 ++++++++++++++++++ .../controller/test/fixtures/scripts/fail.sh | 5 + .../controller/test/fixtures/scripts/pass.sh | 4 + .../test/fixtures/scripts/print-env.sh | 9 + .../controller/test/fixtures/scripts/sleep.sh | 4 + .../scripts/write-outside-candidate.sh | 18 + .../controller/test/local-check-fixtures.ts | 149 ++++++ packages/controller/test/local-check.test.ts | 316 +++++++++++ packages/core/src/index.ts | 4 + packages/core/src/local-check-contract.ts | 69 +++ .../core/test/local-check-contract.test.ts | 119 +++++ ...managed-controller-in-process-execution.md | 18 +- 13 files changed, 1218 insertions(+), 14 deletions(-) create mode 100644 packages/controller/src/local-check.ts create mode 100755 packages/controller/test/fixtures/scripts/fail.sh create mode 100755 packages/controller/test/fixtures/scripts/pass.sh create mode 100755 packages/controller/test/fixtures/scripts/print-env.sh create mode 100755 packages/controller/test/fixtures/scripts/sleep.sh create mode 100755 packages/controller/test/fixtures/scripts/write-outside-candidate.sh create mode 100644 packages/controller/test/local-check-fixtures.ts create mode 100644 packages/controller/test/local-check.test.ts create mode 100644 packages/core/src/local-check-contract.ts create mode 100644 packages/core/test/local-check-contract.test.ts diff --git a/packages/controller/src/candidate-workspace.ts b/packages/controller/src/candidate-workspace.ts index a1a9278d..982ce088 100644 --- a/packages/controller/src/candidate-workspace.ts +++ b/packages/controller/src/candidate-workspace.ts @@ -38,11 +38,15 @@ import { } from './types.js'; import { isWritableCandidateFile, resolveCurrentFileModes } from './step.js'; +/** + * `role: null` materializes a check workspace (`command.v1`): every file writable, and `activeResources` + * names the staged context because a check has no role to select resources. + */ export async function materializeAttemptWorkspace( cycle: Cycle, runRoot: string, attemptId: string, - role: PlannedRole, + role: PlannedRole | null, repair: ControllerAttempt['repair'], hostProtection: HostPathProtectionOptions, activeResources?: ReturnType, @@ -70,8 +74,9 @@ export async function materializeAttemptWorkspace( await privateDirectory(stagingContextDir, excluded); try { - const effectiveTools = repair === 'format' ? [] : role.policy.tools; - const readOnlyRole = repair === 'format' || !effectiveTools.some(tool => tool === 'write' || tool === 'edit' || tool === 'delete' || tool === 'bash'); + if (role === null && activeResources === undefined) refuse('CONFIG_SCHEMA', '/spec/profiles/roles', phase); + const effectiveTools = repair === 'format' ? [] : role?.policy.tools ?? []; + const readOnlyRole = role !== null && (repair === 'format' || !effectiveTools.some(tool => tool === 'write' || tool === 'edit' || tool === 'delete' || tool === 'bash')); const modes = await resolveCurrentFileModes(context, cycle.head, cycle.candidate.files); if (source.version === 2) { @@ -114,7 +119,7 @@ export async function materializeAttemptWorkspace( for (const file of cycle.candidate.files) allPaths.add(file.name); for (const relPath of allPaths) { const gitMode = modes.get(relPath) ?? '100644'; - const writable = !readOnlyRole && isWritableCandidateFile(relPath, plan.scope, hostProtection); + const writable = role === null || (!readOnlyRole && isWritableCandidateFile(relPath, plan.scope, hostProtection)); const perm = gitMode === '100755' ? (writable ? 0o700 : 0o500) : (writable ? 0o600 : 0o400); await chmod(join(stagingCandidateDir, relPath), perm); } @@ -123,7 +128,7 @@ export async function materializeAttemptWorkspace( const targetPath = join(stagingCandidateDir, item.name); await mkdir(dirname(targetPath), { recursive: true, mode: 0o700 }); const gitMode = modes.get(item.name) ?? '100644'; - const writable = !readOnlyRole && isWritableCandidateFile(item.name, plan.scope, hostProtection); + const writable = role === null || (!readOnlyRole && isWritableCandidateFile(item.name, plan.scope, hostProtection)); const perm = gitMode === '100755' ? (writable ? 0o700 : 0o500) : (writable ? 0o600 : 0o400); if ('bytes' in item) { const file = await open(targetPath, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, perm); @@ -150,7 +155,7 @@ export async function materializeAttemptWorkspace( } } - const effectiveResources = activeResources ?? roleResourcesFor(loaded, plan, role.roleId); + const effectiveResources = activeResources ?? (role === null ? refuse('CONFIG_SCHEMA', '/spec/profiles/roles', phase) : roleResourcesFor(loaded, plan, role.roleId)); const stagedContextFiles = await materializeContextFilesDir( stagingContextDir, effectiveResources, diff --git a/packages/controller/src/local-check.ts b/packages/controller/src/local-check.ts new file mode 100644 index 00000000..676e2215 --- /dev/null +++ b/packages/controller/src/local-check.ts @@ -0,0 +1,500 @@ +import { constants } from 'node:fs'; +import { chmod, lstat, mkdir, open, readdir, readFile, rm } from 'node:fs/promises'; +import { spawn, type ChildProcess } from 'node:child_process'; +import { dirname, join } from 'node:path'; +import type { Readable } from 'node:stream'; +import { + LOCAL_CHECK_ENV_FIXED, LOCAL_CHECK_ENV_NAMES, LOCAL_CHECK_LIMITS, LOCAL_CHECK_PATH_BASE, SecretScrubber, bindSubject, digestArtifact, + isLocalCheckEnvName, parseLocalCheckOut, validateDocument, + type ArtifactRef, type Digest, type Evidence, type LocalCheckOutput, type LocalCheckSpec, type Subject, type TaskLock, +} from '@loopwright/core'; +import type { Authority, DispatchPermit, LocalRunStore, OperationReceipt, OperationRecord, RunView } from '@loopwright/state'; +import { materializeAttemptWorkspace } from './candidate-workspace.js'; +import type { Cycle } from './controller.js'; +import { approvedState } from './config.js'; +import { ControllerFailure, refuse, type ControllerDiagnostic } from './errors.js'; +import { readBoundedFile } from './files.js'; +import { parsePrivateJson } from './parser.js'; +import { verifierOperationId } from './progress.js'; +import { effectiveRunHostPolicy, hostProtectionFromPolicy } from './retained.js'; +import { canonical, checkedRef, freeze, hash, id, integer, isRecord, list, record, same, text } from './schema.js'; +import { materializeBaseline, matchesScopePattern } from './source.js'; +import { ArtifactStore, stateValue } from './storage.js'; +import type { CompiledPlan, VerifierSlot } from './types.js'; +import type { ByteInventory, VerifiedCheck } from './verification.js'; + +/** + * Managed Controller `command.v1` executor and authority path, modeled on `Gate.run`: intent, dispatch permit, binding + * marker, execution, proof marker, receipt, `VerifiedCheck`. The controller's own environment is the sandbox (`direct`); + * this module records what ran, bounds time and output, and never reads or passes `process.env` or a credential. + */ +export const LOCAL_CHECK_PRODUCER_ID = 'loopwright.local-check.v1'; +export const LOCAL_CHECK_METHOD = 'direct_script'; +/** Output artifact cap: a 64 KiB check-out plus a 16 KiB stderr tail that JSON escaping may grow sixfold. */ +export const LOCAL_CHECK_OUTPUT_BYTES = 262_144; +export const LOCAL_CHECK_STDERR_BYTES = 16_384; +const MARKER_BYTES = 1_048_576; +const GROUP_EXIT_WAIT_MS = 2_000; +const STDERR_DRAIN_MS = 500; +const FILE_BYTES = 67_108_864; +const SHEBANG = Buffer.from('#!'); +const PARAMETER_KEYS = ['checkId', 'script', 'args', 'env', 'toolchainPaths', 'timeoutMs'] as const; +const HANDLERS_PATH = '/registry/spec/handlers'; + +export interface PreparedLocalCheck { readonly version: 1; readonly slotId: string; readonly generation: number; readonly operationId: string; readonly producerNonce: string; readonly requestDigest: Digest } +/** What admission recorded in the compiled slot for the script's directory; `planDigest` covers it. */ +export interface LocalCheckRecorded { readonly scriptDirectoryDigest: Digest } +export interface LocalCheckScriptEntry { readonly path: string; readonly mode: '100644' | '100755'; readonly byteLength: number; readonly sha256: string } +interface Preparation { readonly slot: VerifierSlot; readonly spec: LocalCheckSpec; readonly recorded: LocalCheckRecorded; readonly subject: Subject; readonly candidateDigest: Digest; readonly candidateBytes: number } +const preparations = new WeakMap(); + +/** The receipt artifact: the store's `OperationReceipt` plus what F1 requires every `command.v1` receipt to carry. */ +export interface LocalCheckReceipt extends OperationReceipt { + readonly script: string; + /** `null` only when the operation settled without a binding marker, that is, when the script never provably ran. */ + readonly scriptDigest: Digest | null; + readonly scriptDirectoryDigest: Digest; + readonly registryDigest: Digest; +} +interface OutputError { readonly code: string; readonly path: string } +interface Observation { + readonly transport: 'completed' | 'timeout' | 'interrupted'; + readonly exitCode: number | null; readonly exitSignal: string | null; readonly timedOut: boolean; readonly elapsedMs: number; + readonly output: LocalCheckOutput | null; readonly outputError: OutputError | null; + readonly stderrTail: string; readonly stderrTruncated: boolean; +} +interface DispatchReceipt { readonly generation: number; readonly dispatchId: string; readonly revision: number; readonly clockEpoch: string } +interface Binding { + readonly version: 1; readonly planDigest: Digest; readonly operationId: string; readonly producerNonce: string; readonly requestDigest: Digest; readonly intentDigest: Digest; + readonly subject: Subject; readonly generation: number; readonly checkId: string; readonly script: string; readonly scriptDigest: Digest; + readonly scriptDirectoryDigest: Digest; readonly registryDigest: Digest; + /** `null` when the child could not be spawned; no group exists then. */ + readonly pgid: number | null; + readonly workspaceDir: string; + readonly dispatchReceipt: DispatchReceipt; +} +type Disposition = { readonly status: VerifiedCheck['status']; readonly reason: string | null; readonly method: typeof LOCAL_CHECK_METHOD }; +interface Workspace { readonly attemptDir: string; readonly candidateDir: string; readonly stagedDir: string; readonly baselineDir: string; readonly scratchDir: string; readonly checkOut: string } +interface Execution { + readonly intentDigest: Digest; readonly permit: DispatchPermit; readonly binding: Binding; readonly observation: Observation; readonly scriptDigest: Digest; +} +export interface LocalCheckObservation { + readonly evidence: Evidence; readonly subject: Subject; readonly outputBytes: Uint8Array; readonly receipt: OperationReceipt; readonly receiptRecord: LocalCheckReceipt; + readonly planDigest: Digest; readonly requestDigest: Digest; readonly pgid: number | null; + readonly header: { readonly handlerDigest: Digest; readonly handler: 'command.v1'; readonly candidate: { readonly ref: { readonly digest: Digest; readonly byteLength: number } } }; +} +const observations = new WeakMap(); +/** Original private producer proof only; nothing else may speak for a `command.v1` check. */ +export function authenticatedLocalCheck(value: VerifiedCheck): LocalCheckObservation { + const trusted = observations.get(value); if (!trusted) refuse('EVIDENCE_UNAVAILABLE', '', 'verification'); return trusted; +} + +/** Where attempt workspaces live; the live cycle is required to execute a check and is absent on recovery, which only settles. */ +export interface LocalCheckWorkspace { readonly runRoot: string; readonly cycle: Cycle | null } + +/** Pure digest over a script directory's entries; admission (T4) and the run-time re-verification call the same function. */ +export function localCheckScriptDirectoryDigest(entries: readonly LocalCheckScriptEntry[]): Digest { + const sorted = [...entries].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0)) + .map(entry => ({ path: entry.path, mode: entry.mode, byteLength: entry.byteLength, sha256: entry.sha256 })); + return hash('loopwright.dev/controller/local-check-script-directory/v1\0' + canonical(sorted)); +} + +/** Reads the script directory (the whole tree under the script's parent) from a materialized baseline. */ +export async function readLocalCheckScriptDirectory(baselineDir: string, script: string): Promise { + const dir = dirname(script) === '.' ? '' : dirname(script), root = dir ? join(baselineDir, dir) : baselineDir, entries: LocalCheckScriptEntry[] = []; + const visit = async (abs: string, rel: string): Promise => { + for (const item of (await readdir(abs, { withFileTypes: true })).sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))) { + const absPath = join(abs, item.name), relPath = rel ? rel + '/' + item.name : item.name, info = await lstat(absPath); + if (info.isSymbolicLink()) refuse('ARTIFACT_INVALID', '', 'verification'); + if (info.isDirectory()) { await visit(absPath, relPath); continue; } + if (!info.isFile()) refuse('ARTIFACT_INVALID', '', 'verification'); + const bytes = await readFile(absPath); + if (bytes.byteLength > FILE_BYTES) refuse('OUTPUT_LIMIT', '', 'verification'); + entries.push({ path: relPath, mode: (info.mode & 0o111) !== 0 ? '100755' : '100644', byteLength: bytes.byteLength, sha256: hash(bytes).hex }); + } + }; + await visit(root, dir); + return entries; +} + +function checkedSpec(parameters: Record, slot: VerifierSlot, scope: CompiledPlan['scope']): LocalCheckSpec { + const values = record(parameters, [...PARAMETER_KEYS], HANDLERS_PATH); + if (id(values.checkId, HANDLERS_PATH) !== slot.checkId) refuse('ARTIFACT_INVALID', '', 'verification'); + const script = text(values.script, HANDLERS_PATH, 1024); + if (!digestArtifact(script, new Uint8Array()).ok || !scope.protected.some(pattern => matchesScopePattern(pattern, script))) refuse('CONFIG_SCHEMA', HANDLERS_PATH, 'verification'); + const args = list(values.args, HANDLERS_PATH, 64).map(item => { const arg = text(item, HANDLERS_PATH); if (arg.includes('\0')) refuse('CONFIG_SCHEMA', HANDLERS_PATH, 'verification'); return arg; }); + if (!isRecord(values.env)) refuse('CONFIG_SCHEMA', HANDLERS_PATH, 'verification'); + const env: Record = Object.create(null) as Record; + for (const [name, raw] of Object.entries(values.env)) { + if (!isLocalCheckEnvName(name) || LOCAL_CHECK_ENV_NAMES.includes(name) || typeof raw !== 'string' || raw.length > 16_384 || raw.includes('\0')) refuse('CONFIG_SCHEMA', HANDLERS_PATH, 'verification'); + env[name] = raw; + } + if (Object.keys(env).length > 32) refuse('CONFIG_SCHEMA', HANDLERS_PATH, 'verification'); + const toolchainPaths = list(values.toolchainPaths, HANDLERS_PATH, 32).map(item => { + const path = text(item, HANDLERS_PATH, 1024); if (!digestArtifact(path, new Uint8Array()).ok) refuse('CONFIG_SCHEMA', HANDLERS_PATH, 'verification'); return path; + }); + const timeoutMs = integer(values.timeoutMs, LOCAL_CHECK_LIMITS.timeoutMsMin, LOCAL_CHECK_LIMITS.timeoutMsMax, HANDLERS_PATH); + return freeze({ script, args, env: freeze(env), toolchainPaths, timeoutMs }); +} + +/** Pure preparation: no intent, permit, timer, process, or filesystem operation. */ +export function prepareLocalCheck(plan: CompiledPlan, lock: TaskLock, slotId: string, candidate: ByteInventory, generation: number, producerNonce: string, recorded: LocalCheckRecorded): PreparedLocalCheck { + if (!same(plan.task, lock.spec.contract) || !/^[a-f0-9]{32}$/.test(producerNonce)) refuse('ARTIFACT_INVALID', '', 'verification'); integer(generation, 0, plan.capacity.V - 1); + const slot = plan.verifierSlots.find(item => item.id === slotId); + if (!slot || slot.handler.implementation !== 'command.v1' || slot.handler.kind !== 'check') refuse('CAPABILITY_UNSUPPORTED', '', 'verification'); + const overlayOpts = lock.spec.contract.spec.budgets.overlay ? { overlay: lock.spec.contract.spec.budgets.overlay } : undefined; + const subject = bindSubject(lock, candidate.manifest, overlayOpts); if (!subject.ok) refuse('ARTIFACT_INVALID', '', 'verification'); + const spec = checkedSpec(slot.handler.parameters, slot, plan.scope), scriptDirectoryDigest = recorded.scriptDirectoryDigest; + if (scriptDirectoryDigest.algorithm !== 'sha256' || !/^[0-9a-f]{64}$/.test(scriptDirectoryDigest.hex)) refuse('CONFIG_SCHEMA', HANDLERS_PATH, 'verification'); + const requestDigest = hash('loopwright.dev/controller/local-check-request/v1\0' + canonical({ planDigest: plan.planDigest, slotId, generation, checkId: slot.checkId, script: spec.script, scriptDirectoryDigest, registryDigest: plan.registryDigest, subject: subject.value, producerNonce })); + const value: PreparedLocalCheck = freeze({ version: 1, slotId, generation, operationId: verifierOperationId(lock.spec.runId, slotId, generation), producerNonce, requestDigest }); + preparations.set(value, { slot, spec, recorded: { scriptDirectoryDigest }, subject: subject.value, candidateDigest: hash(canonical(candidate.manifest)), candidateBytes: Buffer.byteLength(canonical(candidate.manifest)) }); return value; +} + +function killProcessGroup(pgid: number): void { try { process.kill(-pgid, 'SIGKILL'); } catch { /* the exact exit is confirmed below */ } } +function processGroupAlive(pgid: number): boolean { + try { process.kill(-pgid, 0); return true; } catch (error) { return (error as NodeJS.ErrnoException).code === 'EPERM'; } +} +/** SIGKILL the group until `kill(-pgid, 0)` reports ESRCH; a group that survives is a cleanup failure, never a success. */ +async function confirmProcessGroupGone(pgid: number, phase: ControllerDiagnostic['phase']): Promise { + const deadline = performance.now() + GROUP_EXIT_WAIT_MS; + while (processGroupAlive(pgid)) { + if (performance.now() > deadline) refuse('CLEANUP_FAILED', '', phase); + killProcessGroup(pgid); + await new Promise(resolve => { const timer = setTimeout(resolve, 15); timer.unref(); }); + } +} +/** After the group is gone every writer is dead; give the pipe a moment to reach EOF, then release it. */ +function drain(stream: Readable): Promise { + if (stream.readableEnded || stream.destroyed) return Promise.resolve(); + return new Promise(resolve => { + const timer = setTimeout(() => { stream.destroy(); resolve(); }, STDERR_DRAIN_MS); timer.unref(); + stream.once('end', () => { clearTimeout(timer); resolve(); }); stream.once('close', () => { clearTimeout(timer); resolve(); }); + }); +} +/** Directories of a read-only tree refuse `rm`; restore owner write on every directory, never following links. A tree that vanishes mid-walk was discarded by someone else. */ +async function removeTree(root: string, phase: ControllerDiagnostic['phase']): Promise { + const missing = (error: unknown) => (error as NodeJS.ErrnoException).code === 'ENOENT'; + try { + const openUp = async (abs: string): Promise => { + const info = await lstat(abs).catch(error => { if (missing(error)) return null; throw error; }); if (!info || info.isSymbolicLink() || !info.isDirectory()) return; + await chmod(abs, 0o700).catch(error => { if (!missing(error)) throw error; }); + for (const name of await readdir(abs).catch(error => { if (missing(error)) return []; throw error; })) await openUp(join(abs, name)); + }; + await openUp(root); + await rm(root, { recursive: true, force: true }); + } catch { refuse('CLEANUP_FAILED', '', phase); } +} +async function makeReadOnlyTree(root: string): Promise { + const visit = async (abs: string): Promise => { + const info = await lstat(abs); + if (info.isDirectory()) { await chmod(abs, 0o500); for (const name of await readdir(abs)) await visit(join(abs, name)); return; } + await chmod(abs, (info.mode & 0o111) !== 0 ? 0o500 : 0o400); + }; + await visit(root); +} + +/** Local command check: the Verifier intent/permit/receipt discipline with a child process group instead of a Worker. */ +export class LocalCheck { + constructor(readonly store: LocalRunStore, readonly authority: Authority, readonly artifacts: ArtifactStore, readonly plan: CompiledPlan, readonly lock: TaskLock, + readonly currentSubject: () => Subject, readonly workspace: LocalCheckWorkspace) {} + + #identity(): RunView { + const view = stateValue(this.store.inspect()); + if (view.storeId !== this.authority.storeId || view.runId !== this.lock.spec.runId || !same(view.lockHash, this.lock.spec.lockHash) + || this.artifacts.owner.runId !== view.runId || !same(this.artifacts.owner.planDigest, this.plan.planDigest)) refuse('AUTHORITY_REFUSED', '', 'verification'); return view; + } + #permit(permit: DispatchPermit, expected: Subject, target: string): void { + stateValue(this.store.renew(this.authority)); const view = stateValue(this.store.inspect()), operation = stateValue(this.store.getOperation(permit.operationId)); + if (!same(this.currentSubject(), expected) || permit.generation !== this.authority.generation || permit.clockEpoch !== view.clock.basis.clockEpoch + || view.storeId !== permit.storeId || view.runId !== permit.runId || !same(view.lockHash, permit.lockHash) + || BigInt(view.clock.sampledNow.monotonicMs) >= BigInt(permit.notAfterMonotonicMs) || BigInt(view.clock.sampledNow.monotonicMs) >= BigInt(view.clock.basis.taskDeadlineMonotonicMs) + || operation.state !== 'dispatch_uncertain' || operation.dispatch?.dispatchId !== permit.dispatchId || operation.intent.targetIdentity !== target) refuse('AUTHORITY_REFUSED', '', 'verification'); + } + async #marker(operationId: string, nonce: string, kind: 'binding' | 'proof', value: unknown): Promise { + await this.artifacts.owner.assertCurrent(); const name = 'local-check-producer-' + hash(operationId + '\0' + nonce).hex + '.' + kind + '.json', path = join(this.artifacts.directory, name), bytes = Buffer.from(canonical(value)); + if (bytes.byteLength > MARKER_BYTES) refuse('OUTPUT_LIMIT', '', 'verification'); this.artifacts.vault.assertClean(bytes); + let file: Awaited>; + try { file = await open(path, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600); } + catch (error) { if ((error as NodeJS.ErrnoException).code !== 'EEXIST' || !Buffer.from(await readBoundedFile(path, MARKER_BYTES, true)).equals(bytes)) refuse('RECOVERY_REQUIRED', '', 'verification'); return; } + try { await file.writeFile(bytes); await file.sync(); } finally { await file.close(); } + } + #attemptId(job: PreparedLocalCheck): string { return 'check.' + hash(job.operationId + '\0' + job.producerNonce).hex.slice(0, 40); } + #attemptDir(job: PreparedLocalCheck): string { return join(this.workspace.runRoot, 'workspaces', this.lock.spec.runId, this.#attemptId(job)); } + #target(job: PreparedLocalCheck, subject: Subject): string { return 'command:' + job.slotId + ':' + job.generation + ':' + subject.candidateDigest.hex; } + #suffix(job: PreparedLocalCheck): string { return hash(job.operationId + '\0' + job.producerNonce).hex.slice(0, 40); } + + /** Candidate through the shared workspace helper (writable, every trusted resource staged), a read-only baseline, and a scratch directory. */ + async #materialize(cycle: Cycle, job: PreparedLocalCheck, signal: AbortSignal): Promise { + const { context } = cycle, attemptDir = this.#attemptDir(job), source = context.source; + const { candidateDir } = await materializeAttemptWorkspace(cycle, this.workspace.runRoot, this.#attemptId(job), null, 'none', + hostProtectionFromPolicy(effectiveRunHostPolicy(context.descriptor)), approvedState(context.loaded).resources, [], 'verification'); + const stagedDir = join(attemptDir, 'context'), baselineDir = join(attemptDir, 'baseline'), scratchDir = join(attemptDir, 'scratch'); + await mkdir(scratchDir, { mode: 0o700 }); + if (source.version === 2) await materializeBaseline(source, baselineDir, this.artifacts.owner, signal); + else { + await mkdir(baselineDir, { mode: 0o700 }); + for (const item of source.artifacts) { + const target = join(baselineDir, item.name), perm = (item.mode ?? '100644') === '100755' ? 0o500 : 0o400; + await mkdir(dirname(target), { recursive: true, mode: 0o700 }); + const file = await open(target, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, perm); + try { await file.writeFile(item.bytes); await file.chmod(perm); await file.sync(); } finally { await file.close(); } + } + } + // shortcut: a version 2 source materializes the baseline twice per check (candidate copy and BASE_DIR); revisit if large trees make it slow. + await makeReadOnlyTree(baselineDir); + return { attemptDir, candidateDir, stagedDir, baselineDir, scratchDir, checkOut: join(scratchDir, 'check-out.json') }; + } + + /** Everything the baseline must satisfy, checked on the tree the child will see, before any intent is recorded. */ + async #verifyBaseline(data: Preparation, baselineDir: string): Promise<{ readonly scriptAbs: string; readonly scriptDigest: Digest }> { + const spec = data.spec, scriptAbs = join(baselineDir, spec.script), info = await lstat(scriptAbs).catch(() => null); + if (!info || !info.isFile() || (info.mode & 0o111) === 0) refuse('CONFIG_REFERENCE', HANDLERS_PATH, 'verification'); + const scriptBytes = await readFile(scriptAbs); + if (scriptBytes.byteLength > FILE_BYTES) refuse('OUTPUT_LIMIT', '', 'verification'); + // A script without a shebang cannot be exec'd by the spawner (ENOEXEC), so it is refused like a missing executable. + if (!scriptBytes.subarray(0, 2).equals(SHEBANG)) refuse('CONFIG_REFERENCE', HANDLERS_PATH, 'verification'); + const entries = await readLocalCheckScriptDirectory(baselineDir, spec.script); + if (!same(localCheckScriptDirectoryDigest(entries), data.recorded.scriptDirectoryDigest)) refuse('CONFIG_REFERENCE', HANDLERS_PATH, 'verification'); + for (const entry of entries) if (!this.plan.scope.protected.some(pattern => matchesScopePattern(pattern, entry.path))) refuse('CONFIG_SCHEMA', HANDLERS_PATH, 'verification'); + for (const path of spec.toolchainPaths) { + const stat = await lstat(join(baselineDir, path)).catch(() => null); + if (!stat || stat.isSymbolicLink() || !stat.isDirectory()) refuse('CONFIG_REFERENCE', HANDLERS_PATH, 'verification'); + } + return { scriptAbs, scriptDigest: hash(scriptBytes) }; + } + + /** Allowlisted environment only: the controller never reads or passes its own `process.env`. */ + #environment(data: Preparation, workspace: Workspace): Record { + const spec = data.spec, slot = data.slot; + const step = this.plan.orderedDAG.find(node => node.kind === 'check' && node.handler.id === slot.handler.id); + return { + PATH: [...spec.toolchainPaths.map(path => join(workspace.baselineDir, path)), LOCAL_CHECK_PATH_BASE].join(':'), + HOME: workspace.scratchDir, TMPDIR: workspace.scratchDir, ...LOCAL_CHECK_ENV_FIXED, + LOOPWRIGHT_CANDIDATE_DIR: workspace.candidateDir, LOOPWRIGHT_BASE_DIR: workspace.baselineDir, LOOPWRIGHT_STAGED_DIR: workspace.stagedDir, LOOPWRIGHT_CHECK_OUT: workspace.checkOut, + LOOPWRIGHT_RUN_ID: this.lock.spec.runId, LOOPWRIGHT_STEP_ID: step?.id ?? slot.id, LOOPWRIGHT_CHECK_ID: slot.checkId, + ...spec.env, + }; + } + + async #runChild(child: ChildProcess, pgid: number, timeoutMs: number, signal: AbortSignal): Promise<{ readonly exitCode: number | null; readonly exitSignal: string | null; readonly timedOut: boolean; readonly elapsedMs: number; readonly stderrTail: string; readonly stderrTruncated: boolean }> { + let chunks: Buffer[] = [], buffered = 0, truncated = false; + child.stderr!.on('data', (part: Buffer) => { + if (buffered + part.byteLength > LOCAL_CHECK_STDERR_BYTES) truncated = true; + chunks.push(part); buffered += part.byteLength; + if (chunks.length >= 64) chunks = [Buffer.concat(chunks)]; + }); + const exited = new Promise<{ readonly code: number | null; readonly signal: string | null }>(resolve => { + child.once('exit', (code, signal) => resolve({ code, signal })); child.once('error', () => resolve({ code: null, signal: null })); + }); + const stop = () => killProcessGroup(pgid), started = performance.now(); + let timedOut = false; + const timer = setTimeout(() => { timedOut = true; stop(); }, timeoutMs); timer.unref(); + signal.addEventListener('abort', stop, { once: true }); if (signal.aborted) stop(); + try { + // The script's own exit decides the verdict; whatever it left behind in the group is killed before the capture. + const exit = await exited; + await confirmProcessGroupGone(pgid, 'verification'); + await drain(child.stderr!); + const bytes = Buffer.concat(chunks); + return { exitCode: exit.code, exitSignal: exit.signal, timedOut, elapsedMs: Math.ceil(performance.now() - started), stderrTail: bytes.subarray(Math.max(0, bytes.byteLength - LOCAL_CHECK_STDERR_BYTES)).toString('utf8'), stderrTruncated: truncated }; + } finally { + // Release the pipe even when refusing: an escaped process that still holds it must not keep the controller alive. + clearTimeout(timer); signal.removeEventListener('abort', stop); child.stderr!.destroy(); + } + } + + /** `$LOOPWRIGHT_CHECK_OUT` is the only output file read: bounded, vault-checked, strictly parsed. */ + async #readOutput(path: string): Promise<{ readonly output: LocalCheckOutput | null; readonly outputError: OutputError | null }> { + if (!(await lstat(path).then(() => true, () => false))) return { output: null, outputError: null }; + let bytes: Buffer; + try { bytes = await readBoundedFile(path, LOCAL_CHECK_LIMITS.checkOutBytes, false); } + catch (error) { + if (!(error instanceof ControllerFailure)) throw error; + return { output: null, outputError: { code: error.diagnostic.code === 'CONFIG_LIMIT' ? 'OUTPUT_LIMIT' : 'ARTIFACT_INVALID', path: '' } }; + } + this.artifacts.vault.assertClean(bytes); + const parsed = parseLocalCheckOut(bytes); + if (!parsed.ok) return { output: null, outputError: { code: parsed.errors[0]!.code, path: parsed.errors[0]!.path } }; + return { output: parsed.value, outputError: null }; + } + + #disposition(observation: Pick): Disposition { + if (observation.timedOut) return { status: 'failed', reason: 'check_timeout', method: LOCAL_CHECK_METHOD }; + // An unusable check-out is the script's contract violation, not the candidate's: block for the operator instead of reworking the author. + if (observation.outputError !== null) return { status: 'blocked', reason: 'EVIDENCE_UNAVAILABLE', method: LOCAL_CHECK_METHOD }; + if (observation.exitCode === 0) return { status: 'passed', reason: null, method: LOCAL_CHECK_METHOD }; + return { status: 'failed', reason: 'check_failed', method: LOCAL_CHECK_METHOD }; + } + #evidenceSpec(data: Preparation, disposition: Disposition, observation: Pick, output: ArtifactRef) { + return { + checkId: data.slot.checkId, observedStatus: disposition.status, producerId: LOCAL_CHECK_PRODUCER_ID, method: disposition.method, level: 'host_execution' as const, + subject: data.subject, artifacts: [output], reason: disposition.reason, + ...(observation.output?.detail !== undefined ? { detail: observation.output.detail } : {}), + ...(observation.output?.metrics !== undefined ? { metrics: observation.output.metrics } : {}), + ...(observation.output?.findings !== undefined ? { findings: observation.output.findings } : {}), + }; + } + #evidence(job: PreparedLocalCheck, data: Preparation, disposition: Disposition, observation: Pick, output: ArtifactRef, phase: ControllerDiagnostic['phase']): Evidence { + const result = validateDocument({ apiVersion: 'loopwright.dev/v1alpha1', kind: 'Evidence', metadata: { id: 'evidence.' + this.#suffix(job) }, spec: this.#evidenceSpec(data, disposition, observation, output) }, 'Evidence'); + if (!result.ok) refuse('RECOVERY_REQUIRED', '', phase); return result.value; + } + #receipt(job: PreparedLocalCheck, data: Preparation, disposition: Disposition, view: RunView, intentDigest: Digest, permit: DispatchReceipt, output: ArtifactRef, scriptDigest: Digest | null): { readonly receipt: OperationReceipt; readonly record: LocalCheckReceipt } { + const suffix = this.#suffix(job); + const receipt: OperationReceipt = { receiptId: 'receipt.' + suffix, outcome: disposition.status === 'passed' ? 'succeeded' : 'failed', + evidence: { evidenceId: 'receipt-evidence.' + suffix, producerId: LOCAL_CHECK_PRODUCER_ID, method: disposition.method, + subject: { storeId: view.storeId, runId: view.runId, lockHash: view.lockHash, operationId: job.operationId, requestId: null, intentDigest, dispatchGeneration: permit.generation, dispatchId: permit.dispatchId }, artifact: output } }; + const record: LocalCheckReceipt = { ...receipt, script: data.spec.script, scriptDigest, scriptDirectoryDigest: data.recorded.scriptDirectoryDigest, registryDigest: this.plan.registryDigest }; + return { receipt, record }; + } + async #attest(job: PreparedLocalCheck, data: Preparation, disposition: Disposition, output: ArtifactRef, receiptRef: ArtifactRef, evidence: Evidence, receipt: OperationReceipt, record: LocalCheckReceipt, pgid: number | null): Promise { + const value: VerifiedCheck = freeze({ slotId: job.slotId, checkId: data.slot.checkId, generation: job.generation, operationId: job.operationId, producerNonce: job.producerNonce, status: disposition.status, reason: disposition.reason, output, receipt: receiptRef }); + observations.set(value, { evidence: freeze(evidence), subject: data.subject, outputBytes: await this.artifacts.read(output, LOCAL_CHECK_OUTPUT_BYTES), receipt: freeze(receipt), receiptRecord: freeze(record), planDigest: this.plan.planDigest, requestDigest: job.requestDigest, pgid, + header: { handlerDigest: data.slot.handler.digest, handler: 'command.v1', candidate: { ref: { digest: data.candidateDigest, byteLength: data.candidateBytes } } } }); + return value; + } + + async run(job: PreparedLocalCheck, signal: AbortSignal): Promise { + const data = preparations.get(job); if (!data || this.plan.verifierSlots.find(slot => slot.id === job.slotId) !== data.slot) refuse('EVIDENCE_UNAVAILABLE', '', 'verification'); + const cycle = this.workspace.cycle; if (!cycle) refuse('CAPABILITY_UNSUPPORTED', '', 'verification'); + if (signal.aborted) refuse('CANCELLED', '', 'verification'); + await this.artifacts.owner.assertCurrent(); if (!same(this.currentSubject(), data.subject)) refuse('ARTIFACT_INVALID', '', 'verification'); + const done = await this.artifacts.owner.holdLocalActivity(); + try { + const target = this.#target(job, data.subject), before = this.#identity(); if (before.owner.mode !== 'active') refuse('AUTHORITY_REFUSED', '', 'verification'); + if (before.counts.dispatchedRequests || before.counts.unresolvedRequests || before.counts.unresolvedOperations || before.ledger.violations.length) refuse('RECOVERY_REQUIRED', '', 'verification'); + const workspace = await this.#materialize(cycle, job, signal); + let executed: Execution; + try { executed = await this.#execute(job, data, workspace, target, signal); } + finally { await removeTree(workspace.attemptDir, 'verification'); } + const { intentDigest, permit, binding, observation, scriptDigest } = executed, view = stateValue(this.store.inspect()), disposition = this.#disposition(observation); + const output = await this.artifacts.json('local-check-output', { version: 1, binding, observation, disposition }, LOCAL_CHECK_OUTPUT_BYTES); + const evidence = this.#evidence(job, data, disposition, observation, output, 'verification'); + const { receipt, record } = this.#receipt(job, data, disposition, view, intentDigest, binding.dispatchReceipt, output, scriptDigest); + const receiptRef = await this.artifacts.json('local-check-receipt', record, 65536); + await this.#marker(job.operationId, job.producerNonce, 'proof', { version: 1, output, receipt: receiptRef, evidence }); + this.#permit(permit, data.subject, target); stateValue(this.store.recordOperationReceipt(this.authority, job.operationId, receipt)); + return await this.#attest(job, data, disposition, output, receiptRef, evidence, receipt, record, binding.pgid); + } finally { done(); } + } + + /** Intent, permit, binding marker with the process group, execution, capture. Refusals here leave no proof; recovery settles them. */ + async #execute(job: PreparedLocalCheck, data: Preparation, workspace: Workspace, target: string, signal: AbortSignal): Promise { + const { scriptAbs, scriptDigest } = await this.#verifyBaseline(data, workspace.baselineDir); + this.#identity(); const attemptId = this.#attemptId(job); + stateValue(this.store.putIntent(this.authority, { operationId: job.operationId, nodeId: this.plan.orderedDAG[0]!.id, attemptId, effect: 'read_only', requestDigest: job.requestDigest, targetIdentity: target })); + const dispatched = stateValue(this.store.authorizeOperationDispatch(this.authority, job.operationId)); if (dispatched.kind !== 'new_dispatch') refuse('RECOVERY_REQUIRED', '', 'verification'); + const permit = dispatched.permit, intentDigest = stateValue(this.store.getOperation(job.operationId)).intentDigest; + const binding: Binding = { version: 1, planDigest: this.plan.planDigest, operationId: job.operationId, producerNonce: job.producerNonce, requestDigest: job.requestDigest, intentDigest, subject: data.subject, generation: job.generation, + checkId: data.slot.checkId, script: data.spec.script, scriptDigest, scriptDirectoryDigest: data.recorded.scriptDirectoryDigest, registryDigest: this.plan.registryDigest, pgid: null, workspaceDir: workspace.attemptDir, + dispatchReceipt: { generation: permit.generation, dispatchId: permit.dispatchId, revision: permit.authorizedRevision, clockEpoch: permit.clockEpoch } }; + let child: ChildProcess | null = null; + try { child = spawn(scriptAbs, [...data.spec.args], { cwd: workspace.baselineDir, env: this.#environment(data, workspace), stdio: ['ignore', 'ignore', 'pipe'], detached: true }); } + catch { /* refused below with the binding written first */ } + if (!child || child.pid === undefined) { + // No process group exists; bind first so recovery settles the dispatched operation instead of re-dispatching it. + await this.#marker(job.operationId, job.producerNonce, 'binding', binding); + if (child) await new Promise(resolve => { child!.once('error', () => resolve()); child!.once('close', () => resolve()); }); + refuse('CONFIG_REFERENCE', HANDLERS_PATH, 'verification'); + } + const pgid = child.pid, bound: Binding = { ...binding, pgid }; + // The group id is bound before any proof can exist, so recovery always knows what to kill. + // shortcut: a crash between spawn and this fsync (milliseconds) leaves an unrecorded group; Pod exit is the backstop. + await this.#marker(job.operationId, job.producerNonce, 'binding', bound); + const exit = await this.#runChild(child, pgid, data.spec.timeoutMs, signal); + if (signal.aborted) refuse('CANCELLED', '', 'verification'); + const stderrTail = new SecretScrubber().scrub(exit.stderrTail); + this.artifacts.vault.assertClean(stderrTail); + const { output, outputError } = exit.timedOut ? { output: null, outputError: null } : await this.#readOutput(workspace.checkOut); + const observation: Observation = { transport: exit.timedOut ? 'timeout' : 'completed', exitCode: exit.exitCode, exitSignal: exit.exitSignal, timedOut: exit.timedOut, elapsedMs: exit.elapsedMs, output, outputError, stderrTail, stderrTruncated: exit.stderrTruncated }; + return { intentDigest, permit, binding: bound, observation, scriptDigest }; + } + + /** Marker file prefix shared by binding and proof; recovery locates a crashed operation's records through it. */ + #prefix(job: PreparedLocalCheck): string { return join(this.artifacts.directory, 'local-check-producer-' + hash(job.operationId + '\0' + job.producerNonce).hex); } + #binding(bytes: Buffer, job: PreparedLocalCheck, data: Preparation, view: RunView, dispatch: NonNullable, intentDigest: Digest): Binding { + const value = record(parsePrivateJson(bytes, MARKER_BYTES), ['version', 'planDigest', 'operationId', 'producerNonce', 'requestDigest', 'intentDigest', 'subject', 'generation', 'checkId', 'script', 'scriptDigest', 'scriptDirectoryDigest', 'registryDigest', 'pgid', 'workspaceDir', 'dispatchReceipt']); + const receipt = record(value.dispatchReceipt, ['generation', 'dispatchId', 'revision', 'clockEpoch']), scriptDigest = record(value.scriptDigest, ['algorithm', 'hex']); + if (value.version !== 1 || !same(value.planDigest, this.plan.planDigest) || value.operationId !== job.operationId || value.producerNonce !== job.producerNonce || value.generation !== job.generation + || !same(value.subject, data.subject) || !same(value.requestDigest, job.requestDigest) || !same(value.intentDigest, intentDigest) || value.checkId !== data.slot.checkId || value.script !== data.spec.script + || scriptDigest.algorithm !== 'sha256' || !/^[0-9a-f]{64}$/.test(text(scriptDigest.hex)) || !same(value.scriptDirectoryDigest, data.recorded.scriptDirectoryDigest) || !same(value.registryDigest, this.plan.registryDigest) + || !(value.pgid === null || typeof value.pgid === 'number' && Number.isSafeInteger(value.pgid) && value.pgid > 0) || value.workspaceDir !== this.#attemptDir(job) + || !same(receipt, { generation: dispatch.generation, dispatchId: dispatch.dispatchId, revision: dispatch.revision, clockEpoch: view.clock.basis.clockEpoch })) refuse('RECOVERY_REQUIRED', '', 'recovery'); + return value as unknown as Binding; + } + #observation(value: unknown): Observation { + const saved = record(value, ['transport', 'exitCode', 'exitSignal', 'timedOut', 'elapsedMs', 'output', 'outputError', 'stderrTail', 'stderrTruncated']); + if (!['completed', 'timeout', 'interrupted'].includes(text(saved.transport, '', 16)) || !(saved.exitCode === null || Number.isSafeInteger(saved.exitCode)) || !(saved.exitSignal === null || typeof saved.exitSignal === 'string') + || typeof saved.timedOut !== 'boolean' || typeof saved.stderrTail !== 'string' || typeof saved.stderrTruncated !== 'boolean') refuse('RECOVERY_REQUIRED', '', 'recovery'); + integer(saved.elapsedMs, 0, Number.MAX_SAFE_INTEGER); + const outputError = saved.outputError === null ? null : record(saved.outputError, ['code', 'path']); + if (outputError !== null && (typeof outputError.code !== 'string' || typeof outputError.path !== 'string')) refuse('RECOVERY_REQUIRED', '', 'recovery'); + if (saved.transport === 'interrupted') return { transport: 'interrupted', exitCode: null, exitSignal: null, timedOut: false, elapsedMs: 0, output: null, outputError: null, stderrTail: '', stderrTruncated: false }; + const parsed = saved.output === null ? { ok: true as const, value: null } : parseLocalCheckOut(Buffer.from(canonical(saved.output))); + if (!parsed.ok) refuse('RECOVERY_REQUIRED', '', 'recovery'); + if (saved.timedOut !== (saved.transport === 'timeout')) refuse('RECOVERY_REQUIRED', '', 'recovery'); + return { transport: saved.transport as Observation['transport'], exitCode: saved.exitCode as number | null, exitSignal: saved.exitSignal as string | null, timedOut: saved.timedOut, elapsedMs: saved.elapsedMs as number, + output: parsed.value, outputError: outputError as unknown as OutputError | null, stderrTail: saved.stderrTail, stderrTruncated: saved.stderrTruncated }; + } + + /** + * Recovery: a proof marker is re-attested and reconciled; an operation without one (controller killed between the + * markers, a refused capture, a child that could not be spawned) settles `blocked`/`EVIDENCE_UNAVAILABLE` after the + * recorded group is killed and the workspace discarded. The dispatch is already recorded, so it is never repeated. + */ + async restore(job: PreparedLocalCheck): Promise { + const data = preparations.get(job); if (!data || this.plan.verifierSlots.find(slot => slot.id === job.slotId) !== data.slot) refuse('EVIDENCE_UNAVAILABLE', '', 'recovery'); + await this.artifacts.owner.assertCurrent(); if (!same(this.currentSubject(), data.subject)) refuse('RECOVERY_REQUIRED', '', 'recovery'); + const operation = stateValue(this.store.getOperation(job.operationId)), view = this.#identity(), dispatch = operation.dispatch; + if (!dispatch || view.clockStatus !== 'trusted' || operation.intent.effect !== 'read_only' || operation.linkedRequestId !== null || !same(operation.intent.requestDigest, job.requestDigest) + || operation.intent.attemptId !== this.#attemptId(job) || operation.intent.nodeId !== this.plan.orderedDAG[0]!.id + || operation.intent.targetIdentity !== this.#target(job, data.subject)) refuse('RECOVERY_REQUIRED', '', 'recovery'); + const prefix = this.#prefix(job); + let binding: Binding | null = null; + try { binding = this.#binding(await readBoundedFile(prefix + '.binding.json', MARKER_BYTES, true), job, data, view, dispatch, operation.intentDigest); } + catch (error) { + // Only an operation still uncertain may lack a binding: the spawn follows the binding, so nothing ran outside the millisecond window noted above. + if (!(error instanceof ControllerFailure) || error.diagnostic.code !== 'REGISTRY_UNTRUSTED' || operation.state !== 'dispatch_uncertain') throw error; + } + let proofBytes: Buffer; + try { proofBytes = await readBoundedFile(prefix + '.proof.json', MARKER_BYTES, true); } + catch (error) { + if (error instanceof ControllerFailure && error.diagnostic.code === 'REGISTRY_UNTRUSTED' && operation.state === 'dispatch_uncertain') return await this.#settle(job, data, binding, view, dispatch, operation.intentDigest); + if (error instanceof ControllerFailure && error.diagnostic.code === 'REGISTRY_UNTRUSTED') refuse('RECOVERY_REQUIRED', '', 'recovery'); throw error; + } + if (!binding) refuse('RECOVERY_REQUIRED', '', 'recovery'); + const proof = record(parsePrivateJson(proofBytes, MARKER_BYTES), ['version', 'output', 'receipt', 'evidence']); + if (proof.version !== 1) refuse('RECOVERY_REQUIRED', '', 'recovery'); + const output = checkedRef(proof.output), receiptRef = checkedRef(proof.receipt), outputBytes = await this.artifacts.read(output, LOCAL_CHECK_OUTPUT_BYTES); + const saved = record(parsePrivateJson(Buffer.from(outputBytes), LOCAL_CHECK_OUTPUT_BYTES), ['version', 'binding', 'observation', 'disposition']); + if (saved.version !== 1 || !same(saved.binding, binding)) refuse('RECOVERY_REQUIRED', '', 'recovery'); + const observation = this.#observation(saved.observation), disposition = this.#disposition(observation); + if (observation.transport === 'interrupted' || !same(saved.disposition, disposition)) refuse('RECOVERY_REQUIRED', '', 'recovery'); + const evidence = this.#evidence(job, data, disposition, observation, output, 'recovery'); + if (!same(evidence, proof.evidence)) refuse('RECOVERY_REQUIRED', '', 'recovery'); + const { receipt, record: receiptRecord } = this.#receipt(job, data, disposition, view, operation.intentDigest, binding.dispatchReceipt, output, binding.scriptDigest); + if (!same(parsePrivateJson(await this.artifacts.read(receiptRef, 65536), 65536), receiptRecord)) refuse('RECOVERY_REQUIRED', '', 'recovery'); + await this.artifacts.owner.assertCurrent(); if (!same(this.currentSubject(), data.subject)) refuse('RECOVERY_REQUIRED', '', 'recovery'); stateValue(this.store.renew(this.authority)); + if (operation.state === 'confirmed') { if (!same(operation.reconciliation ?? operation.initialReceipt, receipt)) refuse('RECOVERY_REQUIRED', '', 'recovery'); } + else stateValue(this.store.reconcileOperation(this.authority, job.operationId, receipt)); + return await this.#attest(job, data, disposition, output, receiptRef, evidence, receipt, receiptRecord, binding.pgid); + } + + /** An operation without a proof settles fail-closed; a replacement dispatch is never made. */ + async #settle(job: PreparedLocalCheck, data: Preparation, binding: Binding | null, view: RunView, dispatch: NonNullable, intentDigest: Digest): Promise { + await this.artifacts.owner.assertCurrent(); if (!same(this.currentSubject(), data.subject)) refuse('RECOVERY_REQUIRED', '', 'recovery'); stateValue(this.store.renew(this.authority)); + if (binding) { + if (binding.pgid !== null) await confirmProcessGroupGone(binding.pgid, 'recovery'); + await removeTree(binding.workspaceDir, 'recovery'); + } + const disposition: Disposition = { status: 'blocked', reason: 'EVIDENCE_UNAVAILABLE', method: LOCAL_CHECK_METHOD }; + const observation: Observation = { transport: 'interrupted', exitCode: null, exitSignal: null, timedOut: false, elapsedMs: 0, output: null, outputError: null, stderrTail: '', stderrTruncated: false }; + const output = await this.artifacts.json('local-check-output', { version: 1, binding, observation, disposition }, LOCAL_CHECK_OUTPUT_BYTES); + const evidence = this.#evidence(job, data, disposition, observation, output, 'recovery'); + const { receipt, record } = this.#receipt(job, data, disposition, view, intentDigest, binding?.dispatchReceipt ?? { generation: dispatch.generation, dispatchId: dispatch.dispatchId, revision: dispatch.revision, clockEpoch: view.clock.basis.clockEpoch }, output, binding?.scriptDigest ?? null); + const receiptRef = await this.artifacts.json('local-check-receipt', record, 65536); + await this.#marker(job.operationId, job.producerNonce, 'proof', { version: 1, output, receipt: receiptRef, evidence }); + stateValue(this.store.reconcileOperation(this.authority, job.operationId, receipt)); + return await this.#attest(job, data, disposition, output, receiptRef, evidence, receipt, record, binding?.pgid ?? null); + } +} diff --git a/packages/controller/test/fixtures/scripts/fail.sh b/packages/controller/test/fixtures/scripts/fail.sh new file mode 100755 index 00000000..25dc076e --- /dev/null +++ b/packages/controller/test/fixtures/scripts/fail.sh @@ -0,0 +1,5 @@ +#!/bin/sh +# Deterministic failing check: names the reason on stderr and returns a detail for the author. +echo 'forge-evaluate: 2 of 12 cases failed' >&2 +printf '%s\n' '{"detail":"case 7: expected 42, got 41"}' > "$LOOPWRIGHT_CHECK_OUT" +exit 1 diff --git a/packages/controller/test/fixtures/scripts/pass.sh b/packages/controller/test/fixtures/scripts/pass.sh new file mode 100755 index 00000000..83d1f9b9 --- /dev/null +++ b/packages/controller/test/fixtures/scripts/pass.sh @@ -0,0 +1,4 @@ +#!/bin/sh +# Deterministic passing check: reports metrics through the only output file the controller reads. +printf '%s\n' '{"metrics":{"cases":12,"failed":0}}' > "$LOOPWRIGHT_CHECK_OUT" +exit 0 diff --git a/packages/controller/test/fixtures/scripts/print-env.sh b/packages/controller/test/fixtures/scripts/print-env.sh new file mode 100755 index 00000000..5ffa8529 --- /dev/null +++ b/packages/controller/test/fixtures/scripts/print-env.sh @@ -0,0 +1,9 @@ +#!/bin/sh +# Writes the child environment to $LOOPWRIGHT_CHECK_OUT as `detail`, one NAME=VALUE per line, sorted. +# shortcut: escapes only backslash and quote; the contract's values (paths, identifiers) carry no control characters. +{ + printf '%s' '{"detail":"' + env | LC_ALL=C sort | sed -e 's/\\/\\\\/g' -e 's/"/\\"/g' | sed -e 's/$/\\n/' | tr -d '\n' + printf '%s' '"}' +} > "$LOOPWRIGHT_CHECK_OUT" +exit 0 diff --git a/packages/controller/test/fixtures/scripts/sleep.sh b/packages/controller/test/fixtures/scripts/sleep.sh new file mode 100755 index 00000000..9d6accc8 --- /dev/null +++ b/packages/controller/test/fixtures/scripts/sleep.sh @@ -0,0 +1,4 @@ +#!/bin/sh +# Runs past any timeoutMs with a background sibling in the same process group, so the controller must kill the whole group. +( exec sleep 3600 ) & +exec sleep 3600 diff --git a/packages/controller/test/fixtures/scripts/write-outside-candidate.sh b/packages/controller/test/fixtures/scripts/write-outside-candidate.sh new file mode 100755 index 00000000..a97055a5 --- /dev/null +++ b/packages/controller/test/fixtures/scripts/write-outside-candidate.sh @@ -0,0 +1,18 @@ +#!/bin/sh +# Attempts three writes under the read-only baseline tree. Each must be refused by file modes; +# the metrics record which attempts succeeded (all three must stay 0). +created=0 +modified=0 +removed=0 +if printf 'probe\n' > "$LOOPWRIGHT_BASE_DIR/loopwright-probe" 2>/dev/null; then + created=1 + rm -f "$LOOPWRIGHT_BASE_DIR/loopwright-probe" +fi +if printf 'probe\n' > "$LOOPWRIGHT_BASE_DIR/scripts/pass.sh" 2>/dev/null; then + modified=1 +fi +if rm "$LOOPWRIGHT_BASE_DIR/scripts/pass.sh" 2>/dev/null; then + removed=1 +fi +printf '{"metrics":{"created":%s,"modified":%s,"removed":%s}}\n' "$created" "$modified" "$removed" > "$LOOPWRIGHT_CHECK_OUT" +exit 0 diff --git a/packages/controller/test/local-check-fixtures.ts b/packages/controller/test/local-check-fixtures.ts new file mode 100644 index 00000000..96aa4976 --- /dev/null +++ b/packages/controller/test/local-check-fixtures.ts @@ -0,0 +1,149 @@ +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { chmod, copyFile, lstat, mkdir, readFile, readdir, writeFile } from 'node:fs/promises'; +import { dirname, join } from 'node:path'; +import type { Digest } from '@loopwright/core'; +import { configurationFixture } from './config-fixtures.js'; +import { setFixture } from './progress-fixtures.js'; +import { createCycle, Cycle, type CycleContext } from '../src/controller.js'; +import type { Authority } from '@loopwright/state'; +import { localCheckScriptDirectoryDigest, type LocalCheckScriptEntry } from '../src/local-check.js'; +import { hash } from '../src/schema.js'; +import { resolveCanonicalCasBlobPath, stateValue } from '../src/storage.js'; +import type { FrozenSource } from '../src/source.js'; +import type { CompiledPlan, Handler } from '../src/types.js'; +import type { ByteInventory } from '../src/verification.js'; + +/** The five deterministic scripts under test/fixtures/scripts; the test copies them into a throwaway git repository. */ +export const SCRIPTS = ['pass.sh', 'fail.sh', 'sleep.sh', 'write-outside-candidate.sh', 'print-env.sh'] as const; +export function fixtureScriptsDir(): string { return join(process.cwd(), 'packages/controller/test/fixtures/scripts'); } + +export const COMMAND_DIGEST = hash('loopwright.dev/controller/handler/v1\0command.v1-local-check-fixture'); +export const CHECK_ID = 'forge-evaluate'; +export const SLOT_ID = 'check.' + CHECK_ID; + +export function commandHandler(parameters: Record = {}): Handler { + return { + id: 'forge-evaluate', version: 1, kind: 'check', implementation: 'command.v1', digest: COMMAND_DIGEST, + parameters: { checkId: CHECK_ID, script: 'scripts/pass.sh', args: [], env: {}, toolchainPaths: [], timeoutMs: 3000, ...parameters }, + capabilities: ['host_execution'], + }; +} + +/** + * `compilePlan` refuses a `command.v1` handler until `installedHandlerDigests()` lists `command.v1` (T4), so the + * module tests compile the fixture plan and then append the slot exactly as admission will. + */ +export function injectCommandSlot(plan: CompiledPlan, handler: Handler): CompiledPlan { + const checkId = String(handler.parameters.checkId); + return { ...plan, verifierSlots: [...plan.verifierSlots, { id: 'check.' + checkId, checkId, implicit: null, handler }] }; +} + +export interface FixtureExtra { readonly path: string; readonly content: string; readonly executable?: boolean } +export interface LocalCheckFixtureOptions { + readonly protected?: readonly string[]; + readonly extra?: readonly FixtureExtra[]; +} + +const GIT_FIXTURE_ENV = Object.freeze({ + PATH: '/usr/bin:/bin', LANG: 'C', LC_ALL: 'C', GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null', + HOME: '/nonexistent', GIT_TERMINAL_PROMPT: '0', +}); + +/** Registry attesting `direct`, a task whose scope protects `scripts/**`, and a git repository holding the five scripts. */ +export async function localCheckFixture(options: LocalCheckFixtureOptions = {}) { + const f = await configurationFixture(); + setFixture(f.registry, ['spec', 'host'], { localChecks: { backend: 'direct' } }); + setFixture(f.config, ['spec', 'task', 'spec', 'scope', 'protected'], [...(options.protected ?? ['scripts/**'])]); + const repository = join(f.root, 'repository'), runRoot = join(f.root, 'runs'); + await mkdir(repository, { mode: 0o700 }); await mkdir(join(repository, 'scripts'), { mode: 0o700 }); + for (const name of SCRIPTS) { const target = join(repository, 'scripts', name); await copyFile(join(fixtureScriptsDir(), name), target); await chmod(target, 0o755); } + for (const extra of options.extra ?? []) { + const target = join(repository, extra.path), mode = extra.executable ? 0o755 : 0o644; + await mkdir(dirname(target), { recursive: true, mode: 0o700 }); + await writeFile(target, extra.content, { mode }); await chmod(target, mode); + } + const git = (args: string[]) => execFileSync('/usr/bin/git', ['-c', 'core.hooksPath=/dev/null', ...args], { cwd: repository, env: GIT_FIXTURE_ENV, timeout: 5000, encoding: 'utf8' }); + git(['init', '-q']); git(['add', '.']); + git(['-c', 'user.name=Controller Fixture', '-c', 'user.email=fixture@localhost.invalid', 'commit', '-qm', 'freeze check scripts']); + const revision = git(['rev-parse', 'HEAD']).trim(); + setFixture(f.config, ['spec', 'task', 'spec', 'target', 'baseRevision'], revision); + setFixture(f.config, ['spec', 'task', 'spec', 'target', 'sourceRevision'], revision); + await f.save(); const loaded = await f.load(); assert.equal(loaded.ok, true); if (!loaded.ok) throw new Error('fixture'); + return { ...f, repository, runRoot, loaded: loaded.value, revision, git }; +} +export type LocalCheckFixture = Awaited>; + +/** A live cycle (store claimed `active`, owner held) plus the `command.v1` slot appended to the compiled plan. */ +export async function localCheckCycle(f: LocalCheckFixture, runId: string, handler: Handler = commandHandler()) { + const context = await createCycle({ configuration: f.loaded, repository: f.repository, runRoot: f.runRoot, runId }, {}); + const plan = injectCommandSlot(context.plan, handler); + return { context, plan, cycle: new Cycle(context) }; +} + +/** Releases every guard even when an earlier one fails, so a failing assertion never leaves the owner file handle open. */ +export async function releaseCycle(cycle: Cycle, context: CycleContext, authority: Authority = context.authority): Promise { + try { await cycle.deadline.dispose(); } + finally { try { await cycle.events.close(); } + finally { try { stateValue(context.store.release(authority)); } + finally { try { stateValue(context.store.close()); } finally { await context.owner.release(); } } } } +} + +/** Fixture cleanup that first restores owner write on every directory, so a read-only baseline left by a failing path cannot mask the real error. */ +export async function cleanupFixture(f: LocalCheckFixture): Promise { + const openUp = async (abs: string): Promise => { + const info = await lstat(abs).catch(() => null); if (!info || info.isSymbolicLink() || !info.isDirectory()) return; + await chmod(abs, 0o700).catch(() => undefined); + for (const name of await readdir(abs).catch(() => [])) await openUp(join(abs, name)); + }; + await openUp(f.root); + await f.cleanup(); +} + +export function initialCandidate(context: CycleContext): ByteInventory { + return { manifest: context.source.manifest, ref: { name: '', digest: hash(''), byteLength: 0 }, files: context.source.artifacts, baselineProofs: context.source.baselineProofs }; +} + +/** What admission (T4) records for a classic (version 1) source: the script directory's entries, digested by the pure function. */ +export function recordedScriptDigest(source: FrozenSource, script: string): Digest { + assert.equal(source.version, 1); + const dir = dirname(script), prefix = dir === '.' ? '' : dir + '/'; + const entries: LocalCheckScriptEntry[] = source.artifacts + .filter(item => item.name.startsWith(prefix)) + .map(item => ({ path: item.name, mode: item.mode ?? '100644', byteLength: item.bytes.byteLength, sha256: hash(item.bytes).hex })); + return localCheckScriptDirectoryDigest(entries); +} + +/** sha256 over every captured overlay byte read from the store; the test proves it is identical before and after a check. */ +export async function overlayDigest(candidate: ByteInventory, artifactsDirectory: string): Promise { + const digest = createHash('sha256'); + for (const item of candidate.files) { + const bytes = 'bytes' in item ? Buffer.from(item.bytes) : await readFile(await resolveCanonicalCasBlobPath(artifactsDirectory, item.digest.hex, item.blobPath, 'execution')); + digest.update(item.name); digest.update('\0'); digest.update(bytes); digest.update('\0'); + } + return digest.digest('hex'); +} + +export function attemptDirectory(runRoot: string, runId: string, attemptId: string): string { return join(runRoot, 'workspaces', runId, attemptId); } + +export function groupGone(pgid: number): boolean { + try { process.kill(-pgid, 0); return false; } catch (error) { return (error as NodeJS.ErrnoException).code === 'ESRCH'; } +} + +/** Marker names follow the private producer discipline of gate.ts; recovery tests locate them the same way. */ +export function markerPrefix(artifactsDirectory: string, operationId: string, producerNonce: string): string { + return join(artifactsDirectory, 'local-check-producer-' + hash(operationId + '\0' + producerNonce).hex); +} + +export async function exists(path: string): Promise { return lstat(path).then(() => true, () => false); } + +/** Polls for a marker file until it parses; a producer writes it with O_EXCL and fsync, so a partial read simply retries. */ +export async function waitForMarker(path: string, timeoutMs: number): Promise> { + const deadline = Date.now() + timeoutMs; + for (;;) { + try { return JSON.parse(await readFile(path, 'utf8')) as Record; } catch { /* not yet */ } + if (Date.now() > deadline) throw new Error('timeout waiting for ' + path); + await new Promise(resolve => setTimeout(resolve, 20)); + } +} diff --git a/packages/controller/test/local-check.test.ts b/packages/controller/test/local-check.test.ts new file mode 100644 index 00000000..df150854 --- /dev/null +++ b/packages/controller/test/local-check.test.ts @@ -0,0 +1,316 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import { readFile, readdir } from 'node:fs/promises'; +import { join } from 'node:path'; +import { LOCAL_CHECK_ENV_FIXED, LOCAL_CHECK_ENV_NAMES, LOCAL_CHECK_PATH_BASE, bindSubject } from '@loopwright/core'; +import { TOKEN } from './config-fixtures.js'; +import { + CHECK_ID, SLOT_ID, attemptDirectory, cleanupFixture, commandHandler, exists, groupGone, initialCandidate, localCheckCycle, + localCheckFixture, markerPrefix, overlayDigest, recordedScriptDigest, releaseCycle, waitForMarker, + type LocalCheckFixtureOptions, +} from './local-check-fixtures.js'; +import type { Authority } from '@loopwright/state'; +import { ControllerFailure } from '../src/errors.js'; +import { LOCAL_CHECK_OUTPUT_BYTES, LOCAL_CHECK_PRODUCER_ID, LocalCheck, authenticatedLocalCheck, prepareLocalCheck, type LocalCheckReceipt } from '../src/local-check.js'; +import { parsePrivateJson } from '../src/parser.js'; +import { canonical, hash, same } from '../src/schema.js'; +import { inside } from '../src/files.js'; +import { stateValue } from '../src/storage.js'; +import type { Digest } from '@loopwright/core'; +import type { Handler } from '../src/types.js'; + +const NONCE = 'a'.repeat(32); +const SIGNALED_EXIT = 600_000; + +function failure(error: unknown): string { return error instanceof ControllerFailure ? error.diagnostic.code : 'not-a-controller-failure: ' + String(error); } +function parse(bytes: Uint8Array, maximum = LOCAL_CHECK_OUTPUT_BYTES): Record { return parsePrivateJson(Buffer.from(bytes), maximum) as Record; } + +async function live(options: LocalCheckFixtureOptions = {}, handler: Handler = commandHandler(), runId = 'run-local-check') { + const f = await localCheckFixture(options); + const { context, plan, cycle } = await localCheckCycle(f, runId, handler); + const candidate = initialCandidate(context), bound = bindSubject(context.lock, candidate.manifest); + if (!bound.ok) throw new Error('fixture: subject'); + const recorded = { scriptDirectoryDigest: recordedScriptDigest(context.source, String(handler.parameters.script)) }; + const job = prepareLocalCheck(plan, context.lock, SLOT_ID, candidate, 0, NONCE, recorded); + const check = new LocalCheck(context.store, context.authority, context.artifacts, plan, context.lock, () => bound.value, { runRoot: f.runRoot, cycle }); + const attemptId = 'check.' + hash(job.operationId + '\0' + NONCE).hex.slice(0, 40), attemptDir = attemptDirectory(f.runRoot, runId, attemptId); + const operationRaw = () => context.store.getOperation(job.operationId); + const operation = () => stateValue(operationRaw()); + return { f, runId, context, plan, cycle, candidate, bound, job, check, attemptId, attemptDir, recorded, operation, operationRaw, handler, + release: async () => { try { await releaseCycle(cycle, context); } finally { await cleanupFixture(f); } } }; +} +type Live = Awaited>; + +async function assertWorkspaceDiscarded(h: Live): Promise { + assert.equal(await exists(h.attemptDir), false, 'attempt directory discarded'); + assert.deepEqual(await readdir(join(h.f.runRoot, 'workspaces', h.runId)), [], 'no workspace leftovers'); +} + +async function scriptBytes(h: Live, name: string): Promise { + const entry = h.context.source.artifacts.find(item => item.name === name); if (!entry) throw new Error('fixture: ' + name); + return entry.bytes; +} + +test('a passing command.v1 script yields host_execution evidence with its metrics and a receipt naming method, script and digests', async () => { + const h = await live({ extra: [{ path: 'scripts/helper.sh', content: '#!/bin/sh\nexit 0\n', executable: true }] }); + try { + const before = await overlayDigest(h.candidate, h.context.artifacts.directory); + const verified = await h.check.run(h.job, new AbortController().signal); + assert.equal(verified.status, 'passed'); assert.equal(verified.reason, null); + assert.equal(verified.slotId, SLOT_ID); assert.equal(verified.checkId, CHECK_ID); assert.equal(verified.operationId, h.job.operationId); assert.equal(verified.generation, 0); + const trusted = authenticatedLocalCheck(verified), spec = trusted.evidence.spec; + assert.equal(spec.level, 'host_execution'); assert.equal(spec.method, 'direct_script'); assert.equal(spec.producerId, LOCAL_CHECK_PRODUCER_ID); + assert.equal(spec.observedStatus, 'passed'); assert.equal(spec.reason, null); + assert.deepEqual(JSON.parse(JSON.stringify(spec.metrics)), { cases: 12, failed: 0 }); assert.equal(spec.detail, undefined); assert.equal(spec.findings, undefined); + assert.equal(same(spec.artifacts, [verified.output]), true, 'the evidence names exactly the output artifact'); + assert.deepEqual(trusted.subject, h.bound.value); + assert.equal(trusted.header.handler, 'command.v1'); assert.deepEqual(trusted.header.handlerDigest, h.handler.digest); + assert.deepEqual(trusted.header.candidate.ref, { digest: hash(canonical(h.candidate.manifest)), byteLength: Buffer.byteLength(canonical(h.candidate.manifest)) }); + assert.equal(trusted.planDigest, h.plan.planDigest); + assert.equal(trusted.receipt.outcome, 'succeeded'); assert.equal(trusted.receipt.evidence.method, 'direct_script'); assert.equal(trusted.receipt.evidence.producerId, LOCAL_CHECK_PRODUCER_ID); + assert.deepEqual(trusted.receipt.evidence.artifact, verified.output); + const record = trusted.receiptRecord as LocalCheckReceipt; + assert.equal(record.script, 'scripts/pass.sh'); + assert.deepEqual(record.scriptDigest, hash(await scriptBytes(h, 'scripts/pass.sh'))); + assert.deepEqual(record.scriptDirectoryDigest, h.recorded.scriptDirectoryDigest); + assert.deepEqual(record.registryDigest, h.plan.registryDigest); + assert.deepEqual(record.receiptId, trusted.receipt.receiptId); + const operation = h.operation(); + assert.equal(operation.state, 'confirmed'); assert.ok(same(operation.initialReceipt, trusted.receipt), 'store receipt equals the attested receipt'); + assert.ok(same(parse(await h.context.artifacts.read(verified.receipt, 65536), 65536), record), 'receipt artifact is the extended record'); + const prefix = markerPrefix(h.context.artifacts.directory, h.job.operationId, NONCE), binding = parse(await readFile(prefix + '.binding.json'), 1048576), proof = parse(await readFile(prefix + '.proof.json'), 1048576); + assert.equal(binding.checkId, CHECK_ID); assert.equal(binding.script, 'scripts/pass.sh'); assert.equal(binding.workspaceDir, h.attemptDir); assert.equal(typeof binding.pgid, 'number'); + assert.equal(same(binding.scriptDirectoryDigest, h.recorded.scriptDirectoryDigest) && same(binding.registryDigest, h.plan.registryDigest), true); + assert.equal(same(proof.output, verified.output) && same(proof.receipt, verified.receipt), true); + assert.equal(groupGone(Number(binding.pgid)), true, 'process group gone'); + const output = parse(trusted.outputBytes), observation = output.observation as Record; + assert.deepEqual(observation.exitCode, 0); assert.deepEqual(observation.exitSignal, null); assert.deepEqual(observation.timedOut, false); + assert.deepEqual(observation.output, { metrics: { cases: 12, failed: 0 } }); assert.deepEqual(observation.outputError, null); + assert.deepEqual(observation.stderrTail, ''); assert.deepEqual(observation.stderrTruncated, false); + assert.deepEqual(output.disposition, { status: 'passed', reason: null, method: 'direct_script' }); + assert.equal(await overlayDigest(h.candidate, h.context.artifacts.directory), before, 'captured overlay byte-identical'); + await assertWorkspaceDiscarded(h); + const again = await h.check.restore(h.job); + assert.equal(same(again, verified), true, 'restore after a complete run re-attests the same evidence'); + assert.equal(h.operation().state, 'confirmed'); + } finally { await h.release(); } +}); + +test('a failing script settles failed/check_failed and returns its detail and stderr reason to the author', async () => { + const h = await live({}, commandHandler({ script: 'scripts/fail.sh' })); + try { + const verified = await h.check.run(h.job, new AbortController().signal); + assert.equal(verified.status, 'failed'); assert.equal(verified.reason, 'check_failed'); + const trusted = authenticatedLocalCheck(verified); + assert.equal(trusted.evidence.spec.detail, 'case 7: expected 42, got 41'); + assert.equal(trusted.evidence.spec.observedStatus, 'failed'); assert.equal(trusted.evidence.spec.reason, 'check_failed'); + assert.equal(trusted.receipt.outcome, 'failed'); + const observation = parse(trusted.outputBytes).observation as Record; + assert.deepEqual(observation.exitCode, 1); assert.equal(String(observation.stderrTail), 'forge-evaluate: 2 of 12 cases failed\n'); + assert.equal(h.operation().state, 'confirmed'); + await assertWorkspaceDiscarded(h); + } finally { await h.release(); } +}); + +test('a script that runs past timeoutMs settles failed/check_timeout with the process group gone', async () => { + const h = await live({}, commandHandler({ script: 'scripts/sleep.sh', timeoutMs: 1500 })); + try { + const started = Date.now(); + const verified = await h.check.run(h.job, new AbortController().signal); + assert.ok(Date.now() - started >= 1500, 'waited for the timeout'); + assert.equal(verified.status, 'failed'); assert.equal(verified.reason, 'check_timeout'); + const trusted = authenticatedLocalCheck(verified), observation = parse(trusted.outputBytes).observation as Record; + assert.deepEqual(observation.timedOut, true); assert.deepEqual(observation.exitCode, null); assert.equal(observation.exitSignal, 'SIGKILL'); + assert.deepEqual(observation.output, null); + assert.ok(Number(observation.elapsedMs) >= 1500); + const binding = parse(await readFile(markerPrefix(h.context.artifacts.directory, h.job.operationId, NONCE) + '.binding.json'), 1048576); + assert.equal(groupGone(Number(binding.pgid)), true, 'process group gone'); + assert.equal(trusted.receipt.outcome, 'failed'); assert.equal(h.operation().state, 'confirmed'); + await assertWorkspaceDiscarded(h); + } finally { await h.release(); } +}); + +test('aborting the signal kills the group, discards the workspace and refuses CANCELLED without a proof', async () => { + const h = await live({}, commandHandler({ script: 'scripts/sleep.sh', timeoutMs: SIGNALED_EXIT })); + try { + const abort = new AbortController(); setTimeout(() => abort.abort(), 300); + await assert.rejects(() => h.check.run(h.job, abort.signal), error => failure(error) === 'CANCELLED'); + const prefix = markerPrefix(h.context.artifacts.directory, h.job.operationId, NONCE); + assert.equal(await exists(prefix + '.binding.json'), true); assert.equal(await exists(prefix + '.proof.json'), false); + assert.equal(groupGone(Number(parse(await readFile(prefix + '.binding.json'), 1048576).pgid)), true); + assert.equal(h.operation().state, 'dispatch_uncertain'); + await assertWorkspaceDiscarded(h); + const settled = await h.check.restore(h.job); + assert.equal(settled.status, 'blocked'); assert.equal(settled.reason, 'EVIDENCE_UNAVAILABLE'); + assert.equal(h.operation().state, 'confirmed'); + } finally { await h.release(); } +}); + +test('a controller killed between the binding and proof markers settles blocked/EVIDENCE_UNAVAILABLE, kills the group, discards the workspace and is never re-dispatched', async () => { + // In-process crash injection, as benchmark-reconcile.test.ts does it: the controller's continuation is dead (its signal + // reads aborted from then on, so every later step refuses and nothing else is killed), the child outlives it, the + // binding is on disk, no proof exists, and the store lease has lapsed. + const h = await live({}, commandHandler({ script: 'scripts/sleep.sh', timeoutMs: SIGNALED_EXIT })); + let active: Authority | null = null; + try { + const dead = { aborted: false, addEventListener() {}, removeEventListener() {} }; + const continuation = h.check.run(h.job, dead as unknown as AbortSignal).then(() => assert.fail('a dead controller cannot complete'), () => undefined); + const prefix = markerPrefix(h.context.artifacts.directory, h.job.operationId, NONCE), binding = await waitForMarker(prefix + '.binding.json', 10_000); + const pgid = Number(binding.pgid); + assert.equal(typeof pgid, 'number'); assert.equal(groupGone(pgid), false, 'the sleeping script outlives its controller'); + assert.equal(await exists(h.attemptDir), true, 'the crash leaves the materialization behind'); + dead.aborted = true; + stateValue(h.context.store.release(h.context.authority)); + const view = stateValue(h.context.store.inspect()); + assert.equal(h.operation().state, 'dispatch_uncertain'); + const recovery = stateValue(h.context.store.claim({ ownerId: 'controller.' + h.context.owner.nonce, expectedGeneration: view.owner.generation, expectedRevision: view.revision, mode: 'recovery' })).authority; + const settled = await new LocalCheck(h.context.store, recovery, h.context.artifacts, h.plan, h.context.lock, () => h.bound.value, { runRoot: h.f.runRoot, cycle: null }).restore(h.job); + assert.equal(settled.status, 'blocked'); assert.equal(settled.reason, 'EVIDENCE_UNAVAILABLE'); + const trusted = authenticatedLocalCheck(settled), spec = trusted.evidence.spec; + assert.equal(spec.reason, 'EVIDENCE_UNAVAILABLE'); assert.equal(spec.method, 'direct_script'); assert.equal(spec.level, 'host_execution'); assert.equal(spec.observedStatus, 'blocked'); + assert.equal(trusted.receipt.outcome, 'failed'); assert.deepEqual(trusted.receiptRecord.scriptDigest, binding.scriptDigest); assert.equal(trusted.pgid, pgid); + assert.deepEqual(parse(trusted.outputBytes).observation, { transport: 'interrupted', exitCode: null, exitSignal: null, timedOut: false, elapsedMs: 0, output: null, outputError: null, stderrTail: '', stderrTruncated: false }); + assert.equal(groupGone(pgid), true, 'recorded group killed'); + assert.equal(await exists(h.attemptDir), false, 'materialization discarded'); + await continuation; + const confirmed = h.operation(); + assert.equal(confirmed.state, 'confirmed'); assert.ok(same(confirmed.reconciliation, trusted.receipt), 'store receipt equals the settled receipt'); + stateValue(h.context.store.release(recovery)); + const after = stateValue(h.context.store.inspect()); + active = stateValue(h.context.store.claim({ ownerId: 'controller.' + h.context.owner.nonce, expectedGeneration: after.owner.generation, expectedRevision: after.revision, mode: 'active' })).authority; + await assert.rejects(() => new LocalCheck(h.context.store, active!, h.context.artifacts, h.plan, h.context.lock, () => h.bound.value, { runRoot: h.f.runRoot, cycle: h.cycle }).run(h.job, new AbortController().signal), + error => failure(error) === 'RECOVERY_REQUIRED', 'the same operation is never dispatched twice'); + assert.equal(h.operation().state, 'confirmed'); + await assertWorkspaceDiscarded(h); + } finally { await releaseCycle(h.cycle, h.context, active ?? h.context.authority).catch(() => undefined); await cleanupFixture(h.f); } +}); + +test('a script that tries to write under the read-only baseline is refused by file modes and the source repository stays clean', async () => { + const h = await live({}, commandHandler({ script: 'scripts/write-outside-candidate.sh' })); + try { + const verified = await h.check.run(h.job, new AbortController().signal); + assert.equal(verified.status, 'passed'); + assert.deepEqual(JSON.parse(JSON.stringify(authenticatedLocalCheck(verified).evidence.spec.metrics)), { created: 0, modified: 0, removed: 0 }); + const git = (args: string[]) => execFileSync('/usr/bin/git', ['-c', 'core.hooksPath=/dev/null', ...args], { cwd: h.f.repository, env: { PATH: '/usr/bin:/bin', LANG: 'C', LC_ALL: 'C', GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null', HOME: '/nonexistent', GIT_TERMINAL_PROMPT: '0' }, encoding: 'utf8', timeout: 5000 }); + assert.equal(git(['status', '--porcelain']).trim(), ''); + await assertWorkspaceDiscarded(h); + } finally { await h.release(); } +}); + +test('the child environment is exactly the F1 contract plus the configured env, with toolchain paths prepended to PATH', async () => { + const h = await live({ extra: [{ path: 'tools/bin/tool.sh', content: '#!/bin/sh\nexit 0\n', executable: true }] }, + commandHandler({ script: 'scripts/print-env.sh', env: { FORGEVO_KERNEL_ID: 'rmsnorm_0123456789abcdef' }, toolchainPaths: ['scripts', 'tools/bin'] })); + process.env.LOOPWRIGHT_T3_SENTINEL = 'must-not-reach-the-child'; + try { + const verified = await h.check.run(h.job, new AbortController().signal); + assert.equal(verified.status, 'passed'); + const lines = (authenticatedLocalCheck(verified).evidence.spec.detail ?? '').split('\n').filter(line => line.length > 0); + const env = new Map(lines.map(line => { const index = line.indexOf('='); return [line.slice(0, index), line.slice(index + 1)] as const; })); + const shellAdded = ['PWD', 'SHLVL', '_']; + assert.deepEqual([...env.keys()].sort(), [...LOCAL_CHECK_ENV_NAMES, 'FORGEVO_KERNEL_ID', ...shellAdded].sort()); + for (const [name, value] of Object.entries(LOCAL_CHECK_ENV_FIXED)) assert.equal(env.get(name), value, name); + const baseDir = env.get('LOOPWRIGHT_BASE_DIR')!, candidateDir = env.get('LOOPWRIGHT_CANDIDATE_DIR')!, scratch = env.get('HOME')!; + assert.equal(env.get('PATH'), [baseDir, 'scripts'].join('/') + ':' + [baseDir, 'tools/bin'].join('/') + ':' + LOCAL_CHECK_PATH_BASE); + assert.equal(env.get('TMPDIR'), scratch); assert.ok(inside(scratch, h.attemptDir), 'scratch inside the attempt directory'); + assert.equal(candidateDir, join(h.attemptDir, 'candidate')); assert.ok(inside(env.get('LOOPWRIGHT_STAGED_DIR')!, h.attemptDir)); + assert.equal(env.get('LOOPWRIGHT_CHECK_OUT'), join(scratch, 'check-out.json')); + assert.equal(env.get('LOOPWRIGHT_RUN_ID'), h.runId); assert.equal(env.get('LOOPWRIGHT_STEP_ID'), SLOT_ID); assert.equal(env.get('LOOPWRIGHT_CHECK_ID'), CHECK_ID); + assert.equal(env.get('FORGEVO_KERNEL_ID'), 'rmsnorm_0123456789abcdef'); + assert.equal(env.has('LOOPWRIGHT_T3_SENTINEL'), false, 'process.env never reaches the child'); + assert.equal(JSON.stringify([...env]).includes(TOKEN), false); + } finally { delete process.env.LOOPWRIGHT_T3_SENTINEL; await h.release(); } +}); + +test('a generic token on stderr is scrubbed into the output artifact and a vault secret on stderr never reaches any receipt', async () => { + const generic = 'ghp_ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + // The fake tokens travel through `env`; a token committed to the repository would be refused by freezeSource itself. + const echo = { path: 'scripts/echo-env.sh', content: '#!/bin/sh\nprintf \'generic=%s\\nvault=%s\\n\' "$GENERIC" "$LEAKED" >&2\nexit 0\n', executable: true } as const; + const a = await live({ extra: [echo] }, commandHandler({ script: 'scripts/echo-env.sh', env: { GENERIC: generic } })); + try { + const verified = await a.check.run(a.job, new AbortController().signal); + assert.equal(verified.status, 'passed'); + const bytes = authenticatedLocalCheck(verified).outputBytes; + assert.ok(!Buffer.from(bytes).includes(generic), 'generic token scrubbed'); + assert.equal((parse(bytes).observation as Record).stderrTail, 'generic=[scrubbed]\nvault=\n'); + await assertWorkspaceDiscarded(a); + } finally { await a.release(); } + const b = await live({ extra: [echo] }, commandHandler({ script: 'scripts/echo-env.sh', env: { LEAKED: TOKEN } })); + try { + await assert.rejects(() => b.check.run(b.job, new AbortController().signal), error => failure(error) === 'CONFIG_CREDENTIAL_INVALID'); + assert.equal(b.operation().state, 'dispatch_uncertain'); + const names = await readdir(b.context.artifacts.directory); + assert.equal(names.some(name => /^local-check-(?:output|receipt)-/.test(name)), false, 'no evidence written'); + const settled = await b.check.restore(b.job); + assert.equal(settled.status, 'blocked'); assert.equal(settled.reason, 'EVIDENCE_UNAVAILABLE'); + for (const ref of [settled.output, settled.receipt]) assert.equal(Buffer.from(await b.context.artifacts.read(ref, LOCAL_CHECK_OUTPUT_BYTES)).includes(TOKEN), false); + assert.ok(!(await readFile(markerPrefix(b.context.artifacts.directory, b.job.operationId, NONCE) + '.binding.json', 'utf8')).includes(TOKEN)); + await assertWorkspaceDiscarded(b); + } finally { await b.release(); } +}); + +test('exit 0 without an output file passes with no detail, and an invalid output file settles blocked with the parser code recorded', async () => { + const a = await live({ extra: [{ path: 'scripts/no-out.sh', content: '#!/bin/sh\nexit 0\n', executable: true }] }, commandHandler({ script: 'scripts/no-out.sh' })); + try { + const verified = await a.check.run(a.job, new AbortController().signal); + assert.equal(verified.status, 'passed'); + const spec = authenticatedLocalCheck(verified).evidence.spec; + assert.equal(spec.detail, undefined); assert.equal(spec.metrics, undefined); assert.equal(spec.findings, undefined); + assert.deepEqual((parse(authenticatedLocalCheck(verified).outputBytes).observation as Record).output, null); + } finally { await a.release(); } + const b = await live({ extra: [{ path: 'scripts/bad-out.sh', content: '#!/bin/sh\nprintf \'%s\\n\' \'{"passed":true}\' > "$LOOPWRIGHT_CHECK_OUT"\nexit 0\n', executable: true }] }, commandHandler({ script: 'scripts/bad-out.sh' })); + try { + const verified = await b.check.run(b.job, new AbortController().signal); + assert.equal(verified.status, 'blocked'); assert.equal(verified.reason, 'EVIDENCE_UNAVAILABLE'); + const observation = parse(authenticatedLocalCheck(verified).outputBytes).observation as Record; + assert.deepEqual(observation.exitCode, 0); assert.deepEqual(observation.output, null); + assert.deepEqual(observation.outputError, { code: 'FIELD_UNKNOWN', path: '/passed' }); + assert.equal(authenticatedLocalCheck(verified).receipt.outcome, 'failed'); + assert.equal(b.operation().state, 'confirmed'); + } finally { await b.release(); } +}); + +test('refusals before the intent leave no operation and discard the workspace: non-executable script, unprotected directory, digest mismatch, missing toolchain path', async () => { + const cases: { readonly name: string; readonly options: LocalCheckFixtureOptions; readonly handler: Handler; readonly code: string; readonly recorded?: Digest }[] = [ + { name: 'non-executable script', options: { extra: [{ path: 'scripts/noexec.sh', content: '#!/bin/sh\nexit 0\n' }] }, handler: commandHandler({ script: 'scripts/noexec.sh' }), code: 'CONFIG_REFERENCE' }, + { name: 'unprotected sibling', options: { protected: ['scripts/*.sh'], extra: [{ path: 'scripts/README.md', content: 'operator notes\n' }] }, handler: commandHandler(), code: 'CONFIG_SCHEMA' }, + { name: 'digest mismatch', options: {}, handler: commandHandler(), code: 'CONFIG_REFERENCE', recorded: hash('not-the-admitted-directory') }, + { name: 'missing toolchain path', options: {}, handler: commandHandler({ toolchainPaths: ['missing/bin'] }), code: 'CONFIG_REFERENCE' }, + ]; + for (const c of cases) { + const h = await live(c.options, c.handler, 'run-local-check-' + c.name.replace(/[^a-z]+/g, '-')); + try { + const job = c.recorded ? prepareLocalCheck(h.plan, h.context.lock, SLOT_ID, h.candidate, 0, NONCE, { scriptDirectoryDigest: c.recorded }) : h.job; + await assert.rejects(() => h.check.run(job, new AbortController().signal), error => failure(error) === c.code, c.name); + const stored = h.operationRaw(); + assert.equal(stored.ok, false, c.name + ': no operation'); if (stored.ok) throw new Error('unreachable'); + assert.equal(stored.error.code, 'RECORD_NOT_FOUND', c.name); + await assertWorkspaceDiscarded(h); + } finally { await h.release(); } + } +}); + +test('prepareLocalCheck refuses parameter violations before any I/O with CONFIG_SCHEMA', async () => { + const h = await live(); + try { + const bad = [ + commandHandler({ env: { PATH: '/x' } }), commandHandler({ env: { HOME: '/x' } }), commandHandler({ env: { LOOPWRIGHT_X: '1' } }), commandHandler({ env: { lowercase: '1' } }), + commandHandler({ timeoutMs: 999 }), commandHandler({ timeoutMs: 3_600_001 }), commandHandler({ args: ['a\0b'] }), commandHandler({ args: Array.from({ length: 65 }, () => 'x') }), + commandHandler({ script: '../escape.sh' }), commandHandler({ script: '/abs.sh' }), commandHandler({ toolchainPaths: ['../up'] }), commandHandler({ toolchainPaths: Array.from({ length: 33 }, () => 'scripts') }), + ]; + for (const handler of bad) { + const plan = { ...h.plan, verifierSlots: [...h.plan.verifierSlots.filter(slot => slot.id !== SLOT_ID), { id: SLOT_ID, checkId: CHECK_ID, implicit: null, handler }] }; + assert.throws(() => prepareLocalCheck(plan, h.context.lock, SLOT_ID, h.candidate, 0, NONCE, h.recorded), error => failure(error) === 'CONFIG_SCHEMA', JSON.stringify(handler.parameters)); + } + assert.throws(() => prepareLocalCheck(h.plan, h.context.lock, SLOT_ID, h.candidate, 0, 'short', h.recorded), error => failure(error) === 'ARTIFACT_INVALID'); + assert.throws(() => prepareLocalCheck(h.plan, h.context.lock, 'check.tests', h.candidate, 0, NONCE, h.recorded), error => failure(error) === 'CAPABILITY_UNSUPPORTED'); + assert.throws(() => prepareLocalCheck(h.plan, h.context.lock, SLOT_ID, h.candidate, h.plan.capacity.V, NONCE, h.recorded), error => failure(error) === 'CONFIG_SCHEMA'); + } finally { await h.release(); } +}); + +test('localCheckScriptDirectoryDigest is order-independent over entries and bound to content', async () => { + const { localCheckScriptDirectoryDigest } = await import('../src/local-check.js'); + const entries = [{ path: 'scripts/a.sh', mode: '100755' as const, byteLength: 3, sha256: 'a'.repeat(64) }, { path: 'scripts/b.sh', mode: '100644' as const, byteLength: 4, sha256: 'b'.repeat(64) }]; + assert.deepEqual(localCheckScriptDirectoryDigest(entries), localCheckScriptDirectoryDigest([...entries].reverse())); + assert.equal(same(localCheckScriptDirectoryDigest(entries), localCheckScriptDirectoryDigest([{ ...entries[0]!, sha256: 'c'.repeat(64) }, entries[1]!])), false); +}); diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index aa97e195..c4328e02 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -38,6 +38,10 @@ export { } from './evidence.js'; export { aggregateUsage, type RequestUsage, type Quantity, type Aggregate, type UsageSummary } from './usage.js'; export { SecretScrubber } from './scrubber.js'; +export { + LOCAL_CHECK_ENV_NAMES, LOCAL_CHECK_ENV_FIXED, LOCAL_CHECK_PATH_BASE, isLocalCheckEnvName, parseLocalCheckOut, + type LocalCheckSpec, type LocalCheckOutput, +} from './local-check-contract.js'; export { constructRunResult, type RunResult, type RunStatus, type MemoryObservation, type NoChangeVerification } from './results.js'; import { contractSchema, resolveOverlayOptions, type TaskContract } from './contracts.js'; import { lockSchema, type TaskLock } from './identity.js'; diff --git a/packages/core/src/local-check-contract.ts b/packages/core/src/local-check-contract.ts new file mode 100644 index 00000000..bf0c6263 --- /dev/null +++ b/packages/core/src/local-check-contract.ts @@ -0,0 +1,69 @@ +import { snapshot, type Json } from './boundary.js'; +import { findingsSchema, metricsSchema, object, optional, record, text, type MetricsMap, type StructuredFinding } from './contracts.js'; +import { attempt, fail, type Result } from './diagnostics.js'; +import { LIMITS, LOCAL_CHECK_LIMITS } from './limits.js'; + +/** + * Managed Controller `command.v1` contract: what the controller hands the script and what it reads back. + * It is a sibling of the Taskpack `command.v1` contract, not a shared implementation. + */ + +/** Every environment variable name the controller sets for a `command.v1` child. The controller's own `process.env` is never read or passed. */ +export const LOCAL_CHECK_ENV_NAMES: readonly string[] = Object.freeze([ + 'PATH', 'HOME', 'TMPDIR', 'LANG', 'LC_ALL', 'TERM', 'GIT_CONFIG_NOSYSTEM', 'GIT_CONFIG_GLOBAL', 'GIT_TERMINAL_PROMPT', 'GIT_ASKPASS', + 'LOOPWRIGHT_CANDIDATE_DIR', 'LOOPWRIGHT_BASE_DIR', 'LOOPWRIGHT_STAGED_DIR', 'LOOPWRIGHT_CHECK_OUT', 'LOOPWRIGHT_RUN_ID', 'LOOPWRIGHT_STEP_ID', 'LOOPWRIGHT_CHECK_ID', +]); + +/** Fixed values among those names; `PATH`, `HOME`, `TMPDIR`, and the `LOOPWRIGHT_*` names are resolved per check. */ +export const LOCAL_CHECK_ENV_FIXED: Readonly> = Object.freeze({ + LANG: 'C.UTF-8', LC_ALL: 'C.UTF-8', TERM: 'dumb', GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null', GIT_TERMINAL_PROMPT: '0', GIT_ASKPASS: '/usr/bin/false', +}); + +/** `PATH` after the resolved `toolchainPaths` are prepended. */ +export const LOCAL_CHECK_PATH_BASE = '/usr/local/bin:/usr/bin:/bin'; + +const ENV_NAME_PATTERN = /^[A-Z][A-Z0-9_]{0,63}$/; +/** The `env` parameter rule: an uppercase identifier of at most 64 characters that never takes the controller's `LOOPWRIGHT_` prefix. */ +export function isLocalCheckEnvName(name: string): boolean { + return ENV_NAME_PATTERN.test(name) && !name.startsWith('LOOPWRIGHT_'); +} + +/** The handler parameters, already validated by the registry; the controller re-verifies them before execution. */ +export interface LocalCheckSpec { + readonly script: string; + readonly args: readonly string[]; + readonly env: Readonly>; + readonly toolchainPaths: readonly string[]; + readonly timeoutMs: number; +} + +/** What the controller reads back from `$LOOPWRIGHT_CHECK_OUT`. */ +export interface LocalCheckOutput { + readonly detail?: string; + readonly metrics?: MetricsMap; + readonly findings?: readonly StructuredFinding[]; +} + +const localCheckOutputShape = record({ + detail: optional(text(1, LIMITS.string)), + metrics: optional(metricsSchema), + findings: optional(findingsSchema), +}); +const OUTPUT_KEYS: ReadonlySet = new Set(['detail', 'metrics', 'findings']); + +/** + * Strict parser for the `$LOOPWRIGHT_CHECK_OUT` file: at most `LOCAL_CHECK_LIMITS.checkOutBytes` bytes of strict JSON + * `{ detail?, metrics?, findings? }`. `passed`, `summary`, and every other key are refused; `detail` keeps the existing + * detail limit and `metrics`/`findings` keep the gate bounds. Every refusal carries an exact diagnostic code. + */ +export function parseLocalCheckOut(bytes: Uint8Array): Result { + return attempt(() => { + if (bytes.byteLength > LOCAL_CHECK_LIMITS.checkOutBytes) fail('LIMIT_BYTES'); + let source: string; + try { source = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes); } catch { fail('INPUT_UNSUPPORTED'); } + const value: Json = snapshot(source, { inputBytes: LOCAL_CHECK_LIMITS.checkOutBytes }); + const input = object(value, ''); + for (const key of Object.keys(input)) if (!OUTPUT_KEYS.has(key)) fail('FIELD_UNKNOWN', '/' + key); + return localCheckOutputShape(value, ''); + }); +} diff --git a/packages/core/test/local-check-contract.test.ts b/packages/core/test/local-check-contract.test.ts new file mode 100644 index 00000000..63ba2769 --- /dev/null +++ b/packages/core/test/local-check-contract.test.ts @@ -0,0 +1,119 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { + LIMITS, LOCAL_CHECK_LIMITS, LOCAL_CHECK_ENV_FIXED, LOCAL_CHECK_ENV_NAMES, LOCAL_CHECK_PATH_BASE, + isLocalCheckEnvName, parseLocalCheckOut, +} from '../src/index.js'; +import { value } from './fixtures.js'; + +const encode = (text: string) => new TextEncoder().encode(text); +const out = (document: unknown) => encode(JSON.stringify(document)); +function refusal(bytes: Uint8Array): { readonly code: string; readonly path: string } { + const result = parseLocalCheckOut(bytes); + assert.equal(result.ok, false, 'expected a refusal'); + if (result.ok) throw new Error('expected a refusal'); + assert.equal(result.errors.length, 1); + return { code: result.errors[0]!.code, path: result.errors[0]!.path }; +} + +test('the command.v1 contract names every variable the controller sets and pins the fixed values', () => { + const expected = ['PATH', 'HOME', 'TMPDIR', 'LANG', 'LC_ALL', 'TERM', 'GIT_CONFIG_NOSYSTEM', 'GIT_CONFIG_GLOBAL', 'GIT_TERMINAL_PROMPT', 'GIT_ASKPASS', + 'LOOPWRIGHT_CANDIDATE_DIR', 'LOOPWRIGHT_BASE_DIR', 'LOOPWRIGHT_STAGED_DIR', 'LOOPWRIGHT_CHECK_OUT', 'LOOPWRIGHT_RUN_ID', 'LOOPWRIGHT_STEP_ID', 'LOOPWRIGHT_CHECK_ID']; + assert.deepEqual([...LOCAL_CHECK_ENV_NAMES].sort(), expected.sort()); + assert.equal(new Set(LOCAL_CHECK_ENV_NAMES).size, expected.length); + for (const name of Object.keys(LOCAL_CHECK_ENV_FIXED)) assert.ok(expected.includes(name), name); + assert.deepEqual(LOCAL_CHECK_ENV_FIXED, { LANG: 'C.UTF-8', LC_ALL: 'C.UTF-8', TERM: 'dumb', GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null', GIT_TERMINAL_PROMPT: '0', GIT_ASKPASS: '/usr/bin/false' }); + assert.equal(LOCAL_CHECK_PATH_BASE, '/usr/local/bin:/usr/bin:/bin'); + assert.equal(Object.isFrozen(LOCAL_CHECK_ENV_NAMES), true); + assert.equal(Object.isFrozen(LOCAL_CHECK_ENV_FIXED), true); + assert.equal(LOCAL_CHECK_LIMITS.checkOutBytes, 65536); +}); + +test('env names are uppercase identifiers of at most 64 characters and never take the LOOPWRIGHT_ prefix', () => { + for (const name of ['FORGEVO_KERNEL_ID', 'A', 'X1_2', 'Z'.repeat(64), 'A_1_b'.toUpperCase()]) assert.equal(isLocalCheckEnvName(name), true, name); + for (const name of ['', 'forgevo', '1X', 'A-B', 'A.B', 'A B', 'Z'.repeat(65), 'LOOPWRIGHT_X', 'LOOPWRIGHT_', 'Loopwright_X']) assert.equal(isLocalCheckEnvName(name), false, name); +}); + +test('CHECK_OUT accepts an empty object and the optional keys at their exact bounds', () => { + const plain = (value: unknown) => JSON.parse(JSON.stringify(value)) as unknown; + assert.deepEqual(plain(value(parseLocalCheckOut(out({})))), {}); + const metrics = Object.fromEntries(Array.from({ length: LIMITS.metricEntries }, (_, i) => ['m' + i, i === 0 ? -0 : i % 2 ? 'v' : true])); + const finding = { title: 't', severity: 'high', evidence: 'e', path: 'src/x.ts', line: 1 }; + const findings = Array.from({ length: LIMITS.findings }, () => finding); + const parsed = value(parseLocalCheckOut(out({ detail: 'd'.repeat(LIMITS.string), metrics, findings }))); + assert.equal(parsed.detail, 'd'.repeat(LIMITS.string)); + assert.equal(Object.keys(parsed.metrics!).length, LIMITS.metricEntries); + assert.equal(parsed.metrics!['m0'], 0, '-0 normalizes to 0'); + assert.equal(parsed.findings!.length, LIMITS.findings); + assert.deepEqual(plain(parsed.findings![0]), finding); + assert.equal(Object.isFrozen(parsed.findings), true); + const optional = value(parseLocalCheckOut(out({ detail: 'ok' }))); + assert.deepEqual(Object.keys(optional), ['detail']); + assert.equal(Object.hasOwn(optional, 'metrics'), false); + assert.equal(Object.isFrozen(optional), true); +}); + +test('CHECK_OUT refuses passed, summary and every unknown key with the key path', () => { + assert.deepEqual(refusal(out({ passed: true })), { code: 'FIELD_UNKNOWN', path: '/passed' }); + assert.deepEqual(refusal(out({ summary: 'ok' })), { code: 'FIELD_UNKNOWN', path: '/summary' }); + assert.deepEqual(refusal(out({ detail: 'x', status: 'failed' })), { code: 'FIELD_UNKNOWN', path: '/status' }); + assert.deepEqual(refusal(out({ metrics: { a: 1 }, note: null })), { code: 'FIELD_UNKNOWN', path: '/note' }); + assert.deepEqual(refusal(out({ findings: [{ title: 't', severity: 'low', evidence: 'e', note: 1 }] })), { code: 'FIELD_UNKNOWN', path: '/findings/0' }); +}); + +test('CHECK_OUT refuses non-objects, mistyped optionals, and detail outside the existing detail limit', () => { + assert.deepEqual(refusal(encode('[]')), { code: 'VALUE_TYPE', path: '' }); + assert.deepEqual(refusal(encode('"x"')), { code: 'VALUE_TYPE', path: '' }); + assert.deepEqual(refusal(encode('3')), { code: 'VALUE_TYPE', path: '' }); + assert.deepEqual(refusal(encode('null')), { code: 'VALUE_TYPE', path: '' }); + assert.deepEqual(refusal(out({ detail: null })), { code: 'VALUE_TYPE', path: '/detail' }); + assert.deepEqual(refusal(out({ detail: 1 })), { code: 'VALUE_TYPE', path: '/detail' }); + assert.deepEqual(refusal(out({ detail: '' })), { code: 'VALUE_RANGE', path: '/detail' }); + assert.deepEqual(refusal(out({ detail: 'd'.repeat(LIMITS.string + 1) })), { code: 'LIMIT_STRING', path: '' }); + assert.deepEqual(refusal(out({ metrics: [] })), { code: 'VALUE_TYPE', path: '/metrics' }); + assert.deepEqual(refusal(out({ metrics: { a: null } })), { code: 'VALUE_TYPE', path: '/metrics/a' }); +}); + +test('metrics and findings carry exactly the gate bounds', () => { + const entries = (count: number) => Object.fromEntries(Array.from({ length: count }, (_, i) => ['m' + i, i])); + assert.deepEqual(refusal(out({ metrics: entries(LIMITS.metricEntries + 1) })), { code: 'VALUE_RANGE', path: '/metrics' }); + assert.deepEqual(refusal(out({ metrics: { constructor: 1 } })), { code: 'IDENTIFIER_INVALID', path: '/metrics' }); + assert.deepEqual(refusal(out({ metrics: { '1x': 1 } })), { code: 'IDENTIFIER_INVALID', path: '/metrics' }); + assert.deepEqual(refusal(out({ metrics: { '': 1 } })), { code: 'IDENTIFIER_INVALID', path: '/metrics' }); + assert.deepEqual(refusal(out({ metrics: { ['k'.repeat(LIMITS.metricKey + 1)]: 1 } })), { code: 'IDENTIFIER_INVALID', path: '/metrics' }); + assert.deepEqual(refusal(out({ metrics: { ok: 'v'.repeat(LIMITS.metricStringValue + 1) } })), { code: 'VALUE_RANGE', path: '/metrics/ok' }); + assert.deepEqual(refusal(encode('{"metrics":{"ok":1e400}}')), { code: 'VALUE_RANGE', path: '' }); + const finding = { title: 't', severity: 'high', evidence: 'e' }; + assert.deepEqual(refusal(out({ findings: Array.from({ length: LIMITS.findings + 1 }, () => finding) })), { code: 'VALUE_RANGE', path: '/findings' }); + assert.deepEqual(refusal(out({ findings: [{ ...finding, severity: 'fatal' }] })), { code: 'VALUE_ENUM', path: '/findings/0/severity' }); + assert.deepEqual(refusal(out({ findings: [{ ...finding, title: '' }] })), { code: 'VALUE_RANGE', path: '/findings/0/title' }); + assert.deepEqual(refusal(out({ findings: [{ ...finding, title: 't'.repeat(LIMITS.findingTitle + 1) }] })), { code: 'VALUE_RANGE', path: '/findings/0/title' }); + assert.deepEqual(refusal(out({ findings: [{ ...finding, evidence: '' }] })), { code: 'VALUE_RANGE', path: '/findings/0/evidence' }); + assert.deepEqual(refusal(out({ findings: [{ ...finding, line: 0 }] })), { code: 'VALUE_RANGE', path: '/findings/0/line' }); + assert.deepEqual(refusal(out({ findings: [{ ...finding, line: 1.5 }] })), { code: 'VALUE_RANGE', path: '/findings/0/line' }); + assert.deepEqual(refusal(out({ findings: [{ ...finding, path: '../escape' }] })), { code: 'PATH_INVALID', path: '/findings/0/path' }); + assert.deepEqual(refusal(out({ findings: [{ ...finding, path: '/absolute' }] })), { code: 'PATH_INVALID', path: '/findings/0/path' }); + assert.deepEqual(JSON.parse(JSON.stringify(value(parseLocalCheckOut(out({ findings: [{ ...finding, path: null, line: null }] }))).findings)), [{ title: 't', severity: 'high', path: null, line: null, evidence: 'e' }]); +}); + +test('CHECK_OUT refuses malformed, duplicated, non-UTF-8, BOM-prefixed, and oversized input with exact codes', () => { + assert.equal(refusal(encode('{')).code, 'JSON_SYNTAX'); + assert.equal(refusal(encode('')).code, 'JSON_SYNTAX'); + assert.equal(refusal(encode('{"detail":"a","detail":"b"}')).code, 'JSON_DUPLICATE_MEMBER'); + assert.equal(refusal(encode('{"detail":"bad \\ud800 surrogate"}')).code, 'INPUT_UNSUPPORTED'); + assert.equal(refusal(new Uint8Array([0x7b, 0x7d, 0xff])).code, 'INPUT_UNSUPPORTED'); + assert.equal(refusal(new Uint8Array([0xef, 0xbb, 0xbf, 0x7b, 0x7d])).code, 'JSON_SYNTAX'); + assert.deepEqual(refusal(out({ detail: 'd'.repeat(LOCAL_CHECK_LIMITS.checkOutBytes) })), { code: 'LIMIT_BYTES', path: '' }); + // A document of exactly checkOutBytes bytes is accepted; one more byte is refused before any parsing. + const build = (evidenceLength: number, lastPad: number) => { + const findings = Array.from({ length: LIMITS.findings }, (_, i) => ({ title: 't', severity: 'high', evidence: 'e'.repeat(i === LIMITS.findings - 1 ? evidenceLength + lastPad : evidenceLength) })); + return encode(JSON.stringify({ findings })); + }; + let evidenceLength = 950, measured = build(evidenceLength, 0).byteLength, pad = LOCAL_CHECK_LIMITS.checkOutBytes - measured; + while (pad > LIMITS.findingEvidence - evidenceLength) { measured = build(++evidenceLength, 0).byteLength; pad = LOCAL_CHECK_LIMITS.checkOutBytes - measured; } + assert.ok(pad > 0, 'the largest accepted document fits the evidence bound'); + const largest = build(evidenceLength, pad); + assert.equal(largest.byteLength, LOCAL_CHECK_LIMITS.checkOutBytes); + assert.equal(value(parseLocalCheckOut(largest)).findings!.length, LIMITS.findings); + assert.equal(refusal(new Uint8Array(largest.byteLength + 1)).code, 'LIMIT_BYTES'); +}); diff --git a/specs/2026-11-30-managed-controller-in-process-execution.md b/specs/2026-11-30-managed-controller-in-process-execution.md index 0c29d26f..ea4eb87f 100644 --- a/specs/2026-11-30-managed-controller-in-process-execution.md +++ b/specs/2026-11-30-managed-controller-in-process-execution.md @@ -128,7 +128,9 @@ controller's own environment on a host whose isolation the registry attests. disposable materialization of the captured candidate, writable during the check and discarded after it; `LOOPWRIGHT_BASE_DIR` is the read-only baseline tree; `LOOPWRIGHT_STAGED_DIR` is the read-only staged context; `LOOPWRIGHT_CHECK_OUT` is the only output file the controller reads; - `LOOPWRIGHT_RUN_ID`, `LOOPWRIGHT_STEP_ID`, `LOOPWRIGHT_CHECK_ID` identify the slot. No + `LOOPWRIGHT_RUN_ID`, `LOOPWRIGHT_STEP_ID`, `LOOPWRIGHT_CHECK_ID` identify the slot. The child's + working directory is `LOOPWRIGHT_BASE_DIR`; its stdout is not part of the contract and is + discarded. No controller credential reaches the environment. `$LOOPWRIGHT_CHECK_OUT` is strict JSON `{ detail?, metrics?, findings? }` with at most 64 KiB; `passed` and `summary` keys are refused; `metrics` and `findings` pass the bounds in [gate.ts](../packages/controller/src/gate.ts). @@ -139,7 +141,7 @@ controller's own environment on a host whose isolation the registry attests. a run past `timeoutMs` is `failed` with reason `check_timeout` and the process group is killed. A child that called `setsid` can escape the group; recovery and Pod exit are the backstops, and the test asserts only the group. An operation that the controller finds - without a proof marker after a crash settles `blocked` with `EVIDENCE_UNAVAILABLE` after the + without a proof marker after a crash, with or without a binding marker, settles `blocked` with `EVIDENCE_UNAVAILABLE` after the recorded group is killed; it is never re-dispatched under the same operation. - **Evidence.** The output artifact and a bounded, scrubbed stderr tail are bound to `candidateDigest`. The receipt carries `method: 'direct_script'`, the script path, the script @@ -540,15 +542,15 @@ and T11 have disjoint `Owns:` and start together; T5 follows T2. Owns: `packages/core/src/contracts.ts`, `packages/core/src/limits.ts`, `packages/controller/src/types.ts`, `packages/controller/src/registry.ts`, `packages/controller/src/config.ts`, `packages/controller/test/registry-command-v1.test.ts`, `packages/controller/test/exec-profile.test.ts`, `packages/controller/test/config-local-checks.test.ts`, `packages/core/test/contracts.test.ts` Acceptance: `validateRegistry` accepts a `command.v1` handler with the F1 parameters and `host.localChecks.backend: direct`, and an `exec` profile with the F2 keys beside a `pi.agent.v1` agent handler; it refuses the F1 and F2 refusal cases with the codes named there. `loadConfiguration` refuses a registry with a `command.v1` handler but no `host.localChecks`, any backend other than `direct`, and a `command.v1` or `exec` `timeoutMs` that cannot fit between `drainReserveMs` and `wallTimeMs`. `host_execution` is accepted as an evidence level and a capability, and `RoleAdapterKind` includes `'exec'`. Verify: `node scripts/run-tests.mjs --pkg controller && node scripts/run-tests.mjs --pkg core` -- [ ] **T3 · `LocalCheck` module: contract, executor, and authority** +- [x] **T3 · `LocalCheck` module: contract, executor, and authority** Blocked by: T1, T2 - Owns: `packages/core/src/local-check-contract.ts`, `packages/core/src/index.ts`, `packages/core/test/local-check-contract.test.ts`, `packages/controller/src/local-check.ts`, `packages/controller/test/local-check.test.ts`, `packages/controller/test/local-check-fixtures.ts` + Owns: `packages/core/src/local-check-contract.ts`, `packages/core/src/index.ts`, `packages/core/test/local-check-contract.test.ts`, `packages/controller/src/local-check.ts`, `packages/controller/src/candidate-workspace.ts`, `packages/controller/test/local-check.test.ts`, `packages/controller/test/local-check-fixtures.ts`, `packages/controller/test/fixtures/scripts/` Gate: review Acceptance: the contract module exports the environment names, the env name rule, and the `$LOOPWRIGHT_CHECK_OUT` parser (64 KiB, `passed` and `summary` refused, metric and finding bounds); `packages/core/src/index.ts` also exports the T2 limits (`LOCAL_CHECK_LIMITS`, `EXEC_LIMITS`) and `handlerCapability`. `LocalCheck.run(job, signal)` follows `Gate.run` and executes the script in its own process group with the binding marker written first: candidate materialized through the T1 helpers into a disposable directory, the F1 environment, `timeoutMs` with process-group kill, exit-code mapping, output artifact bound to `candidateDigest`, scrubbed stderr tail, receipt with `method: 'direct_script'` and the script and registry digests. The captured overlay is byte-identical before and after; an operation without a proof marker settles `blocked` with `EVIDENCE_UNAVAILABLE` and is not re-dispatched. Verify: `node scripts/run-tests.mjs --pkg core && node scripts/run-tests.mjs --pkg controller` - [ ] **T4 · `command.v1` controller integration** Blocked by: T3 - Owns: `packages/controller/src/compile.ts`, `packages/controller/src/controller.ts`, `packages/controller/src/recovery.ts`, `packages/controller/src/handlers.ts`, `packages/controller/src/errors.ts`, `packages/controller/test/compile.test.ts`, `packages/controller/test/rework.test.ts`, `packages/controller/test/local-check-integration.test.ts`, `packages/controller/test/recovery-cycle.test.ts` + Owns: `packages/controller/src/compile.ts`, `packages/controller/src/controller.ts`, `packages/controller/src/recovery.ts`, `packages/controller/src/handlers.ts`, `packages/controller/src/errors.ts`, `packages/controller/src/retained.ts`, `packages/controller/src/acceptance.ts`, `packages/controller/test/compile.test.ts`, `packages/controller/test/rework.test.ts`, `packages/controller/test/local-check-integration.test.ts`, `packages/controller/test/recovery-cycle.test.ts` Gate: review Acceptance: admission resolves the script and `toolchainPaths` at `target.sourceRevision` from the baseline tree, requires the executable bit and a fully protected script directory, and records the directory digest in the compiled slot; `check` validates schema and budget only; the controller dispatches `command.v1` slots to `LocalCheck`, extracts `detail` for them in the rework summary, and exports the receipt through `inspect`; recovery settles a `command.v1` operation without a proof marker as `blocked`. A controller cycle test with the deterministic fake adapter as author and the T3 stub scripts settles `completed` for a passing script and reworks with `detail` for a failing one. `installedHandlerDigests()` in `handlers.ts` lists `command.v1`, and the `safePath` segment whitelist in `errors.ts` covers the new refusal paths (`host`, `localChecks`, `backend`, `command`, `script`, `env`, `toolchainPaths`, `exec`, `captureBytes`, `credentialRefs`). Verify: `node scripts/run-tests.mjs --pkg controller` @@ -607,9 +609,9 @@ solid enough prior to committing the changes necessary to implement this enhance - Controller fixtures (`config-fixtures.ts`, `scheduling-fixtures.ts`) gain a registry with a `command.v1` handler and `host.localChecks: { backend: direct }`, and a stub script directory - under `test/fixtures/scripts/` with four scripts: pass (writes metrics), fail (exits `1` with a - stderr reason), sleep (runs past `timeoutMs`), and write-outside-candidate (attempts a write - under the baseline). + under `test/fixtures/scripts/` with five scripts: pass (writes metrics), fail (exits `1` with a + stderr reason), sleep (runs past `timeoutMs`), write-outside-candidate (attempts a write + under the baseline), and print-env (prints its environment for the contract diff). - A stub `exec` command under `packages/controller/test/exec-role-fixtures.ts`: writes one file inside `scope.writable`, one outside it, exits `3`, sleeps past `timeoutMs`, calls `setsid` and forks a child, and prints a provided secret to stdout. From 7bb3749b86570f758284dce3fb4d0a5b7e5dde2c Mon Sep 17 00:00:00 2001 From: thxCode Date: Tue, 1 Dec 2026 11:19:05 +0800 Subject: [PATCH 12/26] feat(controller): admit, dispatch, and recover command.v1 checks end to end - compile resolves script directory digest into the slot under planDigest - two-phase owner acquire keeps runs without command.v1 byte-identical - dispatch through LocalCheck; rework detail; recovery settles blocked, no re-dispatch - inspect exports verifier-receipts.json; acceptance, lease, run-eval branches - T4 spec check-off; F1 receipt export wording and resume re-verification Task 4 of managed-controller-in-process-execution. Signed-off-by: thxCode --- packages/controller/src/acceptance.ts | 7 +- packages/controller/src/compile.ts | 65 +++- packages/controller/src/controller.ts | 85 ++++- packages/controller/src/errors.ts | 2 +- packages/controller/src/handlers.ts | 2 +- packages/controller/src/inspect.ts | 10 +- packages/controller/src/reconcile.ts | 7 +- packages/controller/src/recovery.ts | 14 +- packages/controller/src/retained.ts | 9 +- packages/controller/src/run-eval.ts | 4 +- packages/controller/src/types.ts | 4 +- packages/controller/test/compile.test.ts | 85 ++++- .../test/local-check-integration.test.ts | 135 +++++++ .../controller/test/recovery-cycle.test.ts | 90 ++++- packages/controller/test/rework.test.ts | 337 +++--------------- .../controller/test/scheduling-fixtures.ts | 332 ++++++++++++++++- ...managed-controller-in-process-execution.md | 12 +- 17 files changed, 872 insertions(+), 328 deletions(-) create mode 100644 packages/controller/test/local-check-integration.test.ts diff --git a/packages/controller/src/acceptance.ts b/packages/controller/src/acceptance.ts index cd92388b..8c546409 100644 --- a/packages/controller/src/acceptance.ts +++ b/packages/controller/src/acceptance.ts @@ -24,6 +24,7 @@ import type { LocalRunStore } from '@loopwright/state'; import { authenticatedCheck, authenticatedRefusal, type PreflightRefusal, type VerifiedCheck } from './verification.js'; import { authenticatedGate } from './gate.js'; import { authenticatedBenchmarkGate } from './benchmark-gate.js'; +import { LOCAL_CHECK_PRODUCER_ID, authenticatedLocalCheck } from './local-check.js'; import { STREAM_CHUNK_BYTES, inside } from './files.js'; import { journal } from './progress.js'; import { canonical, freeze, hash, same } from './schema.js'; @@ -352,11 +353,13 @@ const tree = (input: unknown): unknown => JSON.parse(canonical(input)); function authenticateCheckByImpl(impl: string | undefined, checked: VerifiedCheck) { if (impl === 'gate.v1') return authenticatedGate(checked); if (impl === 'benchmark-gate.v1') return authenticatedBenchmarkGate(checked); + if (impl === 'command.v1') return authenticatedLocalCheck(checked); return authenticatedCheck(checked); } function expectedProducerByImpl(impl: string | undefined): string { if (impl === 'gate.v1') return 'loopwright.gate-verifier.v1'; if (impl === 'benchmark-gate.v1') return 'loopwright.benchmark-gate.v1'; + if (impl === 'command.v1') return LOCAL_CHECK_PRODUCER_ID; return 'loopwright.byte-verifier.v1'; } export function evaluateControllerAcceptance(plan: CompiledPlan, lock: TaskLock, candidate: ArtifactManifest, candidateFiles: readonly (ResolvedArtifactInput | CandidateFileEntry)[], generation: number, @@ -444,7 +447,9 @@ export function evaluateControllerAcceptance(plan: CompiledPlan, lock: TaskLock, ? authenticatedGate(verified).evidence : slot.handler.implementation === 'benchmark-gate.v1' ? authenticatedBenchmarkGate(verified).evidence - : authenticatedCheck(verified).evidence; + : slot.handler.implementation === 'command.v1' + ? authenticatedLocalCheck(verified).evidence + : authenticatedCheck(verified).evidence; return { checkId: check.id, status: verified.status, diff --git a/packages/controller/src/compile.ts b/packages/controller/src/compile.ts index 81f187b8..37505e9e 100644 --- a/packages/controller/src/compile.ts +++ b/packages/controller/src/compile.ts @@ -1,14 +1,19 @@ +import { createHash } from 'node:crypto'; +import { dirname } from 'node:path'; import { fileURLToPath } from 'node:url'; -import { LIMITS } from '@loopwright/core'; +import { LIMITS, type Digest } from '@loopwright/core'; import { describePiAdapterFiles, type AdapterPolicy } from '@loopwright/agent-pi'; import { resolveBuiltInPiCatalogModel, resolveCatalogModel } from '@loopwright/agent-pi/catalog'; import { approvedState, selectRoleResources } from './config.js'; import { validatePiSelectionOrRefuse } from './registry.js'; import { readBoundedFile } from './files.js'; import { installedHandlerDigests } from './handlers.js'; -import { freeze, canonical, hash, same } from './schema.js'; +import type { ControllerOwner } from './ownership.js'; +import { freeze, canonical, digestValue, hash, list, same, text, type Json } from './schema.js'; import { refuse, result } from './errors.js'; import { compactionTarget, descendants, reworkSubgraph } from './scheduler.js'; +import { localCheckScriptDirectoryDigest, type LocalCheckRecorded, type LocalCheckScriptEntry } from './local-check.js'; +import { matchesScopePattern, type FrozenSource } from './source.js'; import { CONTROLLER_LIMITS, type CheckpointCapacity, type CompiledPlan, type LoadedConfiguration, type PlannedNode, type PlannedRole, type RuntimeProfile, type StepHandoffSelect, type StepHandoffSelector, type StepHandoffSource, type VerifierSlot } from './types.js'; function cloneHandoffSelector(item: StepHandoffSelector): StepHandoffSelector { const source: StepHandoffSource = item.source.kind === 'artifact' @@ -38,7 +43,47 @@ export function checkpointCapacity(A: number, N: number, I: number, C: number, p if (D > 256) refuse('CONFIG_LIMIT', '/spec/controls', 'compile'); return { A, N, I, C, V, J, D, publication, additionalRefs: 4, requiredRefs: 6, checkpointBytes: 40960 }; } -export function compilePlan(loaded: LoadedConfiguration) { +/** What admission adds to every `command.v1` slot: the script directory digest read from the frozen baseline (`run`, `step next`), or the record already retained with the run (`resume`, `reconcile`; `LocalCheck` re-verifies it against the baseline before dispatch). */ +export type SlotAdmission = + | { readonly kind: 'baseline'; readonly source: FrozenSource; readonly owner: ControllerOwner } + | { readonly kind: 'retained'; readonly slots: readonly VerifierSlot[] }; +/** The slot record `prepareLocalCheck` needs; an admitted plan never lacks it. */ +export function recordedLocalCheck(slot: VerifierSlot): LocalCheckRecorded { + const digest = slot.scriptDirectoryDigest; + if (!digest) refuse('RECOVERY_REQUIRED', '', 'verification'); + return { scriptDirectoryDigest: digest }; +} +const scriptPrefix = (script: string): string => { const dir = dirname(script); return dir === '.' ? '' : dir + '/'; }; +/** Every baseline entry under the script directories, without materializing: classic sources hold the bytes, tree-overlay sources stream each blob once. */ +async function entriesUnder(source: FrozenSource, owner: ControllerOwner, prefixes: readonly string[]): Promise> { + const under = (name: string) => prefixes.some(prefix => prefix === '' || name.startsWith(prefix)); + const entries = new Map(); + if (source.version === 1) { + for (const item of source.artifacts) if (under(item.name)) entries.set(item.name, { path: item.name, mode: item.mode ?? '100644', byteLength: item.bytes.byteLength, sha256: hash(item.bytes).hex }); + return entries; + } + const names = (source.baselineEntries ?? []).filter(item => under(item.name)); + await owner.streamGitBatch(source.directory, names, async (entry, readChunks) => { + const digest = createHash('sha256'); + await readChunks(async slice => { digest.update(slice); }); + entries.set(entry.name, { path: entry.name, mode: entry.mode, byteLength: entry.byteLength, sha256: digest.digest('hex') }); + }, { phase: 'compile' }); + return entries; +} +const baselineNames = (source: FrozenSource): readonly string[] => source.version === 1 ? source.artifacts.map(item => item.name) : (source.baselineEntries ?? []).map(item => item.name); +/** The same rules `LocalCheck.#verifyBaseline` applies to the materialized tree, applied to the frozen baseline so the refusal precedes any run. */ +function admitScriptDirectory(entries: ReadonlyMap, names: readonly string[], scope: CompiledPlan['scope'], parameters: Readonly>, path: string): Digest { + const script = text(parameters.script, path + '/script'), prefix = scriptPrefix(script), directory = [...entries.values()].filter(entry => entry.path.startsWith(prefix)); + const executable = directory.find(entry => entry.path === script); + if (!executable || executable.mode !== '100755') refuse('CONFIG_REFERENCE', path + '/script', 'compile'); + for (const entry of directory) if (!scope.protected.some(pattern => matchesScopePattern(pattern, entry.path))) refuse('CONFIG_SCHEMA', path + '/script', 'compile'); + for (const item of list(parameters.toolchainPaths, path + '/toolchainPaths', 32)) { + const toolchain = text(item, path + '/toolchainPaths'); + if (!names.some(name => name.startsWith(toolchain + '/'))) refuse('CONFIG_REFERENCE', path + '/toolchainPaths', 'compile'); + } + return localCheckScriptDirectoryDigest(directory); +} +export function compilePlan(loaded: LoadedConfiguration, admission?: SlotAdmission) { return result(async (): Promise => { const state = approvedState(loaded), config = loaded.configuration, task = config.spec.task, registry = loaded.registry.spec; if ( @@ -114,6 +159,8 @@ export function compilePlan(loaded: LoadedConfiguration) { } } const verifierSlots: VerifierSlot[] = [], networkCredentials: { readonly ref: string; readonly consumer: 'gate' | 'publisher' }[] = []; + // Script directories are read once for every `command.v1` handler the registry holds; a root-level script covers the whole tree. + let scriptEntries: Map | null = null; const networkCredential = (ref: string, consumer: 'gate' | 'publisher', path: string): void => { const binding = registry.credentialBindings.find(item => item.id === ref); if (!binding || binding.consumer !== consumer) refuse('CONFIG_REFERENCE', path, 'compile'); @@ -123,6 +170,7 @@ export function compilePlan(loaded: LoadedConfiguration) { const matches = registry.handlers.filter(handler => handler.kind === 'check' && handler.parameters.checkId === check.id); if (matches.length !== 1) refuse('CONFIG_REFERENCE', '/spec/task/spec/acceptance', 'compile'); const handler = matches[0]!; + let commandScriptDigest: Digest | null = null; const requiresHardware = check.allowedEvidenceLevels.includes('hardware_execution'); if (requiresHardware) { if (check.allowedEvidenceLevels.length !== 1 || !check.targetCellId) { @@ -149,8 +197,17 @@ export function compilePlan(loaded: LoadedConfiguration) { if (!endpoint) refuse('CONFIG_REFERENCE', '/registry/spec/gateEndpoints', 'compile'); networkCredential(endpoint.signingCredentialRef, 'gate', '/registry/spec/gateEndpoints'); if (endpoint.authCredentialRef !== null) networkCredential(endpoint.authCredentialRef, 'gate', '/registry/spec/gateEndpoints'); + } else if (handler.implementation === 'command.v1') { + // `check` has no repository: the scope rule and the evidence level are static; files resolve at admission only. + const handlerPath = '/registry/spec/handlers/' + registry.handlers.indexOf(handler); + if (!check.allowedEvidenceLevels.includes('host_execution')) refuse('CONFIG_SCHEMA', '/spec/task/spec/acceptance', 'compile'); + if (!task.spec.scope.protected.some(pattern => matchesScopePattern(pattern, text(handler.parameters.script, handlerPath + '/parameters/script')))) refuse('CONFIG_SCHEMA', handlerPath + '/parameters/script', 'compile'); + if (admission?.kind === 'baseline') { + if (!scriptEntries) scriptEntries = await entriesUnder(admission.source, admission.owner, registry.handlers.filter(item => item.implementation === 'command.v1').map(item => scriptPrefix(String(item.parameters.script)))); + commandScriptDigest = admitScriptDirectory(scriptEntries, baselineNames(admission.source), task.spec.scope, handler.parameters, handlerPath + '/parameters'); + } else if (admission?.kind === 'retained') commandScriptDigest = digestValue(admission.slots.find(item => item.checkId === check.id && item.handler.implementation === 'command.v1')?.scriptDirectoryDigest, handlerPath + '/parameters/script'); } - verifierSlots.push({ id: 'check.' + check.id, checkId: check.id, implicit: null, handler }); + verifierSlots.push({ id: 'check.' + check.id, checkId: check.id, implicit: null, handler, ...(commandScriptDigest ? { scriptDirectoryDigest: commandScriptDigest } : {}) }); } for (const [implementation, implicit] of [['scope.v1', 'scope'], ['no-change.v1', 'no_change']] as const) { const matches = registry.handlers.filter(handler => handler.implementation === implementation && handler.parameters.checkId === null); diff --git a/packages/controller/src/controller.ts b/packages/controller/src/controller.ts index edb01b13..412fbd33 100644 --- a/packages/controller/src/controller.ts +++ b/packages/controller/src/controller.ts @@ -1,12 +1,12 @@ import { mkdir, open, rm } from 'node:fs/promises'; import { constants } from 'node:fs'; -import { join, resolve } from 'node:path'; +import { dirname, join, resolve } from 'node:path'; import { randomBytes } from 'node:crypto'; import { openPiAdapterV2, type PiAdapterV2, type PiCandidateArtifactInput, type PiHostV2, type PiOpenInputV2, type PiOutcomeV2 } from '@loopwright/agent-pi'; import { LIMITS, admitTask, bindSubject, identifyManifest, validateRelativePath, type ArtifactManifest, type ArtifactRef, type Digest, type StepHandoffSelector, type StructuredFinding, type TaskLock } from '@loopwright/core'; import { createLocalRun, type Authority, type LocalRunIdentity, type LocalRunStore } from '@loopwright/state'; import { approvedState, selectRoleResources } from './config.js'; -import { compilePlan } from './compile.js'; +import { compilePlan, recordedLocalCheck } from './compile.js'; import { ControllerFailure, refuse, result, safeDiagnostic, type ControllerDiagnostic } from './errors.js'; import { privateDirectory, ArtifactStore, checkedRef, stateValue, streamVerifiedCasBlob } from './storage.js'; import { ControllerOwner, bootIdentity } from './ownership.js'; @@ -39,6 +39,7 @@ import { } from './submission.js'; import { prepareVerification, preflightVerification, Verifier, authenticatedCheck, verifierProofPaths, type PreflightRefusal, type VerifiedCheck, type ByteInventory, type PreparedVerification } from './verification.js'; import { prepareGate, Gate, GATE_OUTPUT_BYTES, authenticatedGate, validateGateUrlOverrides, type PreparedGate } from './gate.js'; +import { LocalCheck, authenticatedLocalCheck, prepareLocalCheck, type PreparedLocalCheck } from './local-check.js'; import { prepareBenchmarkGate, BenchmarkGate, @@ -192,7 +193,7 @@ async function exclusiveJson(path: string, value: unknown): Promise { const parent = await open(resolve(path, '..'), constants.O_RDONLY | constants.O_NOFOLLOW); try { await parent.sync(); } finally { await parent.close(); } } export async function createCycle(input: RunCycleInput, ports: ControllerPorts): Promise { - const state = approvedState(input.configuration), compiled = await compilePlan(input.configuration); if (!compiled.ok) throw new ControllerFailure(compiled.error); const plan = compiled.value; + const state = approvedState(input.configuration), compiled = await compilePlan(input.configuration); if (!compiled.ok) throw new ControllerFailure(compiled.error); let plan = compiled.value; validatePortPolicyFields(ports, 'admission'); const normalizedWatchedPaths = normalizeWatchedPaths(ports.watchedPaths, 'admission'); validateGateUrlOverrides(ports.gateUrlOverrides, 'admission', input.configuration.registry.spec.gateEndpoints); @@ -213,16 +214,24 @@ export async function createCycle(input: RunCycleInput, ports: ControllerPorts): let owner: ControllerOwner | null = null, store: LocalRunStore | null = null; try { owner = await ControllerOwner.acquire(directory, runId, plan.planDigest); const artifactDirectory = join(directory, 'artifacts'); await privateDirectory(artifactDirectory); - const artifacts = new ArtifactStore(artifactDirectory, owner, state.vault); + let artifacts = new ArtifactStore(artifactDirectory, owner, state.vault); const jsonPaths = verifierProofPaths(plan.verifierSlots); const source = await freezeSource(repository, plan.task, owner, artifacts, jsonPaths); + if (plan.verifierSlots.some(slot => slot.handler.implementation === 'command.v1')) { + // The script directory digest enters planDigest and the owner is bound to planDigest: admit under a provisional owner, then re-bind to the final plan. + const admitted = await compilePlan(input.configuration, { kind: 'baseline', source, owner }); + if (!admitted.ok) throw new ControllerFailure(admitted.error); + plan = admitted.value; + await owner.release(); owner = await ControllerOwner.acquire(directory, runId, plan.planDigest); + artifacts = new ArtifactStore(artifactDirectory, owner, state.vault); + } const overlayBounds = overlayManifestBounds(plan.budgets.overlay); const admitted = admitTask(plan.task, { admissionId: 'admission.' + hash('loopwright.dev/controller/admission/v1\0' + runId + '\0' + plan.planDigest.hex).hex.slice(0, 40), runId }); if (!admitted.ok) refuse('CONFIG_SCHEMA', '/spec/task', 'admission'); const lock = admitted.value, manifest = await artifacts.json('manifest', source.manifest, overlayBounds.manifestMaxBytes); const initial: ByteInventory = { manifest: source.manifest, ref: manifest, files: source.artifacts, baselineProofs: source.baselineProofs }; // Core identity is pure; complete byte preflight still precedes S02 create/claim and every initial dispatch. for (const slot of plan.verifierSlots) { - if (slot.handler.implementation === 'gate.v1') continue; + if (slot.handler.implementation === 'gate.v1' || slot.handler.implementation === 'command.v1') continue; if (slot.handler.implementation === 'benchmark-gate.v1') { prepareBenchmarkGate(plan, lock, slot.id, initial, 0, randomBytes(16).toString('hex'), input.configuration.registry.spec.gateEndpoints); continue; @@ -291,9 +300,29 @@ function extractGateVerdictExcerpt(checked: VerifiedCheck, isBenchmark: boolean) } } +/** The same bounded view of an authenticated `command.v1` verdict: its check-out `detail` and `findings`, already validated by the contract parser. */ +function extractLocalCheckExcerpt(checked: VerifiedCheck): GateVerdictExcerpt { + const spec = authenticatedLocalCheck(checked).evidence.spec, findings: RepairFinding[] = []; + for (const item of spec.findings ?? []) { + if (findings.length >= MAX_REPAIR_FINDINGS) break; + findings.push({ + title: item.title, + severity: item.severity, + ...(item.path !== undefined ? { path: item.path } : {}), + ...(item.line !== undefined ? { line: item.line } : {}), + ...(typeof item.evidence === 'string' ? { evidence: Array.from(item.evidence).slice(0, MAX_REPAIR_FINDING_EVIDENCE_CODEPOINTS).join('') } : {}), + }); + } + return { + ...(typeof spec.detail === 'string' ? { detail: Array.from(spec.detail).slice(0, MAX_REPAIR_DETAIL_CODEPOINTS).join('') } : {}), + ...(findings.length > 0 ? { findings } : {}), + }; +} + export class Cycle { head: ProgressHead | null; candidate: ByteInventory; submission: RetainedSubmission | null = null; readonly checks = new Map(); readonly refusals = new Map(); readonly deadline: WorkDeadline; readonly events: ControllerEvents; readonly verifier: Verifier; readonly gate: Gate; readonly benchmarkGate: BenchmarkGate; readonly publisher: Publication; + readonly localCheck: LocalCheck; readonly advisoryObservations: Record[] = []; #activeAdapter: PiAdapterV2 | null = null; #candidateKnown = true; #cleanup: ControllerIncident['cleanup'] = 'complete'; readonly #baseTreeBundles = new Map(); @@ -308,6 +337,9 @@ export class Cycle { this.gate = new Gate(context.store, context.authority, context.artifacts, context.plan, context.lock, ref => approvedState(context.loaded).vault.resolveNetworkCredential(ref), () => { const bound = bindSubject(context.lock, this.candidate.manifest, overlayOpts); if (!bound.ok) refuse('ARTIFACT_INVALID', '', 'verification'); return bound.value; }, detail => this.events.push('gate_waiting', null, null, null, [], detail), context.ports.gateUrlOverrides); + this.localCheck = new LocalCheck(context.store, context.authority, context.artifacts, context.plan, context.lock, + () => { const bound = bindSubject(context.lock, this.candidate.manifest, overlayOpts); if (!bound.ok) refuse('ARTIFACT_INVALID', '', 'verification'); return bound.value; }, + { runRoot: dirname(context.directory), cycle: this }); this.benchmarkGate = new BenchmarkGate( context.store, context.authority, @@ -616,6 +648,7 @@ export class Cycle { const impl = slot.handler.implementation; const gateSlot = impl === 'gate.v1'; const benchmarkSlot = impl === 'benchmark-gate.v1'; + const commandSlot = impl === 'command.v1'; const isPreemptedBenchmark = benchmarkSlot && (checked.reason === 'BENCHMARK_PREEMPTED' || authenticatedBenchmarkGate(checked).retryablePreemption); let draft: Draft = { @@ -630,7 +663,9 @@ export class Cycle { ? authenticatedGate(checked) : benchmarkSlot ? authenticatedBenchmarkGate(checked) - : authenticatedCheck(checked); + : commandSlot + ? authenticatedLocalCheck(checked) + : authenticatedCheck(checked); const stable = hash( canonical({ slot: slot.id, @@ -664,7 +699,9 @@ export class Cycle { if (reworkCheckNode?.onRework) { const detail = (gateSlot || benchmarkSlot) ? extractGateVerdictExcerpt(checked, benchmarkSlot).detail - : undefined; + : commandSlot + ? extractLocalCheckExcerpt(checked).detail + : undefined; const reasonText = checked.reason ?? 'check_failed'; const summary = detail ? `Check ${reworkCheckNode.id} (${checked.checkId}) failed: ${reasonText} — ${detail}` @@ -771,12 +808,15 @@ export class Cycle { const impl = plan.verifierSlots.find(item => item.id === slotId)!.handler.implementation; const gateSlot = impl === 'gate.v1'; const benchmarkSlot = impl === 'benchmark-gate.v1'; + const commandSlot = impl === 'command.v1'; const baseTreeBundle = benchmarkSlot ? await this.#ensureBenchmarkBaseTreeBundle() : undefined; - const job: PreparedVerification | PreparedGate | PreparedBenchmarkGate = gateSlot + const job: PreparedVerification | PreparedGate | PreparedBenchmarkGate | PreparedLocalCheck = gateSlot ? prepareGate(plan, lock, slotId, this.candidate, this.generation, existing.producerNonce, this.context.loaded.registry.spec.gateEndpoints) : benchmarkSlot ? prepareBenchmarkGate(plan, lock, slotId, this.candidate, this.generation, existing.producerNonce, this.context.loaded.registry.spec.gateEndpoints, baseTreeBundle) - : prepareVerification(plan, lock, slotId, { manifest: this.context.source.manifest, ref: await artifacts.json('manifest', this.context.source.manifest, bounds.manifestMaxBytes), files: this.context.source.artifacts, baselineProofs: this.context.source.baselineProofs }, this.candidate, this.generation, existing.producerNonce); + : commandSlot + ? prepareLocalCheck(plan, lock, slotId, this.candidate, this.generation, existing.producerNonce, recordedLocalCheck(plan.verifierSlots.find(item => item.id === slotId)!)) + : prepareVerification(plan, lock, slotId, { manifest: this.context.source.manifest, ref: await artifacts.json('manifest', this.context.source.manifest, bounds.manifestMaxBytes), files: this.context.source.artifacts, baselineProofs: this.context.source.baselineProofs }, this.candidate, this.generation, existing.producerNonce); const operation = this.context.store.getOperation(job.operationId); const isFresh = !operation.ok && operation.error.code === 'RECORD_NOT_FOUND' && existing.receipt === null; const restored = isFresh @@ -784,12 +824,16 @@ export class Cycle { ? this.gate.run(job as PreparedGate, this.deadline.abort.signal) : benchmarkSlot ? this.benchmarkGate.run(job as PreparedBenchmarkGate, this.deadline.abort.signal) - : this.verifier.run(job as PreparedVerification, this.deadline.abort.signal)) + : commandSlot + ? this.localCheck.run(job as PreparedLocalCheck, this.deadline.abort.signal) + : this.verifier.run(job as PreparedVerification, this.deadline.abort.signal)) : await (gateSlot ? this.gate.restore(job as PreparedGate) : benchmarkSlot ? this.benchmarkGate.restore(job as PreparedBenchmarkGate, this.deadline.abort.signal) - : this.verifier.restore(job as PreparedVerification)); + : commandSlot + ? this.localCheck.restore(job as PreparedLocalCheck) + : this.verifier.restore(job as PreparedVerification)); if (existing.receipt !== null && (!same(existing.receipt, restored.receipt) || !same(existing.output, restored.output))) refuse('RECOVERY_REQUIRED', '', 'recovery'); this.checks.set(key, restored); const ordinal = plan.verifierSlots.findIndex(slot => slot.id === slotId), phase = 'verify.' + this.generation + '.' + ordinal; @@ -805,7 +849,8 @@ export class Cycle { const impl = plan.verifierSlots[ordinal]!.handler.implementation; const gateSlot = impl === 'gate.v1'; const benchmarkSlot = impl === 'benchmark-gate.v1'; - const sized = gateSlot || benchmarkSlot ? null : preflightVerification(plan, lock, slotId, source, this.candidate, this.generation, nonce), phase = 'verify.' + this.generation + '.' + ordinal; + const commandSlot = impl === 'command.v1'; + const sized = gateSlot || benchmarkSlot || commandSlot ? null : preflightVerification(plan, lock, slotId, source, this.candidate, this.generation, nonce), phase = 'verify.' + this.generation + '.' + ordinal; if (sized && sized.kind === 'refused') { const row = await this.verifier.storeRefusal(sized.prepared); await this.events.push('verification', 'OUTPUT_LIMIT'); await this.publish({ ...this.draft, stage: { ...this.draft.stage, kind: 'verifier_pre' }, verifierRefusals: [...this.draft.verifierRefusals, row] }, phase + '.pre'); @@ -813,11 +858,13 @@ export class Cycle { const checked = await this.verifier.restoreRefusal(sized.prepared, row); this.refusals.set(slotId + ':' + this.generation, checked); return checked; } const baseTreeBundle = benchmarkSlot ? await this.#ensureBenchmarkBaseTreeBundle() : undefined; - const job: PreparedVerification | PreparedGate | PreparedBenchmarkGate = gateSlot + const job: PreparedVerification | PreparedGate | PreparedBenchmarkGate | PreparedLocalCheck = gateSlot ? prepareGate(plan, lock, slotId, this.candidate, this.generation, nonce, this.context.loaded.registry.spec.gateEndpoints) : benchmarkSlot ? prepareBenchmarkGate(plan, lock, slotId, this.candidate, this.generation, nonce, this.context.loaded.registry.spec.gateEndpoints, baseTreeBundle) - : sized!.job; + : commandSlot + ? prepareLocalCheck(plan, lock, slotId, this.candidate, this.generation, nonce, recordedLocalCheck(plan.verifierSlots[ordinal]!)) + : sized!.job; await this.events.push('verification', null); const epochTag = this.reworkEpoch > 0 ? { reworkEpoch: this.reworkEpoch } : {}; await this.publish({ ...this.draft, stage: { ...this.draft.stage, kind: 'verifier_pre' }, verifierReceipts: [...this.draft.verifierReceipts, { slot: slotId, generation: this.generation, operationId: job.operationId, producerNonce: nonce, output: null, receipt: null, ...epochTag }] }, phase + '.pre'); @@ -826,7 +873,9 @@ export class Cycle { ? this.gate.run(job as PreparedGate, this.deadline.abort.signal) : benchmarkSlot ? this.benchmarkGate.run(job as PreparedBenchmarkGate, this.deadline.abort.signal) - : this.verifier.run(job as PreparedVerification, this.deadline.abort.signal)); + : commandSlot + ? this.localCheck.run(job as PreparedLocalCheck, this.deadline.abort.signal) + : this.verifier.run(job as PreparedVerification, this.deadline.abort.signal)); this.checks.set(slotId + ':' + this.generation, checked); await this.#finalizeVerifierPost(slotId, checked, ordinal, phase); return checked; @@ -1133,7 +1182,7 @@ export class Cycle { } } if (!isRecord(parsed)) continue; - const payload = slot.handler.implementation === 'gate.v1' ? parsed.disposition : parsed.response; + const payload = slot.handler.implementation === 'gate.v1' || slot.handler.implementation === 'command.v1' ? parsed.disposition : parsed.response; if (isRecord(payload) && typeof payload.status === 'string' && payload.status !== 'passed') { failedChecks.add(slot.checkId); if (typeof payload.reason === 'string' && payload.reason.length > 0) { @@ -1834,7 +1883,9 @@ let cleanupKnown = false, reader: Promise | null = null, nativeOutcome: Ar const slot = plan.verifierSlots.find(slot => slot.id === check.slotId)!; const excerpt = (slot.handler.implementation === 'gate.v1' || slot.handler.implementation === 'benchmark-gate.v1') ? extractGateVerdictExcerpt(check, slot.handler.implementation === 'benchmark-gate.v1') - : {}; + : slot.handler.implementation === 'command.v1' + ? extractLocalCheckExcerpt(check) + : {}; return { checkId: check.checkId, handler: slot.handler.implementation, diff --git a/packages/controller/src/errors.ts b/packages/controller/src/errors.ts index 3f02056a..2a45cdf3 100644 --- a/packages/controller/src/errors.ts +++ b/packages/controller/src/errors.ts @@ -16,7 +16,7 @@ export type ControllerResult = { readonly ok: true; readonly value: T } | { r export class ControllerFailure extends Error { constructor(readonly diagnostic: ControllerDiagnostic) { super(diagnostic.code); } } -const fields = new Set(('apiVersion kind metadata id name spec registry config task goal taskpack target repository baseRevision sourceRevision matrix platform variant hardware targetCellId metricThresholds allowSyntheticHardwareProbe scope writable protected roles adapter provider model thinking tools trustedContext revision discovery resources path digest algorithm hex budgets wallTimeMs totalTokens perCallOutputTokens maxModelCalls maxConcurrency maxFormatRepairs maxImplementationRepairs maxTransportRetries enforcement wallTime tokens modelCalls concurrency formatRepairs implementationRepairs transportRetries steps uses roleId dependsOn acceptance required checks allowedEvidenceLevels profiles profileRef handlerRef credentials ref template controls drainReserveMs maxAttempts repeatFailureLimit submission mode handlers roleProfiles runtimeProfiles credentialBindings environmentBindings version resourceVersion selection runtimeRef providerCredentialRef mcp names effects idleTimeoutSeconds absoluteTimeoutSeconds transport destinationRef endpoint approvedAddresses credentialRef scriptDigest context estimator proofId evidence workingWindowCeiling maxRequestBytes serviceMargin toolReserve maxOutputTokens identity sdkIntegrity graphDigest imageDigest configDigest profile dockerExecutable dockerSocket consumer environmentNames classification paths parameters capabilities checkId gateId heldOutWorkloadId maxPreemptions prompt purpose implementation publication gate benchmark gateEndpoints publicationEndpoints endpointRef targetBranch headBranchPrefix titleTemplate signingCredentialRef authCredentialRef timeoutMs maxPollMs pollInitialMs pollMaxMs jitter receipt roleModelOverrides gateUrlOverrides leaseToken when handoffs fromStep source select maxBytes heading includeSubheadings pointers changedPaths extensions phases failedChecks failureCodes watchedPaths nodeCandidates activatedResourceIds handoffExtracts').split(' ')); +const fields = new Set(('apiVersion kind metadata id name spec registry config task goal taskpack target repository baseRevision sourceRevision matrix platform variant hardware targetCellId metricThresholds allowSyntheticHardwareProbe scope writable protected roles adapter provider model thinking tools trustedContext revision discovery resources path digest algorithm hex budgets wallTimeMs totalTokens perCallOutputTokens maxModelCalls maxConcurrency maxFormatRepairs maxImplementationRepairs maxTransportRetries enforcement wallTime tokens modelCalls concurrency formatRepairs implementationRepairs transportRetries steps uses roleId dependsOn acceptance required checks allowedEvidenceLevels profiles profileRef handlerRef credentials ref template controls drainReserveMs maxAttempts repeatFailureLimit submission mode handlers roleProfiles runtimeProfiles credentialBindings environmentBindings version resourceVersion selection runtimeRef providerCredentialRef mcp names effects idleTimeoutSeconds absoluteTimeoutSeconds transport destinationRef endpoint approvedAddresses credentialRef scriptDigest context estimator proofId evidence workingWindowCeiling maxRequestBytes serviceMargin toolReserve maxOutputTokens identity sdkIntegrity graphDigest imageDigest configDigest profile dockerExecutable dockerSocket consumer environmentNames classification paths parameters capabilities checkId gateId heldOutWorkloadId maxPreemptions prompt purpose implementation publication gate benchmark gateEndpoints publicationEndpoints endpointRef targetBranch headBranchPrefix titleTemplate signingCredentialRef authCredentialRef timeoutMs maxPollMs pollInitialMs pollMaxMs jitter receipt roleModelOverrides gateUrlOverrides leaseToken when handoffs fromStep source select maxBytes heading includeSubheadings pointers changedPaths extensions phases failedChecks failureCodes watchedPaths nodeCandidates activatedResourceIds handoffExtracts host localChecks backend command script env toolchainPaths exec captureBytes credentialRefs').split(' ')); function safePath(path: string): string { const output: string[] = []; for (const segment of path.split('/').slice(1)) { if (!fields.has(segment) && !/^(?:0|[1-9][0-9]{0,2})$/.test(segment)) break; output.push(segment); } diff --git a/packages/controller/src/handlers.ts b/packages/controller/src/handlers.ts index 8a972290..6e369840 100644 --- a/packages/controller/src/handlers.ts +++ b/packages/controller/src/handlers.ts @@ -30,6 +30,6 @@ export async function installedHandlerDigests() { }; await visit(root, '', 1); } - return Object.fromEntries((['pi.agent.v1', 'pi.compact.v1', 'scope.v1', 'json-artifact.v1', 'json-keys-guard.v1', 'line-section-guard.v1', 'evolve-block-guard.v1', 'no-change.v1', 'gate.v1', 'benchmark-gate.v1'] as Implementation[]) + return Object.fromEntries((['pi.agent.v1', 'pi.compact.v1', 'scope.v1', 'json-artifact.v1', 'json-keys-guard.v1', 'line-section-guard.v1', 'evolve-block-guard.v1', 'no-change.v1', 'gate.v1', 'benchmark-gate.v1', 'command.v1'] as Implementation[]) .map(implementation => [implementation, hash('loopwright.dev/controller/handler/v1\0' + canonical({ implementation, inventory }))])) as Record>; } diff --git a/packages/controller/src/inspect.ts b/packages/controller/src/inspect.ts index b7cb185d..7e9c854e 100644 --- a/packages/controller/src/inspect.ts +++ b/packages/controller/src/inspect.ts @@ -1,7 +1,7 @@ import { lstat } from 'node:fs/promises'; import { join } from 'node:path'; import { reopenLocalRun, type LocalRunStore, type RunView } from '@loopwright/state'; -import { aggregateUsage, digestArtifact, validateDocument, type ArtifactManifest, type RequestUsage, type UsageSummary } from '@loopwright/core'; +import { aggregateUsage, digestArtifact, validateDocument, type ArtifactManifest, type ArtifactRef, type RequestUsage, type UsageSummary } from '@loopwright/core'; import { result, refuse, type ControllerResult } from './errors.js'; import { readRetained, type RetainedRunInput } from './retained.js'; import { ProgressStore, journal, type ProgressHead } from './progress.js'; @@ -290,6 +290,14 @@ export function inspectRun(input: InspectRunInput): Promise { - const { plan, lock, store, authority, artifacts, loaded, source, descriptor, ports } = context; + const { plan, lock, store, authority, artifacts, loaded, source, descriptor, ports, directory } = context; if (head?.progress.stage.kind === 'verifier_pre') { const row = head.progress.verifierReceipts.find(item => item.generation === head.progress.candidate.generation && item.receipt === null); if (row) { @@ -167,6 +169,10 @@ export async function reconcileInterruptedOperations(context: CycleContext, head head.progress.verifierReceipts, ), ).restore(prepared, context.signal); + } else if (slot.handler.implementation === 'command.v1') { + // Recovery only settles: no live cycle, so the module kills the recorded group, discards the workspace and blocks an operation without a proof. + const prepared = prepareLocalCheck(plan, lock, row.slot, candidate, head.progress.candidate.generation, row.producerNonce, recordedLocalCheck(slot)); + await new LocalCheck(store, authority, artifacts, plan, lock, () => subject, { runRoot: dirname(directory), cycle: null }).restore(prepared); } else { const bounds = overlayManifestBounds(plan.budgets.overlay); const prepared = prepareVerification(plan, lock, row.slot, { manifest: source.manifest, ref: await artifacts.json('manifest', source.manifest, bounds.manifestMaxBytes), files: source.artifacts, ...(source.baselineProofs ? { baselineProofs: source.baselineProofs } : {}) }, candidate, head.progress.candidate.generation, row.producerNonce); @@ -282,8 +288,8 @@ export function resumeCycleWithPorts(input: RunCycleInput, ports: ControllerPort } try { const impl = slot.handler.implementation; - const isGateLike = impl === 'gate.v1' || impl === 'benchmark-gate.v1'; - const outCap = impl === 'gate.v1' ? GATE_OUTPUT_BYTES : impl === 'benchmark-gate.v1' ? BENCHMARK_OUTPUT_BYTES : 65536; + const isGateLike = impl === 'gate.v1' || impl === 'benchmark-gate.v1' || impl === 'command.v1'; + const outCap = impl === 'gate.v1' ? GATE_OUTPUT_BYTES : impl === 'benchmark-gate.v1' ? BENCHMARK_OUTPUT_BYTES : impl === 'command.v1' ? LOCAL_CHECK_OUTPUT_BYTES : 65536; const rawOut = parsePrivateJson(await artifacts.read(settledReceipt.evidence.artifact, outCap), outCap) as Record; const dispositionObj = isGateLike ? (rawOut.disposition as Record | undefined) : undefined; const status = isGateLike diff --git a/packages/controller/src/retained.ts b/packages/controller/src/retained.ts index 504de5b6..2ba4c15e 100644 --- a/packages/controller/src/retained.ts +++ b/packages/controller/src/retained.ts @@ -89,6 +89,12 @@ export function validatePortsAgainstHostPolicy( export function resolveStoreLeaseMs(configuration: LoadedConfiguration, plan: CompiledPlan): number { let maxEndpointDurationMs = 0; for (const slot of plan.verifierSlots) { + // A `command.v1` check holds its permit for the whole script run, exactly as a gate endpoint holds its request. + if (slot.handler.implementation === 'command.v1') { + const timeoutMs = slot.handler.parameters.timeoutMs; + maxEndpointDurationMs = Math.max(maxEndpointDurationMs, typeof timeoutMs === 'number' ? timeoutMs : 0); + continue; + } if (slot.handler.implementation !== 'gate.v1' && slot.handler.implementation !== 'benchmark-gate.v1') continue; const ep = configuration.registry.spec.gateEndpoints.find(item => item.id === slot.handler.parameters.endpointRef); if (!ep) continue; @@ -203,7 +209,8 @@ export async function admitRetainedRun(input: { } } const state = approvedState(effectiveConfig); - const compiled = await compilePlan(effectiveConfig); + // Resume and reconcile re-admit the retained plan: its `command.v1` slot records are re-used verbatim, and `LocalCheck` re-verifies them against the baseline before any dispatch. + const compiled = await compilePlan(effectiveConfig, { kind: 'retained', slots: retained.plan.verifierSlots }); if (!compiled.ok) throw new ControllerFailure(compiled.error); const plan = compiled.value; const admitted = admitTask(plan.task, { admissionId: 'admission.' + hash('loopwright.dev/controller/admission/v1\0' + input.runId + '\0' + plan.planDigest.hex).hex.slice(0, 40), runId: input.runId }); diff --git a/packages/controller/src/run-eval.ts b/packages/controller/src/run-eval.ts index ea99808f..22b5bd0a 100644 --- a/packages/controller/src/run-eval.ts +++ b/packages/controller/src/run-eval.ts @@ -553,8 +553,10 @@ function isToolOperation(op: OperationRecord): boolean { if ( op.intent.targetIdentity.startsWith('verifier:') || op.intent.targetIdentity.startsWith('gate:') || + op.intent.targetIdentity.startsWith('command:') || receipt?.evidence.producerId === 'loopwright.byte-verifier.v1' || - receipt?.evidence.producerId === 'loopwright.gate-verifier.v1' + receipt?.evidence.producerId === 'loopwright.gate-verifier.v1' || + receipt?.evidence.producerId === 'loopwright.local-check.v1' ) { return false; } diff --git a/packages/controller/src/types.ts b/packages/controller/src/types.ts index 015a66a0..d52b0750 100644 --- a/packages/controller/src/types.ts +++ b/packages/controller/src/types.ts @@ -286,7 +286,9 @@ export interface LoadedConfiguration { } export interface CheckpointCapacity { readonly A: number; readonly N: number; readonly I: number; readonly C: number; readonly V: number; readonly J: number; readonly D: number; readonly publication: boolean; readonly additionalRefs: 4; readonly requiredRefs: 6; readonly checkpointBytes: 40960 } -export interface VerifierSlot { readonly id: string; readonly checkId: string; readonly implicit: 'scope' | 'no_change' | null; readonly handler: Handler } +export interface VerifierSlot { readonly id: string; readonly checkId: string; readonly implicit: 'scope' | 'no_change' | null; readonly handler: Handler; + /** Admission's record of the `command.v1` script directory digest at `target.sourceRevision`; `planDigest` covers it. Absent until admission. */ + readonly scriptDirectoryDigest?: Digest } export interface PlannedRole { readonly roleId: string; readonly adapter: RoleAdapterKind; readonly profileRef: string; readonly providerCredentialRef: string | null; readonly runtime: RuntimeProfile; readonly policy: AdapterPolicyV2 } /** Planned role for `adapter: 'exec'`: carries the validated command that the exec runner spawns. */ export interface ExecPlannedRole extends PlannedRole { diff --git a/packages/controller/test/compile.test.ts b/packages/controller/test/compile.test.ts index b3d8c9f5..9896e626 100644 --- a/packages/controller/test/compile.test.ts +++ b/packages/controller/test/compile.test.ts @@ -1,13 +1,19 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import { writeFile } from 'node:fs/promises'; -import { join } from 'node:path'; +import { lstat, mkdir, writeFile } from 'node:fs/promises'; +import { dirname, join } from 'node:path'; import { admitTask } from '@loopwright/core'; import { compilePlan, checkpointCapacity } from '../src/compile.js'; +import { createCycle, type CycleContext } from '../src/controller.js'; import { installedHandlerDigests } from '../src/handlers.js'; -import { hash } from '../src/schema.js'; -import type { ControllerResult } from '../src/errors.js'; +import { ControllerFailure, type ControllerResult } from '../src/errors.js'; +import { localCheckScriptDirectoryDigest, readLocalCheckScriptDirectory } from '../src/local-check.js'; +import { canonical, hash } from '../src/schema.js'; +import { stateValue } from '../src/storage.js'; +import { materializeBaseline } from '../src/source.js'; import { configurationFixture } from './config-fixtures.js'; +import { cleanupFixture, recordedScriptDigest, type FixtureExtra } from './local-check-fixtures.js'; +import { COMMAND_CHECK_ID, commandCheckFixture, type CommandCheckFixtureOptions } from './scheduling-fixtures.js'; function assertOk(result: ControllerResult, msg = ''): T { assert.equal(result.ok, true, `${msg}: ${result.ok ? '' : JSON.stringify(result.error)}`); @@ -549,3 +555,74 @@ test('compilePlan refuses onRework.rejectTo targeting pi.compact.v1 and sizes ch await f.cleanup(); } }); + +function failureCode(error: unknown): string { return error instanceof ControllerFailure ? error.diagnostic.code : 'not-a-controller-failure: ' + String(error); } +async function releaseContext(context: CycleContext): Promise { stateValue(context.store.release(context.authority)); stateValue(context.store.close()); await context.owner.release(); } + +test('compilePlan: a command.v1 handler compiles in check mode without resolving files; a script outside scope.protected or a check that cannot accept host_execution is CONFIG_SCHEMA', async () => { + const f = await commandCheckFixture(); + try { + const plan = assertOk(await compilePlan(f.loaded), 'check-mode compile with a command.v1 handler'); + const slot = plan.verifierSlots.find(item => item.handler.implementation === 'command.v1')!; + assert.equal(slot.checkId, COMMAND_CHECK_ID); assert.equal(slot.implicit, null); + assert.equal(slot.scriptDirectoryDigest, undefined, 'check mode has no repository and records nothing'); + assert.deepEqual(plan.evidenceNeeds, [{ checkId: COMMAND_CHECK_ID, levels: ['host_execution'] }]); + } finally { await cleanupFixture(f); } + const outside = await commandCheckFixture({ script: 'tools/x.sh', extra: [{ path: 'tools/x.sh', content: '#!/bin/sh\n', executable: true }] }); + try { + const compiled = await compilePlan(outside.loaded); assert.equal(compiled.ok, false, 'script outside scope.protected'); if (!compiled.ok) assert.equal(compiled.error.code, 'CONFIG_SCHEMA'); + } finally { await cleanupFixture(outside); } + const disallowed = await commandCheckFixture({ allowed: ['local_execution'] }); + try { + const compiled = await compilePlan(disallowed.loaded); assert.equal(compiled.ok, false, 'host_execution not an allowed level'); if (!compiled.ok) assert.equal(compiled.error.code, 'CONFIG_SCHEMA'); + } finally { await cleanupFixture(disallowed); } +}); + +test('admission resolves command.v1 scripts at sourceRevision through createCycle and refuses unprotected siblings, non-executable or missing scripts, and missing toolchain paths with exact codes', async () => { + const cases: { readonly name: string; readonly options: CommandCheckFixtureOptions; readonly code: string }[] = [ + { name: 'unprotected-sibling', options: { protected: ['scripts/*.sh'], extra: [{ path: 'scripts/README.md', content: 'operator notes\n' }] }, code: 'CONFIG_SCHEMA' }, + { name: 'non-executable-script', options: { script: 'scripts/noexec.sh', extra: [{ path: 'scripts/noexec.sh', content: '#!/bin/sh\n' }] }, code: 'CONFIG_REFERENCE' }, + { name: 'missing-script', options: { script: 'scripts/missing.sh' }, code: 'CONFIG_REFERENCE' }, + { name: 'missing-toolchain-path', options: { parameters: { toolchainPaths: ['missing/bin'] } }, code: 'CONFIG_REFERENCE' }, + ]; + for (const c of cases) { + const f = await commandCheckFixture(c.options), runId = 'run-admission-' + c.name; + try { + await assert.rejects(createCycle({ configuration: f.loaded, repository: f.repository, runRoot: f.runRoot, runId }, {}), error => failureCode(error) === c.code, c.name); + assert.equal(await lstat(join(f.runRoot, runId, 'run.json')).then(() => true, () => false), false, c.name + ': no run admitted'); + } finally { await cleanupFixture(f); } + } +}); + +test('admission records the script directory digest in the command.v1 slot, planDigest covers it, and the digest equals what readLocalCheckScriptDirectory yields on the materialized baseline for version 1 and version 2 sources', async () => { + const helper: FixtureExtra = { path: 'scripts/helper.sh', content: '#!/bin/sh\nexit 0\n', executable: true }; + const generated: FixtureExtra[] = Array.from({ length: 130 }, (_, index) => ({ path: `scripts/gen/${index}.sh`, content: '#!/bin/sh\n', executable: true })); + for (const [label, extra] of [['v1', [helper]], ['v2', [helper, ...generated]]] as const) { + const f = await commandCheckFixture({ extra }), runId = 'run-digest-' + label; + try { + const context = await createCycle({ configuration: f.loaded, repository: f.repository, runRoot: f.runRoot, runId }, {}); + try { + assert.equal(context.source.version, label === 'v1' ? 1 : 2); + const slot = context.plan.verifierSlots.find(item => item.handler.implementation === 'command.v1')!; + const recorded = slot.scriptDirectoryDigest; assert.ok(recorded, label + ': digest recorded'); + const baselineDir = join(f.root, 'reader-baseline'); + if (context.source.version === 2) await materializeBaseline(context.source, baselineDir, context.owner, new AbortController().signal); + else { + await mkdir(baselineDir, { recursive: true }); + for (const item of context.source.artifacts) { + const target = join(baselineDir, item.name); await mkdir(dirname(target), { recursive: true }); + await writeFile(target, item.bytes, { mode: item.mode === '100755' ? 0o755 : 0o644 }); + } + } + const entries = await readLocalCheckScriptDirectory(baselineDir, 'scripts/pass.sh'); + assert.deepEqual(recorded, localCheckScriptDirectoryDigest(entries), label + ': admission digest equals the reader digest'); + if (context.source.version === 1) assert.deepEqual(recorded, recordedScriptDigest(context.source, 'scripts/pass.sh')); + assert.ok(entries.some(entry => entry.path === 'scripts/helper.sh'), 'siblings are part of the directory'); + const { planDigest, ...rest } = context.plan; + assert.deepEqual(hash('loopwright.dev/controller/plan/v1\0' + canonical(rest)), planDigest, label + ': planDigest is the hash of the plan including the slot record'); + assert.ok(canonical(context.plan).includes(recorded!.hex), label + ': the slot digest is inside the digested canonical form'); + assert.deepEqual(context.owner.planDigest, planDigest, 'the run owner is bound to the final plan digest'); + } finally { await releaseContext(context); } + } finally { await cleanupFixture(f); } + } +}); diff --git a/packages/controller/test/local-check-integration.test.ts b/packages/controller/test/local-check-integration.test.ts new file mode 100644 index 00000000..67b2db82 --- /dev/null +++ b/packages/controller/test/local-check-integration.test.ts @@ -0,0 +1,135 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { lstat, readFile, readdir, stat } from 'node:fs/promises'; +import { join } from 'node:path'; +import { reopenLocalRun } from '@loopwright/state'; +import { inspectRun, runCycleWithPorts, type CycleExecution } from '../src/index.js'; +import type { RunDescriptor } from '../src/controller.js'; +import type { ControllerDiagnostic } from '../src/errors.js'; +import { LOCAL_CHECK_OUTPUT_BYTES, LOCAL_CHECK_PRODUCER_ID, type LocalCheckReceipt } from '../src/local-check.js'; +import { parsePrivateJson } from '../src/parser.js'; +import { phaseCheckpointId } from '../src/progress.js'; +import { canonical, hash, same } from '../src/schema.js';import { stateValue } from '../src/storage.js'; +import type { ArtifactRef } from '@loopwright/core'; +import { cleanupFixture } from './local-check-fixtures.js'; +import { COMMAND_CHECK_ID, commandCheckFixture, createPiMockPort } from './scheduling-fixtures.js'; + +function assertOk(res: { readonly ok: boolean; readonly value?: T; readonly error?: ControllerDiagnostic }, msg = ''): T { assert.equal(res.ok, true, `${msg}: ${JSON.stringify(res.error)}`); if (!res.ok) throw new Error('expected ok'); return res.value as T; } + +interface ReceiptLine { readonly slot: string; readonly generation: number; readonly operationId: string; readonly output: ArtifactRef | null; readonly receipt: LocalCheckReceipt | null } +interface Inspection { + readonly directory: string; readonly runDirectory: string; readonly verification: { readonly required: { readonly checkId: string; readonly status: string; readonly evidenceId: string | null; readonly reason: string | null; readonly detail: string | null; readonly metrics?: Record }[] }; + readonly receipts: readonly ReceiptLine[]; readonly candidateFiles: { readonly name: string; readonly sha256: string }[]; readonly slotOrdinal: number; +} +async function inspect(f: { readonly runRoot: string; readonly root: string }, runId: string): Promise { + const directory = join(f.root, 'inspection'), runDirectory = join(f.runRoot, runId); + const inspected = assertOk(await inspectRun({ runRoot: f.runRoot, runId, output: directory }), 'inspectRun'); + const names = inspected.manifest!.entries.map(entry => entry.name); + for (const name of ['verification.json', 'verifier-receipts.json', 'candidate.files.json', 'plan.json']) assert.ok(names.includes(name), name + ' exported'); + const read = async (name: string): Promise => JSON.parse(await readFile(join(directory, name), 'utf8')) as T; + const verification = await read('verification.json'), receipts = (await read<{ entries: ReceiptLine[] }>('verifier-receipts.json')).entries; + const files = await read<{ readonly files: readonly ({ readonly name: string; readonly sha256: string } | { readonly name: string; readonly encoding: 'base64'; readonly body: string })[] }>('candidate.files.json'); + // v1 lists base64 bodies, v2 lists content digests; both name every candidate file (baseline plus overlay). + const candidateFiles = files.files.map(file => 'sha256' in file ? { name: file.name, sha256: file.sha256 } : { name: file.name, sha256: hash(Buffer.from(file.body, 'base64')).hex }); + const plan = await read<{ readonly verifierSlots: readonly { readonly handler: { readonly implementation: string } }[] }>('plan.json'); + return { directory, runDirectory, verification, receipts, candidateFiles, slotOrdinal: plan.verifierSlots.findIndex(slot => slot.handler.implementation === 'command.v1') }; +} +/** The script directory as the committed repository holds it, shaped exactly as the admission record, digested by the same pure function. */ +async function committedScriptDigest(repository: string): Promise { + const names = (await readdir(join(repository, 'scripts'))).sort(); + const entries = await Promise.all(names.map(async name => { + const path = join(repository, 'scripts', name), bytes = await readFile(path); + return { path: 'scripts/' + name, mode: ((await stat(path)).mode & 0o111) !== 0 ? '100755' as const : '100644' as const, byteLength: bytes.byteLength, sha256: hash(bytes).hex }; + })); + return hash('loopwright.dev/controller/local-check-script-directory/v1\0' + canonical(entries)).hex; +} +/** The observations artifact's diagnostic and verifier matrix, for assertion messages only. */ +async function observationsOf(f: { readonly runRoot: string }, runId: string, execution: CycleExecution): Promise { + if (execution.kind !== 'result' || execution.observations === null) return execution.kind; + const observed = JSON.parse(await readFile(join(f.runRoot, runId, 'artifacts', execution.observations.name), 'utf8')) as { readonly diagnostic: unknown; readonly verifierMatrix: unknown }; + return { diagnostic: observed.diagnostic, verifierMatrix: observed.verifierMatrix }; +} +const AUTHOR_FILES = { 'packages/ok.txt': 'ok\n' } as const; +const AUTHOR = () => ({ files: { ...AUTHOR_FILES }, responseJson: { version: 1, status: 'completed', checks: [], reason: 'Implemented.' } }); + +test('a full cycle with a passing command.v1 script settles completed with host_execution evidence and metrics, a receipt naming method and digests exported by inspect, and an unchanged overlay', async () => { + const f = await commandCheckFixture({ author: true }), runId = 'run-local-check-pass'; + try { + const prompts: string[] = []; + const execution = assertOk(await runCycleWithPorts({ configuration: f.loaded, repository: f.repository, runRoot: f.runRoot, runId }, { openAdapter: createPiMockPort(({ prompt }) => { prompts.push(prompt); return AUTHOR(); }) }), 'run'); + assert.equal(execution.kind, 'result', JSON.stringify(execution)); if (execution.kind !== 'result') return; + assert.equal(execution.result.spec.status, 'completed', JSON.stringify(await observationsOf(f, runId, execution))); assert.deepEqual(execution.secondary, []); + const row = execution.result.spec.verification.spec.required.find(item => item.checkId === COMMAND_CHECK_ID)!; + assert.equal(row.status, 'passed'); assert.equal(row.reason, 'observed_pass'); assert.equal(row.detail, null); assert.ok(typeof row.evidenceId === 'string'); + assert.deepEqual(JSON.parse(JSON.stringify(row.metrics)), { cases: 12, failed: 0 }, 'the check-out metrics reach the verification row'); + assert.equal(prompts.length, 1, 'the author ran once'); + + const inspected = await inspect(f, runId); + assert.deepEqual(inspected.receipts.map(item => item.slot).sort(), ['check.' + COMMAND_CHECK_ID, 'controller.no-change', 'controller.scope'], 'one receipt line per slot'); + const line = inspected.receipts.find(item => item.slot === 'check.' + COMMAND_CHECK_ID)!; assert.ok(Number.isSafeInteger(line.generation) && line.generation >= 0); assert.ok(line.output); assert.ok(line.receipt); + const receipt = line.receipt!; + assert.equal(receipt.outcome, 'succeeded'); assert.equal(receipt.evidence.method, 'direct_script'); assert.equal(receipt.evidence.producerId, LOCAL_CHECK_PRODUCER_ID); + assert.deepEqual(receipt.evidence.artifact, line.output, 'the receipt names the output artifact'); + assert.equal(receipt.script, 'scripts/pass.sh'); + assert.deepEqual(receipt.scriptDigest, hash(await readFile(join(process.cwd(), 'packages/controller/test/fixtures/scripts/pass.sh')))); + assert.equal(receipt.scriptDirectoryDigest.hex, await committedScriptDigest(f.repository), 'the recorded directory digest is the committed scripts directory'); + assert.deepEqual(receipt.registryDigest, f.loaded.registryDigest, 'the receipt carries the digest-pinned registry'); + assert.ok(!JSON.stringify(receipt).includes('PROVIDER_TOKEN'), 'no credential in the exported receipt'); + + const output = parsePrivateJson(await readFile(join(inspected.runDirectory, 'artifacts', line.output!.name)), LOCAL_CHECK_OUTPUT_BYTES) as { readonly disposition: { readonly status: string; readonly method: string }; readonly observation: { readonly exitCode: number; readonly output: { readonly metrics: unknown } | null; readonly stderrTail: string } }; + assert.deepEqual(output.disposition, { status: 'passed', reason: null, method: 'direct_script' }); + assert.deepEqual(output.observation.output, { metrics: { cases: 12, failed: 0 } }, 'the output artifact carries the metrics'); assert.equal(output.observation.exitCode, 0); + + const proofs = (await readdir(join(inspected.runDirectory, 'artifacts'))).filter(name => /^local-check-producer-[0-9a-f]{64}\.proof\.json$/.test(name)); + assert.equal(proofs.length, 1, 'one private proof marker'); + const evidence = (JSON.parse(await readFile(join(inspected.runDirectory, 'artifacts', proofs[0]!), 'utf8')) as { readonly evidence: { readonly spec: { readonly level: string; readonly producerId: string; readonly method: string; readonly observedStatus: string } } }).evidence.spec; + assert.equal(evidence.level, 'host_execution'); assert.equal(evidence.producerId, LOCAL_CHECK_PRODUCER_ID); assert.equal(evidence.method, 'direct_script'); assert.equal(evidence.observedStatus, 'passed'); + + // The captured overlay is byte-identical before and after the check: the two verify checkpoints share one candidate manifest, and inspect sees exactly the author's bytes. + const descriptor = JSON.parse(await readFile(join(f.runRoot, runId, 'run.json'), 'utf8')) as RunDescriptor, store = stateValue(reopenLocalRun(descriptor.identity)); + try { + const pre = stateValue(store.getCheckpoint(phaseCheckpointId(runId, `verify.${line.generation}.${inspected.slotOrdinal}.pre`))), post = stateValue(store.getCheckpoint(phaseCheckpointId(runId, `verify.${line.generation}.${inspected.slotOrdinal}.post`))); + assert.equal(same(pre.subject.candidateDigest, post.subject.candidateDigest) && same(pre.workspace, post.workspace), true, 'candidate unchanged across the check'); + const overlay = inspected.candidateFiles.filter(file => !file.name.startsWith('scripts/')); + assert.deepEqual(overlay, [{ name: 'packages/ok.txt', sha256: hash('ok\n').hex }], 'the overlay is exactly what the author wrote'); + const committed = await Promise.all((await readdir(join(f.repository, 'scripts'))).map(async name => ({ name: 'scripts/' + name, sha256: hash(await readFile(join(f.repository, 'scripts', name))).hex }))); + assert.deepEqual(inspected.candidateFiles.filter(file => file.name.startsWith('scripts/')), committed, 'the baseline files inside the candidate are byte-identical to the committed scripts'); + } finally { stateValue(store.close()); } + assert.deepEqual(await readdir(join(f.runRoot, 'workspaces', runId)), [], 'the check workspace is discarded'); + } finally { await cleanupFixture(f); } +}); + +test('a failing command.v1 script settles the run failed with the check-out detail in the verification row and a failed receipt; a check that cannot accept host_execution is refused at admission', async () => { + const f = await commandCheckFixture({ script: 'scripts/fail.sh' }), runId = 'run-local-check-fail'; + try { + const execution = assertOk(await runCycleWithPorts({ configuration: f.loaded, repository: f.repository, runRoot: f.runRoot, runId }, { openAdapter: async () => { throw new Error('check-only graph'); } }), 'run'); + assert.equal(execution.kind, 'result', JSON.stringify(execution)); if (execution.kind !== 'result') return; + assert.equal(execution.result.spec.status, 'failed', JSON.stringify(await observationsOf(f, runId, execution))); + const row = execution.result.spec.verification.spec.required.find(item => item.checkId === COMMAND_CHECK_ID)!; + // core's verification rows keep their own reason vocabulary; the script's check-out detail is what the row carries. + assert.equal(row.status, 'failed'); assert.equal(row.reason, 'submitted_failed'); assert.equal(row.detail, 'case 7: expected 42, got 41'); + const inspected = await inspect(f, runId), line = inspected.receipts.find(item => item.slot === 'check.' + COMMAND_CHECK_ID)!; + assert.equal(line.receipt!.outcome, 'failed'); assert.equal(line.receipt!.script, 'scripts/fail.sh'); assert.equal(line.receipt!.evidence.method, 'direct_script'); + const observation = (parsePrivateJson(await readFile(join(inspected.runDirectory, 'artifacts', line.output!.name)), LOCAL_CHECK_OUTPUT_BYTES) as { readonly observation: { readonly exitCode: number; readonly stderrTail: string } }).observation; + assert.equal(observation.exitCode, 1); assert.equal(observation.stderrTail, 'forge-evaluate: 2 of 12 cases failed\n'); + } finally { await cleanupFixture(f); } + const disallowed = await commandCheckFixture({ allowed: ['local_execution'] }); + try { + const refused = await runCycleWithPorts({ configuration: disallowed.loaded, repository: disallowed.repository, runRoot: disallowed.runRoot, runId: 'run-local-check-disallowed' }, {}); + assert.equal(refused.ok, false, 'host_execution evidence the task cannot accept never runs'); if (!refused.ok) assert.equal(refused.error.code, 'CONFIG_SCHEMA'); + assert.equal(await lstat(disallowed.runRoot).then(() => false, () => true), true, 'refused before any run directory is created'); + } finally { await cleanupFixture(disallowed); } +}); + +test('inspect exports every verifier receipt generation with its output reference and record', async () => { + const f = await commandCheckFixture({ script: 'scripts/pass.sh' }), runId = 'run-local-check-inspect'; + try { + const execution: CycleExecution = assertOk(await runCycleWithPorts({ configuration: f.loaded, repository: f.repository, runRoot: f.runRoot, runId }), 'run'); + assert.equal(execution.kind, 'result'); if (execution.kind !== 'result') return; + const inspected = await inspect(f, runId); + assert.deepEqual(inspected.receipts.map(line => line.slot).sort(), ['check.' + COMMAND_CHECK_ID, 'controller.no-change', 'controller.scope']); + assert.ok(inspected.receipts.every(line => line.receipt !== null && line.output !== null && line.operationId.length > 0)); + assert.equal((inspected.receipts[0]!.receipt as LocalCheckReceipt).scriptDirectoryDigest.algorithm, 'sha256'); + assert.equal('script' in (inspected.receipts[1]!.receipt as object), false, 'the implicit byte-verifier receipts keep their own shape'); + } finally { await cleanupFixture(f); } +}); diff --git a/packages/controller/test/recovery-cycle.test.ts b/packages/controller/test/recovery-cycle.test.ts index 33d15db7..071ce712 100644 --- a/packages/controller/test/recovery-cycle.test.ts +++ b/packages/controller/test/recovery-cycle.test.ts @@ -1,19 +1,25 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import { readFile, writeFile, lstat, rename } from 'node:fs/promises'; +import { readFile, writeFile, lstat, readdir, rename } from 'node:fs/promises'; import { join } from 'node:path'; import { randomBytes } from 'node:crypto'; import { bindSubject } from '@loopwright/core'; -import { reopenLocalRun } from '@loopwright/state'; -import { cycleFixture } from './scheduling-fixtures.js'; -import { createCycle, type CycleContext } from '../src/controller.js'; -import { resumeCycle, runCycle } from '../src/index.js'; +import { reopenLocalRun, type Authority } from '@loopwright/state'; +import { cycleFixture, commandCheckFixture, COMMAND_CHECK_ID } from './scheduling-fixtures.js'; +import { cleanupFixture, exists, groupGone, markerPrefix, releaseCycle, waitForMarker } from './local-check-fixtures.js'; +import { createCycle, Cycle, type CycleContext, type RunDescriptor } from '../src/controller.js'; +import { recordedLocalCheck } from '../src/compile.js'; +import { ControllerFailure } from '../src/errors.js'; +import { inspectRun, resumeCycle, runCycle } from '../src/index.js'; +import { prepareLocalCheck } from '../src/local-check.js'; +import { reconcileInterruptedOperations } from '../src/recovery.js'; import { setFixture } from './progress-fixtures.js'; import { hash } from '../src/schema.js'; import { canonical } from '../src/schema.js'; import { stateValue } from '../src/storage.js'; import { prepareVerification, Verifier } from '../src/verification.js'; import type { ControllerProgress } from '../src/types.js'; +const COMMAND_SLOT_ID = 'check.' + COMMAND_CHECK_ID; async function setup(valid = true) { const f = await cycleFixture(valid), input = { configuration: f.loaded, repository: f.repository, runRoot: f.runRoot, runId: 'resume-cycle' }; const context = await createCycle(input, {}), original = stateValue(context.store.inspect()); @@ -86,3 +92,77 @@ test('recovery: operator cancellation revokes new verifier dispatch then returns const f = await cycleFixture(true), abort = new AbortController(); const result = await runCycle({ configuration: f.loaded, repository: f.repository, runRoot: f.runRoot, runId: 'cancel-run', signal: abort.signal, onEvent: async event => { if (event.stage === 'verification') abort.abort(); } }); assert.ok(result.ok, JSON.stringify(result)); if (!result.ok) return; assert.equal(result.value.kind, 'result', JSON.stringify(result)); if (result.value.kind === 'result') assert.equal(result.value.result.spec.status, 'cancelled'); }); + +test('recovery: a command.v1 operation left with a binding marker and no proof marker settles blocked/EVIDENCE_UNAVAILABLE through the controller, kills the group, discards the workspace, and is never re-dispatched', async () => { + const SIGNALED_EXIT = 400_000; // above any test wait, below the budget fit (drainReserveMs 120000 + timeoutMs <= wallTimeMs 600000) + // Part 1: the controller's recovery wiring (reconcileInterruptedOperations) against a live child, as the module test does it in-process. + { + const f = await commandCheckFixture({ script: 'scripts/sleep.sh', parameters: { timeoutMs: SIGNALED_EXIT } }), input = { configuration: f.loaded, repository: f.repository, runRoot: f.runRoot, runId: 'resume-command-live' }; + const context = await createCycle(input, {}), original = stateValue(context.store.inspect()); + let recovery: Authority | null = null; + try { + const head = await bootstrap(context), cycle = new Cycle(context, head); + const slot = context.plan.verifierSlots.find(item => item.handler.implementation === 'command.v1')!, ordinal = context.plan.verifierSlots.indexOf(slot), nonce = randomBytes(16).toString('hex'); + const candidate = { manifest: context.source.manifest, ref: head.progress.candidate.manifest, files: context.source.artifacts, baselineProofs: context.source.baselineProofs }; + const job = prepareLocalCheck(context.plan, context.lock, slot.id, candidate, 0, nonce, recordedLocalCheck(slot)); + const crashed = await context.progress.publish({ ...head.progress, stage: { ...head.progress.stage, kind: 'verifier_pre' }, verifierReceipts: [{ slot: slot.id, generation: 0, operationId: job.operationId, producerNonce: nonce, output: null, receipt: null }] }, `verify.0.${ordinal}.pre`); + const dead = { aborted: false, addEventListener() {}, removeEventListener() {} }; + const continuation = cycle.localCheck.run(job, dead as unknown as AbortSignal).then(() => assert.fail('a dead controller cannot complete'), () => undefined); + const prefix = markerPrefix(context.artifacts.directory, job.operationId, nonce), binding = await waitForMarker(prefix + '.binding.json', 10_000), pgid = Number(binding.pgid); + assert.equal(groupGone(pgid), false, 'the sleeping script outlives its controller'); assert.equal(await exists(prefix + '.proof.json'), false); + const attemptDir = String(binding.workspaceDir); assert.equal(await exists(attemptDir), true, 'the crash leaves the materialization behind'); + dead.aborted = true; + stateValue(context.store.release(context.authority)); + const view = stateValue(context.store.inspect()); assert.equal(stateValue(context.store.getOperation(job.operationId)).state, 'dispatch_uncertain'); + recovery = stateValue(context.store.claim({ ownerId: 'controller.' + context.owner.nonce, expectedGeneration: view.owner.generation, expectedRevision: view.revision, mode: 'recovery' })).authority; + await reconcileInterruptedOperations({ ...context, authority: recovery }, crashed, candidate, original.storeId); + await continuation; + const settled = stateValue(context.store.getOperation(job.operationId)); + assert.equal(settled.state, 'confirmed'); assert.equal(settled.reconciliation?.outcome, 'failed'); assert.equal(settled.reconciliation?.evidence.producerId, 'loopwright.local-check.v1'); + assert.equal(groupGone(pgid), true, 'recorded group killed'); assert.equal(await exists(attemptDir), false, 'materialization discarded'); + assert.equal(await exists(prefix + '.proof.json'), true, 'the settlement wrote its proof'); + assert.equal(stateValue(context.store.inspect()).counts.operations, 1, 'the dispatched operation is settled, never re-dispatched'); + const receiptRow = [...(await context.progress.read())!.progress.verifierReceipts].find(row => row.slot === slot.id)!; + assert.equal(receiptRow.receipt, null, 'settlement records the store receipt; the progress row is closed when the cycle resumes'); + } finally { + await releaseCycle(new Cycle(context), context, recovery ?? context.authority).catch(() => undefined); await cleanupFixture(f); + } + } + // Part 2: the public resume after the controller died between the markers; the crashed continuation has let go of the owner. + { + const later = { path: 'scripts/exit-later.sh', content: '#!/bin/sh\nsleep 0.3\nexit 0\n', executable: true } as const; + const f = await commandCheckFixture({ script: 'scripts/exit-later.sh', extra: [later] }), input = { configuration: f.loaded, repository: f.repository, runRoot: f.runRoot, runId: 'resume-command-crash' }; + const context = await createCycle(input, {}); + try { + const head = await bootstrap(context), cycle = new Cycle(context, head); + const slot = context.plan.verifierSlots.find(item => item.handler.implementation === 'command.v1')!, ordinal = context.plan.verifierSlots.indexOf(slot), nonce = randomBytes(16).toString('hex'); + const candidate = { manifest: context.source.manifest, ref: head.progress.candidate.manifest, files: context.source.artifacts, baselineProofs: context.source.baselineProofs }; + const job = prepareLocalCheck(context.plan, context.lock, slot.id, candidate, 0, nonce, recordedLocalCheck(slot)); + await context.progress.publish({ ...head.progress, stage: { ...head.progress.stage, kind: 'verifier_pre' }, verifierReceipts: [{ slot: slot.id, generation: 0, operationId: job.operationId, producerNonce: nonce, output: null, receipt: null }] }, `verify.0.${ordinal}.pre`); + const dead = { aborted: false, addEventListener() {}, removeEventListener() {} }; + const continuation = cycle.localCheck.run(job, dead as unknown as AbortSignal).then(() => assert.fail('a dead controller cannot complete'), error => { assert.equal(error instanceof ControllerFailure ? error.diagnostic.code : String(error), 'CANCELLED'); }); + const prefix = markerPrefix(context.artifacts.directory, job.operationId, nonce); await waitForMarker(prefix + '.binding.json', 10_000); dead.aborted = true; + await continuation; assert.equal(await exists(prefix + '.proof.json'), false, 'no proof without a live controller'); + assert.equal(stateValue(context.store.getOperation(job.operationId)).state, 'dispatch_uncertain'); + await cycle.deadline.dispose(); await cycle.events.close(); + } finally { stateValue(context.store.release(context.authority)); stateValue(context.store.close()); await context.owner.release(); } + try { + const result = await resumeCycle(input); assert.ok(result.ok, JSON.stringify(result)); if (!result.ok || result.value.kind !== 'result') return; + assert.equal(result.value.result.spec.status, 'blocked'); + const row = result.value.result.spec.verification.spec.required.find(item => item.checkId === COMMAND_CHECK_ID)!; + assert.equal(row.status, 'blocked'); assert.equal(row.detail, 'EVIDENCE_UNAVAILABLE'); + const observations = JSON.parse(await readFile(join(f.runRoot, input.runId, 'artifacts', result.value.observations!.name), 'utf8')) as { readonly verifierMatrix: readonly { readonly slotId: string; readonly status: string; readonly reason: string | null }[] }; + assert.deepEqual(observations.verifierMatrix.find(item => item.slotId === COMMAND_SLOT_ID), { slotId: COMMAND_SLOT_ID, checkId: COMMAND_CHECK_ID, status: 'blocked', reason: 'EVIDENCE_UNAVAILABLE', implicit: null }); + const descriptor = JSON.parse(await readFile(join(f.runRoot, input.runId, 'run.json'), 'utf8')) as RunDescriptor, store = stateValue(reopenLocalRun(descriptor.identity)); + try { + const operations = stateValue(store.listOperations({ limit: 100, cursor: null })).items; + const dispatched = operations.filter(operation => operation.intent.targetIdentity.startsWith('command:')); + assert.equal(dispatched.length, 1, 'one command.v1 operation ever'); assert.equal(dispatched[0]!.state, 'confirmed'); + assert.ok(operations.every(operation => operation.state === 'confirmed' && operation.intent.effect === 'read_only')); + } finally { stateValue(store.close()); } + const inspected = await inspectRun({ runRoot: f.runRoot, runId: input.runId }); + assert.ok(inspected.ok); + assert.deepEqual(await readdir(join(f.runRoot, 'workspaces', input.runId)), [], 'no workspace leftovers'); + } finally { await cleanupFixture(f); } + } +}); diff --git a/packages/controller/test/rework.test.ts b/packages/controller/test/rework.test.ts index 2725609d..b9664b8e 100644 --- a/packages/controller/test/rework.test.ts +++ b/packages/controller/test/rework.test.ts @@ -5,7 +5,6 @@ import { execFileSync } from 'node:child_process'; import { chmod, lstat, mkdir, readFile, symlink, unlink, writeFile } from 'node:fs/promises'; import { dirname, join } from 'node:path'; import { SecretScrubber } from '@loopwright/core'; -import type { PiAdapterV2, PiErrorV2, PiHostV2, PiOpenInputV2, PiOutcomeV2 } from '@loopwright/agent-pi'; import { formatRunReport, inspectRun, @@ -24,12 +23,16 @@ import { } from '../src/index.js'; import { reworkSubgraph, resetSubgraphNodes } from '../src/scheduler.js'; import { matchesScopePattern } from '../src/source.js'; -import { canonical, hash } from '../src/schema.js'; +import { canonical, hash, same } from '../src/schema.js'; import { stateValue } from '../src/storage.js'; import { phaseCheckpointId, stableId, validateProgress } from '../src/progress.js'; import { packetFixture } from './verification-fixtures.js'; import { retainedFixture, setFixture } from './progress-fixtures.js'; import { configurationFixture } from './config-fixtures.js'; +import { COMMAND_CHECK_ID, commandCheckFixture, createPiMockPort } from './scheduling-fixtures.js'; +import { cleanupFixture, type FixtureExtra } from './local-check-fixtures.js'; +import { createCycle, Cycle } from '../src/controller.js'; +import { ControllerFailure } from '../src/errors.js'; function assertOk(res: { readonly ok: boolean; readonly value?: T; readonly error?: unknown }, msg = ''): T { assert.equal(res.ok, true, `${msg}: ${JSON.stringify(res.error)}`); @@ -138,284 +141,6 @@ test('reworkSubgraph and resetSubgraphNodes reset only [rejectTo, ...descendants } }); -function createPiMockPort( - planStep: (ctx: { - readonly stepId: string; - readonly roleId: string; - readonly prompt: string; - readonly resourceIds: readonly string[]; - readonly candidateFiles: ReadonlyMap; - }) => { - readonly files?: Readonly>; - readonly responseJson: unknown; - }, -) { - let reqSeq = 0; - const cancelledErr: PiErrorV2 = { - code: 'CANCELLED', - phase: 'session', - path: '', - retryable: false, - effect: 'none', - requestId: null, - operationId: null, - stateErrorCode: null, - }; - const cancelledOut: PiOutcomeV2 = { - status: 'cancelled', - requestIds: [], - operationIds: [], - providerTermination: 'none', - usage: 'none', - localCleanup: 'complete', - error: cancelledErr, - cleanupError: null, - }; - - return async (host: PiHostV2, input: PiOpenInputV2) => { - let lastCommandText = ''; - let lastRequestId = ''; - let lastOpId = ''; - let currentFiles = new Map( - await Promise.all( - input.candidate.artifacts.map(async a => [ - a.name, - 'bytes' in a ? new Uint8Array(a.bytes) : new Uint8Array(await readFile(a.blobPath)), - ] as const), - ), - ); - let responseText = ''; - - const adapter: PiAdapterV2 = { - capabilities: () => { - throw new Error('unused'); - }, - events: () => ({ - async *[Symbol.asyncIterator]() { - yield* []; - }, - }), - cancel: async () => ({ ok: true, value: cancelledOut }), - close: async () => ({ ok: true, value: { closed: true } }), - compact: async () => ({ - ok: true, - value: { - status: 'execution_settled', - requestIds: [], - operationIds: [], - providerTermination: 'confirmed', - usage: 'complete', - localCleanup: 'complete', - error: null, - cleanupError: null, - }, - }), - execute: async cmd => { - reqSeq++; - lastCommandText = cmd.text; - lastRequestId = `pi-req-${reqSeq}`; - lastOpId = `pi-op-${reqSeq}`; - const stepDecision = planStep({ - stepId: input.stepId, - roleId: input.roleId, - prompt: cmd.text, - resourceIds: input.resources.map(r => r.id), - candidateFiles: currentFiles, - }); - if (stepDecision.files) { - currentFiles = new Map(currentFiles); - for (const [name, content] of Object.entries(stepDecision.files)) { - currentFiles.set(name, new Uint8Array(Buffer.from(content, 'utf8'))); - } - } - responseText = JSON.stringify(stepDecision.responseJson); - - const mappedPurpose: 'task' | 'reviewer' | 'compaction' = - cmd.purpose === 'reviewer' || cmd.purpose === 'compaction' ? cmd.purpose : 'task'; - stateValue( - host.store.reserveRequest(host.authority, { - requestId: lastRequestId, - roleId: input.roleId, - nodeId: input.stepId, - attemptId: cmd.commandId, - purpose: mappedPurpose, - repair: cmd.repair, - transportRetryOf: null, - requestDigest: hash(`req-${reqSeq}`), - inputUpperBound: 100, - outputUpperBound: 50, - totalUpperBound: 150, - capability: { - adapterId: 'pi', - adapterVersion: '0.0.0', - provider: input.policy.selection.provider, - model: input.policy.selection.model, - kind: 'soft_only', - coversAllBillableTokens: false, - enforcesOutputBound: false, - }, - operationId: lastOpId, - targetIdentity: 'fixture:pi-rework', - }), - ); - stateValue(host.store.authorizeRequestDispatch(host.authority, lastRequestId)); - const op = stateValue(host.store.getOperation(lastOpId)); - const view = stateValue(host.store.inspect()); - const usageBytes = Buffer.from(canonical({ seq: reqSeq })); - const usageName = `usage-${hash(usageBytes).hex}.bin`; - await writeFile(join(host.artifactsDirectory, usageName), usageBytes, { mode: 0o600 }); - const usageArtifact = { name: usageName, byteLength: usageBytes.byteLength, digest: hash(usageBytes) }; - stateValue( - host.store.observeRequest(host.authority, lastRequestId, { - receiptId: `rec-${reqSeq}`, - termination: 'confirmed', - outcome: 'succeeded', - evidence: { - evidenceId: `ev-${reqSeq}`, - producerId: 'mock-pi', - method: 'synthetic', - artifact: usageArtifact, - subject: { - storeId: view.storeId, - runId: view.runId, - lockHash: view.lockHash, - operationId: lastOpId, - requestId: lastRequestId, - intentDigest: op.intentDigest, - dispatchGeneration: op.dispatch!.generation, - dispatchId: op.dispatch!.dispatchId, - }, - }, - usage: { - requestId: lastRequestId, - inputTokens: { provenance: 'reported', value: 20 }, - outputTokens: { provenance: 'reported', value: 10 }, - costMicrousd: { provenance: 'reported', value: 500 }, - }, - }), - ); - return { - ok: true, - value: { - status: 'execution_settled', - requestIds: [lastRequestId], - operationIds: [lastOpId], - providerTermination: 'confirmed', - usage: 'complete', - localCleanup: 'complete', - error: null, - cleanupError: null, - }, - }; - }, - capture: async ({ checkpointId }) => { - const sortedEntries = [...currentFiles.entries()] - .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) - .map(([name, bytes]) => ({ - name, - bytes, - ref: { name, byteLength: bytes.byteLength, digest: hash(bytes) }, - })); - const manifest = { - apiVersion: 'loopwright.dev/v1alpha1' as const, - kind: 'ArtifactManifest' as const, - metadata: { id: 'candidate' }, - spec: input.candidate.manifest.spec.baseTree - ? { - baseTree: input.candidate.manifest.spec.baseTree, - entries: sortedEntries.map(e => e.ref), - deleted: input.candidate.manifest.spec.deleted ?? [], - } - : { entries: sortedEntries.map(e => e.ref) }, - }; - const current = stateValue(host.store.inspect()); - const sourceDigest = hash('loopwright.dev/pi-policy/v2\0' + canonical(input.policy)); - const nativePolicy = { - ...input.policy, - version: 1, - policyId: 'v2.' + BigInt('0x' + sourceDigest.hex).toString(36), - }; - const candidateDigest = hash('loopwright.dev/artifact-manifest/v1alpha1\0' + canonical(manifest)); - const binding = { - version: 1, - checkpointId, - storeId: current.storeId, - runId: current.runId, - lockHash: current.lockHash, - sessionId: input.sessionId, - roleId: input.roleId, - stepId: input.stepId, - runtime: input.policy.runtime, - policyDigest: hash(canonical(nativePolicy)), - resourcesDigest: hash(canonical(input.policy.resources)), - candidateDigest, - clockBasis: current.clock.basis, - accountingDigest: hash( - canonical({ - ledger: current.ledger, - requests: current.counts.requests, - operations: current.counts.operations, - }), - ), - sequence: 1, - }; - const line = (v: unknown) => JSON.stringify(v) + '\n'; - let wsBody = line({ type: 'workspace_snapshot', version: 1, binding, manifest }); - for (const item of sortedEntries) { - wsBody += line({ type: 'file', ref: item.ref }); - if (item.bytes.byteLength > 0) { - wsBody += line({ type: 'chunk', index: 0, data: Buffer.from(item.bytes).toString('base64') }); - } - wsBody += line({ type: 'file_end', byteLength: item.bytes.byteLength, digest: item.ref.digest.hex }); - } - wsBody += line({ type: 'end', files: sortedEntries.length }); - const wsBytes = Buffer.from(wsBody, 'utf8'); - const wsName = `ws-${hash(wsBytes).hex}.bin`; - await writeFile(join(host.artifactsDirectory, wsName), wsBytes, { mode: 0o600 }); - const workspaceRef = { name: wsName, byteLength: wsBytes.byteLength, digest: hash(wsBytes) }; - - const ts = '2026-11-19T00:00:00.000Z'; - const sessBody = - line({ type: 'session_snapshot', version: 1, binding }) + - line({ type: 'session', version: 3, id: 'sess_1', cwd: '/workspace/candidate', timestamp: ts }) + - line({ type: 'message', id: 'u1', parentId: null, timestamp: ts, message: { role: 'user', content: lastCommandText } }) + - line({ - type: 'message', - id: 'a1', - parentId: 'u1', - timestamp: ts, - message: { - role: 'assistant', - ...input.policy.selection, - content: [{ type: 'text', text: responseText }], - stopReason: 'stop', - }, - }); - const sessBytes = Buffer.from(sessBody, 'utf8'); - const sessName = `sess-${hash(sessBytes).hex}.bin`; - await writeFile(join(host.artifactsDirectory, sessName), sessBytes, { mode: 0o600 }); - const sessionRef = { name: sessName, byteLength: sessBytes.byteLength, digest: hash(sessBytes) }; - - stateValue( - host.store.writeCheckpoint(host.authority, { - checkpointId, - expectedRevision: stateValue(host.store.inspect()).revision, - candidateManifest: manifest, - workspace: workspaceRef, - privateSession: sessionRef, - additionalArtifacts: [], - }), - ); - return { - ok: true, - value: { checkpointId, candidate: manifest, workspace: workspaceRef, session: sessionRef }, - }; - }, - }; - return { ok: true as const, value: adapter }; - }; -} - async function setupFiveStepPiFixture(maxReworks = 2) { const f = await configurationFixture(); const repository = join(f.root, 'repository'); @@ -2198,3 +1923,55 @@ test('controller.ts: rework with modified candidate resets non-subgraph complete await f.cleanup(); } }); + +/** Fails until the candidate carries `packages/ok`; its stderr line differs on every run while the reason stays `check_failed`. */ +const DECIDE_SCRIPT = '#!/bin/sh\nif [ -f "$LOOPWRIGHT_CANDIDATE_DIR/packages/ok" ]; then\n printf \'{"metrics":{"fixed":1}}\' > "$LOOPWRIGHT_CHECK_OUT"\n exit 0\nfi\nprintf \'run %s: case 7 failed\\n\' "$$" >&2\nprintf \'{"detail":"case 7: expected 42, got 41"}\' > "$LOOPWRIGHT_CHECK_OUT"\nexit 1\n'; +const DECIDE: FixtureExtra = { path: 'scripts/decide.sh', content: DECIDE_SCRIPT, executable: true }; +const AUTHOR_SUBMISSION = { version: 1, status: 'completed', checks: [], reason: 'Implemented.' } as const; +function failureCode(error: unknown): string { return error instanceof ControllerFailure ? error.diagnostic.code : 'not-a-controller-failure: ' + String(error); } + +test('controller.ts: a command.v1 check step with onRework hands the script detail to the author through the rework summary, and the author fixes the candidate', async () => { + const f = await commandCheckFixture({ script: 'scripts/decide.sh', extra: [DECIDE], author: true, onRework: 1 }); + try { + const prompts: string[] = []; + const res = assertOk(await runCycleWithPorts({ configuration: f.loaded, repository: f.repository, runRoot: f.runRoot, runId: 'run-command-rework' }, + { openAdapter: createPiMockPort(({ prompt }) => { prompts.push(prompt); return { files: { 'packages/draft.txt': 'v1\n', ...(prompts.length === 2 ? { 'packages/ok': '' } : {}) }, responseJson: AUTHOR_SUBMISSION }; }) }), 'command.v1 onRework run'); + assert.equal(res.kind, 'result', JSON.stringify(res)); if (res.kind !== 'result') return; + assert.equal(res.result.spec.status, 'completed'); assert.equal(prompts.length, 2, 'initial attempt and one rework'); + assert.equal(prompts[0]!.includes('case 7'), false, 'the first prompt carries no verdict'); + assert.match(prompts[1]!, /from step "verify"/); assert.match(prompts[1]!, /check_failed/); assert.match(prompts[1]!, /case 7: expected 42, got 41/); + assert.equal(res.findings?.length, 1); assert.equal(res.findings?.[0]?.title, 'Check forge-evaluate failed (check_failed)'); assert.equal(res.findings?.[0]?.evidence, 'check_failed: case 7: expected 42, got 41'); + assert.equal(res.stepVerdicts?.length, 1); assert.equal(res.stepVerdicts?.[0]?.stepId, 'verify'); assert.equal(res.stepVerdicts?.[0]?.attemptId, null); + assert.equal(res.stepVerdicts?.[0]?.verdict.verdict, 'rework'); assert.match(res.stepVerdicts?.[0]?.verdict.summary, /^Check verify \(forge-evaluate\) failed: check_failed — case 7: expected 42, got 41$/); + const row = res.result.spec.verification.spec.required.find(item => item.checkId === COMMAND_CHECK_ID)!; + assert.equal(row.status, 'passed'); assert.deepEqual(JSON.parse(JSON.stringify(row.metrics)), { fixed: 1 }, 'the reworked generation is the one verified'); + } finally { await cleanupFixture(f); } +}); + +test('controller.ts: a command.v1 check that fails twice with the same reason on an unchanged candidate halts with REPEAT_FAILURE whatever the stderr says; the author saw detail on the first repair only', async () => { + const author = (prompts: string[]) => createPiMockPort(({ prompt }) => { prompts.push(prompt); return { files: { 'packages/draft.txt': 'v1\n' }, responseJson: AUTHOR_SUBMISSION }; }); + // A. Public run: the refusal is accounted as `exhausted` after exactly one repair prompt. + const f = await commandCheckFixture({ script: 'scripts/decide.sh', extra: [DECIDE], author: true }); + try { + const prompts: string[] = []; + const res = assertOk(await runCycleWithPorts({ configuration: f.loaded, repository: f.repository, runRoot: f.runRoot, runId: 'run-command-repeat' }, { openAdapter: author(prompts) }), 'command.v1 repeat-failure run'); + assert.equal(res.kind, 'result', JSON.stringify(res)); if (res.kind !== 'result') return; + assert.equal(res.result.spec.status, 'exhausted'); assert.equal(prompts.length, 2, 'no second repair prompt'); + assert.match(prompts[1]!, /Repair only writable candidate files/); assert.match(prompts[1]!, /case 7: expected 42, got 41/); + assert.equal(res.result.spec.verification.spec.required.find(item => item.checkId === COMMAND_CHECK_ID)!.status, 'failed'); + } finally { await cleanupFixture(f); } + // B. The refusal code itself, read at the cycle boundary. + const g = await commandCheckFixture({ script: 'scripts/decide.sh', extra: [DECIDE], author: true }); + try { + const prompts: string[] = []; + const ctx = await createCycle({ configuration: g.loaded, repository: g.repository, runRoot: g.runRoot, runId: 'run-command-repeat-code' }, { openAdapter: author(prompts) }); + const cycle = new Cycle(ctx); + try { + await assert.rejects(cycle.execute(), error => failureCode(error) === 'REPEAT_FAILURE'); + assert.equal(prompts.length, 2); + const command = cycle.draft.verifierReceipts.find(row => row.slot === 'check.' + COMMAND_CHECK_ID)!; + assert.equal(cycle.draft.failures.find(item => same(item.evidence, command.output))?.count, 2, 'the same command.v1 signature counted twice'); + assert.equal(cycle.draft.failures.length, 2, 'the no-change check failed once beside it; its count stays 1'); + } finally { await cycle.deadline.dispose(); await cycle.events.close(); stateValue(ctx.store.release(ctx.authority)); stateValue(ctx.store.close()); await ctx.owner.release(); } + } finally { await cleanupFixture(g); } +}); diff --git a/packages/controller/test/scheduling-fixtures.ts b/packages/controller/test/scheduling-fixtures.ts index f1b04eb3..da2bec4d 100644 --- a/packages/controller/test/scheduling-fixtures.ts +++ b/packages/controller/test/scheduling-fixtures.ts @@ -1,10 +1,16 @@ import assert from 'node:assert/strict'; -import { mkdir, writeFile } from 'node:fs/promises'; +import { mkdir, readFile, writeFile } from 'node:fs/promises'; import { appendFileSync, fsyncSync, mkdirSync, openSync, closeSync } from 'node:fs'; import { join, resolve } from 'node:path'; import { execFileSync } from 'node:child_process'; import { configurationFixture } from './config-fixtures.js'; import { setFixture } from './progress-fixtures.js'; +import { localCheckFixture, type FixtureExtra, type LocalCheckFixture } from './local-check-fixtures.js'; +import { installedHandlerDigests } from '../src/handlers.js'; +import { canonical, hash } from '../src/schema.js'; +import { stateValue } from '../src/storage.js'; +import type { PiAdapterV2, PiErrorV2, PiHostV2, PiOpenInputV2, PiOutcomeV2 } from '@loopwright/agent-pi'; +import type { Handler } from '../src/types.js'; export async function cycleFixture(valid: boolean, initialBytes?: Uint8Array) { const f = await configurationFixture(), repository = join(f.root, 'repository'), runRoot = join(f.root, 'runs'); await mkdir(repository, { mode: 0o700 }); mkdirSync(resolve('.claude/s04-qualification'), { recursive: true, mode: 0o700 }); @@ -18,3 +24,327 @@ export async function cycleFixture(valid: boolean, initialBytes?: Uint8Array) { await f.save(); const loaded = await f.load(); assert.equal(loaded.ok, true); if (!loaded.ok) throw new Error('fixture'); return { ...f, repository, runRoot, loaded: loaded.value }; } + +export const COMMAND_CHECK_ID = 'forge-evaluate'; +export const COMMAND_HANDLER_ID = 'forge-evaluate'; +/** A `command.v1` handler carrying the installed digest; `localCheckFixture` builds the repository and the `direct` attestation. */ +export async function commandHandler(parameters: Record = {}): Promise { + const installed = await installedHandlerDigests(); + return { + id: COMMAND_HANDLER_ID, version: 1, kind: 'check', implementation: 'command.v1', digest: installed['command.v1'], + // 20 s: a trivial script still has to outlive a saturated suite worker; below the 58 s lease threshold, so the store lease stays 60 s. + parameters: { checkId: COMMAND_CHECK_ID, script: 'scripts/pass.sh', args: [], env: {}, toolchainPaths: [], timeoutMs: 20000, ...parameters }, + capabilities: ['host_execution'], + }; +} +export interface CommandCheckFixtureOptions { + readonly script?: string; readonly parameters?: Record; readonly protected?: readonly string[]; readonly extra?: readonly FixtureExtra[]; + /** `true` prepends an `implement` agent step (role `builder`, tools read/write/edit) that `verify` depends on. */ + readonly author?: boolean; + /** `onRework.maxReworks` for the `verify` step; absent means no rework policy. */ + readonly onRework?: number; + readonly allowed?: readonly string[]; +} +/** + * The T3 local-check fixture with the `command.v1` handler as the only explicit check: a check-only DAG (`verify`), or + * `implement -> verify` with the fake adapter as author when `author` is set. + */ +export async function commandCheckFixture(options: CommandCheckFixtureOptions = {}): Promise { + const f = await localCheckFixture({ ...(options.protected !== undefined ? { protected: options.protected } : {}), ...(options.extra !== undefined ? { extra: options.extra } : {}) }), handler = await commandHandler({ ...(options.script !== undefined ? { script: options.script } : {}), ...options.parameters }); + const implicit = f.registry.spec.handlers.filter(item => item.id === 'scope' || item.id === 'no-change'), agent = { ...f.registry.spec.handlers.find(item => item.id === 'package.patch')!, id: 'author.h' }; + setFixture(f.registry, ['spec', 'handlers'], [...implicit, handler]); + setFixture(f.config, ['spec', 'task', 'spec', 'acceptance'], { required: [COMMAND_CHECK_ID], checks: [{ id: COMMAND_CHECK_ID, allowedEvidenceLevels: options.allowed ?? ['host_execution'] }] }); + const verify = { id: 'verify', kind: 'check', uses: COMMAND_HANDLER_ID, roleId: null, dependsOn: options.author ? ['implement'] : [], ...(options.onRework !== undefined ? { onRework: { rejectTo: 'implement', maxReworks: options.onRework } } : {}) }; + if (options.author) { + setFixture(f.registry, ['spec', 'handlers'], [agent, ...implicit, handler]); + setFixture(f.registry, ['spec', 'roleProfiles', 0, 'tools'], ['read', 'write', 'edit']); + setFixture(f.config, ['spec', 'task', 'spec', 'roles', 0, 'tools'], ['read', 'write', 'edit']); + setFixture(f.config, ['spec', 'task', 'spec', 'steps'], [{ id: 'implement', kind: 'agent', uses: 'author.h', roleId: 'builder', dependsOn: [] }, verify]); + setFixture(f.config, ['spec', 'profiles', 'steps'], [{ stepId: 'implement', handlerRef: 'author.h' }, { stepId: 'verify', handlerRef: COMMAND_HANDLER_ID }]); + } else { + setFixture(f.config, ['spec', 'task', 'spec', 'steps'], [verify]); + setFixture(f.config, ['spec', 'profiles', 'steps'], [{ stepId: 'verify', handlerRef: COMMAND_HANDLER_ID }]); + setFixture(f.config, ['spec', 'credentials'], []); + } + await f.save(); const loaded = await f.load(); assert.equal(loaded.ok, true, JSON.stringify(loaded)); if (!loaded.ok) throw new Error('fixture'); + return { ...f, loaded: loaded.value, handler, runRoot: f.runRoot }; +} + +/** Deterministic fake Pi adapter port: the author writes the files the callback returns and answers with its submission; every store protocol step is real. */ +export function createPiMockPort( + planStep: (ctx: { + readonly stepId: string; + readonly roleId: string; + readonly prompt: string; + readonly resourceIds: readonly string[]; + readonly candidateFiles: ReadonlyMap; + }) => { + readonly files?: Readonly>; + readonly responseJson: unknown; + }, +) { + let reqSeq = 0; + const cancelledErr: PiErrorV2 = { + code: 'CANCELLED', + phase: 'session', + path: '', + retryable: false, + effect: 'none', + requestId: null, + operationId: null, + stateErrorCode: null, + }; + const cancelledOut: PiOutcomeV2 = { + status: 'cancelled', + requestIds: [], + operationIds: [], + providerTermination: 'none', + usage: 'none', + localCleanup: 'complete', + error: cancelledErr, + cleanupError: null, + }; + + return async (host: PiHostV2, input: PiOpenInputV2) => { + let lastCommandText = ''; + let lastRequestId = ''; + let lastOpId = ''; + let currentFiles = new Map( + await Promise.all( + input.candidate.artifacts.map(async a => [ + a.name, + 'bytes' in a ? new Uint8Array(a.bytes) : new Uint8Array(await readFile(a.blobPath)), + ] as const), + ), + ); + let responseText = ''; + + const adapter: PiAdapterV2 = { + capabilities: () => { + throw new Error('unused'); + }, + events: () => ({ + async *[Symbol.asyncIterator]() { + yield* []; + }, + }), + cancel: async () => ({ ok: true, value: cancelledOut }), + close: async () => ({ ok: true, value: { closed: true } }), + compact: async () => ({ + ok: true, + value: { + status: 'execution_settled', + requestIds: [], + operationIds: [], + providerTermination: 'confirmed', + usage: 'complete', + localCleanup: 'complete', + error: null, + cleanupError: null, + }, + }), + execute: async cmd => { + reqSeq++; + lastCommandText = cmd.text; + lastRequestId = `pi-req-${reqSeq}`; + lastOpId = `pi-op-${reqSeq}`; + const stepDecision = planStep({ + stepId: input.stepId, + roleId: input.roleId, + prompt: cmd.text, + resourceIds: input.resources.map(r => r.id), + candidateFiles: currentFiles, + }); + if (stepDecision.files) { + currentFiles = new Map(currentFiles); + for (const [name, content] of Object.entries(stepDecision.files)) { + currentFiles.set(name, new Uint8Array(Buffer.from(content, 'utf8'))); + } + } + responseText = JSON.stringify(stepDecision.responseJson); + + const mappedPurpose: 'task' | 'reviewer' | 'compaction' = + cmd.purpose === 'reviewer' || cmd.purpose === 'compaction' ? cmd.purpose : 'task'; + stateValue( + host.store.reserveRequest(host.authority, { + requestId: lastRequestId, + roleId: input.roleId, + nodeId: input.stepId, + attemptId: cmd.commandId, + purpose: mappedPurpose, + repair: cmd.repair, + transportRetryOf: null, + requestDigest: hash(`req-${reqSeq}`), + inputUpperBound: 100, + outputUpperBound: 50, + totalUpperBound: 150, + capability: { + adapterId: 'pi', + adapterVersion: '0.0.0', + provider: input.policy.selection.provider, + model: input.policy.selection.model, + kind: 'soft_only', + coversAllBillableTokens: false, + enforcesOutputBound: false, + }, + operationId: lastOpId, + targetIdentity: 'fixture:pi-rework', + }), + ); + stateValue(host.store.authorizeRequestDispatch(host.authority, lastRequestId)); + const op = stateValue(host.store.getOperation(lastOpId)); + const view = stateValue(host.store.inspect()); + const usageBytes = Buffer.from(canonical({ seq: reqSeq })); + const usageName = `usage-${hash(usageBytes).hex}.bin`; + await writeFile(join(host.artifactsDirectory, usageName), usageBytes, { mode: 0o600 }); + const usageArtifact = { name: usageName, byteLength: usageBytes.byteLength, digest: hash(usageBytes) }; + stateValue( + host.store.observeRequest(host.authority, lastRequestId, { + receiptId: `rec-${reqSeq}`, + termination: 'confirmed', + outcome: 'succeeded', + evidence: { + evidenceId: `ev-${reqSeq}`, + producerId: 'mock-pi', + method: 'synthetic', + artifact: usageArtifact, + subject: { + storeId: view.storeId, + runId: view.runId, + lockHash: view.lockHash, + operationId: lastOpId, + requestId: lastRequestId, + intentDigest: op.intentDigest, + dispatchGeneration: op.dispatch!.generation, + dispatchId: op.dispatch!.dispatchId, + }, + }, + usage: { + requestId: lastRequestId, + inputTokens: { provenance: 'reported', value: 20 }, + outputTokens: { provenance: 'reported', value: 10 }, + costMicrousd: { provenance: 'reported', value: 500 }, + }, + }), + ); + return { + ok: true, + value: { + status: 'execution_settled', + requestIds: [lastRequestId], + operationIds: [lastOpId], + providerTermination: 'confirmed', + usage: 'complete', + localCleanup: 'complete', + error: null, + cleanupError: null, + }, + }; + }, + capture: async ({ checkpointId }) => { + const sortedEntries = [...currentFiles.entries()] + .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) + .map(([name, bytes]) => ({ + name, + bytes, + ref: { name, byteLength: bytes.byteLength, digest: hash(bytes) }, + })); + const manifest = { + apiVersion: 'loopwright.dev/v1alpha1' as const, + kind: 'ArtifactManifest' as const, + metadata: { id: 'candidate' }, + spec: input.candidate.manifest.spec.baseTree + ? { + baseTree: input.candidate.manifest.spec.baseTree, + entries: sortedEntries.map(e => e.ref), + deleted: input.candidate.manifest.spec.deleted ?? [], + } + : { entries: sortedEntries.map(e => e.ref) }, + }; + const current = stateValue(host.store.inspect()); + const sourceDigest = hash('loopwright.dev/pi-policy/v2\0' + canonical(input.policy)); + const nativePolicy = { + ...input.policy, + version: 1, + policyId: 'v2.' + BigInt('0x' + sourceDigest.hex).toString(36), + }; + const candidateDigest = hash('loopwright.dev/artifact-manifest/v1alpha1\0' + canonical(manifest)); + const binding = { + version: 1, + checkpointId, + storeId: current.storeId, + runId: current.runId, + lockHash: current.lockHash, + sessionId: input.sessionId, + roleId: input.roleId, + stepId: input.stepId, + runtime: input.policy.runtime, + policyDigest: hash(canonical(nativePolicy)), + resourcesDigest: hash(canonical(input.policy.resources)), + candidateDigest, + clockBasis: current.clock.basis, + accountingDigest: hash( + canonical({ + ledger: current.ledger, + requests: current.counts.requests, + operations: current.counts.operations, + }), + ), + sequence: 1, + }; + const line = (v: unknown) => JSON.stringify(v) + '\n'; + let wsBody = line({ type: 'workspace_snapshot', version: 1, binding, manifest }); + for (const item of sortedEntries) { + wsBody += line({ type: 'file', ref: item.ref }); + if (item.bytes.byteLength > 0) { + wsBody += line({ type: 'chunk', index: 0, data: Buffer.from(item.bytes).toString('base64') }); + } + wsBody += line({ type: 'file_end', byteLength: item.bytes.byteLength, digest: item.ref.digest.hex }); + } + wsBody += line({ type: 'end', files: sortedEntries.length }); + const wsBytes = Buffer.from(wsBody, 'utf8'); + const wsName = `ws-${hash(wsBytes).hex}.bin`; + await writeFile(join(host.artifactsDirectory, wsName), wsBytes, { mode: 0o600 }); + const workspaceRef = { name: wsName, byteLength: wsBytes.byteLength, digest: hash(wsBytes) }; + + const ts = '2026-11-19T00:00:00.000Z'; + const sessBody = + line({ type: 'session_snapshot', version: 1, binding }) + + line({ type: 'session', version: 3, id: 'sess_1', cwd: '/workspace/candidate', timestamp: ts }) + + line({ type: 'message', id: 'u1', parentId: null, timestamp: ts, message: { role: 'user', content: lastCommandText } }) + + line({ + type: 'message', + id: 'a1', + parentId: 'u1', + timestamp: ts, + message: { + role: 'assistant', + ...input.policy.selection, + content: [{ type: 'text', text: responseText }], + stopReason: 'stop', + }, + }); + const sessBytes = Buffer.from(sessBody, 'utf8'); + const sessName = `sess-${hash(sessBytes).hex}.bin`; + await writeFile(join(host.artifactsDirectory, sessName), sessBytes, { mode: 0o600 }); + const sessionRef = { name: sessName, byteLength: sessBytes.byteLength, digest: hash(sessBytes) }; + + stateValue( + host.store.writeCheckpoint(host.authority, { + checkpointId, + expectedRevision: stateValue(host.store.inspect()).revision, + candidateManifest: manifest, + workspace: workspaceRef, + privateSession: sessionRef, + additionalArtifacts: [], + }), + ); + return { + ok: true, + value: { checkpointId, candidate: manifest, workspace: workspaceRef, session: sessionRef }, + }; + }, + }; + return { ok: true as const, value: adapter }; + }; +} diff --git a/specs/2026-11-30-managed-controller-in-process-execution.md b/specs/2026-11-30-managed-controller-in-process-execution.md index ea4eb87f..165a6661 100644 --- a/specs/2026-11-30-managed-controller-in-process-execution.md +++ b/specs/2026-11-30-managed-controller-in-process-execution.md @@ -119,7 +119,10 @@ controller's own environment on a host whose isolation the registry attests. `step next`, which take `--repo`) resolves the script and `toolchainPaths` at `sourceRevision`, checks the executable bit, and records the directory digest in the compiled slot, which `planDigest` covers. `TaskLock` does not change. A missing or non-executable - script at admission fails `CONFIG_REFERENCE`. + script at admission fails `CONFIG_REFERENCE`. On `resume` and reconcile the retained plan + artifact carries the digest, and `LocalCheck` re-verifies digest, executable bit, protection, and + toolchain before dispatch. `check` refuses a plan whose `allowedEvidenceLevels` for a + `command.v1` slot lacks `host_execution`. - **Script contract.** Managed Controller defines its own contract; it does not reuse the Taskpack one. Environment: `PATH` is `/usr/local/bin:/usr/bin:/bin` with `toolchainPaths` prepended; `HOME` and `TMPDIR` point at a disposable scratch directory; `LANG=C.UTF-8`; @@ -145,7 +148,8 @@ controller's own environment on a host whose isolation the registry attests. recorded group is killed; it is never re-dispatched under the same operation. - **Evidence.** The output artifact and a bounded, scrubbed stderr tail are bound to `candidateDigest`. The receipt carries `method: 'direct_script'`, the script path, the script - directory digest, and the registry digest. `inspect` exports them in `verification.json`. + directory digest, and the registry digest. `inspect` exports them in the inspect bundle's + `verifier-receipts.json` (core's `verification.json` rows keep their own shape). `onRework` returns `detail` to the author: the controller's rework summary must extract `detail` for `command.v1` slots as it does for gate slots today ([controller.ts](../packages/controller/src/controller.ts)). A run accepts `host_execution` @@ -548,9 +552,9 @@ and T11 have disjoint `Owns:` and start together; T5 follows T2. Gate: review Acceptance: the contract module exports the environment names, the env name rule, and the `$LOOPWRIGHT_CHECK_OUT` parser (64 KiB, `passed` and `summary` refused, metric and finding bounds); `packages/core/src/index.ts` also exports the T2 limits (`LOCAL_CHECK_LIMITS`, `EXEC_LIMITS`) and `handlerCapability`. `LocalCheck.run(job, signal)` follows `Gate.run` and executes the script in its own process group with the binding marker written first: candidate materialized through the T1 helpers into a disposable directory, the F1 environment, `timeoutMs` with process-group kill, exit-code mapping, output artifact bound to `candidateDigest`, scrubbed stderr tail, receipt with `method: 'direct_script'` and the script and registry digests. The captured overlay is byte-identical before and after; an operation without a proof marker settles `blocked` with `EVIDENCE_UNAVAILABLE` and is not re-dispatched. Verify: `node scripts/run-tests.mjs --pkg core && node scripts/run-tests.mjs --pkg controller` -- [ ] **T4 · `command.v1` controller integration** +- [x] **T4 · `command.v1` controller integration** Blocked by: T3 - Owns: `packages/controller/src/compile.ts`, `packages/controller/src/controller.ts`, `packages/controller/src/recovery.ts`, `packages/controller/src/handlers.ts`, `packages/controller/src/errors.ts`, `packages/controller/src/retained.ts`, `packages/controller/src/acceptance.ts`, `packages/controller/test/compile.test.ts`, `packages/controller/test/rework.test.ts`, `packages/controller/test/local-check-integration.test.ts`, `packages/controller/test/recovery-cycle.test.ts` + Owns: `packages/controller/src/compile.ts`, `packages/controller/src/controller.ts`, `packages/controller/src/recovery.ts`, `packages/controller/src/handlers.ts`, `packages/controller/src/errors.ts`, `packages/controller/src/retained.ts`, `packages/controller/src/acceptance.ts`, `packages/controller/src/types.ts`, `packages/controller/src/reconcile.ts`, `packages/controller/src/inspect.ts`, `packages/controller/src/run-eval.ts`, `packages/controller/test/compile.test.ts`, `packages/controller/test/rework.test.ts`, `packages/controller/test/local-check-integration.test.ts`, `packages/controller/test/recovery-cycle.test.ts` Gate: review Acceptance: admission resolves the script and `toolchainPaths` at `target.sourceRevision` from the baseline tree, requires the executable bit and a fully protected script directory, and records the directory digest in the compiled slot; `check` validates schema and budget only; the controller dispatches `command.v1` slots to `LocalCheck`, extracts `detail` for them in the rework summary, and exports the receipt through `inspect`; recovery settles a `command.v1` operation without a proof marker as `blocked`. A controller cycle test with the deterministic fake adapter as author and the T3 stub scripts settles `completed` for a passing script and reworks with `detail` for a failing one. `installedHandlerDigests()` in `handlers.ts` lists `command.v1`, and the `safePath` segment whitelist in `errors.ts` covers the new refusal paths (`host`, `localChecks`, `backend`, `command`, `script`, `env`, `toolchainPaths`, `exec`, `captureBytes`, `credentialRefs`). Verify: `node scripts/run-tests.mjs --pkg controller` From 48a3f05b4f25ff9469df5000b763436d1b02a41c Mon Sep 17 00:00:00 2001 From: thxCode Date: Tue, 1 Dec 2026 18:28:35 +0800 Subject: [PATCH 13/26] fix(controller): harden LocalCheck, exec-role, scrubber, and isolation parity Address Phase 1 review findings across @loopwright/core and @loopwright/controller: - Fix LocalCheck.restore double-restore on interrupted operations (removing the silent early return in recovery-cycle.test.ts and adding crash-before-binding coverage), attach spawn exit/error/stderr listeners synchronously before binding-marker fsync, cap stderr to a rolling 16 KiB tail, settle aborted dispatches cleanly with DEADLINE vs CANCELLED mapping, and preserve holdLocalActivity and attemptDir on CLEANUP_FAILED. - Enforce canonical path containment and readBoundedFile on exec-role usageOut, expose ExecRoleOutcome.usageReported, raise parseUsage collection limit to LIMITS.requests (1024), cap exec.timeoutMs at 3,600,000 ms, wait on exit with unconditional process-group cleanup via shared process-group.ts, and check timedOut before exit.code. - Reject exec blocks on pi/delegated profiles, enforce full directory protection and #! shebang admission for command.v1 scripts, sanitize control characters in rework detail, widen retained lease headroom and safePath whitelist, align SecretScrubber/CredentialVault.scrub patterns, export HandlerCapability, and accept optional docker isolation (refusing host_attested) in benchmark-gate.ts. Signed-off-by: thxCode --- packages/controller/src/acceptance.ts | 1 + packages/controller/src/benchmark-gate.ts | 28 +- .../controller/src/candidate-workspace.ts | 12 +- packages/controller/src/compile.ts | 62 ++- packages/controller/src/controller.ts | 21 +- packages/controller/src/credentials.ts | 5 + packages/controller/src/errors.ts | 2 +- packages/controller/src/exec-role.ts | 143 +++---- packages/controller/src/local-check.ts | 405 ++++++++++++++---- packages/controller/src/parser.ts | 6 +- packages/controller/src/process-group.ts | 56 +++ packages/controller/src/registry.ts | 62 ++- packages/controller/src/retained.ts | 2 +- .../controller/test/benchmark-gate.test.ts | 125 ++++++ packages/controller/test/compile.test.ts | 44 +- .../test/config-local-checks.test.ts | 7 + packages/controller/test/exec-profile.test.ts | 26 +- .../controller/test/exec-role-fixtures.ts | 44 ++ packages/controller/test/exec-role.test.ts | 83 +++- .../test/local-check-integration.test.ts | 80 +++- packages/controller/test/local-check.test.ts | 100 ++++- .../controller/test/recovery-cycle.test.ts | 59 ++- .../test/registry-command-v1.test.ts | 14 +- packages/controller/test/rework.test.ts | 45 ++ packages/core/src/index.ts | 2 +- packages/core/src/scrubber.ts | 14 +- packages/core/test/scrubber.test.ts | 37 +- 27 files changed, 1226 insertions(+), 259 deletions(-) create mode 100644 packages/controller/src/process-group.ts diff --git a/packages/controller/src/acceptance.ts b/packages/controller/src/acceptance.ts index 8c546409..82be18e6 100644 --- a/packages/controller/src/acceptance.ts +++ b/packages/controller/src/acceptance.ts @@ -394,6 +394,7 @@ export function evaluateControllerAcceptance(plan: CompiledPlan, lock: TaskLock, || original.evidence.spec.checkId !== slot.checkId || original.evidence.spec.producerId !== expectedProducer || (impl === 'benchmark-gate.v1' && original.evidence.spec.level !== 'hardware_execution') + || (impl === 'command.v1') !== (original.evidence.spec.level === 'host_execution') || !same(original.planDigest, plan.planDigest) || !same(original.header.handlerDigest, slot.handler.digest) || original.header.handler !== slot.handler.implementation diff --git a/packages/controller/src/benchmark-gate.ts b/packages/controller/src/benchmark-gate.ts index 58beeabf..5cb380c9 100644 --- a/packages/controller/src/benchmark-gate.ts +++ b/packages/controller/src/benchmark-gate.ts @@ -314,6 +314,7 @@ function checkedPrintableAscii(raw: unknown, max: number): string { export function checkedHardwareProvenance(raw: unknown): HardwareProvenance { if (!isRecord(raw)) refuse('ARTIFACT_INVALID', '', 'verification'); const hasTopology = Object.hasOwn(raw, 'topology') && raw.topology !== undefined; + const hasIsolation = Object.hasOwn(raw, 'isolation') && raw.isolation !== undefined; const fields = record(raw, [ 'targetCellId', 'probeKind', @@ -327,6 +328,7 @@ export function checkedHardwareProvenance(raw: unknown): HardwareProvenance { 'workloadDigest', 'clockLockMode', ...(hasTopology ? ['topology' as const] : []), + ...(hasIsolation ? ['isolation' as const] : []), ]); const targetCellId = id(fields.targetCellId); const probeKind = text(fields.probeKind, '', 32); @@ -345,6 +347,13 @@ export function checkedHardwareProvenance(raw: unknown): HardwareProvenance { if (clockLockMode !== 'locked' && clockLockMode !== 'unlocked' && clockLockMode !== 'unknown') { refuse('ARTIFACT_INVALID', '', 'verification'); } + let isolation: 'docker' | 'host_attested' | undefined; + if (hasIsolation) { + if (fields.isolation !== 'docker' && fields.isolation !== 'host_attested') { + refuse('ARTIFACT_INVALID', '', 'verification'); + } + isolation = fields.isolation; + } const out: Record = Object.create(null) as Record; out.targetCellId = targetCellId; out.probeKind = probeKind; @@ -358,6 +367,7 @@ export function checkedHardwareProvenance(raw: unknown): HardwareProvenance { if (topology !== undefined) out.topology = topology; out.workloadDigest = workloadDigest; out.clockLockMode = clockLockMode; + if (isolation !== undefined) out.isolation = isolation; return freeze(out as unknown as HardwareProvenance); } @@ -1524,6 +1534,16 @@ export function isPreemptedBenchmarkVerdict(verdict: BenchmarkVerdict): boolean ); } +function matchesAllowedHardwareProvenance( + targetHardware: HardwareTargetSpec, + targetCellId: string, + allowSyntheticHardwareProbe: boolean, + provenance: HardwareProvenance | undefined, +): boolean { + if (provenance?.isolation === 'host_attested') return false; + return matchesHardwareTarget(targetHardware, targetCellId, allowSyntheticHardwareProbe, provenance); +} + export function shouldPullBenchmarkOutputs(input: { readonly verdict: BenchmarkVerdict | null; readonly wallClockValid: boolean; @@ -1544,7 +1564,7 @@ export function shouldPullBenchmarkOutputs(input: { if (verdict.status === 'denied') { return ( verdict.hardwareProvenance === undefined - || matchesHardwareTarget( + || matchesAllowedHardwareProvenance( input.targetHardware, input.targetCellId, input.allowSyntheticHardwareProbe, @@ -1555,7 +1575,7 @@ export function shouldPullBenchmarkOutputs(input: { if (verdict.status === 'approved') { return ( input.wallClockValid - && matchesHardwareTarget( + && matchesAllowedHardwareProvenance( input.targetHardware, input.targetCellId, input.allowSyntheticHardwareProbe, @@ -1643,7 +1663,7 @@ export function computeBenchmarkDisposition(input: { if (verdict.status === 'denied') { if ( verdict.hardwareProvenance !== undefined - && !matchesHardwareTarget( + && !matchesAllowedHardwareProvenance( input.targetHardware, input.targetCellId, input.allowSyntheticHardwareProbe, @@ -1680,7 +1700,7 @@ export function computeBenchmarkDisposition(input: { return freeze({ status: 'blocked', reason: 'EVIDENCE_UNAVAILABLE', method: 'benchmark-gate.v1', ...preemptionField }); } if ( - !matchesHardwareTarget( + !matchesAllowedHardwareProvenance( input.targetHardware, input.targetCellId, input.allowSyntheticHardwareProbe, diff --git a/packages/controller/src/candidate-workspace.ts b/packages/controller/src/candidate-workspace.ts index 982ce088..e5ec6173 100644 --- a/packages/controller/src/candidate-workspace.ts +++ b/packages/controller/src/candidate-workspace.ts @@ -13,7 +13,7 @@ import { createHash } from 'node:crypto'; import { digestArtifact, digestArtifactFromMetadata, identifyManifest, isWritablePath, type ArtifactManifest, type ArtifactRef, type Digest, type TaskContract } from '@loopwright/core'; import { type DelegatedCaptureOverlayEntryV2 } from './capture.js'; import { approvedState } from './config.js'; -import { roleResourcesFor, Cycle } from './controller.js'; +import { roleResourcesFor, type Cycle } from './controller.js'; import { refuse, type ControllerDiagnostic } from './errors.js'; import { copyVerifiedFileReadOnly, STREAM_CHUNK_BYTES } from './files.js'; import { materializeContextFilesDir } from './handoff.js'; @@ -99,7 +99,7 @@ export async function materializeAttemptWorkspace( await file.close(); } } else { - const canonicalBlobPath = await resolveCanonicalCasBlobPath(artifacts.directory, item.digest.hex, item.blobPath, 'execution'); + const canonicalBlobPath = await resolveCanonicalCasBlobPath(artifacts.directory, item.digest.hex, item.blobPath, phase); await copyVerifiedFileReadOnly(canonicalBlobPath, targetPath, { expectedBytes: item.byteLength, expectedSha256: item.digest.hex, @@ -108,7 +108,7 @@ export async function materializeAttemptWorkspace( requireReadOnlySource: true, verifyCanonicalSource: true, path: item.name, - phase: 'execution', + phase, }); } } @@ -140,7 +140,7 @@ export async function materializeAttemptWorkspace( await file.close(); } } else { - const canonicalBlobPath = await resolveCanonicalCasBlobPath(artifacts.directory, item.digest.hex, item.blobPath, 'execution'); + const canonicalBlobPath = await resolveCanonicalCasBlobPath(artifacts.directory, item.digest.hex, item.blobPath, phase); await copyVerifiedFileReadOnly(canonicalBlobPath, targetPath, { expectedBytes: item.byteLength, expectedSha256: item.digest.hex, @@ -149,13 +149,13 @@ export async function materializeAttemptWorkspace( requireReadOnlySource: true, verifyCanonicalSource: true, path: item.name, - phase: 'execution', + phase, }); } } } - const effectiveResources = activeResources ?? (role === null ? refuse('CONFIG_SCHEMA', '/spec/profiles/roles', phase) : roleResourcesFor(loaded, plan, role.roleId)); + const effectiveResources = activeResources ?? roleResourcesFor(loaded, plan, role!.roleId); const stagedContextFiles = await materializeContextFilesDir( stagingContextDir, effectiveResources, diff --git a/packages/controller/src/compile.ts b/packages/controller/src/compile.ts index 37505e9e..0f5ad305 100644 --- a/packages/controller/src/compile.ts +++ b/packages/controller/src/compile.ts @@ -12,7 +12,7 @@ import type { ControllerOwner } from './ownership.js'; import { freeze, canonical, digestValue, hash, list, same, text, type Json } from './schema.js'; import { refuse, result } from './errors.js'; import { compactionTarget, descendants, reworkSubgraph } from './scheduler.js'; -import { localCheckScriptDirectoryDigest, type LocalCheckRecorded, type LocalCheckScriptEntry } from './local-check.js'; +import { isScriptDirectoryProtected, localCheckScriptDirectoryDigest, type LocalCheckRecorded, type LocalCheckScriptEntry } from './local-check.js'; import { matchesScopePattern, type FrozenSource } from './source.js'; import { CONTROLLER_LIMITS, type CheckpointCapacity, type CompiledPlan, type LoadedConfiguration, type PlannedNode, type PlannedRole, type RuntimeProfile, type StepHandoffSelect, type StepHandoffSelector, type StepHandoffSource, type VerifierSlot } from './types.js'; function cloneHandoffSelector(item: StepHandoffSelector): StepHandoffSelector { @@ -53,29 +53,57 @@ export function recordedLocalCheck(slot: VerifierSlot): LocalCheckRecorded { if (!digest) refuse('RECOVERY_REQUIRED', '', 'verification'); return { scriptDirectoryDigest: digest }; } +interface AdmittedScriptEntry extends LocalCheckScriptEntry { readonly hasShebang: boolean } const scriptPrefix = (script: string): string => { const dir = dirname(script); return dir === '.' ? '' : dir + '/'; }; -/** Every baseline entry under the script directories, without materializing: classic sources hold the bytes, tree-overlay sources stream each blob once. */ -async function entriesUnder(source: FrozenSource, owner: ControllerOwner, prefixes: readonly string[]): Promise> { +/** Every baseline entry under the referenced script directories, without materializing: classic sources hold the bytes, tree-overlay sources stream each blob once. */ +async function entriesUnder(source: FrozenSource, owner: ControllerOwner, prefixes: readonly string[]): Promise> { const under = (name: string) => prefixes.some(prefix => prefix === '' || name.startsWith(prefix)); - const entries = new Map(); + const entries = new Map(); + if (prefixes.length === 0) return entries; if (source.version === 1) { - for (const item of source.artifacts) if (under(item.name)) entries.set(item.name, { path: item.name, mode: item.mode ?? '100644', byteLength: item.bytes.byteLength, sha256: hash(item.bytes).hex }); + for (const item of source.artifacts) { + if (under(item.name)) { + entries.set(item.name, { + path: item.name, + mode: item.mode ?? '100644', + byteLength: item.bytes.byteLength, + sha256: hash(item.bytes).hex, + hasShebang: item.bytes.byteLength >= 2 && item.bytes[0] === 0x23 && item.bytes[1] === 0x21, + }); + } + } return entries; } const names = (source.baselineEntries ?? []).filter(item => under(item.name)); await owner.streamGitBatch(source.directory, names, async (entry, readChunks) => { const digest = createHash('sha256'); - await readChunks(async slice => { digest.update(slice); }); - entries.set(entry.name, { path: entry.name, mode: entry.mode, byteLength: entry.byteLength, sha256: digest.digest('hex') }); + let head0 = -1, head1 = -1; + await readChunks(async slice => { + if (slice.byteLength > 0 && head0 === -1) { + head0 = slice[0]!; + if (slice.byteLength > 1) head1 = slice[1]!; + } else if (slice.byteLength > 0 && head1 === -1) { + head1 = slice[0]!; + } + digest.update(slice); + }); + entries.set(entry.name, { + path: entry.name, + mode: entry.mode, + byteLength: entry.byteLength, + sha256: digest.digest('hex'), + hasShebang: head0 === 0x23 && head1 === 0x21, + }); }, { phase: 'compile' }); return entries; } const baselineNames = (source: FrozenSource): readonly string[] => source.version === 1 ? source.artifacts.map(item => item.name) : (source.baselineEntries ?? []).map(item => item.name); /** The same rules `LocalCheck.#verifyBaseline` applies to the materialized tree, applied to the frozen baseline so the refusal precedes any run. */ -function admitScriptDirectory(entries: ReadonlyMap, names: readonly string[], scope: CompiledPlan['scope'], parameters: Readonly>, path: string): Digest { +function admitScriptDirectory(entries: ReadonlyMap, names: readonly string[], scope: CompiledPlan['scope'], parameters: Readonly>, path: string): Digest { const script = text(parameters.script, path + '/script'), prefix = scriptPrefix(script), directory = [...entries.values()].filter(entry => entry.path.startsWith(prefix)); const executable = directory.find(entry => entry.path === script); - if (!executable || executable.mode !== '100755') refuse('CONFIG_REFERENCE', path + '/script', 'compile'); + if (!executable || executable.mode !== '100755' || !executable.hasShebang) refuse('CONFIG_REFERENCE', path + '/script', 'compile'); + if (!isScriptDirectoryProtected(scope.protected, script)) refuse('CONFIG_SCHEMA', path + '/script', 'compile'); for (const entry of directory) if (!scope.protected.some(pattern => matchesScopePattern(pattern, entry.path))) refuse('CONFIG_SCHEMA', path + '/script', 'compile'); for (const item of list(parameters.toolchainPaths, path + '/toolchainPaths', 32)) { const toolchain = text(item, path + '/toolchainPaths'); @@ -159,8 +187,16 @@ export function compilePlan(loaded: LoadedConfiguration, admission?: SlotAdmissi } } const verifierSlots: VerifierSlot[] = [], networkCredentials: { readonly ref: string; readonly consumer: 'gate' | 'publisher' }[] = []; - // Script directories are read once for every `command.v1` handler the registry holds; a root-level script covers the whole tree. - let scriptEntries: Map | null = null; + // Script directories are read once for the `command.v1` handlers actually referenced by acceptance checks; a root-level script covers the whole tree. + let scriptEntries: Map | null = null; + const referencedCommandPrefixes = [...new Set( + task.spec.acceptance.checks.flatMap(item => { + const matches = registry.handlers.filter(h => h.kind === 'check' && h.parameters.checkId === item.id); + return matches.length === 1 && matches[0]!.implementation === 'command.v1' + ? [scriptPrefix(String(matches[0]!.parameters.script))] + : []; + }), + )]; const networkCredential = (ref: string, consumer: 'gate' | 'publisher', path: string): void => { const binding = registry.credentialBindings.find(item => item.id === ref); if (!binding || binding.consumer !== consumer) refuse('CONFIG_REFERENCE', path, 'compile'); @@ -201,9 +237,9 @@ export function compilePlan(loaded: LoadedConfiguration, admission?: SlotAdmissi // `check` has no repository: the scope rule and the evidence level are static; files resolve at admission only. const handlerPath = '/registry/spec/handlers/' + registry.handlers.indexOf(handler); if (!check.allowedEvidenceLevels.includes('host_execution')) refuse('CONFIG_SCHEMA', '/spec/task/spec/acceptance', 'compile'); - if (!task.spec.scope.protected.some(pattern => matchesScopePattern(pattern, text(handler.parameters.script, handlerPath + '/parameters/script')))) refuse('CONFIG_SCHEMA', handlerPath + '/parameters/script', 'compile'); + if (!isScriptDirectoryProtected(task.spec.scope.protected, text(handler.parameters.script, handlerPath + '/parameters/script'))) refuse('CONFIG_SCHEMA', handlerPath + '/parameters/script', 'compile'); if (admission?.kind === 'baseline') { - if (!scriptEntries) scriptEntries = await entriesUnder(admission.source, admission.owner, registry.handlers.filter(item => item.implementation === 'command.v1').map(item => scriptPrefix(String(item.parameters.script)))); + if (!scriptEntries) scriptEntries = await entriesUnder(admission.source, admission.owner, referencedCommandPrefixes); commandScriptDigest = admitScriptDirectory(scriptEntries, baselineNames(admission.source), task.spec.scope, handler.parameters, handlerPath + '/parameters'); } else if (admission?.kind === 'retained') commandScriptDigest = digestValue(admission.slots.find(item => item.checkId === check.id && item.handler.implementation === 'command.v1')?.scriptDirectoryDigest, handlerPath + '/parameters/script'); } diff --git a/packages/controller/src/controller.ts b/packages/controller/src/controller.ts index 412fbd33..7884f7b7 100644 --- a/packages/controller/src/controller.ts +++ b/packages/controller/src/controller.ts @@ -300,6 +300,22 @@ function extractGateVerdictExcerpt(checked: VerifiedCheck, isBenchmark: boolean) } } +function sanitizeVerdictText(value: string | undefined, allowMultiline = true): string | undefined { + if (value === undefined) return undefined; + let result = ''; + for (let index = 0; index < value.length; index++) { + const code = value.charCodeAt(index); + if (allowMultiline && (code === 9 || code === 10 || code === 13)) { + result += value.charAt(index); + } else if (code <= 31 || (code >= 127 && code <= 159)) { + result += ' '; + } else { + result += value.charAt(index); + } + } + return result.trim().length > 0 ? result : undefined; +} + /** The same bounded view of an authenticated `command.v1` verdict: its check-out `detail` and `findings`, already validated by the contract parser. */ function extractLocalCheckExcerpt(checked: VerifiedCheck): GateVerdictExcerpt { const spec = authenticatedLocalCheck(checked).evidence.spec, findings: RepairFinding[] = []; @@ -697,12 +713,13 @@ export class Cycle { }) : undefined; if (reworkCheckNode?.onRework) { - const detail = (gateSlot || benchmarkSlot) + const rawDetail = (gateSlot || benchmarkSlot) ? extractGateVerdictExcerpt(checked, benchmarkSlot).detail : commandSlot ? extractLocalCheckExcerpt(checked).detail : undefined; - const reasonText = checked.reason ?? 'check_failed'; + const detail = sanitizeVerdictText(rawDetail, true); + const reasonText = sanitizeVerdictText(checked.reason ?? 'check_failed', false) ?? 'check_failed'; const summary = detail ? `Check ${reworkCheckNode.id} (${checked.checkId}) failed: ${reasonText} — ${detail}` : `Check ${reworkCheckNode.id} (${checked.checkId}) failed: ${reasonText}`; diff --git a/packages/controller/src/credentials.ts b/packages/controller/src/credentials.ts index dd097372..0b61ad54 100644 --- a/packages/controller/src/credentials.ts +++ b/packages/controller/src/credentials.ts @@ -1,5 +1,6 @@ import type { PiHost, PiHostV2, AdapterPolicyV2 } from '@loopwright/agent-pi'; import { resolveProviderDestination } from '@loopwright/agent-pi/catalog'; +import { SecretScrubber } from '@loopwright/core'; import { refuse } from './errors.js'; import { STREAM_CHUNK_BYTES } from './files.js'; import { canonical, id, list, record, text } from './schema.js'; @@ -14,6 +15,7 @@ export interface CredentialStreamChecker { export interface CredentialVault { readonly references: readonly string[]; + readonly scrub: (text: string) => string; readonly assertClean: (value: Uint8Array | string | object) => void; readonly createStreamChecker: () => CredentialStreamChecker; /** Gate and publisher signing/auth secrets only; provider and mcp consumers stay behind their bound resolvers. */ @@ -155,8 +157,11 @@ export function createVault(expanded: unknown, registry: TrustedRegistry): Crede tokens.set(ref, token); } const formBuffers = deriveSecretFormBuffers(tokens.values()); + const scrubber = new SecretScrubber(); + for (const token of tokens.values()) scrubber.register(token); return Object.freeze({ references: Object.freeze([...tokens.keys()].sort()), + scrub: (value: string): string => scrubber.scrub(value), assertClean: (value: Uint8Array | string | object): void => { const serialized = value instanceof Uint8Array ? Buffer.from(value.buffer, value.byteOffset, value.byteLength) diff --git a/packages/controller/src/errors.ts b/packages/controller/src/errors.ts index 2a45cdf3..29bfbd55 100644 --- a/packages/controller/src/errors.ts +++ b/packages/controller/src/errors.ts @@ -16,7 +16,7 @@ export type ControllerResult = { readonly ok: true; readonly value: T } | { r export class ControllerFailure extends Error { constructor(readonly diagnostic: ControllerDiagnostic) { super(diagnostic.code); } } -const fields = new Set(('apiVersion kind metadata id name spec registry config task goal taskpack target repository baseRevision sourceRevision matrix platform variant hardware targetCellId metricThresholds allowSyntheticHardwareProbe scope writable protected roles adapter provider model thinking tools trustedContext revision discovery resources path digest algorithm hex budgets wallTimeMs totalTokens perCallOutputTokens maxModelCalls maxConcurrency maxFormatRepairs maxImplementationRepairs maxTransportRetries enforcement wallTime tokens modelCalls concurrency formatRepairs implementationRepairs transportRetries steps uses roleId dependsOn acceptance required checks allowedEvidenceLevels profiles profileRef handlerRef credentials ref template controls drainReserveMs maxAttempts repeatFailureLimit submission mode handlers roleProfiles runtimeProfiles credentialBindings environmentBindings version resourceVersion selection runtimeRef providerCredentialRef mcp names effects idleTimeoutSeconds absoluteTimeoutSeconds transport destinationRef endpoint approvedAddresses credentialRef scriptDigest context estimator proofId evidence workingWindowCeiling maxRequestBytes serviceMargin toolReserve maxOutputTokens identity sdkIntegrity graphDigest imageDigest configDigest profile dockerExecutable dockerSocket consumer environmentNames classification paths parameters capabilities checkId gateId heldOutWorkloadId maxPreemptions prompt purpose implementation publication gate benchmark gateEndpoints publicationEndpoints endpointRef targetBranch headBranchPrefix titleTemplate signingCredentialRef authCredentialRef timeoutMs maxPollMs pollInitialMs pollMaxMs jitter receipt roleModelOverrides gateUrlOverrides leaseToken when handoffs fromStep source select maxBytes heading includeSubheadings pointers changedPaths extensions phases failedChecks failureCodes watchedPaths nodeCandidates activatedResourceIds handoffExtracts host localChecks backend command script env toolchainPaths exec captureBytes credentialRefs').split(' ')); +const fields = new Set(('apiVersion kind metadata id name spec registry config task goal taskpack target repository baseRevision sourceRevision matrix platform variant hardware targetCellId metricThresholds allowSyntheticHardwareProbe scope writable protected roles adapter provider model thinking tools trustedContext revision discovery resources path digest algorithm hex budgets wallTimeMs totalTokens perCallOutputTokens maxModelCalls maxConcurrency maxFormatRepairs maxImplementationRepairs maxTransportRetries enforcement wallTime tokens modelCalls concurrency formatRepairs implementationRepairs transportRetries steps uses roleId dependsOn acceptance required checks allowedEvidenceLevels profiles profileRef handlerRef credentials ref template controls drainReserveMs maxAttempts repeatFailureLimit submission mode handlers roleProfiles runtimeProfiles credentialBindings environmentBindings version resourceVersion selection runtimeRef providerCredentialRef mcp names effects idleTimeoutSeconds absoluteTimeoutSeconds transport destinationRef endpoint approvedAddresses credentialRef scriptDigest context estimator proofId evidence workingWindowCeiling maxRequestBytes serviceMargin toolReserve maxOutputTokens identity sdkIntegrity graphDigest imageDigest configDigest profile dockerExecutable dockerSocket consumer environmentNames classification paths parameters capabilities checkId gateId heldOutWorkloadId maxPreemptions prompt purpose implementation publication gate benchmark gateEndpoints publicationEndpoints endpointRef targetBranch headBranchPrefix titleTemplate signingCredentialRef authCredentialRef timeoutMs maxPollMs pollInitialMs pollMaxMs jitter receipt roleModelOverrides gateUrlOverrides leaseToken when handoffs fromStep source select maxBytes heading includeSubheadings pointers changedPaths extensions phases failedChecks failureCodes watchedPaths nodeCandidates activatedResourceIds handoffExtracts host localChecks backend command script env toolchainPaths exec captureBytes credentialRefs args usageOut requests promptFile candidateDir scratchDir contextFiles').split(' ')); function safePath(path: string): string { const output: string[] = []; for (const segment of path.split('/').slice(1)) { if (!fields.has(segment) && !/^(?:0|[1-9][0-9]{0,2})$/.test(segment)) break; output.push(segment); } diff --git a/packages/controller/src/exec-role.ts b/packages/controller/src/exec-role.ts index 5626afa2..abc58273 100644 --- a/packages/controller/src/exec-role.ts +++ b/packages/controller/src/exec-role.ts @@ -1,11 +1,11 @@ -import { spawn } from 'node:child_process'; -import { constants } from 'node:fs'; -import { lstat, open } from 'node:fs/promises'; -import { isAbsolute } from 'node:path'; -import { EXEC_LIMITS, LIMITS, SecretScrubber } from '@loopwright/core'; +import { spawn, type ChildProcess } from 'node:child_process'; +import { lstat } from 'node:fs/promises'; +import { isAbsolute, resolve } from 'node:path'; +import { EXEC_LIMITS, LIMITS, LOCAL_CHECK_LIMITS, SecretScrubber } from '@loopwright/core'; import { ControllerFailure, refuse, type ControllerDiagnostic } from './errors.js'; -import { inside } from './files.js'; +import { inside, readBoundedFile } from './files.js'; import { parseDocumentBytes } from './parser.js'; +import { confirmProcessGroupGone, drainStream, killProcessGroup } from './process-group.js'; import { id, integer, list, record } from './schema.js'; import type { CredentialBinding, ExecProfileCommand } from './types.js'; @@ -50,7 +50,7 @@ export interface ExecRoleContext { readonly onSpawned?: ((pgid: number) => Promise) | undefined; } -/** One request from the usage file; T7 wraps it as `RequestUsage` with `provenance: 'reported'`. */ +/** One request from the usage file, wrapped by the controller as `RequestUsage` with `provenance: 'reported'`. */ export interface ExecUsageRequest { readonly requestId: string; readonly inputTokens: number; @@ -74,25 +74,22 @@ export interface ExecRoleOutcome { readonly stderrTruncated: boolean; /** Empty when the child was killed: a half-written usage file is not read. */ readonly usage: readonly ExecUsageRequest[]; + /** `true` iff the child exited without timing out and wrote a valid usage file (even `{ "requests": [] }`). */ + readonly usageReported: boolean; } const ALLOWLIST = Object.freeze({ PATH: '/usr/local/bin:/usr/bin:/bin', LANG: 'C.UTF-8', LC_ALL: 'C.UTF-8', TERM: 'dumb' } as const); +export const EXEC_RESERVED_ENV_NAMES: readonly string[] = Object.freeze(['PATH', 'HOME', 'TMPDIR', 'LANG', 'LC_ALL', 'TERM']); const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/; const ENV_ENTRIES_MAX = 32; /** Above the largest legitimate file (1024 requests × ≈150 bytes) and far below `DOCUMENT_BYTES`. */ const USAGE_FILE_MAX_BYTES = 262_144; /** `reason()` in submission.ts bounds the synthesized submission's reason. */ const REASON_MAX_CHARS = 4_096; -const GROUP_EXIT_WAIT_MS = 2_000; -const GROUP_POLL_MS = 15; function refusing(code: ControllerDiagnostic['code'], path: string, work: () => T): T { try { return work(); } catch (error) { if (error instanceof ControllerFailure) refuse(code, path, 'execution'); throw error; } } -function bounded(value: unknown, min: number, max: number, path: string): number { - if (!Number.isSafeInteger(value) || Object.is(value, -0) || (value as number) < min || (value as number) > max) refuse('CONFIG_SCHEMA', path, 'execution'); - return value as number; -} function absolutePath(value: string, path: string): string { if (!isAbsolute(value) || /[\0\r\n]/.test(value)) refuse('CONFIG_SCHEMA', path, 'execution'); return value; @@ -148,22 +145,6 @@ function capture(maxBytes: number): { push: (chunk: Buffer) => void; text: () => }; } -function groupAlive(pgid: number): boolean { - try { process.kill(-pgid, 0); return true; } catch (error) { return (error as NodeJS.ErrnoException).code === 'EPERM'; } -} -function killGroup(pgid: number): void { - try { process.kill(-pgid, 'SIGKILL'); } catch { /* already gone */ } -} -/** `ESRCH` on the group is the only proof of exit; the poll is bounded so a survivor fails closed. */ -async function confirmGroupGone(pgid: number): Promise { - const deadline = performance.now() + GROUP_EXIT_WAIT_MS; - while (groupAlive(pgid)) { - if (performance.now() >= deadline) refuse('CLEANUP_FAILED', '', 'execution'); - killGroup(pgid); - await new Promise(resolve => { setTimeout(resolve, GROUP_POLL_MS); }); - } -} - /** The submission `reason()` printable rule: C0, DEL, and C1 controls become spaces. */ function printable(value: string): string { let result = ''; @@ -178,7 +159,7 @@ function blockedReason(stderr: string): string { } function parseUsage(bytes: Buffer): readonly ExecUsageRequest[] { - const value = record(parseDocumentBytes(bytes, 'json'), ['requests'], '/usageOut'); + const value = record(parseDocumentBytes(bytes, 'json', LIMITS.requests), ['requests'], '/usageOut'); const requests = list(value['requests'], '/usageOut/requests', LIMITS.requests).map((item, index) => { const path = `/usageOut/requests/${index}`; const entry = record(item, ['requestId', 'inputTokens', 'outputTokens', 'costMicrousd'], path); @@ -195,83 +176,101 @@ function parseUsage(bytes: Buffer): readonly ExecUsageRequest[] { } /** Reads `$LOOPWRIGHT_USAGE_OUT` after the child exited on its own; a missing file is no records, anything malformed is refused. */ -async function readUsage(path: string, secrets: SecretResolver): Promise { - let stats: Awaited>; - try { stats = await lstat(path); } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return []; throw error; } - if (!stats.isFile() || stats.nlink !== 1) refuse('ARTIFACT_INVALID', '/usageOut', 'execution'); - if (stats.size > USAGE_FILE_MAX_BYTES) refuse('OUTPUT_LIMIT', '/usageOut', 'execution'); - const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW); +async function readUsage(path: string, secrets: SecretResolver): Promise<{ readonly usage: readonly ExecUsageRequest[]; readonly usageReported: boolean }> { try { - const bytes = Buffer.alloc(Math.min(stats.size, USAGE_FILE_MAX_BYTES) + 1); let size = 0; - while (size < bytes.length) { const { bytesRead } = await file.read(bytes, size, bytes.length - size, size); if (!bytesRead) break; size += bytesRead; } - const content = bytes.subarray(0, size); - if (size > USAGE_FILE_MAX_BYTES) refuse('OUTPUT_LIMIT', '/usageOut', 'execution'); - // A record that reaches the ledger verbatim is refused on a secret, not scrubbed. - secrets.assertClean(content); - return refusing('SUBMISSION_INVALID', '/usageOut', () => parseUsage(content)); - } finally { await file.close(); } + await lstat(path); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { usage: [], usageReported: false }; + refuse('ARTIFACT_INVALID', '/usageOut', 'execution'); + } + let content: Buffer; + try { + content = await readBoundedFile(path, USAGE_FILE_MAX_BYTES, false); + } catch (error) { + if (!(error instanceof ControllerFailure)) throw error; + refuse(error.diagnostic.code === 'CONFIG_LIMIT' ? 'OUTPUT_LIMIT' : 'ARTIFACT_INVALID', '/usageOut', 'execution'); + } + // A record that reaches the ledger verbatim is refused on a secret, not scrubbed. + secrets.assertClean(content); + const usage = refusing('SUBMISSION_INVALID', '/usageOut', () => parseUsage(content)); + return { usage, usageReported: true }; } export async function runExecRole(spec: ExecRoleSpec, context: ExecRoleContext): Promise { if (context.signal.aborted) refuse('CANCELLED', '', 'execution'); const promptFile = absolutePath(context.promptFile, '/promptFile'), candidateDir = absolutePath(context.candidateDir, '/candidateDir'); const scratchDir = absolutePath(context.scratchDir, '/scratchDir'), usageOut = absolutePath(context.usageOut, '/usageOut'); - if (!inside(usageOut, scratchDir)) refuse('CONFIG_SCHEMA', '/usageOut', 'execution'); + if (resolve(scratchDir) !== scratchDir) refuse('CONFIG_SCHEMA', '/scratchDir', 'execution'); + if (resolve(usageOut) !== usageOut || usageOut === scratchDir || !inside(usageOut, scratchDir)) refuse('CONFIG_SCHEMA', '/usageOut', 'execution'); for (const file of context.contextFiles) absolutePath(file, '/contextFiles'); const [program, ...prefix] = spec.exec.command; if (program === undefined || !isAbsolute(program) || /[\0\r\n]/.test(program) || program.endsWith('/')) refuse('CONFIG_SCHEMA', '/exec/command/0', 'execution'); const argv = [...prefix, ...(spec.exec.args ?? []), promptFile, candidateDir]; for (const entry of argv) if (/\0/.test(entry)) refuse('CONFIG_SCHEMA', '/exec/command', 'execution'); - const timeoutMs = bounded(spec.exec.timeoutMs, 1, Number.MAX_SAFE_INTEGER, '/exec/timeoutMs'); - const captureBytes = spec.exec.captureBytes === undefined ? EXEC_LIMITS.captureBytesDefault : bounded(spec.exec.captureBytes, EXEC_LIMITS.captureBytesMin, EXEC_LIMITS.captureBytesMax, '/exec/captureBytes'); + const timeoutMs = refusing('CONFIG_SCHEMA', '/exec/timeoutMs', () => integer(spec.exec.timeoutMs, 1, LOCAL_CHECK_LIMITS.timeoutMsMax, '/exec/timeoutMs')); + const captureBytes = spec.exec.captureBytes === undefined + ? EXEC_LIMITS.captureBytesDefault + : refusing('CONFIG_SCHEMA', '/exec/captureBytes', () => integer(spec.exec.captureBytes, EXEC_LIMITS.captureBytesMin, EXEC_LIMITS.captureBytesMax, '/exec/captureBytes')); const scrubber = new SecretScrubber(); const env = environment(spec, context, scrubber); if (context.signal.aborted) refuse('CANCELLED', '', 'execution'); - // `detached: true` puts the child at the head of its own process group; stdin is `/dev/null`, so the child reads EOF. - const child = spawn(program, argv, { cwd: candidateDir, env, stdio: ['ignore', 'pipe', 'pipe'], detached: true }); + let child: ChildProcess | null = null; + let pgid = 0, timedOut = false, killed = false; + let timer: ReturnType | undefined; + let exited: Promise<{ readonly code: number | null; readonly signal: NodeJS.Signals | null }> | null = null; const stdout = capture(captureBytes), stderr = capture(captureBytes); - child.stdout!.on('data', (part: Buffer) => stdout.push(part)); child.stderr!.on('data', (part: Buffer) => stderr.push(part)); - child.stdout!.on('error', () => undefined); child.stderr!.on('error', () => undefined); - const pgid = child.pid ?? 0; - let timedOut = false, killed = false, grace: ReturnType | undefined; - // Idempotent: the group is signalled once, then the pipes are dropped if a `setsid` escapee still holds them past the grace. const stop = (): void => { if (killed) return; killed = true; - if (pgid <= 0) return; - killGroup(pgid); - grace = setTimeout(() => { child.stdout?.destroy(); child.stderr?.destroy(); }, GROUP_EXIT_WAIT_MS); + if (pgid > 0) killProcessGroup(pgid); }; - const exited = new Promise<{ readonly code: number | null; readonly signal: NodeJS.Signals | null }>((resolve, reject) => { - child.once('close', (code, signal) => resolve({ code, signal })); - child.once('error', reject); - }); - const timer = setTimeout(() => { timedOut = true; stop(); }, timeoutMs); context.signal.addEventListener('abort', stop, { once: true }); - if (context.signal.aborted) stop(); try { - if (pgid > 0 && context.onSpawned) await context.onSpawned(pgid); + // `detached: true` puts the child at the head of its own process group; stdin is `/dev/null`, so the child reads EOF. + child = spawn(program, argv, { cwd: candidateDir, env, stdio: ['ignore', 'pipe', 'pipe'], detached: true }); + child.stdout?.on('error', () => undefined); child.stderr?.on('error', () => undefined); + child.stdout?.on('data', (part: Buffer) => stdout.push(part)); child.stderr?.on('data', (part: Buffer) => stderr.push(part)); + pgid = child.pid ?? 0; + exited = new Promise<{ readonly code: number | null; readonly signal: NodeJS.Signals | null }>((resolveExit, rejectExit) => { + child!.once('exit', (code, signal) => resolveExit({ code, signal })); + child!.once('error', rejectExit); + }); + if (pgid <= 0) { + await exited; + refuse('CONFIG_REFERENCE', '/exec/command/0', 'execution'); + } + timer = setTimeout(() => { timedOut = true; stop(); }, timeoutMs); + timer.unref(); + if (context.signal.aborted) stop(); + if (context.onSpawned) await context.onSpawned(pgid); const exit = await exited; - if (killed && pgid > 0) await confirmGroupGone(pgid); + clearTimeout(timer); + await confirmProcessGroupGone(pgid, 'execution'); + await Promise.all([drainStream(child.stdout), drainStream(child.stderr)]); if (context.signal.aborted) refuse('CANCELLED', '', 'execution'); const clean = (captured: string): string => { const scrubbed = scrubber.scrub(captured); context.secrets.assertClean(scrubbed); return scrubbed; }; // shortcut: truncation may cut a secret longer than `captureBytes`; scrubber and assertion see only the captured bytes, as `artifacts.put` would. const out = clean(stdout.text()), err = clean(stderr.text()); - const usage = timedOut ? [] : await readUsage(usageOut, context.secrets); - const status = exit.code === 0 ? 'completed' : exit.code === 3 ? 'blocked' : 'failed'; + const { usage, usageReported } = timedOut ? { usage: [] as readonly ExecUsageRequest[], usageReported: false } : await readUsage(usageOut, context.secrets); + const status = timedOut ? 'failed' : exit.code === 0 ? 'completed' : exit.code === 3 ? 'blocked' : 'failed'; const reason = timedOut ? 'exec_timeout' : status === 'completed' ? null : status === 'blocked' ? blockedReason(err) : exit.code === null ? `exec_signal_${exit.signal}` : `exec_exit_${exit.code}`; - return { status, reason, exitCode: exit.code, exitSignal: exit.signal, timedOut, pgid, stdout: out, stderr: err, stdoutTruncated: stdout.truncated, stderrTruncated: stderr.truncated, usage }; + return { status, reason, exitCode: exit.code, exitSignal: exit.signal, timedOut, pgid, stdout: out, stderr: err, stdoutTruncated: stdout.truncated, stderrTruncated: stderr.truncated, usage, usageReported }; } catch (error) { - stop(); await exited.catch(() => undefined); - if (pgid > 0) await confirmGroupGone(pgid); + stop(); + if (exited) await exited.catch(() => undefined); + if (pgid > 0 && !(error instanceof ControllerFailure && error.diagnostic.code === 'CLEANUP_FAILED')) { + await confirmProcessGroupGone(pgid, 'execution'); + } if (error instanceof ControllerFailure || pgid > 0) throw error; - refuse('CONFIG_REFERENCE', '/exec/command/0', 'execution'); + return refuse('CONFIG_REFERENCE', '/exec/command/0', 'execution'); } finally { - clearTimeout(timer); clearTimeout(grace); + clearTimeout(timer); context.signal.removeEventListener('abort', stop); + child?.stdout?.destroy(); + child?.stderr?.destroy(); } } diff --git a/packages/controller/src/local-check.ts b/packages/controller/src/local-check.ts index 676e2215..3b36c62a 100644 --- a/packages/controller/src/local-check.ts +++ b/packages/controller/src/local-check.ts @@ -1,10 +1,9 @@ import { constants } from 'node:fs'; -import { chmod, lstat, mkdir, open, readdir, readFile, rm } from 'node:fs/promises'; +import { chmod, lstat, mkdir, open, readdir, rm } from 'node:fs/promises'; import { spawn, type ChildProcess } from 'node:child_process'; import { dirname, join } from 'node:path'; -import type { Readable } from 'node:stream'; import { - LOCAL_CHECK_ENV_FIXED, LOCAL_CHECK_ENV_NAMES, LOCAL_CHECK_LIMITS, LOCAL_CHECK_PATH_BASE, SecretScrubber, bindSubject, digestArtifact, + LOCAL_CHECK_ENV_FIXED, LOCAL_CHECK_ENV_NAMES, LOCAL_CHECK_LIMITS, LOCAL_CHECK_PATH_BASE, bindSubject, digestArtifact, isLocalCheckEnvName, parseLocalCheckOut, validateDocument, type ArtifactRef, type Digest, type Evidence, type LocalCheckOutput, type LocalCheckSpec, type Subject, type TaskLock, } from '@loopwright/core'; @@ -15,6 +14,7 @@ import { approvedState } from './config.js'; import { ControllerFailure, refuse, type ControllerDiagnostic } from './errors.js'; import { readBoundedFile } from './files.js'; import { parsePrivateJson } from './parser.js'; +import { confirmProcessGroupGone, drainStream, killProcessGroup } from './process-group.js'; import { verifierOperationId } from './progress.js'; import { effectiveRunHostPolicy, hostProtectionFromPolicy } from './retained.js'; import { canonical, checkedRef, freeze, hash, id, integer, isRecord, list, record, same, text } from './schema.js'; @@ -34,8 +34,6 @@ export const LOCAL_CHECK_METHOD = 'direct_script'; export const LOCAL_CHECK_OUTPUT_BYTES = 262_144; export const LOCAL_CHECK_STDERR_BYTES = 16_384; const MARKER_BYTES = 1_048_576; -const GROUP_EXIT_WAIT_MS = 2_000; -const STDERR_DRAIN_MS = 500; const FILE_BYTES = 67_108_864; const SHEBANG = Buffer.from('#!'); const PARAMETER_KEYS = ['checkId', 'script', 'args', 'env', 'toolchainPaths', 'timeoutMs'] as const; @@ -48,7 +46,7 @@ export interface LocalCheckScriptEntry { readonly path: string; readonly mode: ' interface Preparation { readonly slot: VerifierSlot; readonly spec: LocalCheckSpec; readonly recorded: LocalCheckRecorded; readonly subject: Subject; readonly candidateDigest: Digest; readonly candidateBytes: number } const preparations = new WeakMap(); -/** The receipt artifact: the store's `OperationReceipt` plus what F1 requires every `command.v1` receipt to carry. */ +/** The receipt artifact: the store's `OperationReceipt` plus the script and digest fields every `command.v1` receipt carries. */ export interface LocalCheckReceipt extends OperationReceipt { readonly script: string; /** `null` only when the operation settled without a binding marker, that is, when the script never provably ran. */ @@ -92,25 +90,80 @@ export function authenticatedLocalCheck(value: VerifiedCheck): LocalCheckObserva /** Where attempt workspaces live; the live cycle is required to execute a check and is absent on recovery, which only settles. */ export interface LocalCheckWorkspace { readonly runRoot: string; readonly cycle: Cycle | null } -/** Pure digest over a script directory's entries; admission (T4) and the run-time re-verification call the same function. */ +/** True iff some recursive pattern in `scope.protected` covers every possible path inside `script`'s parent directory. */ +export function isScriptDirectoryProtected(protectedPatterns: readonly string[], script: string): boolean { + const dir = dirname(script); + const dirSegments = dir === '.' ? [] : dir.split('/'); + return protectedPatterns.some(pattern => { + if (pattern === '**') return true; + if (!pattern.endsWith('/**')) return false; + const prefixSegments = pattern.slice(0, -3).split('/'); + for (let index = 0; index < prefixSegments.length; index++) { + const seg = prefixSegments[index]!; + if (index < dirSegments.length) { + if (!matchesScopePattern(seg, dirSegments[index]!)) return false; + } else if (!/^\*+$/.test(seg)) { + return false; + } + } + return true; + }); +} + +/** Pure digest over a script directory's entries; baseline admission and run-time re-verification call the same function. */ export function localCheckScriptDirectoryDigest(entries: readonly LocalCheckScriptEntry[]): Digest { const sorted = [...entries].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0)) .map(entry => ({ path: entry.path, mode: entry.mode, byteLength: entry.byteLength, sha256: entry.sha256 })); return hash('loopwright.dev/controller/local-check-script-directory/v1\0' + canonical(sorted)); } +async function readRegularFileNoFollow(absPath: string, maxBytes: number): Promise<{ readonly bytes: Buffer; readonly mode: '100644' | '100755' }> { + const before = await lstat(absPath); + if (before.isSymbolicLink() || !before.isFile()) refuse('ARTIFACT_INVALID', '', 'verification'); + if (before.size > maxBytes) refuse('OUTPUT_LIMIT', '', 'verification'); + let file: Awaited>; + try { file = await open(absPath, constants.O_RDONLY | constants.O_NOFOLLOW); } + catch { refuse('ARTIFACT_INVALID', '', 'verification'); } + try { + const info = await file.stat(); + if (!info.isFile() || info.dev !== before.dev || info.ino !== before.ino || info.size !== before.size) refuse('ARTIFACT_INVALID', '', 'verification'); + if (info.size > maxBytes) refuse('OUTPUT_LIMIT', '', 'verification'); + const buf = Buffer.allocUnsafe(info.size + 1); + let size = 0; + while (size < buf.byteLength) { + const { bytesRead } = await file.read(buf, size, buf.byteLength - size, size); + if (!bytesRead) break; + size += bytesRead; + } + if (size !== info.size) refuse('ARTIFACT_INVALID', '', 'verification'); + return { bytes: buf.subarray(0, size), mode: (info.mode & 0o111) !== 0 ? '100755' : '100644' }; + } finally { + await file.close(); + } +} + /** Reads the script directory (the whole tree under the script's parent) from a materialized baseline. */ export async function readLocalCheckScriptDirectory(baselineDir: string, script: string): Promise { - const dir = dirname(script) === '.' ? '' : dirname(script), root = dir ? join(baselineDir, dir) : baselineDir, entries: LocalCheckScriptEntry[] = []; + const dir = dirname(script) === '.' ? '' : dirname(script), entries: LocalCheckScriptEntry[] = []; + let root = baselineDir; + if (dir) { + for (const seg of dir.split('/')) { + root = join(root, seg); + const stat = await lstat(root).catch(error => { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') refuse('CONFIG_REFERENCE', HANDLERS_PATH, 'verification'); + throw error; + }); + if (stat.isSymbolicLink() || !stat.isDirectory()) refuse('ARTIFACT_INVALID', '', 'verification'); + } + } const visit = async (abs: string, rel: string): Promise => { for (const item of (await readdir(abs, { withFileTypes: true })).sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))) { const absPath = join(abs, item.name), relPath = rel ? rel + '/' + item.name : item.name, info = await lstat(absPath); if (info.isSymbolicLink()) refuse('ARTIFACT_INVALID', '', 'verification'); if (info.isDirectory()) { await visit(absPath, relPath); continue; } if (!info.isFile()) refuse('ARTIFACT_INVALID', '', 'verification'); - const bytes = await readFile(absPath); - if (bytes.byteLength > FILE_BYTES) refuse('OUTPUT_LIMIT', '', 'verification'); - entries.push({ path: relPath, mode: (info.mode & 0o111) !== 0 ? '100755' : '100644', byteLength: bytes.byteLength, sha256: hash(bytes).hex }); + const { bytes, mode } = await readRegularFileNoFollow(absPath, FILE_BYTES); + entries.push({ path: relPath, mode, byteLength: bytes.byteLength, sha256: hash(bytes).hex }); } }; await visit(root, dir); @@ -151,27 +204,48 @@ export function prepareLocalCheck(plan: CompiledPlan, lock: TaskLock, slotId: st preparations.set(value, { slot, spec, recorded: { scriptDirectoryDigest }, subject: subject.value, candidateDigest: hash(canonical(candidate.manifest)), candidateBytes: Buffer.byteLength(canonical(candidate.manifest)) }); return value; } -function killProcessGroup(pgid: number): void { try { process.kill(-pgid, 'SIGKILL'); } catch { /* the exact exit is confirmed below */ } } -function processGroupAlive(pgid: number): boolean { - try { process.kill(-pgid, 0); return true; } catch (error) { return (error as NodeJS.ErrnoException).code === 'EPERM'; } -} -/** SIGKILL the group until `kill(-pgid, 0)` reports ESRCH; a group that survives is a cleanup failure, never a success. */ -async function confirmProcessGroupGone(pgid: number, phase: ControllerDiagnostic['phase']): Promise { - const deadline = performance.now() + GROUP_EXIT_WAIT_MS; - while (processGroupAlive(pgid)) { - if (performance.now() > deadline) refuse('CLEANUP_FAILED', '', phase); - killProcessGroup(pgid); - await new Promise(resolve => { const timer = setTimeout(resolve, 15); timer.unref(); }); - } +interface RollingTail { + readonly push: (part: Buffer) => void; + readonly text: () => string; + readonly truncated: boolean; } -/** After the group is gone every writer is dead; give the pipe a moment to reach EOF, then release it. */ -function drain(stream: Readable): Promise { - if (stream.readableEnded || stream.destroyed) return Promise.resolve(); - return new Promise(resolve => { - const timer = setTimeout(() => { stream.destroy(); resolve(); }, STDERR_DRAIN_MS); timer.unref(); - stream.once('end', () => { clearTimeout(timer); resolve(); }); stream.once('close', () => { clearTimeout(timer); resolve(); }); - }); +function createRollingTail(maxBytes: number): RollingTail { + let buf: Buffer | null = null, start = 0, len = 0, truncated = false; + return { + push: (part: Buffer): void => { + if (part.byteLength === 0) return; + buf ??= Buffer.allocUnsafe(maxBytes); + if (part.byteLength >= maxBytes) { + if (len > 0 || part.byteLength > maxBytes) truncated = true; + part.copy(buf, 0, part.byteLength - maxBytes, part.byteLength); + start = 0; + len = maxBytes; + return; + } + if (len + part.byteLength > maxBytes) { + truncated = true; + const drop = len + part.byteLength - maxBytes; + start = (start + drop) % maxBytes; + len -= drop; + } + const writePos = (start + len) % maxBytes; + const first = Math.min(part.byteLength, maxBytes - writePos); + part.copy(buf, writePos, 0, first); + if (first < part.byteLength) part.copy(buf, 0, first, part.byteLength); + len += part.byteLength; + }, + text: (): string => { + if (!buf || len === 0) return ''; + if (start + len <= maxBytes) return buf.subarray(start, start + len).toString('utf8'); + const out = Buffer.allocUnsafe(len), first = maxBytes - start; + buf.copy(out, 0, start, maxBytes); + buf.copy(out, first, 0, len - first); + return out.toString('utf8'); + }, + get truncated(): boolean { return truncated; }, + }; } + /** Directories of a read-only tree refuse `rm`; restore owner write on every directory, never following links. A tree that vanishes mid-walk was discarded by someone else. */ async function removeTree(root: string, phase: ControllerDiagnostic['phase']): Promise { const missing = (error: unknown) => (error as NodeJS.ErrnoException).code === 'ENOENT'; @@ -188,6 +262,7 @@ async function removeTree(root: string, phase: ControllerDiagnostic['phase']): P async function makeReadOnlyTree(root: string): Promise { const visit = async (abs: string): Promise => { const info = await lstat(abs); + if (info.isSymbolicLink()) refuse('ARTIFACT_INVALID', '', 'verification'); if (info.isDirectory()) { await chmod(abs, 0o500); for (const name of await readdir(abs)) await visit(join(abs, name)); return; } await chmod(abs, (info.mode & 0o111) !== 0 ? 0o500 : 0o400); }; @@ -199,6 +274,9 @@ export class LocalCheck { constructor(readonly store: LocalRunStore, readonly authority: Authority, readonly artifacts: ArtifactStore, readonly plan: CompiledPlan, readonly lock: TaskLock, readonly currentSubject: () => Subject, readonly workspace: LocalCheckWorkspace) {} + #stopCode(): 'DEADLINE' | 'CANCELLED' { + return this.workspace.cycle?.deadline.reason === 'DEADLINE' ? 'DEADLINE' : 'CANCELLED'; + } #identity(): RunView { const view = stateValue(this.store.inspect()); if (view.storeId !== this.authority.storeId || view.runId !== this.lock.spec.runId || !same(view.lockHash, this.lock.spec.lockHash) @@ -227,41 +305,84 @@ export class LocalCheck { /** Candidate through the shared workspace helper (writable, every trusted resource staged), a read-only baseline, and a scratch directory. */ async #materialize(cycle: Cycle, job: PreparedLocalCheck, signal: AbortSignal): Promise { const { context } = cycle, attemptDir = this.#attemptDir(job), source = context.source; - const { candidateDir } = await materializeAttemptWorkspace(cycle, this.workspace.runRoot, this.#attemptId(job), null, 'none', - hostProtectionFromPolicy(effectiveRunHostPolicy(context.descriptor)), approvedState(context.loaded).resources, [], 'verification'); - const stagedDir = join(attemptDir, 'context'), baselineDir = join(attemptDir, 'baseline'), scratchDir = join(attemptDir, 'scratch'); - await mkdir(scratchDir, { mode: 0o700 }); - if (source.version === 2) await materializeBaseline(source, baselineDir, this.artifacts.owner, signal); - else { - await mkdir(baselineDir, { mode: 0o700 }); - for (const item of source.artifacts) { - const target = join(baselineDir, item.name), perm = (item.mode ?? '100644') === '100755' ? 0o500 : 0o400; - await mkdir(dirname(target), { recursive: true, mode: 0o700 }); - const file = await open(target, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, perm); - try { await file.writeFile(item.bytes); await file.chmod(perm); await file.sync(); } finally { await file.close(); } + if (signal.aborted) refuse(this.#stopCode(), '', 'verification'); + try { + const { candidateDir } = await materializeAttemptWorkspace(cycle, this.workspace.runRoot, this.#attemptId(job), null, 'none', + hostProtectionFromPolicy(effectiveRunHostPolicy(context.descriptor)), approvedState(context.loaded).resources, [], 'verification'); + const stagedDir = join(attemptDir, 'context'), baselineDir = join(attemptDir, 'baseline'), scratchDir = join(attemptDir, 'scratch'); + await mkdir(scratchDir, { mode: 0o700 }); + if (signal.aborted) refuse(this.#stopCode(), '', 'verification'); + if (source.version === 2) { + try { await materializeBaseline(source, baselineDir, this.artifacts.owner, signal); } + catch (error) { + if (error instanceof ControllerFailure && error.diagnostic.code === 'CANCELLED' && this.#stopCode() === 'DEADLINE') refuse('DEADLINE', '', 'verification'); + throw error; + } + } else { + await mkdir(baselineDir, { mode: 0o700 }); + for (const item of source.artifacts) { + const target = join(baselineDir, item.name), perm = (item.mode ?? '100644') === '100755' ? 0o500 : 0o400; + await mkdir(dirname(target), { recursive: true, mode: 0o700 }); + const file = await open(target, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, perm); + try { await file.writeFile(item.bytes); await file.chmod(perm); await file.sync(); } finally { await file.close(); } + } } + // shortcut: a version 2 source materializes the baseline twice per check (candidate copy and BASE_DIR); revisit if large trees make it slow. + await makeReadOnlyTree(baselineDir); + return { attemptDir, candidateDir, stagedDir, baselineDir, scratchDir, checkOut: join(scratchDir, 'check-out.json') }; + } catch (error) { + await removeTree(attemptDir, 'verification'); + throw error; } - // shortcut: a version 2 source materializes the baseline twice per check (candidate copy and BASE_DIR); revisit if large trees make it slow. - await makeReadOnlyTree(baselineDir); - return { attemptDir, candidateDir, stagedDir, baselineDir, scratchDir, checkOut: join(scratchDir, 'check-out.json') }; } /** Everything the baseline must satisfy, checked on the tree the child will see, before any intent is recorded. */ async #verifyBaseline(data: Preparation, baselineDir: string): Promise<{ readonly scriptAbs: string; readonly scriptDigest: Digest }> { - const spec = data.spec, scriptAbs = join(baselineDir, spec.script), info = await lstat(scriptAbs).catch(() => null); - if (!info || !info.isFile() || (info.mode & 0o111) === 0) refuse('CONFIG_REFERENCE', HANDLERS_PATH, 'verification'); - const scriptBytes = await readFile(scriptAbs); - if (scriptBytes.byteLength > FILE_BYTES) refuse('OUTPUT_LIMIT', '', 'verification'); + const spec = data.spec, scriptAbs = join(baselineDir, spec.script); + const dir = dirname(spec.script) === '.' ? '' : dirname(spec.script); + if (dir) { + let cur = baselineDir; + for (const seg of dir.split('/')) { + cur = join(cur, seg); + const st = await lstat(cur).catch(() => null); + if (!st) refuse('CONFIG_REFERENCE', HANDLERS_PATH, 'verification'); + if (st.isSymbolicLink()) refuse('ARTIFACT_INVALID', '', 'verification'); + if (!st.isDirectory()) refuse('CONFIG_REFERENCE', HANDLERS_PATH, 'verification'); + } + } + const info = await lstat(scriptAbs).catch(() => null); + if (!info) refuse('CONFIG_REFERENCE', HANDLERS_PATH, 'verification'); + if (info.isSymbolicLink()) refuse('ARTIFACT_INVALID', '', 'verification'); + if (!info.isFile() || (info.mode & 0o111) === 0) refuse('CONFIG_REFERENCE', HANDLERS_PATH, 'verification'); + if (info.size > FILE_BYTES) refuse('OUTPUT_LIMIT', '', 'verification'); // A script without a shebang cannot be exec'd by the spawner (ENOEXEC), so it is refused like a missing executable. - if (!scriptBytes.subarray(0, 2).equals(SHEBANG)) refuse('CONFIG_REFERENCE', HANDLERS_PATH, 'verification'); + let scriptHandle: Awaited>; + try { scriptHandle = await open(scriptAbs, constants.O_RDONLY | constants.O_NOFOLLOW); } + catch { refuse('ARTIFACT_INVALID', '', 'verification'); } + try { + const fstat = await scriptHandle.stat(); + if (!fstat.isFile() || fstat.dev !== info.dev || fstat.ino !== info.ino || fstat.size !== info.size) refuse('ARTIFACT_INVALID', '', 'verification'); + const head = Buffer.allocUnsafe(2); + const { bytesRead } = await scriptHandle.read(head, 0, 2, 0); + if (bytesRead < 2 || !head.equals(SHEBANG)) refuse('CONFIG_REFERENCE', HANDLERS_PATH, 'verification'); + } finally { + await scriptHandle.close(); + } const entries = await readLocalCheckScriptDirectory(baselineDir, spec.script); + const scriptEntry = entries.find(entry => entry.path === spec.script); + if (!scriptEntry || scriptEntry.mode !== '100755') refuse('CONFIG_REFERENCE', HANDLERS_PATH, 'verification'); if (!same(localCheckScriptDirectoryDigest(entries), data.recorded.scriptDirectoryDigest)) refuse('CONFIG_REFERENCE', HANDLERS_PATH, 'verification'); + if (!isScriptDirectoryProtected(this.plan.scope.protected, spec.script)) refuse('CONFIG_SCHEMA', HANDLERS_PATH, 'verification'); for (const entry of entries) if (!this.plan.scope.protected.some(pattern => matchesScopePattern(pattern, entry.path))) refuse('CONFIG_SCHEMA', HANDLERS_PATH, 'verification'); for (const path of spec.toolchainPaths) { - const stat = await lstat(join(baselineDir, path)).catch(() => null); - if (!stat || stat.isSymbolicLink() || !stat.isDirectory()) refuse('CONFIG_REFERENCE', HANDLERS_PATH, 'verification'); + let cur = baselineDir; + for (const seg of path.split('/')) { + cur = join(cur, seg); + const stat = await lstat(cur).catch(() => null); + if (!stat || stat.isSymbolicLink() || !stat.isDirectory()) refuse('CONFIG_REFERENCE', HANDLERS_PATH, 'verification'); + } } - return { scriptAbs, scriptDigest: hash(scriptBytes) }; + return { scriptAbs, scriptDigest: { algorithm: 'sha256', hex: scriptEntry.sha256 } }; } /** Allowlisted environment only: the controller never reads or passes its own `process.env`. */ @@ -277,16 +398,15 @@ export class LocalCheck { }; } - async #runChild(child: ChildProcess, pgid: number, timeoutMs: number, signal: AbortSignal): Promise<{ readonly exitCode: number | null; readonly exitSignal: string | null; readonly timedOut: boolean; readonly elapsedMs: number; readonly stderrTail: string; readonly stderrTruncated: boolean }> { - let chunks: Buffer[] = [], buffered = 0, truncated = false; - child.stderr!.on('data', (part: Buffer) => { - if (buffered + part.byteLength > LOCAL_CHECK_STDERR_BYTES) truncated = true; - chunks.push(part); buffered += part.byteLength; - if (chunks.length >= 64) chunks = [Buffer.concat(chunks)]; - }); - const exited = new Promise<{ readonly code: number | null; readonly signal: string | null }>(resolve => { - child.once('exit', (code, signal) => resolve({ code, signal })); child.once('error', () => resolve({ code: null, signal: null })); - }); + async #runChild( + child: ChildProcess, + pgid: number, + exited: Promise<{ readonly code: number | null; readonly signal: string | null }>, + stderr: RollingTail, + timeoutMs: number, + signal: AbortSignal, + onGroupCleaned: () => void, + ): Promise<{ readonly exitCode: number | null; readonly exitSignal: string | null; readonly timedOut: boolean; readonly elapsedMs: number; readonly stderrTail: string; readonly stderrTruncated: boolean }> { const stop = () => killProcessGroup(pgid), started = performance.now(); let timedOut = false; const timer = setTimeout(() => { timedOut = true; stop(); }, timeoutMs); timer.unref(); @@ -294,19 +414,24 @@ export class LocalCheck { try { // The script's own exit decides the verdict; whatever it left behind in the group is killed before the capture. const exit = await exited; + clearTimeout(timer); await confirmProcessGroupGone(pgid, 'verification'); - await drain(child.stderr!); - const bytes = Buffer.concat(chunks); - return { exitCode: exit.code, exitSignal: exit.signal, timedOut, elapsedMs: Math.ceil(performance.now() - started), stderrTail: bytes.subarray(Math.max(0, bytes.byteLength - LOCAL_CHECK_STDERR_BYTES)).toString('utf8'), stderrTruncated: truncated }; + onGroupCleaned(); + await drainStream(child.stderr); + return { exitCode: exit.code, exitSignal: exit.signal, timedOut, elapsedMs: Math.ceil(performance.now() - started), stderrTail: stderr.text(), stderrTruncated: stderr.truncated }; } finally { // Release the pipe even when refusing: an escaped process that still holds it must not keep the controller alive. - clearTimeout(timer); signal.removeEventListener('abort', stop); child.stderr!.destroy(); + clearTimeout(timer); signal.removeEventListener('abort', stop); child.stderr?.destroy(); } } /** `$LOOPWRIGHT_CHECK_OUT` is the only output file read: bounded, vault-checked, strictly parsed. */ async #readOutput(path: string): Promise<{ readonly output: LocalCheckOutput | null; readonly outputError: OutputError | null }> { - if (!(await lstat(path).then(() => true, () => false))) return { output: null, outputError: null }; + try { await lstat(path); } + catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { output: null, outputError: null }; + throw error; + } let bytes: Buffer; try { bytes = await readBoundedFile(path, LOCAL_CHECK_LIMITS.checkOutBytes, false); } catch (error) { @@ -319,7 +444,8 @@ export class LocalCheck { return { output: parsed.value, outputError: null }; } - #disposition(observation: Pick): Disposition { + #disposition(observation: Pick): Disposition { + if (observation.transport === 'interrupted') return { status: 'blocked', reason: 'EVIDENCE_UNAVAILABLE', method: LOCAL_CHECK_METHOD }; if (observation.timedOut) return { status: 'failed', reason: 'check_timeout', method: LOCAL_CHECK_METHOD }; // An unusable check-out is the script's contract violation, not the candidate's: block for the operator instead of reworking the author. if (observation.outputError !== null) return { status: 'blocked', reason: 'EVIDENCE_UNAVAILABLE', method: LOCAL_CHECK_METHOD }; @@ -357,16 +483,30 @@ export class LocalCheck { async run(job: PreparedLocalCheck, signal: AbortSignal): Promise { const data = preparations.get(job); if (!data || this.plan.verifierSlots.find(slot => slot.id === job.slotId) !== data.slot) refuse('EVIDENCE_UNAVAILABLE', '', 'verification'); const cycle = this.workspace.cycle; if (!cycle) refuse('CAPABILITY_UNSUPPORTED', '', 'verification'); - if (signal.aborted) refuse('CANCELLED', '', 'verification'); + if (signal.aborted) refuse(this.#stopCode(), '', 'verification'); await this.artifacts.owner.assertCurrent(); if (!same(this.currentSubject(), data.subject)) refuse('ARTIFACT_INVALID', '', 'verification'); const done = await this.artifacts.owner.holdLocalActivity(); + let groupClean = true, workspacePresent = false; try { const target = this.#target(job, data.subject), before = this.#identity(); if (before.owner.mode !== 'active') refuse('AUTHORITY_REFUSED', '', 'verification'); if (before.counts.dispatchedRequests || before.counts.unresolvedRequests || before.counts.unresolvedOperations || before.ledger.violations.length) refuse('RECOVERY_REQUIRED', '', 'verification'); - const workspace = await this.#materialize(cycle, job, signal); + workspacePresent = true; + let workspace: Workspace; + try { + workspace = await this.#materialize(cycle, job, signal); + } catch (error) { + if (!(error instanceof ControllerFailure && error.diagnostic.code === 'CLEANUP_FAILED')) workspacePresent = false; + throw error; + } let executed: Execution; - try { executed = await this.#execute(job, data, workspace, target, signal); } - finally { await removeTree(workspace.attemptDir, 'verification'); } + try { + executed = await this.#execute(job, data, workspace, target, signal, () => { groupClean = false; }, () => { groupClean = true; }); + } finally { + if (groupClean) { + await removeTree(workspace.attemptDir, 'verification'); + workspacePresent = false; + } + } const { intentDigest, permit, binding, observation, scriptDigest } = executed, view = stateValue(this.store.inspect()), disposition = this.#disposition(observation); const output = await this.artifacts.json('local-check-output', { version: 1, binding, observation, disposition }, LOCAL_CHECK_OUTPUT_BYTES); const evidence = this.#evidence(job, data, disposition, observation, output, 'verification'); @@ -375,12 +515,48 @@ export class LocalCheck { await this.#marker(job.operationId, job.producerNonce, 'proof', { version: 1, output, receipt: receiptRef, evidence }); this.#permit(permit, data.subject, target); stateValue(this.store.recordOperationReceipt(this.authority, job.operationId, receipt)); return await this.#attest(job, data, disposition, output, receiptRef, evidence, receipt, record, binding.pgid); - } finally { done(); } + } finally { + if (groupClean && !workspacePresent) done(); + } + } + + async #settleAbortedDispatch(job: PreparedLocalCheck, data: Preparation, binding: Binding, intentDigest: Digest): Promise { + const inspected = this.store.inspect(); + if ( + !inspected.ok + || inspected.value.clockStatus !== 'trusted' + || inspected.value.owner.mode !== 'active' + || inspected.value.owner.ownerId !== this.authority.ownerId + || inspected.value.owner.generation !== this.authority.generation + ) { + refuse('AUTHORITY_REFUSED', '', 'verification'); + } + await this.artifacts.owner.assertCurrent(); + if (!same(this.currentSubject(), data.subject)) refuse('AUTHORITY_REFUSED', '', 'verification'); + stateValue(this.store.renew(this.authority)); + const view = stateValue(this.store.inspect()); + const disposition: Disposition = { status: 'blocked', reason: 'EVIDENCE_UNAVAILABLE', method: LOCAL_CHECK_METHOD }; + const observation: Observation = { transport: 'interrupted', exitCode: null, exitSignal: null, timedOut: false, elapsedMs: 0, output: null, outputError: null, stderrTail: '', stderrTruncated: false }; + const output = await this.artifacts.json('local-check-output', { version: 1, binding, observation, disposition }, LOCAL_CHECK_OUTPUT_BYTES); + const evidence = this.#evidence(job, data, disposition, observation, output, 'verification'); + const { receipt, record } = this.#receipt(job, data, disposition, view, intentDigest, binding.dispatchReceipt, output, binding.scriptDigest); + const receiptRef = await this.artifacts.json('local-check-receipt', record, 65536); + await this.#marker(job.operationId, job.producerNonce, 'proof', { version: 1, output, receipt: receiptRef, evidence }); + stateValue(this.store.recordOperationReceipt(this.authority, job.operationId, receipt)); } /** Intent, permit, binding marker with the process group, execution, capture. Refusals here leave no proof; recovery settles them. */ - async #execute(job: PreparedLocalCheck, data: Preparation, workspace: Workspace, target: string, signal: AbortSignal): Promise { + async #execute( + job: PreparedLocalCheck, + data: Preparation, + workspace: Workspace, + target: string, + signal: AbortSignal, + onGroupSpawned: () => void, + onGroupCleaned: () => void, + ): Promise { const { scriptAbs, scriptDigest } = await this.#verifyBaseline(data, workspace.baselineDir); + if (signal.aborted) refuse(this.#stopCode(), '', 'verification'); this.#identity(); const attemptId = this.#attemptId(job); stateValue(this.store.putIntent(this.authority, { operationId: job.operationId, nodeId: this.plan.orderedDAG[0]!.id, attemptId, effect: 'read_only', requestDigest: job.requestDigest, targetIdentity: target })); const dispatched = stateValue(this.store.authorizeOperationDispatch(this.authority, job.operationId)); if (dispatched.kind !== 'new_dispatch') refuse('RECOVERY_REQUIRED', '', 'verification'); @@ -388,22 +564,52 @@ export class LocalCheck { const binding: Binding = { version: 1, planDigest: this.plan.planDigest, operationId: job.operationId, producerNonce: job.producerNonce, requestDigest: job.requestDigest, intentDigest, subject: data.subject, generation: job.generation, checkId: data.slot.checkId, script: data.spec.script, scriptDigest, scriptDirectoryDigest: data.recorded.scriptDirectoryDigest, registryDigest: this.plan.registryDigest, pgid: null, workspaceDir: workspace.attemptDir, dispatchReceipt: { generation: permit.generation, dispatchId: permit.dispatchId, revision: permit.authorizedRevision, clockEpoch: permit.clockEpoch } }; + if (signal.aborted) { + await this.#marker(job.operationId, job.producerNonce, 'binding', binding); + await this.#settleAbortedDispatch(job, data, binding, intentDigest); + refuse(this.#stopCode(), '', 'verification'); + } let child: ChildProcess | null = null; try { child = spawn(scriptAbs, [...data.spec.args], { cwd: workspace.baselineDir, env: this.#environment(data, workspace), stdio: ['ignore', 'ignore', 'pipe'], detached: true }); } catch { /* refused below with the binding written first */ } + const stderr = createRollingTail(LOCAL_CHECK_STDERR_BYTES); + let exited: Promise<{ readonly code: number | null; readonly signal: string | null }> | null = null; + if (child) { + child.stderr?.on('error', () => undefined); + child.stderr?.on('data', (part: Buffer) => stderr.push(part)); + exited = new Promise(resolve => { + child!.once('exit', (code, exitSignal) => resolve({ code, signal: exitSignal })); + child!.once('error', () => resolve({ code: null, signal: null })); + }); + } if (!child || child.pid === undefined) { // No process group exists; bind first so recovery settles the dispatched operation instead of re-dispatching it. await this.#marker(job.operationId, job.producerNonce, 'binding', binding); - if (child) await new Promise(resolve => { child!.once('error', () => resolve()); child!.once('close', () => resolve()); }); + if (exited) await exited; + child?.stderr?.destroy(); refuse('CONFIG_REFERENCE', HANDLERS_PATH, 'verification'); } const pgid = child.pid, bound: Binding = { ...binding, pgid }; + onGroupSpawned(); // The group id is bound before any proof can exist, so recovery always knows what to kill. // shortcut: a crash between spawn and this fsync (milliseconds) leaves an unrecorded group; Pod exit is the backstop. - await this.#marker(job.operationId, job.producerNonce, 'binding', bound); - const exit = await this.#runChild(child, pgid, data.spec.timeoutMs, signal); - if (signal.aborted) refuse('CANCELLED', '', 'verification'); - const stderrTail = new SecretScrubber().scrub(exit.stderrTail); + try { + await this.#marker(job.operationId, job.producerNonce, 'binding', bound); + } catch (error) { + try { + await confirmProcessGroupGone(pgid, 'verification'); + onGroupCleaned(); + } finally { + child.stderr?.destroy(); + } + throw error; + } + const exit = await this.#runChild(child, pgid, exited!, stderr, data.spec.timeoutMs, signal, onGroupCleaned); + if (signal.aborted) { + await this.#settleAbortedDispatch(job, data, bound, intentDigest); + refuse(this.#stopCode(), '', 'verification'); + } + const stderrTail = this.artifacts.vault.scrub(exit.stderrTail); this.artifacts.vault.assertClean(stderrTail); const { output, outputError } = exit.timedOut ? { output: null, outputError: null } : await this.#readOutput(workspace.checkOut); const observation: Observation = { transport: exit.timedOut ? 'timeout' : 'completed', exitCode: exit.exitCode, exitSignal: exit.exitSignal, timedOut: exit.timedOut, elapsedMs: exit.elapsedMs, output, outputError, stderrTail, stderrTruncated: exit.stderrTruncated }; @@ -450,43 +656,56 @@ export class LocalCheck { || operation.intent.attemptId !== this.#attemptId(job) || operation.intent.nodeId !== this.plan.orderedDAG[0]!.id || operation.intent.targetIdentity !== this.#target(job, data.subject)) refuse('RECOVERY_REQUIRED', '', 'recovery'); const prefix = this.#prefix(job); + const bindingPath = prefix + '.binding.json'; + const hasBinding = await lstat(bindingPath).then( + () => true, + error => { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false; + throw error; + }, + ); let binding: Binding | null = null; - try { binding = this.#binding(await readBoundedFile(prefix + '.binding.json', MARKER_BYTES, true), job, data, view, dispatch, operation.intentDigest); } - catch (error) { - // Only an operation still uncertain may lack a binding: the spawn follows the binding, so nothing ran outside the millisecond window noted above. - if (!(error instanceof ControllerFailure) || error.diagnostic.code !== 'REGISTRY_UNTRUSTED' || operation.state !== 'dispatch_uncertain') throw error; + if (hasBinding) { + let bindingBytes: Buffer; + try { bindingBytes = await readBoundedFile(bindingPath, MARKER_BYTES, true); } + catch (error) { + if (error instanceof ControllerFailure && (error.diagnostic.code === 'REGISTRY_UNTRUSTED' || error.diagnostic.code === 'CONFIG_LIMIT')) refuse('RECOVERY_REQUIRED', '', 'recovery'); + throw error; + } + binding = this.#binding(bindingBytes, job, data, view, dispatch, operation.intentDigest); + } else if (operation.state !== 'dispatch_uncertain' && operation.state !== 'confirmed') { + refuse('RECOVERY_REQUIRED', '', 'recovery'); } let proofBytes: Buffer; try { proofBytes = await readBoundedFile(prefix + '.proof.json', MARKER_BYTES, true); } catch (error) { if (error instanceof ControllerFailure && error.diagnostic.code === 'REGISTRY_UNTRUSTED' && operation.state === 'dispatch_uncertain') return await this.#settle(job, data, binding, view, dispatch, operation.intentDigest); - if (error instanceof ControllerFailure && error.diagnostic.code === 'REGISTRY_UNTRUSTED') refuse('RECOVERY_REQUIRED', '', 'recovery'); throw error; + if (error instanceof ControllerFailure && (error.diagnostic.code === 'REGISTRY_UNTRUSTED' || error.diagnostic.code === 'CONFIG_LIMIT')) refuse('RECOVERY_REQUIRED', '', 'recovery'); + throw error; } - if (!binding) refuse('RECOVERY_REQUIRED', '', 'recovery'); const proof = record(parsePrivateJson(proofBytes, MARKER_BYTES), ['version', 'output', 'receipt', 'evidence']); if (proof.version !== 1) refuse('RECOVERY_REQUIRED', '', 'recovery'); const output = checkedRef(proof.output), receiptRef = checkedRef(proof.receipt), outputBytes = await this.artifacts.read(output, LOCAL_CHECK_OUTPUT_BYTES); const saved = record(parsePrivateJson(Buffer.from(outputBytes), LOCAL_CHECK_OUTPUT_BYTES), ['version', 'binding', 'observation', 'disposition']); if (saved.version !== 1 || !same(saved.binding, binding)) refuse('RECOVERY_REQUIRED', '', 'recovery'); const observation = this.#observation(saved.observation), disposition = this.#disposition(observation); - if (observation.transport === 'interrupted' || !same(saved.disposition, disposition)) refuse('RECOVERY_REQUIRED', '', 'recovery'); + if ((binding === null && observation.transport !== 'interrupted') || !same(saved.disposition, disposition)) refuse('RECOVERY_REQUIRED', '', 'recovery'); const evidence = this.#evidence(job, data, disposition, observation, output, 'recovery'); if (!same(evidence, proof.evidence)) refuse('RECOVERY_REQUIRED', '', 'recovery'); - const { receipt, record: receiptRecord } = this.#receipt(job, data, disposition, view, operation.intentDigest, binding.dispatchReceipt, output, binding.scriptDigest); + const dispatchReceipt: DispatchReceipt = binding?.dispatchReceipt ?? { generation: dispatch.generation, dispatchId: dispatch.dispatchId, revision: dispatch.revision, clockEpoch: view.clock.basis.clockEpoch }; + const { receipt, record: receiptRecord } = this.#receipt(job, data, disposition, view, operation.intentDigest, dispatchReceipt, output, binding?.scriptDigest ?? null); if (!same(parsePrivateJson(await this.artifacts.read(receiptRef, 65536), 65536), receiptRecord)) refuse('RECOVERY_REQUIRED', '', 'recovery'); await this.artifacts.owner.assertCurrent(); if (!same(this.currentSubject(), data.subject)) refuse('RECOVERY_REQUIRED', '', 'recovery'); stateValue(this.store.renew(this.authority)); if (operation.state === 'confirmed') { if (!same(operation.reconciliation ?? operation.initialReceipt, receipt)) refuse('RECOVERY_REQUIRED', '', 'recovery'); } else stateValue(this.store.reconcileOperation(this.authority, job.operationId, receipt)); - return await this.#attest(job, data, disposition, output, receiptRef, evidence, receipt, receiptRecord, binding.pgid); + return await this.#attest(job, data, disposition, output, receiptRef, evidence, receipt, receiptRecord, binding?.pgid ?? null); } /** An operation without a proof settles fail-closed; a replacement dispatch is never made. */ async #settle(job: PreparedLocalCheck, data: Preparation, binding: Binding | null, view: RunView, dispatch: NonNullable, intentDigest: Digest): Promise { await this.artifacts.owner.assertCurrent(); if (!same(this.currentSubject(), data.subject)) refuse('RECOVERY_REQUIRED', '', 'recovery'); stateValue(this.store.renew(this.authority)); - if (binding) { - if (binding.pgid !== null) await confirmProcessGroupGone(binding.pgid, 'recovery'); - await removeTree(binding.workspaceDir, 'recovery'); - } + if (binding?.pgid !== null && binding?.pgid !== undefined) await confirmProcessGroupGone(binding.pgid, 'recovery'); + await removeTree(binding?.workspaceDir ?? this.#attemptDir(job), 'recovery'); const disposition: Disposition = { status: 'blocked', reason: 'EVIDENCE_UNAVAILABLE', method: LOCAL_CHECK_METHOD }; const observation: Observation = { transport: 'interrupted', exitCode: null, exitSignal: null, timedOut: false, elapsedMs: 0, output: null, outputError: null, stderrTail: '', stderrTruncated: false }; const output = await this.artifacts.json('local-check-output', { version: 1, binding, observation, disposition }, LOCAL_CHECK_OUTPUT_BYTES); diff --git a/packages/controller/src/parser.ts b/packages/controller/src/parser.ts index 89461e45..39812e1e 100644 --- a/packages/controller/src/parser.ts +++ b/packages/controller/src/parser.ts @@ -94,10 +94,10 @@ function yaml(source: string): Json { } visit(document.contents, 1); return document.toJS({ maxAliasCount: 0 }) as Json; } -export function parseDocumentBytes(bytes: Uint8Array, format: 'json' | 'yaml'): Json { - if (bytes.byteLength > DOCUMENT_BYTES) refuse('CONFIG_LIMIT'); +export function parseDocumentBytes(bytes: Uint8Array, format: 'json' | 'yaml', collectionLimit = 128): Json { + if (bytes.byteLength > DOCUMENT_BYTES || !Number.isSafeInteger(collectionLimit) || collectionLimit < 1 || collectionLimit > 65_536) refuse('CONFIG_LIMIT'); let source: string; try { source = new TextDecoder('utf-8', { fatal: true }).decode(bytes); } catch { refuse('CONFIG_SYNTAX'); } - return format === 'json' ? json(source) : yaml(source); + return format === 'json' ? json(source, collectionLimit, Math.max(8192, collectionLimit * 16)) : yaml(source); } /** Private immutable records have their own explicit collection bound; authoring config keeps the default 128. */ export function parsePrivateJson(bytes: Uint8Array, maximum: number, collectionLimit = 256): Json { diff --git a/packages/controller/src/process-group.ts b/packages/controller/src/process-group.ts new file mode 100644 index 00000000..cec26356 --- /dev/null +++ b/packages/controller/src/process-group.ts @@ -0,0 +1,56 @@ +import type { Readable } from 'node:stream'; +import { refuse, type ControllerDiagnostic } from './errors.js'; + +export const GROUP_EXIT_WAIT_MS = 2_000; +const GROUP_POLL_MS = 15; +const STREAM_DRAIN_MS = 500; + +export function killProcessGroup(pgid: number): void { + try { + process.kill(-pgid, 'SIGKILL'); + } catch { + // Exact exit is confirmed by ESRCH below. + } +} + +export function processGroupAlive(pgid: number): boolean { + try { + process.kill(-pgid, 0); + return true; + } catch (error) { + return (error as NodeJS.ErrnoException).code === 'EPERM'; + } +} + +/** SIGKILL the group until `kill(-pgid, 0)` reports ESRCH; a group that survives is a cleanup failure, never a success. */ +export async function confirmProcessGroupGone(pgid: number, phase: ControllerDiagnostic['phase']): Promise { + const deadline = performance.now() + GROUP_EXIT_WAIT_MS; + while (processGroupAlive(pgid)) { + if (performance.now() >= deadline) refuse('CLEANUP_FAILED', '', phase); + killProcessGroup(pgid); + await new Promise(resolve => { + const timer = setTimeout(resolve, GROUP_POLL_MS); + timer.unref(); + }); + } +} + +/** After the group is gone every in-group writer is dead; give the pipe a bounded grace window to reach EOF, then destroy it. */ +export function drainStream(stream: Readable | null | undefined, timeoutMs = STREAM_DRAIN_MS): Promise { + if (!stream || stream.readableEnded || stream.destroyed) return Promise.resolve(); + return new Promise(resolve => { + const done = () => { + clearTimeout(timer); + stream.removeListener('end', done); + stream.removeListener('close', done); + resolve(); + }; + const timer = setTimeout(() => { + stream.destroy(); + done(); + }, timeoutMs); + timer.unref(); + stream.once('end', done); + stream.once('close', done); + }); +} diff --git a/packages/controller/src/registry.ts b/packages/controller/src/registry.ts index 105cd588..0891ca28 100644 --- a/packages/controller/src/registry.ts +++ b/packages/controller/src/registry.ts @@ -1,9 +1,10 @@ import { isAbsolute } from 'node:path'; import { isIP } from 'node:net'; -import { digestArtifact } from '@loopwright/core'; +import { EXEC_LIMITS, LOCAL_CHECK_ENV_NAMES, LOCAL_CHECK_LIMITS, digestArtifact, isLocalCheckEnvName } from '@loopwright/core'; import { validateSelection } from '@loopwright/agent-pi/catalog'; import { isExternalMcpToolName } from '@loopwright/agent-pi/mcp'; import { CONTROLLER_API_VERSION, type TrustedRegistry, type RoleProfile, type Handler, type Implementation, type GateEndpoint, type PublicationEndpoint, type ExecProfileCommand } from './types.js'; +import { EXEC_RESERVED_ENV_NAMES } from './exec-role.js'; import { digestValue, id, integer, isRecord, list, record, same, text, type Scalar } from './schema.js'; import { template } from './interpolation.js'; import { refuse, type ControllerDiagnostic } from './errors.js'; @@ -70,12 +71,15 @@ export function validateHandler(raw: unknown, path: string): Handler { const parameters = record(value.parameters, ['checkId', 'script', 'args', 'env', 'toolchainPaths', 'timeoutMs'], path + '/parameters'); id(parameters.checkId, path + '/parameters/checkId'); if (!digestArtifact(text(parameters.script, path + '/parameters/script', 1024), new Uint8Array()).ok) refuse('CONFIG_SCHEMA', path + '/parameters/script'); - list(parameters.args, path + '/parameters/args', 64).forEach((item, index) => text(item, `${path}/parameters/args/${index}`)); + list(parameters.args, path + '/parameters/args', 64).forEach((item, index) => { + const arg = text(item, `${path}/parameters/args/${index}`); + if (arg.includes('\0')) refuse('CONFIG_SCHEMA', `${path}/parameters/args/${index}`); + }); if (!isRecord(parameters.env)) refuse('CONFIG_SCHEMA', path + '/parameters/env'); const envEntries = Object.entries(parameters.env); if (envEntries.length > 32) refuse('CONFIG_SCHEMA', path + '/parameters/env'); for (const [name, raw] of envEntries) { - if (!/^[A-Z][A-Z0-9_]{0,63}$/.test(name) || name.startsWith('LOOPWRIGHT_') || typeof raw !== 'string' || raw.length > 16384) { + if (!isLocalCheckEnvName(name) || LOCAL_CHECK_ENV_NAMES.includes(name) || typeof raw !== 'string' || raw.length > 16384 || raw.includes('\0')) { refuse('CONFIG_SCHEMA', `${path}/parameters/env/${name}`); } } @@ -83,7 +87,7 @@ export function validateHandler(raw: unknown, path: string): Handler { toolchainPaths.forEach((item, index) => { if (!digestArtifact(text(item, `${path}/parameters/toolchainPaths/${index}`, 1024), new Uint8Array()).ok) refuse('CONFIG_SCHEMA', `${path}/parameters/toolchainPaths/${index}`); }); - integer(parameters.timeoutMs, 1000, 3600000, path + '/parameters/timeoutMs'); + integer(parameters.timeoutMs, LOCAL_CHECK_LIMITS.timeoutMsMin, LOCAL_CHECK_LIMITS.timeoutMsMax, path + '/parameters/timeoutMs'); } else if (implementation === 'json-keys-guard.v1') { const parameters = record(value.parameters, ['checkId', 'path', 'allowedPointers'], path + '/parameters'); id(parameters.checkId, path + '/parameters/checkId'); @@ -224,12 +228,22 @@ function execCommand(raw: unknown, path: string): ExecProfileCommand { if (!raw || typeof raw !== 'object' || Array.isArray(raw)) refuse('CONFIG_SCHEMA', path); const hasArgs = Object.hasOwn(raw, 'args'), hasEnv = Object.hasOwn(raw, 'env'), hasCredentialRefs = Object.hasOwn(raw, 'credentialRefs'), hasCaptureBytes = Object.hasOwn(raw, 'captureBytes'); const value = record(raw, ['command', 'timeoutMs', ...(hasArgs ? ['args' as const] : []), ...(hasEnv ? ['env' as const] : []), ...(hasCredentialRefs ? ['credentialRefs' as const] : []), ...(hasCaptureBytes ? ['captureBytes' as const] : [])], path); - const command = list(value.command, path + '/command', 64); - if (command.length < 1) refuse('CONFIG_SCHEMA', path + '/command'); - const entries = command.map((item, index) => text(item, `${path}/command/${index}`, 4096)); + const command = list(value.command, path + '/command', EXEC_LIMITS.commandEntriesMax); + if (command.length < EXEC_LIMITS.commandEntriesMin) refuse('CONFIG_SCHEMA', path + '/command'); + const entries = command.map((item, index) => { + const entry = text(item, `${path}/command/${index}`, 4096); + if (entry.includes('\0')) refuse('CONFIG_SCHEMA', `${path}/command/${index}`); + return entry; + }); const program = entries[0]!; if (!isAbsolute(program) || /[\0\r\n]/.test(program) || program.endsWith('/')) refuse('CONFIG_SCHEMA', `${path}/command/0`); - const args = hasArgs ? list(value.args, path + '/args', 64).map((item, index) => text(item, `${path}/args/${index}`, 4096)) : undefined; + const args = hasArgs + ? list(value.args, path + '/args', 64).map((item, index) => { + const arg = text(item, `${path}/args/${index}`, 4096); + if (arg.includes('\0')) refuse('CONFIG_SCHEMA', `${path}/args/${index}`); + return arg; + }) + : undefined; let env: Readonly> | undefined; if (hasEnv) { if (!isRecord(value.env)) refuse('CONFIG_SCHEMA', path + '/env'); @@ -237,15 +251,19 @@ function execCommand(raw: unknown, path: string): ExecProfileCommand { if (rawEnv.length > 32) refuse('CONFIG_SCHEMA', path + '/env'); const checkedEnv: Record = Object.create(null) as Record; for (const [name, rawValue] of rawEnv) { - if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) || name.length > 64) refuse('CONFIG_SCHEMA', `${path}/env/${name}`); - checkedEnv[name] = text(rawValue, `${path}/env/${name}`); + if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) || name.length > 64 || EXEC_RESERVED_ENV_NAMES.includes(name) || name.startsWith('LOOPWRIGHT_')) { + refuse('CONFIG_SCHEMA', `${path}/env/${name}`); + } + const checkedVal = text(rawValue, `${path}/env/${name}`); + if (checkedVal.includes('\0')) refuse('CONFIG_SCHEMA', `${path}/env/${name}`); + checkedEnv[name] = checkedVal; } env = checkedEnv; } const credentialRefs = hasCredentialRefs ? list(value.credentialRefs, path + '/credentialRefs', 16).map((item, index) => id(item, `${path}/credentialRefs/${index}`)) : undefined; if (credentialRefs !== undefined && new Set(credentialRefs).size !== credentialRefs.length) refuse('CONFIG_SCHEMA', path + '/credentialRefs'); - const timeoutMs = integer(value.timeoutMs, 1, Number.MAX_SAFE_INTEGER, path + '/timeoutMs'); - const captureBytes = hasCaptureBytes ? integer(value.captureBytes, 1024, 1048576, path + '/captureBytes') : undefined; + const timeoutMs = integer(value.timeoutMs, 1, LOCAL_CHECK_LIMITS.timeoutMsMax, path + '/timeoutMs'); + const captureBytes = hasCaptureBytes ? integer(value.captureBytes, EXEC_LIMITS.captureBytesMin, EXEC_LIMITS.captureBytesMax, path + '/captureBytes') : undefined; return { command: entries, ...(args !== undefined ? { args } : {}), @@ -256,15 +274,14 @@ function execCommand(raw: unknown, path: string): ExecProfileCommand { }; } function role(raw: unknown, path: string): RoleProfile { - if (!raw || typeof raw !== 'object' || Array.isArray(raw)) refuse('CONFIG_SCHEMA', path); - const hasAdapter = Object.hasOwn(raw, 'adapter'), hasContext = Object.hasOwn(raw, 'context'), hasLimits = Object.hasOwn(raw, 'limits'), hasExec = Object.hasOwn(raw, 'exec'); - const keys = ['id', ...(hasAdapter ? ['adapter' as const] : []), 'selection', 'tools', ...(hasContext ? ['context' as const] : []), 'runtimeRef', 'providerCredentialRef', 'mcp', ...(hasLimits ? ['limits' as const] : []), ...(hasExec ? ['exec' as const] : [])]; - const value = record(raw, keys, path); - const adapterRaw = hasAdapter ? value.adapter : 'pi'; + if (!isRecord(raw)) refuse('CONFIG_SCHEMA', path); + const hasAdapter = Object.hasOwn(raw, 'adapter'), hasContext = Object.hasOwn(raw, 'context'), hasLimits = Object.hasOwn(raw, 'limits'); + const adapterRaw = hasAdapter ? raw.adapter : 'pi'; if (adapterRaw !== 'pi' && adapterRaw !== 'delegated' && adapterRaw !== 'exec') refuse('CONFIG_SCHEMA', path + '/adapter'); + const keys = ['id', ...(hasAdapter ? ['adapter' as const] : []), 'selection', 'tools', ...(hasContext ? ['context' as const] : []), 'runtimeRef', 'providerCredentialRef', 'mcp', ...(hasLimits ? ['limits' as const] : []), ...(adapterRaw === 'exec' ? ['exec' as const] : [])]; + const value = record(raw, keys, path); const checkedLimits = hasLimits ? roleLimits(value.limits, path + '/limits') : undefined; if (adapterRaw === 'exec') { - if (!hasExec) refuse('CONFIG_SCHEMA', path + '/exec'); id(value.id, path + '/id'); if (value.runtimeRef !== null) refuse('CONFIG_SCHEMA', path + '/runtimeRef'); if (value.providerCredentialRef !== null) refuse('CONFIG_SCHEMA', path + '/providerCredentialRef'); @@ -327,7 +344,7 @@ function role(raw: unknown, path: string): RoleProfile { const tools = list(value.tools, path + '/tools', 128).map(item => text(item, path + '/tools', 128)); if (new Set(tools).size !== tools.length || tools.some(name => !['read', 'bash', 'write', 'edit', 'delete', 'codemode', 'mcp__workspace__read_file'].includes(name) && !isExternalMcpToolName(name))) refuse('CAPABILITY_UNSUPPORTED', path + '/tools'); const checkedContext = context(value.context, path + '/context'); mcp(value.mcp, tools, path + '/mcp'); - return { ...(raw as RoleProfile), adapter: 'pi', context: checkedContext, ...(checkedLimits !== undefined ? { limits: checkedLimits } : {}) }; + return { ...(raw as unknown as RoleProfile), adapter: 'pi', context: checkedContext, ...(checkedLimits !== undefined ? { limits: checkedLimits } : {}) }; } /** Outbound endpoints accept exact https URLs or explicit-port loopback http; credentials, query strings and fragments never pass. */ function endpointUrl(raw: unknown, path: string): string { @@ -393,9 +410,16 @@ export function validateRegistry(raw: unknown): TrustedRegistry { unique(bindings as unknown as readonly { id: string }[], '/registry/spec/credentialBindings'); roles.forEach((profile, index) => { if (profile.adapter !== 'exec' || profile.exec?.credentialRefs === undefined) return; + const claimed = new Set(Object.keys(profile.exec.env ?? {})); for (const ref of profile.exec.credentialRefs) { const binding = bindings.find(item => item.id === ref); if (!binding || binding.consumer !== 'exec') refuse('CONFIG_REFERENCE', `/registry/spec/roleProfiles/${index}/exec/credentialRefs`); + for (const name of list(binding.environmentNames).map(item => text(item))) { + if (name.length > 64 || EXEC_RESERVED_ENV_NAMES.includes(name) || name.startsWith('LOOPWRIGHT_') || claimed.has(name)) { + refuse('CONFIG_SCHEMA', `/registry/spec/roleProfiles/${index}/exec/credentialRefs`); + } + claimed.add(name); + } } }); const environment = list(value.environmentBindings).map(item => { diff --git a/packages/controller/src/retained.ts b/packages/controller/src/retained.ts index 2ba4c15e..14c44066 100644 --- a/packages/controller/src/retained.ts +++ b/packages/controller/src/retained.ts @@ -101,7 +101,7 @@ export function resolveStoreLeaseMs(configuration: LoadedConfiguration, plan: Co const durationMs = slot.handler.implementation === 'benchmark-gate.v1' ? Math.max(ep.timeoutMs, ep.maxPollMs) : ep.timeoutMs; if (durationMs > maxEndpointDurationMs) maxEndpointDurationMs = durationMs; } - return maxEndpointDurationMs > 58000 ? Math.min(3700000, maxEndpointDurationMs + 30000) : 60000; + return maxEndpointDurationMs > 30000 ? Math.min(3700000, maxEndpointDurationMs + 30000) : 60000; } function retainedRoleModelOverrides(raw: unknown): readonly RoleModelOverride[] | undefined { diff --git a/packages/controller/test/benchmark-gate.test.ts b/packages/controller/test/benchmark-gate.test.ts index 7c37cded..d62b5ea5 100644 --- a/packages/controller/test/benchmark-gate.test.ts +++ b/packages/controller/test/benchmark-gate.test.ts @@ -3078,3 +3078,128 @@ test('Fix Pass #3 — exact 0o7777 CAS permission mask (rejects 0o1400) and mixe await mixedRelay.close(); } }); + +test('benchmark-gate.v1 accepts optional isolation: docker in hardwareProvenance and refuses isolation: host_attested fail-closed', async () => { + // 1. Schema-level checkedHardwareProvenance checks + const omitted = checkedHardwareProvenance(makeProvenance()); + assert.equal(omitted.isolation, undefined); + + const dockerProv = checkedHardwareProvenance(makeProvenance({ isolation: 'docker' })); + assert.equal(dockerProv.isolation, 'docker'); + + const hostProv = checkedHardwareProvenance(makeProvenance({ isolation: 'host_attested' })); + assert.equal(hostProv.isolation, 'host_attested'); + + for (const badIsolation of ['podman', '', null, 123, {}]) { + assert.throws( + () => checkedHardwareProvenance({ ...makeProvenance(), isolation: badIsolation }), + /ARTIFACT_INVALID/, + `expected ARTIFACT_INVALID for isolation=${JSON.stringify(badIsolation)}`, + ); + } + + // 2. Disposition and blob-pull gating: docker passes; host_attested blocks with HARDWARE_PROVENANCE_MISMATCH + const targetHardware = { accelerator: 'sm_90a', isolationMode: 'whole_device' as const, deviceCount: 1 }; + const dockerDisp = computeBenchmarkDisposition({ + verdict: { + status: 'approved', + reason: null, + expiresAtMs: String(Date.now() + 600_000), + preemptionCount: 0, + hardwareProvenance: dockerProv, + metrics: { latency_us: 42 }, + }, + timedOut: false, + sawPreemption: false, + wallClockValid: true, + targetHardware, + targetCellId: 'cuda-sm90', + allowSyntheticHardwareProbe: false, + metricThresholds: [{ kind: 'bounds', metric: 'latency_us', max: 100 }], + casOutcome: 'ok', + }); + assert.equal(dockerDisp.status, 'passed'); + assert.equal(dockerDisp.reason, null); + + const hostDisp = computeBenchmarkDisposition({ + verdict: { + status: 'approved', + reason: null, + expiresAtMs: String(Date.now() + 600_000), + preemptionCount: 0, + hardwareProvenance: hostProv, + metrics: { latency_us: 42 }, + }, + timedOut: false, + sawPreemption: false, + wallClockValid: true, + targetHardware, + targetCellId: 'cuda-sm90', + allowSyntheticHardwareProbe: false, + metricThresholds: [{ kind: 'bounds', metric: 'latency_us', max: 100 }], + casOutcome: 'ok', + }); + assert.equal(hostDisp.status, 'blocked'); + assert.equal(hostDisp.reason, 'HARDWARE_PROVENANCE_MISMATCH'); + + // 3. Full relay round-trip: isolation: 'docker' passes end-to-end; isolation: 'host_attested' blocks without pulling blobs + const outBytes = Buffer.from('profile-trace\n', 'utf8'); + const outSha = sha256Hex(outBytes); + const dockerRelay = await startMockRelay({ + outputBlobs: new Map([[outSha, { bytes: outBytes }]]), + onPoll: () => ({ + status: 'approved', + metrics: { latency_us: 42 }, + hardwareProvenance: makeProvenance({ isolation: 'docker' }), + outputArtifacts: [{ name: 'trace.txt', digest: { algorithm: 'sha256', hex: outSha }, byteLength: outBytes.byteLength }], + }), + }); + const fDocker = await createBenchmarkFixture({ relayUrl: dockerRelay.url }); + try { + const res = assertOk( + await runCycleWithPorts({ + configuration: fDocker.loaded, + repository: fDocker.repository, + runRoot: fDocker.runRoot, + runId: 'run-bench-docker-isolation', + }), + ); + assert.equal(res.kind, 'result'); + if (res.kind === 'result') { + assert.equal(res.result.spec.status, 'completed'); + } + assert.equal(dockerRelay.getRequests.length, 1); + } finally { + await fDocker.cleanup(); + await dockerRelay.close(); + } + + const hostRelay = await startMockRelay({ + outputBlobs: new Map([[outSha, { bytes: outBytes }]]), + onPoll: () => ({ + status: 'approved', + metrics: { latency_us: 42 }, + hardwareProvenance: makeProvenance({ isolation: 'host_attested' }), + outputArtifacts: [{ name: 'trace.txt', digest: { algorithm: 'sha256', hex: outSha }, byteLength: outBytes.byteLength }], + }), + }); + const fHost = await createBenchmarkFixture({ relayUrl: hostRelay.url }); + try { + const res = assertOk( + await runCycleWithPorts({ + configuration: fHost.loaded, + repository: fHost.repository, + runRoot: fHost.runRoot, + runId: 'run-bench-host-attested-refused', + }), + ); + assert.equal(res.kind, 'result'); + if (res.kind === 'result') { + assert.equal(res.result.spec.status, 'blocked'); + } + assert.equal(hostRelay.getRequests.length, 0, 'untrusted host_attested output blobs must never be pulled'); + } finally { + await fHost.cleanup(); + await hostRelay.close(); + } +}); diff --git a/packages/controller/test/compile.test.ts b/packages/controller/test/compile.test.ts index 9896e626..d6cfc483 100644 --- a/packages/controller/test/compile.test.ts +++ b/packages/controller/test/compile.test.ts @@ -4,7 +4,7 @@ import { lstat, mkdir, writeFile } from 'node:fs/promises'; import { dirname, join } from 'node:path'; import { admitTask } from '@loopwright/core'; import { compilePlan, checkpointCapacity } from '../src/compile.js'; -import { createCycle, type CycleContext } from '../src/controller.js'; +import { createCycle, resolveStoreLeaseMs, type CycleContext } from '../src/controller.js'; import { installedHandlerDigests } from '../src/handlers.js'; import { ControllerFailure, type ControllerResult } from '../src/errors.js'; import { localCheckScriptDirectoryDigest, readLocalCheckScriptDirectory } from '../src/local-check.js'; @@ -572,6 +572,22 @@ test('compilePlan: a command.v1 handler compiles in check mode without resolving try { const compiled = await compilePlan(outside.loaded); assert.equal(compiled.ok, false, 'script outside scope.protected'); if (!compiled.ok) assert.equal(compiled.error.code, 'CONFIG_SCHEMA'); } finally { await cleanupFixture(outside); } + const singleFileOnly = await commandCheckFixture({ protected: ['scripts/pass.sh'] }); + try { + const compiled = await compilePlan(singleFileOnly.loaded); + assert.equal(compiled.ok, false, 'single-file scope.protected does not protect parent directory'); + if (!compiled.ok) assert.equal(compiled.error.code, 'CONFIG_SCHEMA'); + } finally { await cleanupFixture(singleFileOnly); } + const allProtected = await commandCheckFixture({ protected: ['**'] }); + try { + const plan = assertOk(await compilePlan(allProtected.loaded), 'wildcard ** protects script directory'); + assert.equal(resolveStoreLeaseMs(allProtected.loaded, plan), 60_000); + } finally { await cleanupFixture(allProtected); } + const midTimeout = await commandCheckFixture({ parameters: { timeoutMs: 45_000 } }); + try { + const plan = assertOk(await compilePlan(midTimeout.loaded), '45s command timeout'); + assert.equal(resolveStoreLeaseMs(midTimeout.loaded, plan), 75_000, 'at least 30s lease headroom above command.v1 timeoutMs'); + } finally { await cleanupFixture(midTimeout); } const disallowed = await commandCheckFixture({ allowed: ['local_execution'] }); try { const compiled = await compilePlan(disallowed.loaded); assert.equal(compiled.ok, false, 'host_execution not an allowed level'); if (!compiled.ok) assert.equal(compiled.error.code, 'CONFIG_SCHEMA'); @@ -581,7 +597,9 @@ test('compilePlan: a command.v1 handler compiles in check mode without resolving test('admission resolves command.v1 scripts at sourceRevision through createCycle and refuses unprotected siblings, non-executable or missing scripts, and missing toolchain paths with exact codes', async () => { const cases: { readonly name: string; readonly options: CommandCheckFixtureOptions; readonly code: string }[] = [ { name: 'unprotected-sibling', options: { protected: ['scripts/*.sh'], extra: [{ path: 'scripts/README.md', content: 'operator notes\n' }] }, code: 'CONFIG_SCHEMA' }, + { name: 'single-script-protected', options: { protected: ['scripts/pass.sh'] }, code: 'CONFIG_SCHEMA' }, { name: 'non-executable-script', options: { script: 'scripts/noexec.sh', extra: [{ path: 'scripts/noexec.sh', content: '#!/bin/sh\n' }] }, code: 'CONFIG_REFERENCE' }, + { name: 'missing-shebang-script', options: { script: 'scripts/noshebang.sh', extra: [{ path: 'scripts/noshebang.sh', content: 'exit 0\n', executable: true }] }, code: 'CONFIG_REFERENCE' }, { name: 'missing-script', options: { script: 'scripts/missing.sh' }, code: 'CONFIG_REFERENCE' }, { name: 'missing-toolchain-path', options: { parameters: { toolchainPaths: ['missing/bin'] } }, code: 'CONFIG_REFERENCE' }, ]; @@ -592,6 +610,30 @@ test('admission resolves command.v1 scripts at sourceRevision through createCycl assert.equal(await lstat(join(f.runRoot, runId, 'run.json')).then(() => true, () => false), false, c.name + ': no run admitted'); } finally { await cleanupFixture(f); } } + + // Unreferenced command.v1 handler in the registry (even root-level) does not trigger scanning or admission failure for its unreferenced script + const fUnused = await commandCheckFixture(); + try { + const installed = await installedHandlerDigests(); + set(fUnused.registry, ['spec', 'handlers'], [ + ...fUnused.registry.spec.handlers, + { + id: 'unused-root-command', + version: 1, + kind: 'check', + implementation: 'command.v1', + digest: installed['command.v1'], + parameters: { checkId: 'unused-check', script: 'nonexistent-root.sh', args: [], env: {}, toolchainPaths: [], timeoutMs: 3000 }, + capabilities: ['host_execution'], + }, + ]); + await fUnused.save(); + const reloaded = assertOk(await fUnused.load(), 'load registry with unreferenced command.v1 handler'); + const context = await createCycle({ configuration: reloaded, repository: fUnused.repository, runRoot: fUnused.runRoot, runId: 'run-unused-cmd' }, {}); + await releaseContext(context); + } finally { + await cleanupFixture(fUnused); + } }); test('admission records the script directory digest in the command.v1 slot, planDigest covers it, and the digest equals what readLocalCheckScriptDirectory yields on the materialized baseline for version 1 and version 2 sources', async () => { diff --git a/packages/controller/test/config-local-checks.test.ts b/packages/controller/test/config-local-checks.test.ts index 5cf5a4e0..5b8e55db 100644 --- a/packages/controller/test/config-local-checks.test.ts +++ b/packages/controller/test/config-local-checks.test.ts @@ -132,4 +132,11 @@ test('loadConfiguration refuses a command.v1 handler whose schema is invalid bef const loaded = await withLocalChecksFixture(f => set(f.registry, ['spec', 'handlers', 4, 'parameters', 'env'], { LOOPWRIGHT_RUN_ID: 'run-1' })); assert.equal(loaded.ok, false); if (!loaded.ok) assert.equal(loaded.error.code, 'CONFIG_SCHEMA'); + + const overMaxExec = await withLocalChecksFixture(f => { + set(f.config, ['spec', 'task', 'spec', 'budgets', 'wallTimeMs'], 10_000_000); + set(f.registry, ['spec', 'roleProfiles', 1, 'exec', 'timeoutMs'], 3_600_001); + }); + assert.equal(overMaxExec.ok, false); + if (!overMaxExec.ok) assert.equal(overMaxExec.error.code, 'CONFIG_SCHEMA'); }); diff --git a/packages/controller/test/exec-profile.test.ts b/packages/controller/test/exec-profile.test.ts index 473ec36e..6f89541a 100644 --- a/packages/controller/test/exec-profile.test.ts +++ b/packages/controller/test/exec-profile.test.ts @@ -221,10 +221,16 @@ test('exec profiles refuse a missing exec block, non-null runtime and credential { name: 'unknown exec key', mutate: registry => set(registry, ['spec', 'roleProfiles', 0, 'exec', 'cwd'], '/') }, { name: 'missing timeoutMs', mutate: registry => delete (registry.spec as { roleProfiles: { exec: Record }[] }).roleProfiles[0]!.exec.timeoutMs }, { name: 'zero timeoutMs', mutate: registry => set(registry, ['spec', 'roleProfiles', 0, 'exec', 'timeoutMs'], 0) }, + { name: 'timeoutMs above 3600000', mutate: registry => set(registry, ['spec', 'roleProfiles', 0, 'exec', 'timeoutMs'], 3600001) }, { name: 'fractional timeoutMs', mutate: registry => set(registry, ['spec', 'roleProfiles', 0, 'exec', 'timeoutMs'], 1.5) }, { name: 'missing command', mutate: registry => delete (registry.spec as { roleProfiles: { exec: Record }[] }).roleProfiles[0]!.exec.command }, { name: 'empty command', mutate: registry => set(registry, ['spec', 'roleProfiles', 0, 'exec', 'command'], []) }, { name: 'null exec', mutate: registry => set(registry, ['spec', 'roleProfiles', 0, 'exec'], null) }, + { name: 'exec block on delegated adapter', mutate: registry => set(registry, ['spec', 'roleProfiles', 0, 'adapter'], 'delegated') }, + { name: 'exec block on pi adapter', mutate: registry => set(registry, ['spec', 'roleProfiles', 0, 'adapter'], 'pi') }, + { name: 'exec block on omitted adapter', mutate: registry => delete (registry.spec as { roleProfiles: Record[] }).roleProfiles[0]!.adapter }, + { name: 'NUL in command[1]', mutate: registry => set(registry, ['spec', 'roleProfiles', 0, 'exec', 'command'], ['/usr/local/bin/forgevo-author', 'bad\0arg']) }, + { name: 'NUL in args[0]', mutate: registry => set(registry, ['spec', 'roleProfiles', 0, 'exec', 'args'], ['bad\0arg']) }, ]; for (const item of cases) { assert.equal(refusal(item.mutate), 'CONFIG_SCHEMA', item.name); @@ -258,12 +264,21 @@ test('exec captureBytes refuses out-of-bounds values and accepts the F2 limits', } }); -test('exec env refuses malformed names and non-string values', () => { +test('exec env refuses malformed names, reserved names, NUL values, and credential env collisions', () => { const envCases: readonly { readonly name: string; readonly env: unknown }[] = [ { name: 'empty name', env: { '': 'x' } }, { name: 'digit-leading name', env: { '1FORGE': 'x' } }, { name: 'space in name', env: { 'FORGE VO': 'x' } }, { name: 'dash in name', env: { 'FORGE-VO': 'x' } }, + { name: 'reserved PATH', env: { PATH: '/tmp' } }, + { name: 'reserved HOME', env: { HOME: '/tmp' } }, + { name: 'reserved TMPDIR', env: { TMPDIR: '/tmp' } }, + { name: 'reserved LANG', env: { LANG: 'C' } }, + { name: 'reserved LC_ALL', env: { LC_ALL: 'C' } }, + { name: 'reserved TERM', env: { TERM: 'xterm' } }, + { name: 'reserved LOOPWRIGHT_ prefix', env: { LOOPWRIGHT_CUSTOM: '1' } }, + { name: 'NUL in env value', env: { FORGEVO_LLM_BASE_URL: 'https://example.com/\0bad' } }, + { name: 'collision with bound credential env', env: { LLM_TOKEN: 'override' } }, { name: 'null value', env: { FORGEVO_LLM_BASE_URL: null } }, { name: 'numeric value', env: { FORGEVO_LLM_BASE_URL: 1 } }, { name: 'array env', env: [] }, @@ -271,6 +286,15 @@ test('exec env refuses malformed names and non-string values', () => { for (const item of envCases) { assert.equal(refusal(registry => set(registry, ['spec', 'roleProfiles', 0, 'exec', 'env'], item.env)), 'CONFIG_SCHEMA', item.name); } + assert.equal( + refusal(registry => { + set(registry, ['spec', 'credentialBindings', 0, 'environmentNames'], ['HOME']); + set(registry, ['spec', 'credentialBindings', 0, 'template'], '${HOME}'); + }), + 'CONFIG_SCHEMA', + 'bound exec credential cannot claim reserved HOME', + ); + assert.equal(refusal(registry => set(registry, ['spec', 'roleProfiles', 0, 'exec', 'timeoutMs'], 3600000)), 'accepted'); }); test('exec tools follow the delegated vocabulary without codemode or MCP tools', () => { diff --git a/packages/controller/test/exec-role-fixtures.ts b/packages/controller/test/exec-role-fixtures.ts index 1b9a9207..3e862e00 100644 --- a/packages/controller/test/exec-role-fixtures.ts +++ b/packages/controller/test/exec-role-fixtures.ts @@ -29,6 +29,27 @@ switch (mode) { setInterval(() => {}, 1000); break; } + case 'fork-and-exit-0': { + // Leader exits 0 immediately while the grandchild inherits stdout/stderr and tries to sleep 60s. + const grandchild = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { stdio: ['ignore', 'inherit', 'inherit'] }); + grandchild.once('spawn', () => { + process.stdout.write(JSON.stringify({ child: grandchild.pid }) + '\n', () => { + process.exit(0); + }); + }); + break; + } + case 'fork-bg-exit-0': { + // Leader exits 0 while a background process in the group has closed stdio and lingers. + const grandchild = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { stdio: 'ignore' }); + grandchild.unref(); + grandchild.once('spawn', () => { + process.stdout.write(JSON.stringify({ child: grandchild.pid }) + '\n', () => { + process.exit(0); + }); + }); + break; + } case 'flood': process.stdout.write('0123456789abcdef'.repeat(256) + '\n'); process.stderr.write('0123456789abcdef'.repeat(256) + '\n'); @@ -36,6 +57,29 @@ switch (mode) { case 'write-usage': writeFileSync(env['LOOPWRIGHT_USAGE_OUT']!, JSON.stringify({ requests: [{ requestId: 'req_1', inputTokens: 120, outputTokens: 45, costMicrousd: 1500 }] })); break; + case 'write-empty-usage': + writeFileSync(env['LOOPWRIGHT_USAGE_OUT']!, JSON.stringify({ requests: [] })); + break; + case 'write-150-usage': + writeFileSync( + env['LOOPWRIGHT_USAGE_OUT']!, + JSON.stringify({ + requests: Array.from({ length: 150 }, (_, index) => ({ + requestId: `req_${index}`, + inputTokens: 10 + index, + outputTokens: 5, + costMicrousd: 100, + })), + }), + ); + break; + case 'write-symlink-usage': { + const target = `${env['TMPDIR']!}/real-usage.json`; + writeFileSync(target, JSON.stringify({ requests: [] })); + const { symlinkSync } = await import('node:fs'); + symlinkSync(target, env['LOOPWRIGHT_USAGE_OUT']!); + break; + } case 'write-malformed-usage': writeFileSync(env['LOOPWRIGHT_USAGE_OUT']!, '{"requests":[{"requestId":"req 1","inputTokens":-1}]}'); break; diff --git a/packages/controller/test/exec-role.test.ts b/packages/controller/test/exec-role.test.ts index 9a554175..7dbf2d91 100644 --- a/packages/controller/test/exec-role.test.ts +++ b/packages/controller/test/exec-role.test.ts @@ -1,11 +1,11 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { createHash } from 'node:crypto'; -import { mkdir, mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises'; +import { mkdir, mkdtemp, readFile, realpath, rm, symlink, writeFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { fileURLToPath } from 'node:url'; -import { EXEC_LIMITS } from '@loopwright/core'; +import { EXEC_LIMITS, LOCAL_CHECK_LIMITS } from '@loopwright/core'; import { ControllerFailure } from '../src/errors.js'; import { runExecRole, type ExecRoleContext, type ExecRoleSpec, type SecretResolver } from '../src/exec-role.js'; import type { CredentialBinding } from '../src/types.js'; @@ -75,7 +75,7 @@ interface StubReport { readonly env: Record; readonly argv: stri test('exec role maps exit 0 to completed and hands promptFile and candidateDir over as the last argv with cwd = candidateDir and a closed stdin', () => withAttempt(async current => { const outcome = await runExecRole(spec(), context(current)); assert.equal(outcome.status, 'completed'); assert.equal(outcome.reason, null); assert.equal(outcome.exitCode, 0); assert.equal(outcome.exitSignal, null); assert.equal(outcome.timedOut, false); - assert.deepEqual(outcome.usage, []); assert.equal(outcome.stderr, ''); + assert.deepEqual(outcome.usage, []); assert.equal(outcome.usageReported, false); assert.equal(outcome.stderr, ''); const report = JSON.parse(outcome.stdout) as StubReport; assert.deepEqual(report.argv.slice(-2), [current.promptFile, current.candidateDir]); assert.equal(report.cwd, current.candidateDir); @@ -124,7 +124,7 @@ test('exec role maps exit 3 to blocked with the last non-empty stderr line as th test('exec role times out into failed exec_timeout and kills the whole process group, including a forked grandchild holding the pipes', { timeout: 30_000 }, () => withAttempt(async current => { const outcome = await runExecRole(spec({ mode: 'fork-and-sleep', timeoutMs: 1_500 }), context(current)); assert.equal(outcome.status, 'failed'); assert.equal(outcome.reason, 'exec_timeout'); assert.equal(outcome.timedOut, true); assert.equal(outcome.exitCode, null); - assert.deepEqual(outcome.usage, []); + assert.deepEqual(outcome.usage, []); assert.equal(outcome.usageReported, false); const { child } = JSON.parse(outcome.stdout.trim()) as { readonly child: number }; assert.ok(child > 0); gone(outcome.pgid); @@ -133,14 +133,50 @@ test('exec role times out into failed exec_timeout and kills the whole process g test('exec role cancel kills the process group and refuses CANCELLED', { timeout: 30_000 }, () => withAttempt(async current => { const controller = new AbortController(); let pgid = 0; - const timer = setTimeout(() => controller.abort(), 300); - try { - await assert.rejects(runExecRole(spec({ mode: 'sleep' }), context(current, { signal: controller.signal, onSpawned: async id => { pgid = id; } })), refusal('CANCELLED')); - } finally { clearTimeout(timer); } + let resolveSpawned!: () => void; + const spawned = new Promise(resolve => { resolveSpawned = resolve; }); + const running = runExecRole(spec({ mode: 'sleep' }), context(current, { + signal: controller.signal, + onSpawned: async id => { pgid = id; resolveSpawned(); }, + })); + await spawned; + controller.abort(); + await assert.rejects(running, refusal('CANCELLED')); assert.ok(pgid > 1); gone(pgid); })); +test('exec role normal exit kills lingering background children and grandchildren holding stdout/stderr without hanging into exec_timeout, and kills pgid when onSpawned throws', { timeout: 30_000 }, () => withAttempt(async current => { + const pipeHolder = await runExecRole(spec({ mode: 'fork-and-exit-0', timeoutMs: 3_000 }), context(current)); + assert.equal(pipeHolder.status, 'completed'); + assert.equal(pipeHolder.timedOut, false); + assert.equal(pipeHolder.exitCode, 0); + const { child: pipeChild } = JSON.parse(pipeHolder.stdout.trim()) as { readonly child: number }; + assert.ok(pipeChild > 0); + gone(pipeHolder.pgid); + assert.throws(() => process.kill(pipeChild, 0), { code: 'ESRCH' }); + + const bgChild = await runExecRole(spec({ mode: 'fork-bg-exit-0', timeoutMs: 3_000 }), context(current)); + assert.equal(bgChild.status, 'completed'); + const { child: detachedInGroup } = JSON.parse(bgChild.stdout.trim()) as { readonly child: number }; + assert.ok(detachedInGroup > 0); + gone(bgChild.pgid); + assert.throws(() => process.kill(detachedInGroup, 0), { code: 'ESRCH' }); + + let thrownPgid = 0; + await assert.rejects( + runExecRole(spec({ mode: 'sleep' }), context(current, { + onSpawned: async id => { + thrownPgid = id; + throw new Error('spawn-record-failed'); + }, + })), + /spawn-record-failed/, + ); + assert.ok(thrownPgid > 1); + gone(thrownPgid); +})); + test('exec role captures each stream up to captureBytes and reports truncation', () => withAttempt(async current => { const truncated = await runExecRole(spec({ mode: 'flood', captureBytes: EXEC_LIMITS.captureBytesMin }), context(current)); assert.equal(truncated.stdout.length, EXEC_LIMITS.captureBytesMin); assert.equal(truncated.stderr.length, EXEC_LIMITS.captureBytesMin); @@ -149,11 +185,37 @@ test('exec role captures each stream up to captureBytes and reports truncation', assert.equal(full.stdout, FLOOD); assert.equal(full.stderr, FLOOD); assert.equal(full.stdoutTruncated, false); assert.equal(full.stderrTruncated, false); })); -test('exec role reads the usage file after exit into request records and yields none when the file is missing', () => withAttempt(async current => { +test('exec role reads the usage file after exit into request records (including >128 items and empty arrays) and distinguishes usageReported from absent usageOut', () => withAttempt(async current => { const written = await runExecRole(spec({ mode: 'write-usage' }), context(current)); assert.deepEqual(written.usage, [{ requestId: 'req_1', inputTokens: 120, outputTokens: 45, costMicrousd: 1500 }]); + assert.equal(written.usageReported, true); + + const empty = await runExecRole(spec({ mode: 'write-empty-usage' }), context(current, { usageOut: join(current.scratchDir, 'empty-usage.json') })); + assert.deepEqual(empty.usage, []); + assert.equal(empty.usageReported, true); + + const many = await runExecRole(spec({ mode: 'write-150-usage' }), context(current, { usageOut: join(current.scratchDir, 'many-usage.json') })); + assert.equal(many.usage.length, 150); + assert.equal(many.usageReported, true); + assert.equal(many.usage[149]?.requestId, 'req_149'); + const missing = await runExecRole(spec(), context(current, { usageOut: join(current.scratchDir, 'absent.json') })); assert.deepEqual(missing.usage, []); + assert.equal(missing.usageReported, false); +})); + +test('exec role refuses symlinked or oversized usage files with ARTIFACT_INVALID / OUTPUT_LIMIT', () => withAttempt(async current => { + await assert.rejects(runExecRole(spec({ mode: 'write-symlink-usage' }), context(current, { usageOut: join(current.scratchDir, 'link-usage.json') })), refusal('ARTIFACT_INVALID')); + + const targetDir = join(current.root, 'outside'); + await mkdir(targetDir, { mode: 0o700 }); + await writeFile(join(targetDir, 'usage.json'), JSON.stringify({ requests: [] })); + await symlink(targetDir, join(current.scratchDir, 'dir-link')); + await assert.rejects(runExecRole(spec(), context(current, { usageOut: join(current.scratchDir, 'dir-link', 'usage.json') })), refusal('ARTIFACT_INVALID')); + + const hugePath = join(current.scratchDir, 'huge-usage.json'); + await writeFile(hugePath, ' '.repeat(262_145)); + await assert.rejects(runExecRole(spec(), context(current, { usageOut: hugePath })), refusal('OUTPUT_LIMIT')); })); test('exec role refuses a malformed usage file with SUBMISSION_INVALID after the child is gone', () => withAttempt(async current => { @@ -176,9 +238,12 @@ test('exec role refuses an invalid command[0], colliding env names, non-exec bin [spec({ captureBytes: EXEC_LIMITS.captureBytesMin - 1 }), 'CONFIG_SCHEMA'], [spec({ captureBytes: EXEC_LIMITS.captureBytesMax + 1 }), 'CONFIG_SCHEMA'], [spec({ timeoutMs: 0 }), 'CONFIG_SCHEMA'], + [spec({ timeoutMs: LOCAL_CHECK_LIMITS.timeoutMsMax + 1 }), 'CONFIG_SCHEMA'], ]; for (const [input, code] of cases) await assert.rejects(runExecRole(input, context(current, { secrets: forbiddenVault })), refusal(code)); await assert.rejects(runExecRole(spec(), context(current, { secrets: forbiddenVault, usageOut: join(current.root, 'usage.json') })), refusal('CONFIG_SCHEMA')); + await assert.rejects(runExecRole(spec(), context(current, { secrets: forbiddenVault, usageOut: `${current.scratchDir}/../usage.json` })), refusal('CONFIG_SCHEMA')); + await assert.rejects(runExecRole(spec(), context(current, { secrets: forbiddenVault, usageOut: current.scratchDir })), refusal('CONFIG_SCHEMA')); const aborted = new AbortController(); aborted.abort(); await assert.rejects(runExecRole(spec(), context(current, { secrets: forbiddenVault, signal: aborted.signal })), refusal('CANCELLED')); })); diff --git a/packages/controller/test/local-check-integration.test.ts b/packages/controller/test/local-check-integration.test.ts index 67b2db82..f8d5aaee 100644 --- a/packages/controller/test/local-check-integration.test.ts +++ b/packages/controller/test/local-check-integration.test.ts @@ -11,8 +11,9 @@ import { parsePrivateJson } from '../src/parser.js'; import { phaseCheckpointId } from '../src/progress.js'; import { canonical, hash, same } from '../src/schema.js';import { stateValue } from '../src/storage.js'; import type { ArtifactRef } from '@loopwright/core'; -import { cleanupFixture } from './local-check-fixtures.js'; +import { cleanupFixture, waitForMarker } from './local-check-fixtures.js'; import { COMMAND_CHECK_ID, commandCheckFixture, createPiMockPort } from './scheduling-fixtures.js'; +import { setFixture } from './progress-fixtures.js'; function assertOk(res: { readonly ok: boolean; readonly value?: T; readonly error?: ControllerDiagnostic }, msg = ''): T { assert.equal(res.ok, true, `${msg}: ${JSON.stringify(res.error)}`); if (!res.ok) throw new Error('expected ok'); return res.value as T; } @@ -133,3 +134,80 @@ test('inspect exports every verifier receipt generation with its output referenc assert.equal('script' in (inspected.receipts[1]!.receipt as object), false, 'the implicit byte-verifier receipts keep their own shape'); } finally { await cleanupFixture(f); } }); + +test('cancelling or hitting the work deadline mid-command.v1 check kills the process group, settles the operation, and finalizes cancelled or expired instead of reconcile_required', async () => { + // 1. Operator cancellation mid-script -> cancelled (never reconcile_required) + const fCancel = await commandCheckFixture({ script: 'scripts/sleep.sh', parameters: { timeoutMs: 60_000 } }), runIdCancel = 'run-local-check-cancel'; + try { + const abort = new AbortController(); + const executionPromise = runCycleWithPorts( + { configuration: fCancel.loaded, repository: fCancel.repository, runRoot: fCancel.runRoot, runId: runIdCancel, signal: abort.signal }, + {}, + ); + const artifactsDir = join(fCancel.runRoot, runIdCancel, 'artifacts'); + let bindingPath = ''; + const deadline = Date.now() + 10_000; + while (Date.now() < deadline) { + const files = await readdir(artifactsDir).catch(() => [] as string[]); + const found = files.find(name => /^local-check-producer-[0-9a-f]{64}\.binding\.json$/.test(name)); + if (found) { + bindingPath = join(artifactsDir, found); + break; + } + await new Promise(r => setTimeout(r, 20)); + } + assert.ok(bindingPath.length > 0, 'binding marker written'); + await waitForMarker(bindingPath, 5_000); + abort.abort(); + const execution = assertOk(await executionPromise, 'cancelled run'); + assert.equal(execution.kind, 'result', JSON.stringify(execution)); + if (execution.kind === 'result') { + assert.equal(execution.result.spec.status, 'cancelled'); + } + const descriptor = JSON.parse(await readFile(join(fCancel.runRoot, runIdCancel, 'run.json'), 'utf8')) as RunDescriptor; + const store = stateValue(reopenLocalRun(descriptor.identity)); + try { + assert.equal(stateValue(store.inspect()).counts.unresolvedOperations, 0); + } finally { + stateValue(store.close()); + } + assert.deepEqual(await readdir(join(fCancel.runRoot, 'workspaces', runIdCancel)), []); + } finally { + await cleanupFixture(fCancel); + } + + // 2. Work deadline firing mid-script -> expired (never cancelled or reconcile_required) + const fExpire = await commandCheckFixture({ author: true, script: 'scripts/sleep.sh', parameters: { timeoutMs: 2_500 } }), runIdExpire = 'run-local-check-expire'; + try { + setFixture(fExpire.config, ['spec', 'controls', 'drainReserveMs'], 120_000); + setFixture(fExpire.config, ['spec', 'task', 'spec', 'budgets', 'wallTimeMs'], 122_600); + await fExpire.save(); + const reloaded = assertOk(await fExpire.load(), 'load tight-deadline config'); + const basePort = createPiMockPort(() => AUTHOR()); + const execution = assertOk( + await runCycleWithPorts( + { configuration: reloaded, repository: fExpire.repository, runRoot: fExpire.runRoot, runId: runIdExpire }, + { + openAdapter: async (host, input) => { + await new Promise(resolve => setTimeout(resolve, 900)); + return basePort(host, input); + }, + }, + ), + 'expired run', + ); + assert.equal(execution.kind, 'result', JSON.stringify(execution)); + if (execution.kind === 'result') { + assert.equal(execution.result.spec.status, 'expired'); + } + const descriptor = JSON.parse(await readFile(join(fExpire.runRoot, runIdExpire, 'run.json'), 'utf8')) as RunDescriptor; + const store = stateValue(reopenLocalRun(descriptor.identity)); + try { + assert.equal(stateValue(store.inspect()).counts.unresolvedOperations, 0); + } finally { + stateValue(store.close()); + } + } finally { + await cleanupFixture(fExpire); + } +}); diff --git a/packages/controller/test/local-check.test.ts b/packages/controller/test/local-check.test.ts index df150854..8eeae276 100644 --- a/packages/controller/test/local-check.test.ts +++ b/packages/controller/test/local-check.test.ts @@ -1,7 +1,7 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { execFileSync } from 'node:child_process'; -import { readFile, readdir } from 'node:fs/promises'; +import { mkdir, readFile, readdir, symlink, writeFile } from 'node:fs/promises'; import { join } from 'node:path'; import { LOCAL_CHECK_ENV_FIXED, LOCAL_CHECK_ENV_NAMES, LOCAL_CHECK_PATH_BASE, bindSubject } from '@loopwright/core'; import { TOKEN } from './config-fixtures.js'; @@ -12,7 +12,7 @@ import { } from './local-check-fixtures.js'; import type { Authority } from '@loopwright/state'; import { ControllerFailure } from '../src/errors.js'; -import { LOCAL_CHECK_OUTPUT_BYTES, LOCAL_CHECK_PRODUCER_ID, LocalCheck, authenticatedLocalCheck, prepareLocalCheck, type LocalCheckReceipt } from '../src/local-check.js'; +import { LOCAL_CHECK_OUTPUT_BYTES, LOCAL_CHECK_PRODUCER_ID, LOCAL_CHECK_STDERR_BYTES, LocalCheck, authenticatedLocalCheck, prepareLocalCheck, readLocalCheckScriptDirectory, type LocalCheckReceipt } from '../src/local-check.js'; import { parsePrivateJson } from '../src/parser.js'; import { canonical, hash, same } from '../src/schema.js'; import { inside } from '../src/files.js'; @@ -131,20 +131,38 @@ test('a script that runs past timeoutMs settles failed/check_timeout with the pr } finally { await h.release(); } }); -test('aborting the signal kills the group, discards the workspace and refuses CANCELLED without a proof', async () => { +test('aborting the signal kills the group, discards the workspace, settles the operation, and refuses CANCELLED or DEADLINE', async () => { const h = await live({}, commandHandler({ script: 'scripts/sleep.sh', timeoutMs: SIGNALED_EXIT })); try { - const abort = new AbortController(); setTimeout(() => abort.abort(), 300); - await assert.rejects(() => h.check.run(h.job, abort.signal), error => failure(error) === 'CANCELLED'); + const abort = new AbortController(); const prefix = markerPrefix(h.context.artifacts.directory, h.job.operationId, NONCE); - assert.equal(await exists(prefix + '.binding.json'), true); assert.equal(await exists(prefix + '.proof.json'), false); - assert.equal(groupGone(Number(parse(await readFile(prefix + '.binding.json'), 1048576).pgid)), true); - assert.equal(h.operation().state, 'dispatch_uncertain'); + const running = h.check.run(h.job, abort.signal); + const binding = await waitForMarker(prefix + '.binding.json', 10_000); + abort.abort(); + await assert.rejects(() => running, error => failure(error) === 'CANCELLED'); + assert.equal(await exists(prefix + '.binding.json'), true); + assert.equal(await exists(prefix + '.proof.json'), true); + assert.equal(groupGone(Number(binding.pgid)), true); + assert.equal(h.operation().state, 'confirmed'); + assert.equal(stateValue(h.context.store.inspect()).counts.unresolvedOperations, 0); await assertWorkspaceDiscarded(h); const settled = await h.check.restore(h.job); assert.equal(settled.status, 'blocked'); assert.equal(settled.reason, 'EVIDENCE_UNAVAILABLE'); assert.equal(h.operation().state, 'confirmed'); } finally { await h.release(); } + + const d = await live({}, commandHandler({ script: 'scripts/sleep.sh', timeoutMs: SIGNALED_EXIT }), 'run-local-check-deadline'); + try { + const prefix = markerPrefix(d.context.artifacts.directory, d.job.operationId, NONCE); + const running = d.check.run(d.job, d.cycle.deadline.abort.signal); + const binding = await waitForMarker(prefix + '.binding.json', 10_000); + d.cycle.deadline.stop('DEADLINE'); + await assert.rejects(() => running, error => failure(error) === 'DEADLINE'); + assert.equal(groupGone(Number(binding.pgid)), true); + assert.equal(d.operation().state, 'confirmed'); + assert.equal(stateValue(d.context.store.inspect()).counts.unresolvedOperations, 0); + await assertWorkspaceDiscarded(d); + } finally { await d.release(); } }); test('a controller killed between the binding and proof markers settles blocked/EVIDENCE_UNAVAILABLE, kills the group, discards the workspace and is never re-dispatched', async () => { @@ -222,20 +240,21 @@ test('the child environment is exactly the F1 contract plus the configured env, } finally { delete process.env.LOOPWRIGHT_T3_SENTINEL; await h.release(); } }); -test('a generic token on stderr is scrubbed into the output artifact and a vault secret on stderr never reaches any receipt', async () => { - const generic = 'ghp_ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; - // The fake tokens travel through `env`; a token committed to the repository would be refused by freezeSource itself. +test('generic tokens and vault secrets on stderr are scrubbed into the output artifact, while a vault secret in check-out is refused', async () => { + const generic = 'sk-ant-api03-ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; const echo = { path: 'scripts/echo-env.sh', content: '#!/bin/sh\nprintf \'generic=%s\\nvault=%s\\n\' "$GENERIC" "$LEAKED" >&2\nexit 0\n', executable: true } as const; - const a = await live({ extra: [echo] }, commandHandler({ script: 'scripts/echo-env.sh', env: { GENERIC: generic } })); + const a = await live({ extra: [echo] }, commandHandler({ script: 'scripts/echo-env.sh', env: { GENERIC: generic, LEAKED: TOKEN } })); try { const verified = await a.check.run(a.job, new AbortController().signal); assert.equal(verified.status, 'passed'); const bytes = authenticatedLocalCheck(verified).outputBytes; assert.ok(!Buffer.from(bytes).includes(generic), 'generic token scrubbed'); - assert.equal((parse(bytes).observation as Record).stderrTail, 'generic=[scrubbed]\nvault=\n'); + assert.ok(!Buffer.from(bytes).includes(TOKEN), 'vault secret scrubbed from stderr'); + assert.equal((parse(bytes).observation as Record).stderrTail, 'generic=[scrubbed]\nvault=[scrubbed]\n'); await assertWorkspaceDiscarded(a); } finally { await a.release(); } - const b = await live({ extra: [echo] }, commandHandler({ script: 'scripts/echo-env.sh', env: { LEAKED: TOKEN } })); + const leakOut = { path: 'scripts/leak-out.sh', content: '#!/bin/sh\nprintf \'{"detail":"%s"}\\n\' "$LEAKED" > "$LOOPWRIGHT_CHECK_OUT"\nexit 0\n', executable: true } as const; + const b = await live({ extra: [leakOut] }, commandHandler({ script: 'scripts/leak-out.sh', env: { LEAKED: TOKEN } })); try { await assert.rejects(() => b.check.run(b.job, new AbortController().signal), error => failure(error) === 'CONFIG_CREDENTIAL_INVALID'); assert.equal(b.operation().state, 'dispatch_uncertain'); @@ -243,6 +262,8 @@ test('a generic token on stderr is scrubbed into the output artifact and a vault assert.equal(names.some(name => /^local-check-(?:output|receipt)-/.test(name)), false, 'no evidence written'); const settled = await b.check.restore(b.job); assert.equal(settled.status, 'blocked'); assert.equal(settled.reason, 'EVIDENCE_UNAVAILABLE'); + const again = await b.check.restore(b.job); + assert.equal(same(again, settled), true, 'second restore on settled interrupted proof succeeds idempotently'); for (const ref of [settled.output, settled.receipt]) assert.equal(Buffer.from(await b.context.artifacts.read(ref, LOCAL_CHECK_OUTPUT_BYTES)).includes(TOKEN), false); assert.ok(!(await readFile(markerPrefix(b.context.artifacts.directory, b.job.operationId, NONCE) + '.binding.json', 'utf8')).includes(TOKEN)); await assertWorkspaceDiscarded(b); @@ -273,6 +294,8 @@ test('exit 0 without an output file passes with no detail, and an invalid output test('refusals before the intent leave no operation and discard the workspace: non-executable script, unprotected directory, digest mismatch, missing toolchain path', async () => { const cases: { readonly name: string; readonly options: LocalCheckFixtureOptions; readonly handler: Handler; readonly code: string; readonly recorded?: Digest }[] = [ { name: 'non-executable script', options: { extra: [{ path: 'scripts/noexec.sh', content: '#!/bin/sh\nexit 0\n' }] }, handler: commandHandler({ script: 'scripts/noexec.sh' }), code: 'CONFIG_REFERENCE' }, + { name: 'missing shebang script', options: { extra: [{ path: 'scripts/noshebang.sh', content: 'exit 0\n', executable: true }] }, handler: commandHandler({ script: 'scripts/noshebang.sh' }), code: 'CONFIG_REFERENCE' }, + { name: 'single-file scope protection', options: { protected: ['scripts/pass.sh'] }, handler: commandHandler(), code: 'CONFIG_SCHEMA' }, { name: 'unprotected sibling', options: { protected: ['scripts/*.sh'], extra: [{ path: 'scripts/README.md', content: 'operator notes\n' }] }, handler: commandHandler(), code: 'CONFIG_SCHEMA' }, { name: 'digest mismatch', options: {}, handler: commandHandler(), code: 'CONFIG_REFERENCE', recorded: hash('not-the-admitted-directory') }, { name: 'missing toolchain path', options: {}, handler: commandHandler({ toolchainPaths: ['missing/bin'] }), code: 'CONFIG_REFERENCE' }, @@ -314,3 +337,52 @@ test('localCheckScriptDirectoryDigest is order-independent over entries and boun assert.deepEqual(localCheckScriptDirectoryDigest(entries), localCheckScriptDirectoryDigest([...entries].reverse())); assert.equal(same(localCheckScriptDirectoryDigest(entries), localCheckScriptDirectoryDigest([{ ...entries[0]!, sha256: 'c'.repeat(64) }, entries[1]!])), false); }); + +test('stderr rolling tail caps memory at 16 KiB across multi-chunk floods and readLocalCheckScriptDirectory / toolchainPaths reject symlinks', async () => { + const floodScript = { + path: 'scripts/stderr-flood.sh', + content: '#!/bin/sh\ni=0\nwhile [ "$i" -lt 64 ]; do\n printf \'%01023d\\n\' "$i" >&2\n i=$((i + 1))\ndone\nprintf \'TAIL-MARKER-END\\n\' >&2\nexit 0\n', + executable: true, + } as const; + const h = await live({ extra: [floodScript] }, commandHandler({ script: 'scripts/stderr-flood.sh' }), 'run-stderr-tail'); + try { + const verified = await h.check.run(h.job, new AbortController().signal); + assert.equal(verified.status, 'passed'); + const observation = parse(authenticatedLocalCheck(verified).outputBytes).observation as Record; + assert.equal(observation.stderrTruncated, true); + const tail = String(observation.stderrTail); + assert.equal(Buffer.byteLength(tail, 'utf8'), LOCAL_CHECK_STDERR_BYTES); + assert.ok(tail.endsWith('TAIL-MARKER-END\n')); + + // Symlink checks on baseline tree reader: symlinked script, symlinked sibling, symlinked parent dir + const symRoot = join(h.f.root, 'symlink-baseline'); + await mkdir(join(symRoot, 'scripts'), { recursive: true, mode: 0o700 }); + await writeFile(join(symRoot, 'real.sh'), '#!/bin/sh\nexit 0\n', { mode: 0o755 }); + await symlink(join(symRoot, 'real.sh'), join(symRoot, 'scripts', 'pass.sh')); + await assert.rejects(() => readLocalCheckScriptDirectory(symRoot, 'scripts/pass.sh'), error => failure(error) === 'ARTIFACT_INVALID'); + + const sibRoot = join(h.f.root, 'sibling-link-baseline'); + await mkdir(join(sibRoot, 'scripts'), { recursive: true, mode: 0o700 }); + await writeFile(join(sibRoot, 'scripts', 'pass.sh'), '#!/bin/sh\nexit 0\n', { mode: 0o755 }); + await symlink(join(symRoot, 'real.sh'), join(sibRoot, 'scripts', 'helper-link.sh')); + await assert.rejects(() => readLocalCheckScriptDirectory(sibRoot, 'scripts/pass.sh'), error => failure(error) === 'ARTIFACT_INVALID'); + + const parentLinkRoot = join(h.f.root, 'parent-link-baseline'); + await mkdir(parentLinkRoot, { recursive: true, mode: 0o700 }); + await symlink(join(symRoot, 'scripts'), join(parentLinkRoot, 'scripts')); + await assert.rejects(() => readLocalCheckScriptDirectory(parentLinkRoot, 'scripts/pass.sh'), error => failure(error) === 'ARTIFACT_INVALID'); + } finally { await h.release(); } + + // Symlinked toolchainPaths (in a v2 git baseline carrying a 120000 symlink or a regular file in place of a toolchain directory) are refused before putIntent + const symRun = await live({ extra: [{ path: 'tools/bin/tool.sh', content: '#!/bin/sh\nexit 0\n', executable: true }] }, + commandHandler({ toolchainPaths: ['tools/bin'] }), 'run-symlink-toolchain'); + try { + const fileAsToolchain = commandHandler({ toolchainPaths: ['scripts/pass.sh'] }); + const planWithFileToolchain = { ...symRun.plan, verifierSlots: [...symRun.plan.verifierSlots.filter(s => s.id !== SLOT_ID), { id: SLOT_ID, checkId: CHECK_ID, implicit: null, handler: fileAsToolchain }] }; + const badJob = prepareLocalCheck(planWithFileToolchain, symRun.context.lock, SLOT_ID, symRun.candidate, 0, NONCE, symRun.recorded); + const badCheck = new LocalCheck(symRun.context.store, symRun.context.authority, symRun.context.artifacts, planWithFileToolchain, symRun.context.lock, () => symRun.bound.value, { runRoot: symRun.f.runRoot, cycle: symRun.cycle }); + await assert.rejects(() => badCheck.run(badJob, new AbortController().signal), error => failure(error) === 'CONFIG_REFERENCE'); + assert.equal(symRun.context.store.getOperation(badJob.operationId).ok, false); + await assertWorkspaceDiscarded(symRun); + } finally { await symRun.release(); } +}); diff --git a/packages/controller/test/recovery-cycle.test.ts b/packages/controller/test/recovery-cycle.test.ts index 071ce712..76a30679 100644 --- a/packages/controller/test/recovery-cycle.test.ts +++ b/packages/controller/test/recovery-cycle.test.ts @@ -1,12 +1,12 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import { readFile, writeFile, lstat, readdir, rename } from 'node:fs/promises'; +import { mkdir, readFile, writeFile, lstat, readdir, rename } from 'node:fs/promises'; import { join } from 'node:path'; import { randomBytes } from 'node:crypto'; import { bindSubject } from '@loopwright/core'; import { reopenLocalRun, type Authority } from '@loopwright/state'; import { cycleFixture, commandCheckFixture, COMMAND_CHECK_ID } from './scheduling-fixtures.js'; -import { cleanupFixture, exists, groupGone, markerPrefix, releaseCycle, waitForMarker } from './local-check-fixtures.js'; +import { attemptDirectory, cleanupFixture, exists, groupGone, markerPrefix, releaseCycle, waitForMarker } from './local-check-fixtures.js'; import { createCycle, Cycle, type CycleContext, type RunDescriptor } from '../src/controller.js'; import { recordedLocalCheck } from '../src/compile.js'; import { ControllerFailure } from '../src/errors.js'; @@ -133,6 +133,7 @@ test('recovery: a command.v1 operation left with a binding marker and no proof m const later = { path: 'scripts/exit-later.sh', content: '#!/bin/sh\nsleep 0.3\nexit 0\n', executable: true } as const; const f = await commandCheckFixture({ script: 'scripts/exit-later.sh', extra: [later] }), input = { configuration: f.loaded, repository: f.repository, runRoot: f.runRoot, runId: 'resume-command-crash' }; const context = await createCycle(input, {}); + let released = false; try { const head = await bootstrap(context), cycle = new Cycle(context, head); const slot = context.plan.verifierSlots.find(item => item.handler.implementation === 'command.v1')!, ordinal = context.plan.verifierSlots.indexOf(slot), nonce = randomBytes(16).toString('hex'); @@ -140,14 +141,20 @@ test('recovery: a command.v1 operation left with a binding marker and no proof m const job = prepareLocalCheck(context.plan, context.lock, slot.id, candidate, 0, nonce, recordedLocalCheck(slot)); await context.progress.publish({ ...head.progress, stage: { ...head.progress.stage, kind: 'verifier_pre' }, verifierReceipts: [{ slot: slot.id, generation: 0, operationId: job.operationId, producerNonce: nonce, output: null, receipt: null }] }, `verify.0.${ordinal}.pre`); const dead = { aborted: false, addEventListener() {}, removeEventListener() {} }; - const continuation = cycle.localCheck.run(job, dead as unknown as AbortSignal).then(() => assert.fail('a dead controller cannot complete'), error => { assert.equal(error instanceof ControllerFailure ? error.diagnostic.code : String(error), 'CANCELLED'); }); - const prefix = markerPrefix(context.artifacts.directory, job.operationId, nonce); await waitForMarker(prefix + '.binding.json', 10_000); dead.aborted = true; + const continuation = cycle.localCheck.run(job, dead as unknown as AbortSignal).then(() => assert.fail('a dead controller cannot complete'), error => { assert.equal(error instanceof ControllerFailure ? error.diagnostic.code : String(error), 'AUTHORITY_REFUSED'); }); + const prefix = markerPrefix(context.artifacts.directory, job.operationId, nonce); await waitForMarker(prefix + '.binding.json', 10_000); + dead.aborted = true; + stateValue(context.store.release(context.authority)); + released = true; await continuation; assert.equal(await exists(prefix + '.proof.json'), false, 'no proof without a live controller'); assert.equal(stateValue(context.store.getOperation(job.operationId)).state, 'dispatch_uncertain'); await cycle.deadline.dispose(); await cycle.events.close(); - } finally { stateValue(context.store.release(context.authority)); stateValue(context.store.close()); await context.owner.release(); } + } finally { if (!released) stateValue(context.store.release(context.authority)); stateValue(context.store.close()); await context.owner.release(); } try { - const result = await resumeCycle(input); assert.ok(result.ok, JSON.stringify(result)); if (!result.ok || result.value.kind !== 'result') return; + const result = await resumeCycle(input); + assert.ok(result.ok, JSON.stringify(result)); + assert.equal(result.value.kind, 'result', JSON.stringify(result)); + if (result.value.kind !== 'result') assert.fail(JSON.stringify(result)); assert.equal(result.value.result.spec.status, 'blocked'); const row = result.value.result.spec.verification.spec.required.find(item => item.checkId === COMMAND_CHECK_ID)!; assert.equal(row.status, 'blocked'); assert.equal(row.detail, 'EVIDENCE_UNAVAILABLE'); @@ -165,4 +172,44 @@ test('recovery: a command.v1 operation left with a binding marker and no proof m assert.deepEqual(await readdir(join(f.runRoot, 'workspaces', input.runId)), [], 'no workspace leftovers'); } finally { await cleanupFixture(f); } } + // Part 3: crash after authorizeOperationDispatch and workspace materialization, BEFORE .binding.json is written. + { + const f = await commandCheckFixture({ script: 'scripts/pass.sh' }), input = { configuration: f.loaded, repository: f.repository, runRoot: f.runRoot, runId: 'resume-command-no-binding' }; + const context = await createCycle(input, {}); + try { + const head = await bootstrap(context); + const slot = context.plan.verifierSlots.find(item => item.handler.implementation === 'command.v1')!, ordinal = context.plan.verifierSlots.indexOf(slot), nonce = randomBytes(16).toString('hex'); + const candidate = { manifest: context.source.manifest, ref: head.progress.candidate.manifest, files: context.source.artifacts, baselineProofs: context.source.baselineProofs }; + const job = prepareLocalCheck(context.plan, context.lock, slot.id, candidate, 0, nonce, recordedLocalCheck(slot)); + await context.progress.publish({ ...head.progress, stage: { ...head.progress.stage, kind: 'verifier_pre' }, verifierReceipts: [{ slot: slot.id, generation: 0, operationId: job.operationId, producerNonce: nonce, output: null, receipt: null }] }, `verify.0.${ordinal}.pre`); + const attemptId = 'check.' + hash(job.operationId + '\0' + nonce).hex.slice(0, 40); + const workspaceDir = attemptDirectory(f.runRoot, input.runId, attemptId); + await mkdir(workspaceDir, { recursive: true, mode: 0o700 }); + await mkdir(join(workspaceDir, 'baseline'), { mode: 0o500 }); + const target = 'command:' + slot.id + ':0:' + head.checkpoint.subject.candidateDigest.hex; + stateValue(context.store.putIntent(context.authority, { operationId: job.operationId, nodeId: context.plan.orderedDAG[0]!.id, attemptId, effect: 'read_only', requestDigest: job.requestDigest, targetIdentity: target })); + stateValue(context.store.authorizeOperationDispatch(context.authority, job.operationId)); + const prefix = markerPrefix(context.artifacts.directory, job.operationId, nonce); + assert.equal(await exists(prefix + '.binding.json'), false); + assert.equal(await exists(prefix + '.proof.json'), false); + } finally { + await release(context); + } + try { + const result = await resumeCycle(input); + assert.ok(result.ok, JSON.stringify(result)); + assert.equal(result.value.kind, 'result', JSON.stringify(result)); + if (result.value.kind !== 'result') assert.fail(JSON.stringify(result)); + assert.equal(result.value.result.spec.status, 'blocked'); + const row = result.value.result.spec.verification.spec.required.find(item => item.checkId === COMMAND_CHECK_ID)!; + assert.equal(row.status, 'blocked'); assert.equal(row.detail, 'EVIDENCE_UNAVAILABLE'); + const inspectOut = join(f.root, 'inspect-no-binding'); + const inspected = await inspectRun({ runRoot: f.runRoot, runId: input.runId, output: inspectOut }); + assert.ok(inspected.ok); + const receipts = JSON.parse(await readFile(join(inspectOut, 'verifier-receipts.json'), 'utf8')) as { readonly entries: readonly { readonly slot: string; readonly receipt: { readonly scriptDigest: unknown } | null }[] }; + const cmdReceipt = receipts.entries.find(item => item.slot === COMMAND_SLOT_ID); + assert.equal(cmdReceipt?.receipt?.scriptDigest, null, 'missing binding settles with scriptDigest: null'); + assert.deepEqual(await readdir(join(f.runRoot, 'workspaces', input.runId)), [], 'no workspace leftovers'); + } finally { await cleanupFixture(f); } + } }); diff --git a/packages/controller/test/registry-command-v1.test.ts b/packages/controller/test/registry-command-v1.test.ts index 8f28a180..2c0389de 100644 --- a/packages/controller/test/registry-command-v1.test.ts +++ b/packages/controller/test/registry-command-v1.test.ts @@ -103,10 +103,21 @@ test('command.v1 parameters refuse unknown or missing keys with CONFIG_SCHEMA', } }); -test('command.v1 env refuses reserved names, malformed names, non-strings, and too many entries', () => { +test('command.v1 env refuses reserved names, malformed names, non-strings, NUL values, and too many entries', () => { const envCases: readonly { readonly name: string; readonly env: unknown }[] = [ { name: 'reserved LOOPWRIGHT_RUN_ID', env: { LOOPWRIGHT_RUN_ID: 'run-1' } }, { name: 'reserved LOOPWRIGHT_ prefix', env: { LOOPWRIGHT_STEP_ID: 'build' } }, + { name: 'reserved PATH', env: { PATH: '/custom/bin' } }, + { name: 'reserved HOME', env: { HOME: '/tmp' } }, + { name: 'reserved TMPDIR', env: { TMPDIR: '/tmp' } }, + { name: 'reserved LANG', env: { LANG: 'en_US.UTF-8' } }, + { name: 'reserved LC_ALL', env: { LC_ALL: 'en_US.UTF-8' } }, + { name: 'reserved TERM', env: { TERM: 'xterm' } }, + { name: 'reserved GIT_CONFIG_NOSYSTEM', env: { GIT_CONFIG_NOSYSTEM: '0' } }, + { name: 'reserved GIT_CONFIG_GLOBAL', env: { GIT_CONFIG_GLOBAL: '/etc/gitconfig' } }, + { name: 'reserved GIT_TERMINAL_PROMPT', env: { GIT_TERMINAL_PROMPT: '1' } }, + { name: 'reserved GIT_ASKPASS', env: { GIT_ASKPASS: '/bin/echo' } }, + { name: 'NUL in env value', env: { FORGEVO_KERNEL_ID: 'rmsnorm\0bad' } }, { name: 'lowercase name', env: { forgevo_kernel_id: 'x' } }, { name: 'digit-leading name', env: { '1FORGE': 'x' } }, { name: 'lowercase letter in tail', env: { FORGEVO_kernel: 'x' } }, @@ -126,6 +137,7 @@ test('command.v1 args, toolchainPaths, script, and timeoutMs refuse out-of-bound const cases: readonly { readonly name: string; readonly mutate: (registry: Record) => void }[] = [ { name: 'sixty-five args', mutate: registry => set(registry, ['spec', 'handlers', 0, 'parameters', 'args'], Array.from({ length: 65 }, (_, i) => 'arg-' + i)) }, { name: 'non-string arg', mutate: registry => set(registry, ['spec', 'handlers', 0, 'parameters', 'args'], [3]) }, + { name: 'NUL in arg', mutate: registry => set(registry, ['spec', 'handlers', 0, 'parameters', 'args'], ['--flag\0bad']) }, { name: 'thirty-three toolchainPaths', mutate: registry => set(registry, ['spec', 'handlers', 0, 'parameters', 'toolchainPaths'], Array.from({ length: 33 }, (_, i) => 'toolchains/' + i)) }, { name: 'absolute script', mutate: registry => set(registry, ['spec', 'handlers', 0, 'parameters', 'script'], '/etc/passwd') }, { name: 'escaping script', mutate: registry => set(registry, ['spec', 'handlers', 0, 'parameters', 'script'], '../forge-evaluate.sh') }, diff --git a/packages/controller/test/rework.test.ts b/packages/controller/test/rework.test.ts index b9664b8e..56c3f9b2 100644 --- a/packages/controller/test/rework.test.ts +++ b/packages/controller/test/rework.test.ts @@ -1975,3 +1975,48 @@ test('controller.ts: a command.v1 check that fails twice with the same reason on } finally { await cycle.deadline.dispose(); await cycle.events.close(); stateValue(ctx.store.release(ctx.authority)); stateValue(ctx.store.close()); await ctx.owner.release(); } } finally { await cleanupFixture(g); } }); + +test('controller.ts: ANSI escapes and C0/DEL/C1 control characters in command.v1 check-out detail are sanitized before StepVerdict serialization so onRework never fails with RECOVERY_REQUIRED', async () => { + const ansiScript: FixtureExtra = { + path: 'scripts/ansi-decide.sh', + content: [ + '#!/bin/sh', + 'if [ -f "$LOOPWRIGHT_CANDIDATE_DIR/packages/ok" ]; then', + ' printf \'{"metrics":{"fixed":1}}\' > "$LOOPWRIGHT_CHECK_OUT"', + ' exit 0', + 'fi', + 'printf \'{"detail":"\\u001b[31mANSI failure\\u001b[0m\\u0007\\u007f\\u009b line 2"}\' > "$LOOPWRIGHT_CHECK_OUT"', + 'exit 1', + '', + ].join('\n'), + executable: true, + }; + const f = await commandCheckFixture({ script: 'scripts/ansi-decide.sh', extra: [ansiScript], author: true, onRework: 1 }); + try { + const prompts: string[] = []; + const res = assertOk( + await runCycleWithPorts( + { configuration: f.loaded, repository: f.repository, runRoot: f.runRoot, runId: 'run-command-ansi-rework' }, + { + openAdapter: createPiMockPort(({ prompt }) => { + prompts.push(prompt); + return { + files: { 'packages/draft.txt': 'v1\n', ...(prompts.length === 2 ? { 'packages/ok': '' } : {}) }, + responseJson: AUTHOR_SUBMISSION, + }; + }), + }, + ), + 'command.v1 ANSI detail rework run', + ); + assert.equal(res.kind, 'result', JSON.stringify(res)); + if (res.kind !== 'result') return; + assert.equal(res.result.spec.status, 'completed'); + assert.equal(prompts.length, 2); + assert.match(prompts[1]!, /ANSI failure/); + assert.equal(res.stepVerdicts?.length, 1); + assert.equal(res.findings?.length, 1); + } finally { + await cleanupFixture(f); + } +}); diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index c4328e02..f54bc9ba 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -13,7 +13,7 @@ export { } from './scope.js'; export { isWritablePath, resolveOverlayLimits, matchesDriverConstraint, handlerCapability, - type TaskContract, type ReworkPolicy, type Digest, type ArtifactRef, type EvidenceLevel, type CheckStatus, + type HandlerCapability, type TaskContract, type ReworkPolicy, type Digest, type ArtifactRef, type EvidenceLevel, type CheckStatus, type MetricValue, type MetricsMap, type FindingSeverity, type StructuredFinding, type StepHandoffSource, type StepHandoffSelect, type StepHandoffSelector, type ResourceActivationPhase, type ResourceActivationRule, diff --git a/packages/core/src/scrubber.ts b/packages/core/src/scrubber.ts index cfd47d3a..9e006f5a 100644 --- a/packages/core/src/scrubber.ts +++ b/packages/core/src/scrubber.ts @@ -2,8 +2,12 @@ const GENERIC_SECRET_PATTERNS: readonly RegExp[] = Object.freeze([ /ghs_[A-Za-z0-9]{20,}/g, /ghu_[A-Za-z0-9]{20,}/g, /ghp_[A-Za-z0-9]{20,}/g, + /gh[pousr]_[A-Za-z0-9]{20,}/g, /github_pat_[A-Za-z0-9_]{20,}/g, /-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/g, + /-----BEGIN (?:RSA |EC |DSA |OPENSSH |ENCRYPTED )?PRIVATE KEY-----/g, + /sk-(?:ant-|proj-)[A-Za-z0-9_-]{20,}/g, + /(?= MIN_FORM_LENGTH) this.#forms.add(form); } diff --git a/packages/core/test/scrubber.test.ts b/packages/core/test/scrubber.test.ts index 7ae54b25..09ba856a 100644 --- a/packages/core/test/scrubber.test.ts +++ b/packages/core/test/scrubber.test.ts @@ -1,18 +1,25 @@ import assert from 'node:assert/strict'; import { describe, it } from 'node:test'; -import { SecretScrubber } from '../src/scrubber.js'; +import { SecretScrubber, type HandlerCapability } from '../src/index.js'; describe('SecretScrubber', () => { - it('scrubs registered secrets in raw, JSON-escaped, URL-encoded, and base64 forms', () => { + it('re-exports HandlerCapability from @loopwright/core root', () => { + const cap: HandlerCapability = 'host_execution'; + assert.equal(cap, 'host_execution'); + }); + + it('scrubs registered secrets in raw, JSON-escaped, slash-escaped, URL-encoded, and base64 forms', () => { const scrubber = new SecretScrubber(); - scrubber.register('hunter2-secret-value'); - const raw = 'token=hunter2-secret-value'; - const escaped = 'token="hunter2-secret-value"'; - const encoded = `token=${encodeURIComponent('hunter2-secret-value')}`; - const base64 = `token=${Buffer.from('hunter2-secret-value', 'utf8').toString('base64')}`; - for (const text of [raw, escaped, encoded, base64]) { + scrubber.register('hunter2/secret"value'); + scrubber.register('\ud800-lone-surrogate-secret'); + const raw = 'token=hunter2/secret"value'; + const escaped = 'token=hunter2/secret\\"value'; + const slashEscaped = 'token=hunter2\\/secret\\"value'; + const encoded = `token=${encodeURIComponent('hunter2/secret"value')}`; + const base64 = `token=${Buffer.from('hunter2/secret"value', 'utf8').toString('base64')}`; + for (const text of [raw, escaped, slashEscaped, encoded, base64]) { assert.equal(scrubber.containsSecret(text), true); - assert.equal(scrubber.scrub(text).includes('hunter2-secret-value'), false); + assert.equal(scrubber.scrub(text).includes('hunter2'), false); assert.equal(scrubber.scrub(text).includes('[scrubbed]'), true); } }); @@ -29,10 +36,22 @@ describe('SecretScrubber', () => { const scrubber = new SecretScrubber(); assert.equal(scrubber.containsSecret('found ghs_AAAABBBBCCCCDDDDEEEE token'), true); assert.equal(scrubber.containsSecret('found ghp_AAAABBBBCCCCDDDDEEEE token'), true); + assert.equal(scrubber.containsSecret('found gho_AAAABBBBCCCCDDDDEEEE token'), true); + assert.equal(scrubber.containsSecret('found ghr_AAAABBBBCCCCDDDDEEEE token'), true); assert.equal(scrubber.containsSecret('found github_pat_AAAA_BBBBCCCCDDDDEEEE token'), true); assert.equal(scrubber.containsSecret('-----BEGIN RSA PRIVATE KEY-----'), true); + assert.equal(scrubber.containsSecret('-----BEGIN DSA PRIVATE KEY-----'), true); + assert.equal(scrubber.containsSecret('-----BEGIN ENCRYPTED PRIVATE KEY-----'), true); + assert.equal(scrubber.containsSecret('sk-ant-api03-AAAABBBBCCCCDDDDEEEE'), true); + assert.equal(scrubber.containsSecret('sk-proj-AAAABBBBCCCCDDDDEEEE_1234'), true); + assert.equal(scrubber.containsSecret('aws=AKIA0123456789ABCDEF!'), true); + assert.equal(scrubber.containsSecret('XAKIA0123456789ABCDEF'), false); + assert.equal(scrubber.containsSecret('AKIA0123456789ABCDEFX'), false); assert.equal(scrubber.containsSecret('nothing secret here'), false); assert.equal(scrubber.scrub('keep ghs_AAAABBBBCCCCDDDDEEEE out'), 'keep [scrubbed] out'); + assert.equal(scrubber.scrub('keep gho_AAAABBBBCCCCDDDDEEEE out'), 'keep [scrubbed] out'); + assert.equal(scrubber.scrub('keep sk-ant-AAAABBBBCCCCDDDDEEEE out'), 'keep [scrubbed] out'); + assert.equal(scrubber.scrub('aws=AKIA0123456789ABCDEF!'), 'aws=[scrubbed]!'); }); it('scrubs every occurrence and leaves clean text untouched', () => { From fbb85d60f995bc4443f0128007ab708af1811e9f Mon Sep 17 00:00:00 2001 From: thxCode Date: Tue, 1 Dec 2026 18:28:35 +0800 Subject: [PATCH 14/26] fix(evolution): harden campaign snapshot secrets, bounds, receipt binding, and import atomicity Address Phase 2 review findings across @loopwright/evolution: - Secret-scan scratchpads, textual CAS blobs, and all text members on snapshot export, verify, and import, threading resolved.scrubber into document parsers. - Raise snapshot manifest parsing/canonicalization caps to 16,384 members (131,072 nodes) aligned with MAX_SNAPSHOT_MANIFEST_BYTES while keeping default parser limits unchanged. - Allow signed finite negative scalarFitness values, topologically sort team_configs with cycle rejection, and wrap legacy snapshot_provenance migration in BEGIN IMMEDIATE with IF NOT EXISTS. - Bind receipted individuals' status, metrics, bucketMetrics, and hardwareDiagnostics to their signed verdict receipt, reject unreceipted hardwareProvenance and unreferenced manifest members, stage absent stateDir imports atomically with O_EXCL empty-dir claiming, include isolation in bundle compatibility checks, deduplicate bundle-fs helpers, and add negative tests. Signed-off-by: thxCode --- packages/evolution/src/bundle-fs.ts | 223 +++++- packages/evolution/src/bundle.ts | 80 +- packages/evolution/src/schema.ts | 41 +- packages/evolution/src/snapshot.ts | 975 +++++++++++++++-------- packages/evolution/src/store.ts | 55 +- packages/evolution/test/snapshot.test.ts | 741 ++++++++++++++++- 6 files changed, 1651 insertions(+), 464 deletions(-) diff --git a/packages/evolution/src/bundle-fs.ts b/packages/evolution/src/bundle-fs.ts index dbbd215d..717226e2 100644 --- a/packages/evolution/src/bundle-fs.ts +++ b/packages/evolution/src/bundle-fs.ts @@ -18,13 +18,15 @@ import { type SignedBenchmarkVerdictReceipt, } from '@loopwright/hardware-runner'; import { + canonicalizeJson, parseBucketMetricsJson, parseHardwareDiagnosticsJson, parseHardwareProvenanceJson, + parseMetricsRecordJson, parseNullProtoJson, type NullProtoJson, } from './schema.js'; -import { EvolutionError, type IndividualRecord } from './types.js'; +import { EvolutionError, type IndividualRecord, type TeamConfigRecord } from './types.js'; /** * Internal helpers shared by `bundle.ts` and `snapshot.ts`: symlink-hardened filesystem and CAS @@ -113,11 +115,36 @@ export interface ParsedReceiptBundle { readonly rawDigest: Digest; readonly provenance: HardwareProvenance; readonly outputArtifacts: readonly BenchmarkOutputArtifact[]; + readonly metrics?: Readonly>; readonly bucketMetrics?: readonly BucketMetricEntry[]; readonly hardwareDiagnostics?: HardwareDiagnostics; readonly heldOutWorkloadId?: string; } +const TEXT_ARTIFACT_EXTENSIONS: readonly string[] = Object.freeze([ + '.json', + '.yaml', + '.yml', + '.txt', + '.md', + '.toml', + '.cfg', +]); + +export function isTextualArtifact(name: string, mediaType: string | null | undefined): boolean { + const lowerName = name.toLowerCase(); + if (TEXT_ARTIFACT_EXTENSIONS.some(ext => lowerName.endsWith(ext))) { + return true; + } + if (typeof mediaType === 'string') { + const lowerMt = mediaType.toLowerCase(); + if (lowerMt.startsWith('text/') || lowerMt.includes('json') || lowerMt.includes('yaml')) { + return true; + } + } + return false; +} + export function createNullRecord>(): T { return Object.create(null) as T; } @@ -714,7 +741,7 @@ export async function parseAndVerifyReceiptBytes( let provenance: HardwareProvenance; try { provenance = parseHardwareProvenanceJson( - obj['hardwareProvenance'] as unknown as HardwareProvenance, + obj['hardwareProvenance'], `${diagPath}/hardwareProvenance`, ); } catch (err: unknown) { @@ -755,20 +782,27 @@ export async function parseAndVerifyReceiptBytes( `${diagPath}/outputArtifacts`, ); + let metrics: Readonly> | undefined; + if (Object.hasOwn(obj, 'metrics') && obj['metrics'] !== undefined) { + try { + metrics = parseMetricsRecordJson(obj['metrics'], `${diagPath}/metrics`); + } catch (err: unknown) { + throw new EvolutionError( + 'ARTIFACT_INVALID', + `invalid metrics on receipt for ${options.individualId}: ${err instanceof Error ? err.message : String(err)}`, + `${diagPath}/metrics`, + ); + } + } + let bucketMetrics: readonly BucketMetricEntry[] | undefined; if (Object.hasOwn(obj, 'bucketMetrics') && obj['bucketMetrics'] !== undefined) { - bucketMetrics = parseBucketMetricsJson( - obj['bucketMetrics'] as unknown as readonly BucketMetricEntry[], - options.scrubber, - ); + bucketMetrics = parseBucketMetricsJson(obj['bucketMetrics'], options.scrubber); } let hardwareDiagnostics: HardwareDiagnostics | undefined; if (Object.hasOwn(obj, 'hardwareDiagnostics') && obj['hardwareDiagnostics'] !== undefined) { - hardwareDiagnostics = parseHardwareDiagnosticsJson( - obj['hardwareDiagnostics'] as unknown as HardwareDiagnostics, - options.scrubber, - ); + hardwareDiagnostics = parseHardwareDiagnosticsJson(obj['hardwareDiagnostics'], options.scrubber); } let heldOutWorkloadId: string | undefined; @@ -786,12 +820,90 @@ export async function parseAndVerifyReceiptBytes( rawDigest: makeDigest(sha256Hex(rawBytes)), provenance, outputArtifacts, + ...(metrics !== undefined ? { metrics } : {}), ...(bucketMetrics !== undefined ? { bucketMetrics } : {}), ...(hardwareDiagnostics !== undefined ? { hardwareDiagnostics } : {}), ...(heldOutWorkloadId !== undefined ? { heldOutWorkloadId } : {}), }; } +export async function verifyIndividualReceiptBytes( + rawBytes: Buffer, + individual: Pick< + IndividualRecord, + 'individualId' | 'status' | 'outputArtifacts' | 'hardwareProvenance' | 'metrics' | 'bucketMetrics' | 'hardwareDiagnostics' + >, + options: Omit & { + readonly bindReceiptFields?: boolean; + }, +): Promise { + const parsed = await parseAndVerifyReceiptBytes(rawBytes, { + ...options, + individualId: individual.individualId, + }); + + if (parsed.receipt.runId.startsWith('ind-') && parsed.receipt.runId !== individual.individualId) { + throw new EvolutionError( + 'EXPORT_UNVERIFIED_FORBIDDEN', + `receipt runId "${parsed.receipt.runId}" does not match individual "${individual.individualId}"`, + `/receipts/${individual.individualId}/runId`, + ); + } + + if ( + individual.hardwareProvenance !== undefined + && canonicalizeJson(individual.hardwareProvenance) !== canonicalizeJson(parsed.provenance) + ) { + throw new EvolutionError( + 'ARTIFACT_INVALID', + `individual "${individual.individualId}" persisted hardwareProvenance diverges from signed verdict receipt`, + ); + } + + assertIndividualArtifactsBoundToReceipt(individual, parsed.outputArtifacts); + + if (options.bindReceiptFields === true) { + if (individual.status !== 'passed') { + throw new EvolutionError( + 'ARTIFACT_INVALID', + `individual "${individual.individualId}" has status "${individual.status}" with a signed receipt (expected "passed")`, + '/individuals.jsonl', + ); + } + if (parsed.metrics !== undefined && canonicalizeJson(individual.metrics) !== canonicalizeJson(parsed.metrics)) { + throw new EvolutionError( + 'ARTIFACT_INVALID', + `individual "${individual.individualId}" metrics diverge from its signed verdict receipt`, + '/individuals.jsonl', + ); + } + if ( + parsed.bucketMetrics !== undefined + && (individual.bucketMetrics === undefined + || canonicalizeJson(individual.bucketMetrics) !== canonicalizeJson(parsed.bucketMetrics)) + ) { + throw new EvolutionError( + 'ARTIFACT_INVALID', + `individual "${individual.individualId}" bucketMetrics diverge from its signed verdict receipt`, + '/individuals.jsonl', + ); + } + if ( + parsed.hardwareDiagnostics !== undefined + && (individual.hardwareDiagnostics === undefined + || canonicalizeJson(individual.hardwareDiagnostics) !== canonicalizeJson(parsed.hardwareDiagnostics)) + ) { + throw new EvolutionError( + 'ARTIFACT_INVALID', + `individual "${individual.individualId}" hardwareDiagnostics diverge from its signed verdict receipt`, + '/individuals.jsonl', + ); + } + } + + return parsed; +} + export function assertIndividualArtifactsBoundToReceipt( individual: Pick, receiptArtifacts: readonly BenchmarkOutputArtifact[], @@ -812,6 +924,97 @@ export function assertIndividualArtifactsBoundToReceipt( } } +export async function assertWritableOutputDir( + rawDir: string, + label: string, + overwrite: boolean, +): Promise { + const resolvedDir = validateAbsoluteFilesystemPath(rawDir, label); + await assertNoSymlinkPath(resolvedDir, { checkLeaf: true, diagPath: resolvedDir }); + + const preOutStat = await lstat(resolvedDir).catch((err: NodeJS.ErrnoException) => { + if (err.code === 'ENOENT') return null; + if (err.code === 'ELOOP') { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `symlink forbidden at ${label}: ${resolvedDir}`, resolvedDir); + } + throw err; + }); + if (preOutStat !== null) { + if (preOutStat.isSymbolicLink()) { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `${label} cannot be a symlink: ${resolvedDir}`, resolvedDir); + } + if (!preOutStat.isDirectory()) { + throw new EvolutionError('ARTIFACT_INVALID', `${label} exists and is not a directory: ${resolvedDir}`, resolvedDir); + } + if (!overwrite) { + throw new EvolutionError('EVOLUTION_CONFLICT', `${label} already exists: ${resolvedDir}`, resolvedDir); + } + } + return resolvedDir; +} + +function compareTeamConfigOrder(a: TeamConfigRecord, b: TeamConfigRecord): number { + if (a.createdGeneration !== b.createdGeneration) return a.createdGeneration - b.createdGeneration; + return compareUtf16(a.teamConfigId, b.teamConfigId); +} + +/** + * Topologically order `team_configs` so every parent precedes its children, breaking ties + * deterministically by `(createdGeneration, teamConfigId)`, and reject duplicates, unknown + * parents, self-parents, or parent cycles. + */ +export function sortTeamConfigsTopologically( + teamConfigs: readonly TeamConfigRecord[], + errorCode: 'ARTIFACT_INVALID' | 'EVOLUTION_SCHEMA_INVALID', + diagPath: string, +): readonly TeamConfigRecord[] { + const byId = new Map(); + const children = new Map(); + for (const tc of teamConfigs) { + if (byId.has(tc.teamConfigId)) { + throw new EvolutionError(errorCode, `duplicate teamConfigId "${tc.teamConfigId}"`, diagPath); + } + byId.set(tc.teamConfigId, tc); + children.set(tc.teamConfigId, []); + } + + const ready: TeamConfigRecord[] = []; + for (const tc of teamConfigs) { + if (tc.parentTeamConfigId === null) { + ready.push(tc); + } else { + if (tc.parentTeamConfigId === tc.teamConfigId) { + throw new EvolutionError(errorCode, `team_config "${tc.teamConfigId}" cannot be its own parent`, diagPath); + } + if (!byId.has(tc.parentTeamConfigId)) { + throw new EvolutionError( + errorCode, + `team_config "${tc.teamConfigId}" references unknown parent "${tc.parentTeamConfigId}"`, + diagPath, + ); + } + children.get(tc.parentTeamConfigId)!.push(tc); + } + } + + ready.sort(compareTeamConfigOrder); + const ordered: TeamConfigRecord[] = []; + while (ready.length > 0) { + const current = ready.shift()!; + ordered.push(current); + const next = children.get(current.teamConfigId); + if (next !== undefined && next.length > 0) { + ready.push(...next); + ready.sort(compareTeamConfigOrder); + } + } + + if (ordered.length !== teamConfigs.length) { + throw new EvolutionError(errorCode, 'team_configs contains a parent cycle', diagPath); + } + return ordered; +} + export async function publishStagingDirectoryAtomically( stagingDir: string, targetDir: string, diff --git a/packages/evolution/src/bundle.ts b/packages/evolution/src/bundle.ts index 724054cb..c867075a 100644 --- a/packages/evolution/src/bundle.ts +++ b/packages/evolution/src/bundle.ts @@ -46,13 +46,14 @@ import { SAFE_ID_RE, SHA256_HEX_RE, assertCleanSecretText, - assertIndividualArtifactsBoundToReceipt, assertNoSymlinkPath, + assertWritableOutputDir, compareUtf16, createNullRecord, decodeUtf8Strict, ensureDirectoryChainNoSymlink, expectRecord, + isTextualArtifact, makeDigest, parseAndVerifyReceiptBytes, parseDigestValue, @@ -61,6 +62,7 @@ import { readVerifiedRegularFileNoFollow, sha256Hex, validateAbsoluteFilesystemPath, + verifyIndividualReceiptBytes, verifyNonSymlinkDirectoryFd, writeNewFileNoFollow, type ParsedReceiptBundle, @@ -97,16 +99,6 @@ const BINARY_ARTIFACT_EXTENSIONS: readonly string[] = Object.freeze([ '.bin', ]); -const TEXT_ARTIFACT_EXTENSIONS: readonly string[] = Object.freeze([ - '.json', - '.yaml', - '.yml', - '.txt', - '.md', - '.toml', - '.cfg', -]); - const BUNDLE_MANIFEST_KEYS: ReadonlySet = new Set([ 'kind', 'version', @@ -206,20 +198,6 @@ interface VerifiedStageABlob { textChecked: boolean; } -function isTextualArtifact(name: string, mediaType: string | null | undefined): boolean { - const lowerName = name.toLowerCase(); - if (TEXT_ARTIFACT_EXTENSIONS.some(ext => lowerName.endsWith(ext))) { - return true; - } - if (typeof mediaType === 'string') { - const lowerMt = mediaType.toLowerCase(); - if (lowerMt.startsWith('text/') || lowerMt.includes('json') || lowerMt.includes('yaml')) { - return true; - } - } - return false; -} - function inferBlobMediaType(name: string, declaredMediaType?: string | null): string { if ( typeof declaredMediaType === 'string' @@ -248,6 +226,7 @@ function assertCompatibleHardwareProvenance( if ( base.accelerator !== other.accelerator || base.isolationMode !== other.isolationMode + || (base.isolation ?? 'docker') !== (other.isolation ?? 'docker') || base.deviceCount !== other.deviceCount || base.driverVersion !== other.driverVersion || base.runtimeVersion !== other.runtimeVersion @@ -814,28 +793,7 @@ export async function exportEvolutionBundle( throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'maxBlobBytes must be a positive integer', '/maxBlobBytes'); } - const resolvedOutputDir = validateAbsoluteFilesystemPath(options.outputDir, 'outputDir'); - await assertNoSymlinkPath(resolvedOutputDir, { checkLeaf: true, diagPath: resolvedOutputDir }); - - // Pre-check existing outputDir state before doing staging work - const preOutStat = await lstat(resolvedOutputDir).catch((err: NodeJS.ErrnoException) => { - if (err.code === 'ENOENT') return null; - if (err.code === 'ELOOP') { - throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `symlink forbidden at outputDir: ${resolvedOutputDir}`, resolvedOutputDir); - } - throw err; - }); - if (preOutStat !== null) { - if (preOutStat.isSymbolicLink()) { - throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `outputDir cannot be a symlink: ${resolvedOutputDir}`, resolvedOutputDir); - } - if (!preOutStat.isDirectory()) { - throw new EvolutionError('ARTIFACT_INVALID', `outputDir exists and is not a directory: ${resolvedOutputDir}`, resolvedOutputDir); - } - if (!overwrite) { - throw new EvolutionError('EVOLUTION_CONFLICT', `outputDir already exists: ${resolvedOutputDir}`, resolvedOutputDir); - } - } + const resolvedOutputDir = await assertWritableOutputDir(options.outputDir, 'outputDir', overwrite); const campaign = await options.store.getCampaign(options.campaignId); if (!campaign) { @@ -884,8 +842,7 @@ export async function exportEvolutionBundle( const rawBytes = await readVerifiedCasBlob(options.store.campaignRoot, ind.verdictReceiptCasDigest.hex, { maxBytes: MAX_RECEIPT_FILE_BYTES, }); - const parsed = await parseAndVerifyReceiptBytes(rawBytes, { - individualId: ind.individualId, + const parsed = await verifyIndividualReceiptBytes(rawBytes, ind, { expectedTargetCellId: campaign.manifest.spec.targetCellId, allowSyntheticProbe, allowHostAttested, @@ -895,23 +852,6 @@ export async function exportEvolutionBundle( maxBlobBytes, }); - if (parsed.receipt.runId.startsWith('ind-') && parsed.receipt.runId !== ind.individualId) { - throw new EvolutionError( - 'EXPORT_UNVERIFIED_FORBIDDEN', - `receipt runId "${parsed.receipt.runId}" does not match individual "${ind.individualId}"`, - `/receipts/${ind.individualId}/runId`, - ); - } - - if (ind.hardwareProvenance !== undefined) { - if (canonicalizeJson(ind.hardwareProvenance) !== canonicalizeJson(parsed.provenance)) { - throw new EvolutionError( - 'ARTIFACT_INVALID', - `individual "${ind.individualId}" persisted hardwareProvenance diverges from signed verdict receipt`, - ); - } - } - receiptCache.set(ind.individualId, parsed); return parsed; }; @@ -1105,8 +1045,6 @@ export async function exportEvolutionBundle( ); } - assertIndividualArtifactsBoundToReceipt(ind, receiptBundle.outputArtifacts); - const sortedReceiptArtifacts = [...receiptBundle.outputArtifacts].sort((a, b) => { const nameCmp = compareUtf16(a.name, b.name); return nameCmp !== 0 ? nameCmp : compareUtf16(a.digest.hex, b.digest.hex); @@ -1544,6 +1482,7 @@ export async function verifyEvolutionBundle( // Verify every receipt listed in manifest.lineage.individualIds const verifiedReceiptDigests = new Map(); + let anchorIsolation: 'docker' | 'host_attested' | null = null; for (const individualId of manifest.lineage.individualIds) { const relPath = `receipts/${individualId}.verdict.json`; const receiptBytes = verifiedMemberBytes.get(relPath); @@ -1559,9 +1498,14 @@ export async function verifyEvolutionBundle( scrubber, maxBlobBytes, }); + const receiptIsolation = parsedReceipt.provenance.isolation ?? 'docker'; + if (anchorIsolation === null) { + anchorIsolation = receiptIsolation; + } if ( parsedReceipt.provenance.accelerator !== manifest.compatibility.accelerator || parsedReceipt.provenance.isolationMode !== manifest.compatibility.isolationMode + || receiptIsolation !== anchorIsolation || parsedReceipt.provenance.deviceCount !== manifest.compatibility.deviceCount || parsedReceipt.provenance.driverVersion !== manifest.compatibility.driverVersion || parsedReceipt.provenance.runtimeVersion !== manifest.compatibility.runtimeVersion diff --git a/packages/evolution/src/schema.ts b/packages/evolution/src/schema.ts index 69eee00a..c234ce2a 100644 --- a/packages/evolution/src/schema.ts +++ b/packages/evolution/src/schema.ts @@ -149,6 +149,13 @@ export interface SanitizeUntrustedOptions { readonly path?: string; } +export interface ParseNullProtoJsonOptions { + readonly maxNodes?: number; + readonly maxDepth?: number; + readonly maxCollection?: number; + readonly maxString?: number; +} + /** * Strictly parse a JSON string into null-prototype objects, rejecting duplicate keys, * prototype keys (`__proto__`, `constructor`, `prototype`), lone surrogates, `NaN`, `Infinity`, and `-0`. @@ -157,7 +164,13 @@ export function parseNullProtoJson( source: string, maxBytes: number = EVOLUTION_CAMPAIGN_MAX_BYTES, diagPath = '/', + options: ParseNullProtoJsonOptions = {}, ): NullProtoJson { + const maxNodes = options.maxNodes ?? MAX_JSON_NODES; + const maxDepth = options.maxDepth ?? MAX_JSON_DEPTH; + const maxCollection = options.maxCollection ?? MAX_JSON_COLLECTION; + const maxString = options.maxString ?? MAX_JSON_STRING; + if (typeof source !== 'string') { schemaInvalid('expected JSON string', diagPath); } @@ -206,12 +219,12 @@ export function parseNullProtoJson( if (typeof parsed !== 'string') { schemaInvalid('invalid JSON string literal', path); } - assertValidStringContent(parsed, MAX_JSON_STRING, path); + assertValidStringContent(parsed, maxString, path); return parsed; }; const readValue = (depth: number, path: string): NullProtoJson => { - if (++nodes > MAX_JSON_NODES || depth > MAX_JSON_DEPTH) { + if (++nodes > maxNodes || depth > maxDepth) { schemaInvalid('JSON document exceeds node or depth limits', path); } skipSpace(); @@ -237,7 +250,7 @@ export function parseNullProtoJson( if (seen.has(key)) { schemaInvalid(`duplicate JSON key "${key}"`, `${path}/${key}`); } - if (seen.size >= MAX_JSON_COLLECTION) { + if (seen.size >= maxCollection) { schemaInvalid('JSON object exceeds property limits', path); } seen.add(key); @@ -261,7 +274,7 @@ export function parseNullProtoJson( return arr; } while (true) { - if (arr.length >= MAX_JSON_COLLECTION) { + if (arr.length >= maxCollection) { schemaInvalid('JSON array exceeds collection limits', path); } arr.push(readValue(depth + 1, `${path}/${arr.length}`)); @@ -418,8 +431,12 @@ export function sanitizeUntrustedValue( } /** Deterministic canonical JSON serializer sorting object keys lexicographically. */ -export function canonicalizeJson(value: unknown): string { - const sanitized = sanitizeUntrustedValue(value, { maxBytes: 1_048_576, maxCollection: 2_048 }); +export function canonicalizeJson(value: unknown, options: SanitizeUntrustedOptions = {}): string { + const sanitized = sanitizeUntrustedValue(value, { + maxBytes: 1_048_576, + maxCollection: 2_048, + ...options, + }); const render = (node: NullProtoJson): string => { if (node === null || typeof node === 'boolean' || typeof node === 'number' || typeof node === 'string') { return JSON.stringify(node); @@ -1804,7 +1821,7 @@ export function parseDispatchManifestV1( // Strict SQLite JSON column validators into null-prototype records // --------------------------------------------------------------------------- -export function parseMetricsRecordJson(rawJson: string | Readonly>, path = '/metrics'): Readonly> { +export function parseMetricsRecordJson(rawJson: unknown, path = '/metrics'): Readonly> { const val = typeof rawJson === 'string' ? parseNullProtoJson(rawJson, 16_384, path) : sanitizeUntrustedValue(rawJson, { maxBytes: 16_384, path }); @@ -1827,7 +1844,7 @@ export function parseMetricsRecordJson(rawJson: string | Readonly, - requiredKeys: readonly string[], - path: string, -): Record { - if (value === undefined || value === null || typeof value !== 'object' || Array.isArray(value)) { - invalid('expected object record', path); - } - const obj = value as Record; - for (const key of Object.keys(obj)) { - if (!Object.hasOwn(obj, key)) continue; - if (FORBIDDEN_PROTOTYPE_KEYS.has(key) || !allowedKeys.has(key)) { - invalid(`unknown or forbidden field "${key}"`, `${path}/${key}`); - } - } - for (const req of requiredKeys) { - if (!Object.hasOwn(obj, req) || obj[req] === undefined) { - invalid(`missing required field "${req}"`, `${path}/${req}`); - } - } - return obj; -} - function expectString(value: NullProtoJson | undefined, minLen: number, maxLen: number, path: string): string { if (typeof value !== 'string') invalid('expected string', path); if (value.length < minLen || value.length > maxLen || LONE_SURROGATE_RE.test(value)) { @@ -314,6 +312,14 @@ function expectNullableSafeId(value: NullProtoJson | undefined, path: string): s return value === null || value === undefined ? null : expectSafeId(value, path); } +function expectModelLabel(value: NullProtoJson | undefined, path: string): string { + const s = expectString(value, 1, 128, path); + if (FORBIDDEN_PROTOTYPE_KEYS.has(s) || !MODEL_LABEL_RE.test(s)) { + invalid(`invalid modelId "${s}"`, path); + } + return s; +} + function expectInteger(value: NullProtoJson | undefined, min: number, max: number, path: string): number { if (typeof value !== 'number' || !Number.isSafeInteger(value) || Object.is(value, -0) || value < min || value > max) { invalid(`expected integer within ${min}..${max}`, path); @@ -336,6 +342,17 @@ function expectNullableFinite(value: NullProtoJson | undefined, path: string): n return value === null || value === undefined ? null : expectFinite(value, path); } +function expectSignedFinite(value: NullProtoJson | undefined, path: string): number { + if (typeof value !== 'number' || !Number.isFinite(value) || Object.is(value, -0)) { + invalid('expected finite non-negative-zero number', path); + } + return value; +} + +function expectNullableSignedFinite(value: NullProtoJson | undefined, path: string): number | null { + return value === null || value === undefined ? null : expectSignedFinite(value, path); +} + function expectBoolean(value: NullProtoJson | undefined, path: string): boolean { if (typeof value !== 'boolean') invalid('expected boolean', path); return value; @@ -356,9 +373,14 @@ function expectNullableDigest(value: NullProtoJson | undefined, path: string): D return value === null || value === undefined ? null : parseDigestValue(value, 'ARTIFACT_INVALID', path); } -function parseJsonMember(text: string, diagPath: string, maxBytes: number): NullProtoJson { +function parseJsonMember( + text: string, + diagPath: string, + maxBytes: number, + parseOptions?: ParseNullProtoJsonOptions, +): NullProtoJson { try { - return parseNullProtoJson(text, maxBytes, diagPath); + return parseNullProtoJson(text, maxBytes, diagPath, parseOptions); } catch (err: unknown) { throw new EvolutionError( 'ARTIFACT_INVALID', @@ -388,7 +410,7 @@ function parseManifest(obj: Record, path: string): Campai invalid(`manifest.json must have kind: "${CAMPAIGN_SNAPSHOT_KIND}" and version: ${CAMPAIGN_SNAPSHOT_VERSION}`, path); } const campaignId = expectSafeId(obj['campaignId'], `${path}/campaignId`); - const genObj = expectObject(obj['generations'], GENERATIONS_KEYS, ['min', 'max'], `${path}/generations`); + const genObj = expectRecord(obj['generations'], GENERATIONS_KEYS, ['min', 'max'], 'ARTIFACT_INVALID', `${path}/generations`); const min = expectInteger(genObj['min'], 0, Number.MAX_SAFE_INTEGER, `${path}/generations/min`); const max = expectInteger(genObj['max'], min, Number.MAX_SAFE_INTEGER, `${path}/generations/max`); let parentDigest: Digest | undefined; @@ -398,11 +420,14 @@ function parseManifest(obj: Record, path: string): Campai if (!Array.isArray(obj['members']) || obj['members'].length === 0) { invalid('members must be a non-empty array', `${path}/members`); } + if (obj['members'].length > MAX_SNAPSHOT_MEMBERS) { + invalid(`members exceeds maximum count ${MAX_SNAPSHOT_MEMBERS}`, `${path}/members`); + } const seenPaths = new Set(); const members: BundleMemberDigest[] = []; for (let i = 0; i < obj['members'].length; i++) { const mPath = `${path}/members/${i}`; - const mObj = expectObject(obj['members'][i], MEMBER_KEYS, ['path', 'digest', 'byteLength'], mPath); + const mObj = expectRecord(obj['members'][i], MEMBER_KEYS, ['path', 'digest', 'byteLength'], 'ARTIFACT_INVALID', mPath); const relPath = expectString(mObj['path'], 1, 512, `${mPath}/path`); if (!validateRelativePath(relPath).ok || !isAllowedMemberPath(relPath)) { invalid(`invalid snapshot member path "${relPath}"`, `${mPath}/path`); @@ -435,15 +460,13 @@ function parseManifest(obj: Record, path: string): Campai out.generations = Object.freeze({ min, max }); if (parentDigest !== undefined) out.parentDigest = parentDigest; out.members = Object.freeze(members.sort((a, b) => compareUtf16(a.path, b.path))); - return out as CampaignSnapshotManifestV1; + return out; } function isAllowedMemberPath(relPath: string): boolean { if (REQUIRED_MEMBERS.includes(relPath)) return true; - const blob = /^blobs\/sha256\/([0-9a-f]{64})$/.exec(relPath); - if (blob !== null) return true; - const scratchpad = /^scratchpad\/([0-9a-f]{64})\.md$/.exec(relPath); - if (scratchpad !== null) return true; + if (/^blobs\/sha256\/([0-9a-f]{64})$/.test(relPath)) return true; + if (/^scratchpad\/([0-9a-f]{64})\.md$/.test(relPath)) return true; const receipt = /^receipts\/([A-Za-z0-9][A-Za-z0-9._-]{0,127})\.verdict\.json$/.exec(relPath); return receipt !== null && receipt[1] !== '.' && receipt[1] !== '..'; } @@ -452,7 +475,11 @@ function scratchpadPath(hex: string): string { return `scratchpad/${hex}.md`; } -function parseCampaign(obj: Record, path: string): SnapshotCampaignRecordV1 { +function parseCampaign( + obj: Record, + path: string, + scrubber: SecretScrubber, +): SnapshotCampaignRecordV1 { const campaignId = expectSafeId(obj['campaignId'], `${path}/campaignId`); const manifestValue = obj['manifest']; if (manifestValue === null || typeof manifestValue !== 'object' || Array.isArray(manifestValue)) { @@ -460,8 +487,9 @@ function parseCampaign(obj: Record, path: string): Snapsh } let manifest: EvolutionCampaignManifest; try { - manifest = parseEvolutionCampaignDocument(manifestValue); + manifest = parseEvolutionCampaignDocument(manifestValue, { scrubber }); } catch (err: unknown) { + if (err instanceof EvolutionError && err.code === 'SECRET_LEAK_DETECTED') throw err; throw new EvolutionError( 'ARTIFACT_INVALID', `invalid ${path}/manifest: ${err instanceof Error ? err.message : String(err)}`, @@ -500,19 +528,49 @@ function parseCampaign(obj: Record, path: string): Snapsh out.currentGeneration = expectInteger(obj['currentGeneration'], 0, Number.MAX_SAFE_INTEGER, `${path}/currentGeneration`); out.evaluationsUsed = expectInteger(obj['evaluationsUsed'], 0, Number.MAX_SAFE_INTEGER, `${path}/evaluationsUsed`); out.preemptionsCount = expectInteger(obj['preemptionsCount'], 0, Number.MAX_SAFE_INTEGER, `${path}/preemptionsCount`); - return out as SnapshotCampaignRecordV1; + return out; } -function parseIndividual(obj: Record, path: string): SnapshotIndividualRecordV1 { - const out = createNullRecord>(); +function parseIndividual( + obj: Record, + path: string, + scrubber: SecretScrubber, +): SnapshotIndividualRecordV1 { + const out = createNullRecord<{ + individualId: string; + campaignId: string; + islandId: number; + generation: number; + bucketId: string | null; + teamConfigId: string; + modelId: string; + trackId: string | null; + mutationKind: IndividualMutationKind; + status: IndividualStatus; + failureReason: string | null; + nicheKey: string | null; + paretoRank: number | null; + crowdingDistance: number | null; + crowdingIsBoundary: boolean; + scalarFitness: number | null; + offspringCount: number; + codeSliceCasDigest: Digest | null; + evidenceDigest: Digest | null; + receipt: Digest | null; + outputArtifacts: readonly ArtifactRef[]; + metrics: Readonly>; + bucketMetrics?: readonly BucketMetricEntry[]; + hardwareDiagnostics?: HardwareDiagnostics; + hardwareProvenance?: HardwareProvenance; + findings?: readonly StructuredFinding[]; + }>(); out.individualId = expectSafeId(obj['individualId'], `${path}/individualId`); out.campaignId = expectSafeId(obj['campaignId'], `${path}/campaignId`); out.islandId = expectInteger(obj['islandId'], 0, 15, `${path}/islandId`); out.generation = expectInteger(obj['generation'], 0, Number.MAX_SAFE_INTEGER, `${path}/generation`); out.bucketId = expectNullableString(obj['bucketId'], 1, 128, `${path}/bucketId`); out.teamConfigId = expectSafeId(obj['teamConfigId'], `${path}/teamConfigId`); - out.modelId = expectString(obj['modelId'], 1, 128, `${path}/modelId`); - if (!MODEL_LABEL_RE.test(out.modelId as string)) invalid('modelId must be printable ASCII', `${path}/modelId`); + out.modelId = expectModelLabel(obj['modelId'], `${path}/modelId`); out.trackId = expectNullableString(obj['trackId'], 1, 128, `${path}/trackId`); out.mutationKind = expectEnum(obj['mutationKind'], MUTATION_KINDS, `${path}/mutationKind`); out.status = expectEnum(obj['status'], INDIVIDUAL_STATUSES, `${path}/status`); @@ -526,25 +584,25 @@ function parseIndividual(obj: Record, path: string): Snap } out.crowdingIsBoundary = crowdingIsBoundary; out.crowdingDistance = crowdingDistance; - out.scalarFitness = expectNullableFinite(obj['scalarFitness'], `${path}/scalarFitness`); + out.scalarFitness = expectNullableSignedFinite(obj['scalarFitness'], `${path}/scalarFitness`); out.offspringCount = expectInteger(obj['offspringCount'], 0, Number.MAX_SAFE_INTEGER, `${path}/offspringCount`); out.codeSliceCasDigest = expectNullableDigest(obj['codeSliceCasDigest'], `${path}/codeSliceCasDigest`); out.evidenceDigest = expectNullableDigest(obj['evidenceDigest'], `${path}/evidenceDigest`); out.receipt = expectNullableDigest(obj['receipt'], `${path}/receipt`); try { - out.outputArtifacts = parseArtifactRefsJson(obj['outputArtifacts'] as unknown as readonly ArtifactRef[], `${path}/outputArtifacts`); - out.metrics = parseMetricsRecordJson(obj['metrics'] as Readonly>, `${path}/metrics`); + out.outputArtifacts = parseArtifactRefsJson(obj['outputArtifacts'], `${path}/outputArtifacts`); + out.metrics = parseMetricsRecordJson(obj['metrics'], `${path}/metrics`); if (obj['bucketMetrics'] !== undefined && obj['bucketMetrics'] !== null) { - out.bucketMetrics = parseBucketMetricsJson(obj['bucketMetrics'] as unknown as readonly BucketMetricEntry[]); + out.bucketMetrics = parseBucketMetricsJson(obj['bucketMetrics'], scrubber); } if (obj['hardwareDiagnostics'] !== undefined && obj['hardwareDiagnostics'] !== null) { - out.hardwareDiagnostics = parseHardwareDiagnosticsJson(obj['hardwareDiagnostics'] as unknown as HardwareDiagnostics); + out.hardwareDiagnostics = parseHardwareDiagnosticsJson(obj['hardwareDiagnostics'], scrubber); } if (obj['hardwareProvenance'] !== undefined && obj['hardwareProvenance'] !== null) { - out.hardwareProvenance = parseHardwareProvenanceJson(obj['hardwareProvenance'] as unknown as HardwareProvenance, `${path}/hardwareProvenance`); + out.hardwareProvenance = parseHardwareProvenanceJson(obj['hardwareProvenance'], `${path}/hardwareProvenance`); } if (obj['findings'] !== undefined && obj['findings'] !== null) { - out.findings = parseStructuredFindingsJson(obj['findings'] as unknown as readonly StructuredFinding[], `${path}/findings`); + out.findings = parseStructuredFindingsJson(obj['findings'], `${path}/findings`); } } catch (err: unknown) { if (err instanceof EvolutionError && err.code === 'SECRET_LEAK_DETECTED') throw err; @@ -554,11 +612,20 @@ function parseIndividual(obj: Record, path: string): Snap path, ); } - return out as unknown as SnapshotIndividualRecordV1; + return out; } function parseIsland(obj: Record, path: string): IslandRecord { - const out = createNullRecord>(); + const out = createNullRecord<{ + campaignId: string; + islandId: number; + activeTeamConfigId: string; + currentGeneration: number; + consecutiveNoGainGenerations: number; + consecutivePathologyRuns: number; + lastHypervolume: number; + bestRooflineHeadroom: number | null; + }>(); out.campaignId = expectSafeId(obj['campaignId'], `${path}/campaignId`); out.islandId = expectInteger(obj['islandId'], 0, 15, `${path}/islandId`); out.activeTeamConfigId = expectSafeId(obj['activeTeamConfigId'], `${path}/activeTeamConfigId`); @@ -567,12 +634,12 @@ function parseIsland(obj: Record, path: string): IslandRe out.consecutivePathologyRuns = expectInteger(obj['consecutivePathologyRuns'], 0, Number.MAX_SAFE_INTEGER, `${path}/consecutivePathologyRuns`); out.lastHypervolume = expectFinite(obj['lastHypervolume'], `${path}/lastHypervolume`); out.bestRooflineHeadroom = expectNullableFinite(obj['bestRooflineHeadroom'], `${path}/bestRooflineHeadroom`); - return out as unknown as IslandRecord; + return out; } function parseTeamDiagnosis(value: NullProtoJson | undefined, path: string): TeamPatchDiagnosis | null { if (value === null || value === undefined) return null; - const obj = expectObject(value, DIAGNOSIS_KEYS, ['summary', 'plateauCategory', 'rationale'], path); + const obj = expectRecord(value, DIAGNOSIS_KEYS, ['summary', 'plateauCategory', 'rationale'], 'ARTIFACT_INVALID', path); try { return parseTeamDiagnosisValue(obj, path); } catch (err: unknown) { @@ -581,7 +648,20 @@ function parseTeamDiagnosis(value: NullProtoJson | undefined, path: string): Tea } function parseTeamConfig(obj: Record, path: string): TeamConfigRecord { - const out = createNullRecord>(); + const out = createNullRecord<{ + teamConfigId: string; + campaignId: string; + islandId: number; + parentTeamConfigId: string | null; + createdGeneration: number; + status: TeamConfigStatus; + trialBudgetGenerations: number; + trialUsedGenerations: number; + diagnosis: TeamPatchDiagnosis | null; + patchCasDigest: Digest | null; + paretoAdvances: number; + nicheDiscoveries: number; + }>(); out.teamConfigId = expectSafeId(obj['teamConfigId'], `${path}/teamConfigId`); out.campaignId = expectSafeId(obj['campaignId'], `${path}/campaignId`); out.islandId = expectInteger(obj['islandId'], 0, 15, `${path}/islandId`); @@ -594,11 +674,18 @@ function parseTeamConfig(obj: Record, path: string): Team out.patchCasDigest = expectNullableDigest(obj['patchCasDigest'], `${path}/patchCasDigest`); out.paretoAdvances = expectInteger(obj['paretoAdvances'], 0, Number.MAX_SAFE_INTEGER, `${path}/paretoAdvances`); out.nicheDiscoveries = expectInteger(obj['nicheDiscoveries'], 0, Number.MAX_SAFE_INTEGER, `${path}/nicheDiscoveries`); - return out as unknown as TeamConfigRecord; + return out; } function parseLineageEdge(obj: Record, path: string): LineageEdgeRecord { - const out = createNullRecord>(); + const out = createNullRecord<{ + campaignId: string; + childIndividualId: string; + parentIndividualId: string; + role: LineageRole; + sourceIslandId: number; + createdGeneration: number; + }>(); out.campaignId = expectSafeId(obj['campaignId'], `${path}/campaignId`); out.childIndividualId = expectSafeId(obj['childIndividualId'], `${path}/childIndividualId`); out.parentIndividualId = expectSafeId(obj['parentIndividualId'], `${path}/parentIndividualId`); @@ -606,22 +693,37 @@ function parseLineageEdge(obj: Record, path: string): Lin out.role = expectEnum(obj['role'], LINEAGE_ROLES, `${path}/role`); out.sourceIslandId = expectInteger(obj['sourceIslandId'], 0, 15, `${path}/sourceIslandId`); out.createdGeneration = expectInteger(obj['createdGeneration'], 0, Number.MAX_SAFE_INTEGER, `${path}/createdGeneration`); - return out as unknown as LineageEdgeRecord; + return out; } function parseBanditArm(obj: Record, path: string): ModelBanditArmRecord { - const out = createNullRecord>(); + const out = createNullRecord<{ + campaignId: string; + modelId: string; + pullCount: number; + totalReward: number; + meanReward: number; + lastPulledGeneration: number | null; + }>(); out.campaignId = expectSafeId(obj['campaignId'], `${path}/campaignId`); - out.modelId = expectString(obj['modelId'], 1, 128, `${path}/modelId`); + out.modelId = expectModelLabel(obj['modelId'], `${path}/modelId`); out.pullCount = expectInteger(obj['pullCount'], 0, Number.MAX_SAFE_INTEGER, `${path}/pullCount`); out.totalReward = expectFinite(obj['totalReward'], `${path}/totalReward`); out.meanReward = expectFinite(obj['meanReward'], `${path}/meanReward`); out.lastPulledGeneration = expectNullableInteger(obj['lastPulledGeneration'], 0, Number.MAX_SAFE_INTEGER, `${path}/lastPulledGeneration`); - return out as unknown as ModelBanditArmRecord; + return out; } function parseScratchpad(obj: Record, path: string): SnapshotScratchpadRecordV1 { - const out = createNullRecord>(); + const out = createNullRecord<{ + snapshotId: string; + campaignId: string; + generation: number; + casDigest: Digest; + byteLength: number; + topGainsCount: number; + failurePatternsCount: number; + }>(); out.snapshotId = expectSafeId(obj['snapshotId'], `${path}/snapshotId`); out.campaignId = expectSafeId(obj['campaignId'], `${path}/campaignId`); out.generation = expectInteger(obj['generation'], 0, Number.MAX_SAFE_INTEGER, `${path}/generation`); @@ -629,17 +731,49 @@ function parseScratchpad(obj: Record, path: string): Snap out.byteLength = expectInteger(obj['byteLength'], 0, SCRATCHPAD_MAX_BYTES, `${path}/byteLength`); out.topGainsCount = expectInteger(obj['topGainsCount'], 0, Number.MAX_SAFE_INTEGER, `${path}/topGainsCount`); out.failurePatternsCount = expectInteger(obj['failurePatternsCount'], 0, Number.MAX_SAFE_INTEGER, `${path}/failurePatternsCount`); - return out as unknown as SnapshotScratchpadRecordV1; + return out; } // --------------------------------------------------------------------------- -// Serialization (deterministic canonical JSON; no timestamps) +// Serialization & shared helpers (deterministic canonical JSON; no timestamps) // --------------------------------------------------------------------------- function serializeJsonl(records: readonly object[]): string { return records.length === 0 ? '' : `${records.map(r => canonicalizeJson(r)).join('\n')}\n`; } +function computeGenerationRange( + individuals: readonly Pick[], +): { readonly min: number; readonly max: number } { + if (individuals.length === 0) return Object.freeze({ min: 0, max: 0 }); + let min = individuals[0]!.generation; + let max = min; + for (let i = 1; i < individuals.length; i++) { + const gen = individuals[i]!.generation; + if (gen < min) min = gen; + if (gen > max) max = gen; + } + return Object.freeze({ min, max }); +} + +function toCampaignV1(campaign: CampaignRecord): SnapshotCampaignRecordV1 { + return { + campaignId: campaign.campaignId, + name: campaign.name, + status: campaign.status, + stagePhase: campaign.stagePhase, + activeBucketId: campaign.activeBucketId, + manifest: campaign.manifest, + manifestDigest: campaign.manifestDigest, + baseRevision: campaign.baseRevision, + lockHash: campaign.lockHash, + driverConstraint: campaign.driverConstraint, + currentGeneration: campaign.currentGeneration, + evaluationsUsed: campaign.evaluationsUsed, + preemptionsCount: campaign.preemptionsCount, + }; +} + /** `crowdingDistance: +Infinity` becomes `crowdingIsBoundary: true`; `verdictReceiptCasDigest` becomes `receipt`. */ function toIndividualV1(ind: IndividualRecord, receipt: Digest | null): SnapshotIndividualRecordV1 { const isBoundary = ind.crowdingDistance === Number.POSITIVE_INFINITY; @@ -668,7 +802,7 @@ function toIndividualV1(ind: IndividualRecord, receipt: Digest | null): Snapshot metrics: ind.metrics, ...(ind.bucketMetrics !== undefined ? { bucketMetrics: ind.bucketMetrics } : {}), ...(ind.hardwareDiagnostics !== undefined ? { hardwareDiagnostics: ind.hardwareDiagnostics } : {}), - ...(ind.hardwareProvenance !== undefined ? { hardwareProvenance: ind.hardwareProvenance } : {}), + ...(receipt !== null && ind.hardwareProvenance !== undefined ? { hardwareProvenance: ind.hardwareProvenance } : {}), ...(ind.findings !== undefined ? { findings: ind.findings } : {}), }; } @@ -706,27 +840,7 @@ function peekReceiptStatus(rawBytes: Uint8Array, individualId: string): string { return status; } -async function readVerifiedCasBlobIfExists( - campaignRoot: string, - digestHex: string, - maxBlobBytes: number, -): Promise { - try { - const bytes = await readVerifiedCasBlob(campaignRoot, digestHex, { maxBytes: maxBlobBytes }); - return bytes.byteLength; - } catch (err: unknown) { - if (err instanceof EvolutionError && err.code === 'ARTIFACT_MISSING') return null; - throw err; - } -} - -function resolveOptions(options: CampaignSnapshotCommonOptions): { - readonly scrubber: SecretScrubber; - readonly allowSyntheticProbe: boolean; - readonly allowHostAttested: boolean; - readonly maxBlobBytes: number; - readonly receiptSigningSecret: string | undefined; -} { +function resolveOptions(options: CampaignSnapshotCommonOptions): ResolvedSnapshotOptions { if (!options || typeof options !== 'object') { throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'campaign snapshot options must be an object'); } @@ -756,26 +870,7 @@ export async function writeCampaignSnapshot(options: WriteCampaignSnapshotOption const overwrite = options.overwrite !== false; const campaignRoot = options.store.campaignRoot; - const outDir = validateAbsoluteFilesystemPath(options.outDir, 'outDir'); - await assertNoSymlinkPath(outDir, { checkLeaf: true, diagPath: outDir }); - const preOutStat = await lstat(outDir).catch((err: NodeJS.ErrnoException) => { - if (err.code === 'ENOENT') return null; - if (err.code === 'ELOOP') { - throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `symlink forbidden at outDir: ${outDir}`, outDir); - } - throw err; - }); - if (preOutStat !== null) { - if (preOutStat.isSymbolicLink()) { - throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `outDir cannot be a symlink: ${outDir}`, outDir); - } - if (!preOutStat.isDirectory()) { - throw new EvolutionError('ARTIFACT_INVALID', `outDir exists and is not a directory: ${outDir}`, outDir); - } - if (!overwrite) { - throw new EvolutionError('EVOLUTION_CONFLICT', `outDir already exists: ${outDir}`, outDir); - } - } + const outDir = await assertWritableOutputDir(options.outDir, 'outDir', overwrite); const campaign = await options.store.getCampaign(options.campaignId); if (!campaign) { @@ -807,29 +902,68 @@ export async function writeCampaignSnapshot(options: WriteCampaignSnapshotOption const banditArms = await options.store.listModelBanditArms(options.campaignId); const scratchpads = await options.store.listScratchpadSnapshots(options.campaignId); - // Receipts: only approved verdicts travel; every other stored verdict exports as receipt: null. + // Receipts: only approved verdicts on passed individuals travel; all others export as receipt: null. const receiptBytes = new Map(); const blobByteLengths = new Map(); + const textCheckedBlobs = new Set(); const scratchpadByteLengths = new Map(); - const requireCasBlob = async (digest: Digest, memberPath: string): Promise => { - const byteLength = await readVerifiedCasBlobIfExists(campaignRoot, digest.hex, resolved.maxBlobBytes); - if (byteLength === null) { - throw new EvolutionError('ARTIFACT_MISSING', `CAS blob ${digest.hex} not found in campaign store`, memberPath); + + const scanTextBlob = (bytes: Buffer, diagPath: string): void => { + assertCleanSecretText(decodeUtf8Strict(bytes, diagPath), resolved.scrubber, diagPath); + }; + + const requireBlob = async (digest: Digest, textual: boolean, expectedByteLength?: number): Promise => { + const diagPath = `/blobs/sha256/${digest.hex}`; + const existing = blobByteLengths.get(digest.hex); + if (existing !== undefined) { + if (expectedByteLength !== undefined && existing !== expectedByteLength) { + throw new EvolutionError('ARTIFACT_INVALID', `conflicting byteLength for CAS blob ${digest.hex}`, diagPath); + } + if (!textual || textCheckedBlobs.has(digest.hex)) return; + } + const bytes = await readVerifiedCasBlob(campaignRoot, digest.hex, { + ...(expectedByteLength !== undefined ? { expectedByteLength } : {}), + maxBytes: resolved.maxBlobBytes, + }); + if (textual) { + scanTextBlob(bytes, diagPath); + textCheckedBlobs.add(digest.hex); } - return byteLength; + blobByteLengths.set(digest.hex, bytes.byteLength); }; - const requireBlob = async (digest: Digest): Promise => { - blobByteLengths.set(digest.hex, await requireCasBlob(digest, `/blobs/sha256/${digest.hex}`)); + + const includeBlobIfExists = async (digest: Digest, textual: boolean, expectedByteLength: number): Promise => { + const diagPath = `/blobs/sha256/${digest.hex}`; + const existing = blobByteLengths.get(digest.hex); + if (existing !== undefined) { + if (existing !== expectedByteLength) { + throw new EvolutionError('ARTIFACT_INVALID', `conflicting byteLength for CAS blob ${digest.hex}`, diagPath); + } + if (!textual || textCheckedBlobs.has(digest.hex)) return; + } + let bytes: Buffer; + try { + bytes = await readVerifiedCasBlob(campaignRoot, digest.hex, { + expectedByteLength, + maxBytes: resolved.maxBlobBytes, + }); + } catch (err: unknown) { + if (err instanceof EvolutionError && err.code === 'ARTIFACT_MISSING') return; + throw err; + } + if (textual) { + scanTextBlob(bytes, diagPath); + textCheckedBlobs.add(digest.hex); + } + blobByteLengths.set(digest.hex, bytes.byteLength); }; const individualDocs: SnapshotIndividualRecordV1[] = []; - let minGeneration = 0; - let maxGeneration = 0; for (const ind of individuals) { const { codeSliceCasDigest, verdictReceiptCasDigest } = ind; - if (codeSliceCasDigest !== null) await requireBlob(codeSliceCasDigest); + if (codeSliceCasDigest !== null) await requireBlob(codeSliceCasDigest, true); let receipt: Digest | null = null; - if (verdictReceiptCasDigest !== null) { + if (ind.status === 'passed' && verdictReceiptCasDigest !== null) { if (!SAFE_FILENAME_ID_RE.test(ind.individualId) || ind.individualId === '.' || ind.individualId === '..') { throw new EvolutionError('ARTIFACT_INVALID', `unsafe individualId for receipt filename: "${ind.individualId}"`); } @@ -844,8 +978,7 @@ export async function writeCampaignSnapshot(options: WriteCampaignSnapshotOption '/receiptSigningSecret', ); } - const parsed = await parseAndVerifyReceiptBytes(rawBytes, { - individualId: ind.individualId, + const parsed = await verifyIndividualReceiptBytes(rawBytes, ind, { expectedLockHash: campaign.lockHash, expectedTargetCellId: campaign.manifest.spec.targetCellId, allowSyntheticProbe: resolved.allowSyntheticProbe, @@ -853,23 +986,11 @@ export async function writeCampaignSnapshot(options: WriteCampaignSnapshotOption receiptSigningSecret: resolved.receiptSigningSecret, scrubber: resolved.scrubber, maxBlobBytes: resolved.maxBlobBytes, + bindReceiptFields: true, }); - if (parsed.receipt.runId.startsWith('ind-') && parsed.receipt.runId !== ind.individualId) { - throw new EvolutionError( - 'EXPORT_UNVERIFIED_FORBIDDEN', - `receipt runId "${parsed.receipt.runId}" does not match individual "${ind.individualId}"`, - `/receipts/${ind.individualId}/runId`, - ); + for (const art of parsed.outputArtifacts) { + await requireBlob(art.digest, isTextualArtifact(art.name, art.mediaType), art.byteLength); } - if (ind.hardwareProvenance !== undefined - && canonicalizeJson(ind.hardwareProvenance) !== canonicalizeJson(parsed.provenance)) { - throw new EvolutionError( - 'ARTIFACT_INVALID', - `individual "${ind.individualId}" persisted hardwareProvenance diverges from signed verdict receipt`, - ); - } - assertIndividualArtifactsBoundToReceipt(ind, parsed.outputArtifacts); - for (const art of parsed.outputArtifacts) await requireBlob(art.digest); receiptBytes.set(ind.individualId, rawBytes); receipt = makeDigest(verdictReceiptCasDigest.hex); } @@ -877,33 +998,31 @@ export async function writeCampaignSnapshot(options: WriteCampaignSnapshotOption if (receipt === null) { // Without a signed claim, artifact blobs travel only when the store still holds them. for (const art of ind.outputArtifacts) { - const byteLength = await readVerifiedCasBlobIfExists(campaignRoot, art.digest.hex, resolved.maxBlobBytes); - if (byteLength !== null) blobByteLengths.set(art.digest.hex, byteLength); + await includeBlobIfExists(art.digest, isTextualArtifact(art.name, art.mediaType), art.byteLength); } } individualDocs.push(toIndividualV1(ind, receipt)); - if (individualDocs.length === 1) { - minGeneration = ind.generation; - maxGeneration = ind.generation; - } else { - minGeneration = Math.min(minGeneration, ind.generation); - maxGeneration = Math.max(maxGeneration, ind.generation); - } } + for (const tc of teamConfigs) { - const { patchCasDigest } = tc; - if (patchCasDigest !== null) await requireBlob(patchCasDigest); - } - for (const snap of scratchpads) { - scratchpadByteLengths.set(snap.casDigest.hex, await requireCasBlob(snap.casDigest, scratchpadPath(snap.casDigest.hex))); + if (tc.patchCasDigest !== null) await requireBlob(tc.patchCasDigest, true); } - const campaignDoc: Record = {}; - for (const key of [ - 'campaignId', 'name', 'status', 'stagePhase', 'activeBucketId', 'manifest', 'manifestDigest', - 'baseRevision', 'lockHash', 'driverConstraint', 'currentGeneration', 'evaluationsUsed', 'preemptionsCount', - ] as const) { - campaignDoc[key] = campaign[key]; + for (const snap of scratchpads) { + const relPath = scratchpadPath(snap.casDigest.hex); + const existingLen = scratchpadByteLengths.get(snap.casDigest.hex); + if (existingLen !== undefined) { + if (existingLen !== snap.byteLength) { + throw new EvolutionError('ARTIFACT_INVALID', `conflicting byteLength for scratchpad ${snap.casDigest.hex}`, `/${relPath}`); + } + continue; + } + const bytes = await readVerifiedCasBlob(campaignRoot, snap.casDigest.hex, { + expectedByteLength: snap.byteLength, + maxBytes: SCRATCHPAD_MAX_BYTES, + }); + scanTextBlob(bytes, `/${relPath}`); + scratchpadByteLengths.set(snap.casDigest.hex, bytes.byteLength); } const members: BundleMemberDigest[] = []; @@ -912,7 +1031,7 @@ export async function writeCampaignSnapshot(options: WriteCampaignSnapshotOption assertCleanSecretText(text, resolved.scrubber, `/${relPath}`); stagedFiles.push({ relPath, bytes: Buffer.from(text, 'utf8'), mediaType }); }; - pushText(CAMPAIGN_MEMBER, canonicalizeJson(campaignDoc), CAMPAIGN_SNAPSHOT_JSON_MEDIA_TYPE); + pushText(CAMPAIGN_MEMBER, canonicalizeJson(toCampaignV1(campaign)), CAMPAIGN_SNAPSHOT_JSON_MEDIA_TYPE); pushText(INDIVIDUALS_MEMBER, serializeJsonl(individualDocs), CAMPAIGN_SNAPSHOT_NDJSON_MEDIA_TYPE); pushText(LINEAGE_MEMBER, serializeJsonl(lineageEdges), CAMPAIGN_SNAPSHOT_NDJSON_MEDIA_TYPE); pushText(ISLANDS_MEMBER, canonicalizeJson(islands), CAMPAIGN_SNAPSHOT_JSON_MEDIA_TYPE); @@ -949,17 +1068,36 @@ export async function writeCampaignSnapshot(options: WriteCampaignSnapshotOption }); } members.sort((a, b) => compareUtf16(a.path, b.path)); + if (members.length > MAX_SNAPSHOT_MEMBERS) { + throw new EvolutionError('ARTIFACT_INVALID', `snapshot member count ${members.length} exceeds ${MAX_SNAPSHOT_MEMBERS}`, '/manifest.json/members'); + } - const manifest = createNullRecord>(); + const manifest = createNullRecord<{ + kind: typeof CAMPAIGN_SNAPSHOT_KIND; + version: typeof CAMPAIGN_SNAPSHOT_VERSION; + campaignId: string; + generations: { readonly min: number; readonly max: number }; + parentDigest?: Digest; + members: readonly BundleMemberDigest[]; + }>(); manifest.kind = CAMPAIGN_SNAPSHOT_KIND; manifest.version = CAMPAIGN_SNAPSHOT_VERSION; manifest.campaignId = campaign.campaignId; - manifest.generations = { min: minGeneration, max: maxGeneration }; + manifest.generations = computeGenerationRange(individuals); if (parentDigest !== undefined) manifest.parentDigest = parentDigest; manifest.members = members; - const manifestText = canonicalizeJson(manifest); + + const manifestText = canonicalizeJson(manifest, { + maxBytes: MAX_SNAPSHOT_MANIFEST_BYTES, + maxCollection: MAX_SNAPSHOT_MEMBERS, + maxNodes: MAX_SNAPSHOT_MANIFEST_NODES, + path: '/manifest.json', + }); assertCleanSecretText(manifestText, resolved.scrubber, '/manifest.json'); const manifestBytes = Buffer.from(manifestText, 'utf8'); + if (manifestBytes.byteLength > MAX_SNAPSHOT_MANIFEST_BYTES) { + throw new EvolutionError('ARTIFACT_INVALID', `manifest.json exceeds ${MAX_SNAPSHOT_MANIFEST_BYTES} bytes`, '/manifest.json'); + } const manifestDigest = makeDigest(sha256Hex(manifestBytes)); const parentDir = dirname(outDir); @@ -975,11 +1113,18 @@ export async function writeCampaignSnapshot(options: WriteCampaignSnapshotOption for (const rec of stagedFiles) await writeNewFileNoFollow(join(stagingDir, rec.relPath), rec.bytes, 0o644); for (const relPath of scratchpadRelPaths) { const hex = relPath.slice('scratchpad/'.length, -'.md'.length); - const bytes = await readVerifiedCasBlob(campaignRoot, hex, { maxBytes: resolved.maxBlobBytes }); + const bytes = await readVerifiedCasBlob(campaignRoot, hex, { + expectedByteLength: scratchpadByteLengths.get(hex)!, + maxBytes: SCRATCHPAD_MAX_BYTES, + }); await writeNewFileNoFollow(join(stagingDir, relPath), bytes, 0o644); } for (const relPath of blobRelPaths) { - const bytes = await readVerifiedCasBlob(campaignRoot, relPath.slice('blobs/sha256/'.length), { maxBytes: resolved.maxBlobBytes }); + const hex = relPath.slice('blobs/sha256/'.length); + const bytes = await readVerifiedCasBlob(campaignRoot, hex, { + expectedByteLength: blobByteLengths.get(hex)!, + maxBytes: resolved.maxBlobBytes, + }); await writeNewFileNoFollow(join(stagingDir, relPath), bytes, 0o644); } for (const id of receiptBytes.keys()) { @@ -993,14 +1138,14 @@ export async function writeCampaignSnapshot(options: WriteCampaignSnapshotOption } } - const result = createNullRecord>(); - result.outDir = outDir; - result.manifestDigest = manifestDigest; - if (parentDigest !== undefined) result.parentDigest = parentDigest; - result.individualCount = individuals.length; - result.receiptCount = receiptBytes.size; - result.blobCount = blobByteLengths.size; - return result as unknown as WriteCampaignSnapshotResult; + return Object.freeze({ + outDir, + manifestDigest, + ...(parentDigest !== undefined ? { parentDigest } : {}), + individualCount: individuals.length, + receiptCount: receiptBytes.size, + blobCount: blobByteLengths.size, + }); } /** @@ -1010,14 +1155,14 @@ export async function writeCampaignSnapshot(options: WriteCampaignSnapshotOption */ export async function verifyCampaignSnapshot(options: VerifyCampaignSnapshotOptions): Promise { const verified = await loadAndVerifySnapshot(options); - const result = createNullRecord>(); - result.bundleDir = verified.bundleDir; - result.manifest = verified.manifest; - result.manifestDigest = verified.manifestDigest; - result.individualCount = verified.individuals.length; - result.receiptCount = verified.receiptBytes.size; - result.blobCount = verified.blobByteLengths.size; - return result as unknown as VerifyCampaignSnapshotResult; + return Object.freeze({ + bundleDir: verified.bundleDir, + manifest: verified.manifest, + manifestDigest: verified.manifestDigest, + individualCount: verified.individuals.length, + receiptCount: verified.receiptBytes.size, + blobCount: verified.blobByteLengths.size, + }); } async function loadAndVerifySnapshot(options: VerifyCampaignSnapshotOptions): Promise { @@ -1026,59 +1171,86 @@ async function loadAndVerifySnapshot(options: VerifyCampaignSnapshotOptions): Pr await assertNoSymlinkPath(bundleDir, { checkLeaf: true, diagPath: bundleDir }); await verifyNonSymlinkDirectoryFd(bundleDir); - const manifestBytes = await readVerifiedRegularFileNoFollow(join(bundleDir, 'manifest.json'), { + const manifestPath = join(bundleDir, 'manifest.json'); + await assertNoSymlinkPath(manifestPath, { checkLeaf: true, diagPath: manifestPath }); + const manifestBytes = await readVerifiedRegularFileNoFollow(manifestPath, { maxBytes: MAX_SNAPSHOT_MANIFEST_BYTES, missingCode: 'ARTIFACT_MISSING', }); const manifestDigest = makeDigest(sha256Hex(manifestBytes)); - const manifestObj = expectObject( - parseJsonMember(decodeUtf8Strict(manifestBytes, '/manifest.json'), '/manifest.json', MAX_SNAPSHOT_MANIFEST_BYTES), + const manifestText = decodeUtf8Strict(manifestBytes, '/manifest.json'); + assertCleanSecretText(manifestText, resolved.scrubber, '/manifest.json'); + const manifestObj = expectRecord( + parseJsonMember(manifestText, '/manifest.json', MAX_SNAPSHOT_MANIFEST_BYTES, SNAPSHOT_MANIFEST_PARSE_OPTIONS), MANIFEST_KEYS, ['kind', 'version', 'campaignId', 'generations', 'members'], + 'ARTIFACT_INVALID', '/manifest.json', ); const manifest = parseManifest(manifestObj, '/manifest.json'); // Verify every member digest and length; keep only the small text members in memory. const memberBytes = new Map(); + const memberByPath = new Map(); const blobByteLengths = new Map(); - for (const member of manifest.members) { - const absPath = join(bundleDir, member.path); + for (const entry of manifest.members) { + memberByPath.set(entry.path, entry); + const absPath = join(bundleDir, entry.path); await assertNoSymlinkPath(absPath, { checkLeaf: true, diagPath: absPath }); - const isBlob = member.path.startsWith('blobs/sha256/'); + const isBlob = entry.path.startsWith('blobs/sha256/'); + const isReceipt = entry.path.startsWith('receipts/'); + const isScratchpad = entry.path.startsWith('scratchpad/'); + const maxBytes = isBlob + ? resolved.maxBlobBytes + : isReceipt + ? MAX_RECEIPT_FILE_BYTES + : isScratchpad + ? SCRATCHPAD_MAX_BYTES + : MAX_SNAPSHOT_MEMBER_BYTES; const bytes = await readVerifiedRegularFileNoFollow(absPath, { - expectedSha256Hex: member.digest.hex, - expectedByteLength: member.byteLength, - maxBytes: isBlob ? resolved.maxBlobBytes : MAX_SNAPSHOT_MEMBER_BYTES, + expectedSha256Hex: entry.digest.hex, + expectedByteLength: entry.byteLength, + maxBytes, missingCode: 'ARTIFACT_MISSING', }); if (isBlob) { - const hexFromPath = member.path.slice('blobs/sha256/'.length); - if (hexFromPath !== member.digest.hex) { - throw new EvolutionError('ARTIFACT_INVALID', `blob path "${member.path}" does not match digest ${member.digest.hex}`, member.path); + const hexFromPath = entry.path.slice('blobs/sha256/'.length); + if (hexFromPath !== entry.digest.hex) { + throw new EvolutionError('ARTIFACT_INVALID', `blob path "${entry.path}" does not match digest ${entry.digest.hex}`, entry.path); + } + blobByteLengths.set(entry.digest.hex, entry.byteLength); + } else if (isScratchpad) { + const hexFromPath = entry.path.slice('scratchpad/'.length, -'.md'.length); + if (hexFromPath !== entry.digest.hex) { + throw new EvolutionError('ARTIFACT_INVALID', `scratchpad path "${entry.path}" does not match digest ${entry.digest.hex}`, entry.path); } - blobByteLengths.set(member.digest.hex, member.byteLength); + assertCleanSecretText(decodeUtf8Strict(bytes, `/${entry.path}`), resolved.scrubber, `/${entry.path}`); + memberBytes.set(entry.path, bytes); } else { - memberBytes.set(member.path, bytes); + memberBytes.set(entry.path, bytes); } } - const member = (relPath: string): Buffer => { + const memberText = (relPath: string): string => { const bytes = memberBytes.get(relPath); if (bytes === undefined) { throw new EvolutionError('ARTIFACT_MISSING', `manifest.json does not list ${relPath}`, `/${relPath}`); } - return bytes; + const text = decodeUtf8Strict(bytes, `/${relPath}`); + assertCleanSecretText(text, resolved.scrubber, `/${relPath}`); + return text; }; const campaign = parseCampaign( - expectObject( - parseJsonMember(decodeUtf8Strict(member(CAMPAIGN_MEMBER), `/${CAMPAIGN_MEMBER}`), `/${CAMPAIGN_MEMBER}`, MAX_SNAPSHOT_MEMBER_BYTES), + expectRecord( + parseJsonMember(memberText(CAMPAIGN_MEMBER), `/${CAMPAIGN_MEMBER}`, MAX_SNAPSHOT_MEMBER_BYTES), CAMPAIGN_KEYS, [...CAMPAIGN_KEYS], + 'ARTIFACT_INVALID', `/${CAMPAIGN_MEMBER}`, ), `/${CAMPAIGN_MEMBER}`, + resolved.scrubber, ); if (campaign.campaignId !== manifest.campaignId) { throw new EvolutionError('ARTIFACT_INVALID', `campaign.json campaignId "${campaign.campaignId}" does not match manifest "${manifest.campaignId}"`, `/${CAMPAIGN_MEMBER}/campaignId`); @@ -1090,45 +1262,51 @@ async function loadAndVerifySnapshot(options: VerifyCampaignSnapshotOptions): Pr } }; - const individuals = parseJsonLines(decodeUtf8Strict(member(INDIVIDUALS_MEMBER), `/${INDIVIDUALS_MEMBER}`), INDIVIDUALS_MEMBER, MAX_SNAPSHOT_MEMBER_BYTES) - .map((line, i) => parseIndividual(expectObject(line, INDIVIDUAL_KEYS, INDIVIDUAL_REQUIRED_KEYS, `/${INDIVIDUALS_MEMBER}/${i}`), `/${INDIVIDUALS_MEMBER}/${i}`)); - const lineageEdges = parseJsonLines(decodeUtf8Strict(member(LINEAGE_MEMBER), `/${LINEAGE_MEMBER}`), LINEAGE_MEMBER, MAX_SNAPSHOT_MEMBER_BYTES) - .map((line, i) => parseLineageEdge(expectObject(line, LINEAGE_KEYS, [...LINEAGE_KEYS], `/${LINEAGE_MEMBER}/${i}`), `/${LINEAGE_MEMBER}/${i}`)); - const islands = parseArrayMember(decodeUtf8Strict(member(ISLANDS_MEMBER), `/${ISLANDS_MEMBER}`), ISLANDS_MEMBER) - .map((entry, i) => parseIsland(expectObject(entry, ISLAND_KEYS, [...ISLAND_KEYS], `/${ISLANDS_MEMBER}/${i}`), `/${ISLANDS_MEMBER}/${i}`)); - const banditArms = parseArrayMember(decodeUtf8Strict(member(BANDIT_MEMBER), `/${BANDIT_MEMBER}`), BANDIT_MEMBER) - .map((entry, i) => parseBanditArm(expectObject(entry, BANDIT_KEYS, [...BANDIT_KEYS], `/${BANDIT_MEMBER}/${i}`), `/${BANDIT_MEMBER}/${i}`)); - const teamConfigs = parseJsonLines(decodeUtf8Strict(member(TEAM_CONFIGS_MEMBER), `/${TEAM_CONFIGS_MEMBER}`), TEAM_CONFIGS_MEMBER, MAX_SNAPSHOT_MEMBER_BYTES) - .map((line, i) => parseTeamConfig(expectObject(line, TEAM_CONFIG_KEYS, [...TEAM_CONFIG_KEYS], `/${TEAM_CONFIGS_MEMBER}/${i}`), `/${TEAM_CONFIGS_MEMBER}/${i}`)); - const scratchpads = parseJsonLines(decodeUtf8Strict(member(SCRATCHPAD_INDEX_MEMBER), `/${SCRATCHPAD_INDEX_MEMBER}`), SCRATCHPAD_INDEX_MEMBER, MAX_SNAPSHOT_MEMBER_BYTES) - .map((line, i) => parseScratchpad(expectObject(line, SCRATCHPAD_KEYS, [...SCRATCHPAD_KEYS], `/${SCRATCHPAD_INDEX_MEMBER}/${i}`), `/${SCRATCHPAD_INDEX_MEMBER}/${i}`)); + const individuals = parseJsonLines(memberText(INDIVIDUALS_MEMBER), INDIVIDUALS_MEMBER, MAX_SNAPSHOT_MEMBER_BYTES) + .map((line, i) => parseIndividual( + expectRecord(line, INDIVIDUAL_KEYS, INDIVIDUAL_REQUIRED_KEYS, 'ARTIFACT_INVALID', `/${INDIVIDUALS_MEMBER}/${i}`), + `/${INDIVIDUALS_MEMBER}/${i}`, + resolved.scrubber, + )); + const lineageEdges = parseJsonLines(memberText(LINEAGE_MEMBER), LINEAGE_MEMBER, MAX_SNAPSHOT_MEMBER_BYTES) + .map((line, i) => parseLineageEdge( + expectRecord(line, LINEAGE_KEYS, [...LINEAGE_KEYS], 'ARTIFACT_INVALID', `/${LINEAGE_MEMBER}/${i}`), + `/${LINEAGE_MEMBER}/${i}`, + )); + const islands = parseArrayMember(memberText(ISLANDS_MEMBER), ISLANDS_MEMBER) + .map((entry, i) => parseIsland( + expectRecord(entry, ISLAND_KEYS, [...ISLAND_KEYS], 'ARTIFACT_INVALID', `/${ISLANDS_MEMBER}/${i}`), + `/${ISLANDS_MEMBER}/${i}`, + )); + const banditArms = parseArrayMember(memberText(BANDIT_MEMBER), BANDIT_MEMBER) + .map((entry, i) => parseBanditArm( + expectRecord(entry, BANDIT_KEYS, [...BANDIT_KEYS], 'ARTIFACT_INVALID', `/${BANDIT_MEMBER}/${i}`), + `/${BANDIT_MEMBER}/${i}`, + )); + const rawTeamConfigs = parseJsonLines(memberText(TEAM_CONFIGS_MEMBER), TEAM_CONFIGS_MEMBER, MAX_SNAPSHOT_MEMBER_BYTES) + .map((line, i) => parseTeamConfig( + expectRecord(line, TEAM_CONFIG_KEYS, [...TEAM_CONFIG_KEYS], 'ARTIFACT_INVALID', `/${TEAM_CONFIGS_MEMBER}/${i}`), + `/${TEAM_CONFIGS_MEMBER}/${i}`, + )); + const scratchpads = parseJsonLines(memberText(SCRATCHPAD_INDEX_MEMBER), SCRATCHPAD_INDEX_MEMBER, MAX_SNAPSHOT_MEMBER_BYTES) + .map((line, i) => parseScratchpad( + expectRecord(line, SCRATCHPAD_KEYS, [...SCRATCHPAD_KEYS], 'ARTIFACT_INVALID', `/${SCRATCHPAD_INDEX_MEMBER}/${i}`), + `/${SCRATCHPAD_INDEX_MEMBER}/${i}`, + )); // Generations in the manifest must describe the individuals actually present. - let minGeneration = 0; - let maxGeneration = 0; - individuals.forEach((ind, index) => { - if (index === 0) { - minGeneration = ind.generation; - maxGeneration = ind.generation; - } else { - minGeneration = Math.min(minGeneration, ind.generation); - maxGeneration = Math.max(maxGeneration, ind.generation); - } - }); - if (manifest.generations.min !== minGeneration || manifest.generations.max !== maxGeneration) { + const observedRange = computeGenerationRange(individuals); + if (manifest.generations.min !== observedRange.min || manifest.generations.max !== observedRange.max) { throw new EvolutionError('ARTIFACT_INVALID', 'manifest.json generations do not match individuals.jsonl', '/manifest.json/generations'); } - // Cross-references: unique keys, every campaignId, and every foreign reference resolvable. - const teamConfigIds = new Set(); - for (const tc of teamConfigs) { + // Cross-references: unique keys, every campaignId, topological team_configs, and every foreign reference resolvable. + for (const tc of rawTeamConfigs) { assertCampaignId(tc.campaignId, `/${TEAM_CONFIGS_MEMBER}`); - if (teamConfigIds.has(tc.teamConfigId)) invalid(`duplicate teamConfigId "${tc.teamConfigId}"`, `/${TEAM_CONFIGS_MEMBER}`); - teamConfigIds.add(tc.teamConfigId); - if (tc.parentTeamConfigId !== null && !teamConfigIds.has(tc.parentTeamConfigId) && !teamConfigs.some(t => t.teamConfigId === tc.parentTeamConfigId)) { - invalid(`team_config "${tc.teamConfigId}" references unknown parent "${tc.parentTeamConfigId}"`, `/${TEAM_CONFIGS_MEMBER}`); - } } + const teamConfigs = sortTeamConfigsTopologically(rawTeamConfigs, 'ARTIFACT_INVALID', `/${TEAM_CONFIGS_MEMBER}`); + const teamConfigIds = new Set(teamConfigs.map(tc => tc.teamConfigId)); + const islandIds = new Set(); for (const island of islands) { assertCampaignId(island.campaignId, `/${ISLANDS_MEMBER}`); @@ -1138,6 +1316,9 @@ async function loadAndVerifySnapshot(options: VerifyCampaignSnapshotOptions): Pr invalid(`island ${island.islandId} references unknown team_config "${island.activeTeamConfigId}"`, `/${ISLANDS_MEMBER}`); } } + + const referencedMemberPaths = new Set(REQUIRED_MEMBERS); + const textualBlobHexes = new Set(); const individualIds = new Set(); for (const ind of individuals) { assertCampaignId(ind.campaignId, `/${INDIVIDUALS_MEMBER}`); @@ -1149,16 +1330,27 @@ async function loadAndVerifySnapshot(options: VerifyCampaignSnapshotOptions): Pr if (!islandIds.has(ind.islandId)) { invalid(`individual "${ind.individualId}" references unknown island ${ind.islandId}`, `/${INDIVIDUALS_MEMBER}`); } - if (ind.codeSliceCasDigest !== null && !blobByteLengths.has(ind.codeSliceCasDigest.hex)) { - invalid(`individual "${ind.individualId}" code slice ${ind.codeSliceCasDigest.hex} is missing from blobs`, `/${INDIVIDUALS_MEMBER}`); + if (ind.codeSliceCasDigest !== null) { + if (!blobByteLengths.has(ind.codeSliceCasDigest.hex)) { + invalid(`individual "${ind.individualId}" code slice ${ind.codeSliceCasDigest.hex} is missing from blobs`, `/${INDIVIDUALS_MEMBER}`); + } + referencedMemberPaths.add(`blobs/sha256/${ind.codeSliceCasDigest.hex}`); + textualBlobHexes.add(ind.codeSliceCasDigest.hex); } for (const art of ind.outputArtifacts) { const present = blobByteLengths.get(art.digest.hex); - if (present !== undefined && present !== art.byteLength) { - invalid(`individual "${ind.individualId}" outputArtifact "${art.name}" byteLength does not match blob`, `/${INDIVIDUALS_MEMBER}`); + if (present !== undefined) { + if (present !== art.byteLength) { + invalid(`individual "${ind.individualId}" outputArtifact "${art.name}" byteLength does not match blob`, `/${INDIVIDUALS_MEMBER}`); + } + referencedMemberPaths.add(`blobs/sha256/${art.digest.hex}`); + if (isTextualArtifact(art.name, art.mediaType)) { + textualBlobHexes.add(art.digest.hex); + } } } } + const lineageKeys = new Set(); for (const edge of lineageEdges) { assertCampaignId(edge.campaignId, `/${LINEAGE_MEMBER}`); @@ -1169,17 +1361,24 @@ async function loadAndVerifySnapshot(options: VerifyCampaignSnapshotOptions): Pr if (!individualIds.has(id)) invalid(`lineage edge references unknown individual "${id}"`, `/${LINEAGE_MEMBER}`); } } + const banditKeys = new Set(); for (const arm of banditArms) { assertCampaignId(arm.campaignId, `/${BANDIT_MEMBER}`); if (banditKeys.has(arm.modelId)) invalid(`duplicate bandit arm "${arm.modelId}"`, `/${BANDIT_MEMBER}`); banditKeys.add(arm.modelId); } + for (const tc of teamConfigs) { - if (tc.patchCasDigest !== null && !blobByteLengths.has(tc.patchCasDigest.hex)) { - invalid(`team_config "${tc.teamConfigId}" patch ${tc.patchCasDigest.hex} is missing from blobs`, `/${TEAM_CONFIGS_MEMBER}`); + if (tc.patchCasDigest !== null) { + if (!blobByteLengths.has(tc.patchCasDigest.hex)) { + invalid(`team_config "${tc.teamConfigId}" patch ${tc.patchCasDigest.hex} is missing from blobs`, `/${TEAM_CONFIGS_MEMBER}`); + } + referencedMemberPaths.add(`blobs/sha256/${tc.patchCasDigest.hex}`); + textualBlobHexes.add(tc.patchCasDigest.hex); } } + const scratchpadBytes = new Map(); const snapshotIds = new Set(); for (const snap of scratchpads) { @@ -1192,17 +1391,26 @@ async function loadAndVerifySnapshot(options: VerifyCampaignSnapshotOptions): Pr if (bytes.byteLength !== snap.byteLength || sha256Hex(bytes) !== snap.casDigest.hex) { invalid(`scratchpad "${snap.snapshotId}" content does not match its CAS digest`, `/${SCRATCHPAD_INDEX_MEMBER}`); } + referencedMemberPaths.add(relPath); scratchpadBytes.set(snap.casDigest.hex, bytes); } - // Receipts: every approved receipt is verified fail-closed exactly as bundle export verifies it. + // Receipts: every approved receipt is verified fail-closed and bound to the individual record. const receiptBytes = new Map(); for (const ind of individuals) { - if (ind.receipt === null) continue; + if (ind.receipt === null) { + if (ind.hardwareProvenance !== undefined) { + invalid( + `individual "${ind.individualId}" cannot declare hardwareProvenance without a signed receipt`, + `/${INDIVIDUALS_MEMBER}`, + ); + } + continue; + } const relPath = `receipts/${ind.individualId}.verdict.json`; const bytes = memberBytes.get(relPath); if (bytes === undefined) invalid(`individual "${ind.individualId}" has a receipt digest but no receipt member`, `/${relPath}`); - const listed = manifest.members.find(m => m.path === relPath)!; + const listed = memberByPath.get(relPath)!; if (listed.digest.hex !== ind.receipt.hex) { invalid(`receipt member "${relPath}" digest does not match individual "${ind.individualId}"`, `/${relPath}`); } @@ -1213,8 +1421,7 @@ async function loadAndVerifySnapshot(options: VerifyCampaignSnapshotOptions): Pr '/receiptSigningSecret', ); } - const parsed = await parseAndVerifyReceiptBytes(bytes, { - individualId: ind.individualId, + const parsed = await verifyIndividualReceiptBytes(bytes, ind, { expectedLockHash: campaign.lockHash, expectedTargetCellId: campaign.manifest.spec.targetCellId, allowSyntheticProbe: resolved.allowSyntheticProbe, @@ -1222,51 +1429,117 @@ async function loadAndVerifySnapshot(options: VerifyCampaignSnapshotOptions): Pr receiptSigningSecret: resolved.receiptSigningSecret, scrubber: resolved.scrubber, maxBlobBytes: resolved.maxBlobBytes, + bindReceiptFields: true, }); - if (parsed.rawDigest.hex !== ind.receipt.hex) { - invalid(`receipt "${relPath}" does not match the receipt digest of individual "${ind.individualId}"`, `/${relPath}`); - } - if (parsed.receipt.runId.startsWith('ind-') && parsed.receipt.runId !== ind.individualId) { - throw new EvolutionError( - 'EXPORT_UNVERIFIED_FORBIDDEN', - `receipt runId "${parsed.receipt.runId}" does not match individual "${ind.individualId}"`, - `/${relPath}/runId`, - ); - } - if (ind.hardwareProvenance !== undefined && canonicalizeJson(ind.hardwareProvenance) !== canonicalizeJson(parsed.provenance)) { - invalid(`individual "${ind.individualId}" hardwareProvenance diverges from its signed verdict receipt`, `/${INDIVIDUALS_MEMBER}`); - } - assertIndividualArtifactsBoundToReceipt(ind, parsed.outputArtifacts); + referencedMemberPaths.add(relPath); for (const art of parsed.outputArtifacts) { - if (!blobByteLengths.has(art.digest.hex)) { + const presentLen = blobByteLengths.get(art.digest.hex); + if (presentLen === undefined) { invalid(`receipt "${ind.individualId}" references blob ${art.digest.hex} missing from snapshot members`, `/${relPath}/outputArtifacts`); } + if (presentLen !== art.byteLength) { + invalid(`receipt "${ind.individualId}" outputArtifact "${art.name}" byteLength does not match blob`, `/${relPath}/outputArtifacts`); + } + referencedMemberPaths.add(`blobs/sha256/${art.digest.hex}`); + if (isTextualArtifact(art.name, art.mediaType)) { + textualBlobHexes.add(art.digest.hex); + } } receiptBytes.set(ind.individualId, bytes); } - const result = createNullRecord>(); - result.bundleDir = bundleDir; - result.manifest = manifest; - result.manifestDigest = manifestDigest; - result.campaign = campaign; - result.individuals = individuals; - result.lineageEdges = lineageEdges; - result.islands = islands; - result.modelBanditArms = banditArms; - result.teamConfigs = teamConfigs; - result.scratchpadSnapshots = scratchpads; - result.scratchpadBytes = scratchpadBytes; - result.receiptBytes = receiptBytes; - result.blobByteLengths = blobByteLengths; - return result as unknown as VerifiedCampaignSnapshot; + // Reject any unreferenced member so rogue receipts, scratchpads, or blobs cannot bypass verification. + for (const entry of manifest.members) { + if (!referencedMemberPaths.has(entry.path)) { + invalid(`manifest.json lists unreferenced member "${entry.path}"`, '/manifest.json/members'); + } + } + + // Secret-scan all textual CAS blobs one at a time so peak memory stays O(1) blob. + for (const hex of [...textualBlobHexes].sort(compareUtf16)) { + const relPath = `blobs/sha256/${hex}`; + const bytes = await readVerifiedRegularFileNoFollow(join(bundleDir, relPath), { + expectedSha256Hex: hex, + expectedByteLength: blobByteLengths.get(hex)!, + maxBytes: resolved.maxBlobBytes, + missingCode: 'ARTIFACT_MISSING', + }); + assertCleanSecretText(decodeUtf8Strict(bytes, `/${relPath}`), resolved.scrubber, `/${relPath}`); + } + + return Object.freeze({ + bundleDir, + manifest, + manifestDigest, + campaign, + individuals, + lineageEdges, + islands, + modelBanditArms: banditArms, + teamConfigs, + scratchpadSnapshots: scratchpads, + scratchpadBytes, + receiptBytes, + blobByteLengths, + }); } -async function removeImportedState(stateDir: string, createdStateDir: boolean): Promise { - if (createdStateDir) { - await rm(stateDir, { recursive: true, force: true }).catch(() => undefined); - return; +async function populateImportedStore( + targetDir: string, + verified: VerifiedCampaignSnapshot, + resolved: ResolvedSnapshotOptions, + clock: CampaignClockSource, +): Promise { + const store = await EvolutionCampaignStore.open({ + campaignRoot: targetDir, + clock, + createIfMissing: true, + }); + try { + const lease = await store.acquireLease(`import-${randomBytes(6).toString('hex')}`); + + for (const hex of [...verified.blobByteLengths.keys()].sort(compareUtf16)) { + const bytes = await readVerifiedRegularFileNoFollow(join(verified.bundleDir, 'blobs', 'sha256', hex), { + expectedSha256Hex: hex, + expectedByteLength: verified.blobByteLengths.get(hex)!, + maxBytes: resolved.maxBlobBytes, + missingCode: 'ARTIFACT_MISSING', + }); + await store.writeCasBlob(bytes); + } + for (const id of [...verified.receiptBytes.keys()].sort(compareUtf16)) { + await store.writeCasBlob(verified.receiptBytes.get(id)!); + } + for (const hex of [...verified.scratchpadBytes.keys()].sort(compareUtf16)) { + await store.writeCasBlob(verified.scratchpadBytes.get(hex)!); + } + + await store.importCampaignState(lease, { + campaign: verified.campaign, + islands: verified.islands, + teamConfigs: verified.teamConfigs, + individuals: verified.individuals.map(ind => { + const { crowdingIsBoundary, receipt, ...rest } = ind; + return { + ...rest, + crowdingDistance: crowdingIsBoundary ? Number.POSITIVE_INFINITY : rest.crowdingDistance, + verdictReceiptCasDigest: receipt, + }; + }), + lineageEdges: verified.lineageEdges, + modelBanditArms: verified.modelBanditArms, + scratchpadSnapshots: verified.scratchpadSnapshots, + snapshotDigest: verified.manifestDigest, + }); + await store.releaseLease(lease); + } catch (err: unknown) { + await store.close().catch(() => undefined); + throw err; } + await store.close(); +} + +async function removeImportedFilesInExistingDir(stateDir: string): Promise { for (const name of [CAMPAIGN_SQLITE_FILENAME, `${CAMPAIGN_SQLITE_FILENAME}-journal`]) { await rm(join(stateDir, name), { force: true }).catch(() => undefined); } @@ -1281,6 +1554,7 @@ async function removeImportedState(stateDir: string, createdStateDir: boolean): */ export async function importCampaignSnapshot(options: ImportCampaignSnapshotOptions): Promise { const resolved = resolveOptions(options); + const clock = options.clock ?? DEFAULT_CAMPAIGN_CLOCK; const stateDir = validateAbsoluteFilesystemPath(options.stateDir, 'stateDir'); await assertNoSymlinkPath(stateDir, { checkLeaf: true, diagPath: stateDir }); const existing = await lstat(stateDir).catch((err: NodeJS.ErrnoException) => { @@ -1308,84 +1582,99 @@ export async function importCampaignSnapshot(options: ImportCampaignSnapshotOpti } const verified = await loadAndVerifySnapshot(options); - const createdStateDir = existing === null; - await ensureDirectoryChainNoSymlink(dirname(stateDir), 0o755); + const parentDir = dirname(stateDir); + await ensureDirectoryChainNoSymlink(parentDir, 0o755); - const store = await EvolutionCampaignStore.open({ - campaignRoot: stateDir, - clock: options.clock ?? DEFAULT_CAMPAIGN_CLOCK, - createIfMissing: true, - }); - try { - const lease = await store.acquireLease(`import-${randomBytes(6).toString('hex')}`); + if (existing === null) { + const stagingDir = join(parentDir, `.evolution-import-stage-${randomBytes(8).toString('hex')}`); + let published = false; + try { + await mkdir(stagingDir, { mode: 0o700, recursive: false }); + await populateImportedStore(stagingDir, verified, resolved, clock); + + const concurrent = await lstat(stateDir).catch((err: NodeJS.ErrnoException) => { + if (err.code === 'ENOENT') return null; + if (err.code === 'ELOOP') { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `symlink forbidden at stateDir: ${stateDir}`, stateDir); + } + throw err; + }); + if (concurrent !== null) { + if (concurrent.isSymbolicLink()) { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `stateDir cannot be a symlink: ${stateDir}`, stateDir); + } + throw new EvolutionError('EVOLUTION_CONFLICT', `stateDir was created concurrently during import: ${stateDir}`, '/stateDir'); + } - for (const hex of [...verified.blobByteLengths.keys()].sort(compareUtf16)) { - const bytes = await readVerifiedRegularFileNoFollow(join(verified.bundleDir, 'blobs', 'sha256', hex), { - expectedSha256Hex: hex, - expectedByteLength: verified.blobByteLengths.get(hex)!, - maxBytes: resolved.maxBlobBytes, - missingCode: 'ARTIFACT_MISSING', + await rename(stagingDir, stateDir).catch((err: NodeJS.ErrnoException) => { + if (err.code === 'EEXIST' || err.code === 'ENOTEMPTY' || err.code === 'ENOTDIR') { + throw new EvolutionError('EVOLUTION_CONFLICT', `stateDir already exists: ${stateDir}`, '/stateDir'); + } + throw err; }); - await store.writeCasBlob(bytes); - } - for (const id of [...verified.receiptBytes.keys()].sort(compareUtf16)) { - await store.writeCasBlob(verified.receiptBytes.get(id)!); + published = true; + } finally { + if (!published) { + await rm(stagingDir, { recursive: true, force: true }).catch(() => undefined); + } } - for (const hex of [...verified.scratchpadBytes.keys()].sort(compareUtf16)) { - await store.writeCasBlob(verified.scratchpadBytes.get(hex)!); + } else { + // stateDir already existed and was empty; claim campaign.sqlite exclusively before writing. + await assertNoSymlinkPath(stateDir, { checkLeaf: true, diagPath: stateDir }); + await verifyNonSymlinkDirectoryFd(stateDir); + const entriesBefore = await readdir(stateDir); + if (entriesBefore.length > 0) { + throw new EvolutionError( + 'EVOLUTION_CONFLICT', + `stateDir already holds state (${entriesBefore.length} entries); import requires an empty directory`, + '/stateDir', + ); } - await store.importCampaignState(lease, { - campaign: verified.campaign, - islands: verified.islands, - teamConfigs: verified.teamConfigs, - individuals: verified.individuals.map(ind => ({ - individualId: ind.individualId, - campaignId: ind.campaignId, - islandId: ind.islandId, - generation: ind.generation, - bucketId: ind.bucketId, - teamConfigId: ind.teamConfigId, - modelId: ind.modelId, - trackId: ind.trackId, - mutationKind: ind.mutationKind, - status: ind.status, - failureReason: ind.failureReason, - nicheKey: ind.nicheKey, - paretoRank: ind.paretoRank, - crowdingDistance: ind.crowdingIsBoundary ? Number.POSITIVE_INFINITY : ind.crowdingDistance, - scalarFitness: ind.scalarFitness, - offspringCount: ind.offspringCount, - codeSliceCasDigest: ind.codeSliceCasDigest, - evidenceDigest: ind.evidenceDigest, - verdictReceiptCasDigest: ind.receipt, - outputArtifacts: ind.outputArtifacts, - metrics: ind.metrics, - ...(ind.bucketMetrics !== undefined ? { bucketMetrics: ind.bucketMetrics } : {}), - ...(ind.hardwareDiagnostics !== undefined ? { hardwareDiagnostics: ind.hardwareDiagnostics } : {}), - ...(ind.hardwareProvenance !== undefined ? { hardwareProvenance: ind.hardwareProvenance } : {}), - ...(ind.findings !== undefined ? { findings: ind.findings } : {}), - })), - lineageEdges: verified.lineageEdges, - modelBanditArms: verified.modelBanditArms, - scratchpadSnapshots: verified.scratchpadSnapshots, - snapshotDigest: verified.manifestDigest, + const dbPath = join(stateDir, CAMPAIGN_SQLITE_FILENAME); + const noFollow = 'O_NOFOLLOW' in fsConstants ? fsConstants.O_NOFOLLOW : 0; + const claimHandle = await open( + dbPath, + fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_RDWR | noFollow, + 0o600, + ).catch((err: NodeJS.ErrnoException) => { + if (err.code === 'EEXIST') { + throw new EvolutionError('EVOLUTION_CONFLICT', `stateDir already holds ${CAMPAIGN_SQLITE_FILENAME}`, '/stateDir'); + } + if (err.code === 'ELOOP' || err.code === 'EFTYPE') { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `symlink forbidden at ${dbPath}`, dbPath); + } + throw err; }); - await store.releaseLease(lease); - } catch (err: unknown) { - await store.close().catch(() => undefined); - await removeImportedState(stateDir, createdStateDir); - throw err; + await claimHandle.close(); + + const entriesAfterClaim = await readdir(stateDir); + if (entriesAfterClaim.some(entry => entry !== CAMPAIGN_SQLITE_FILENAME)) { + await rm(dbPath, { force: true }).catch(() => undefined); + throw new EvolutionError( + 'EVOLUTION_CONFLICT', + 'stateDir became non-empty concurrently during import', + '/stateDir', + ); + } + + try { + await populateImportedStore(stateDir, verified, resolved, clock); + } catch (err: unknown) { + if (!(err instanceof EvolutionError && err.code === 'EVOLUTION_CONFLICT')) { + await removeImportedFilesInExistingDir(stateDir); + } + throw err; + } } - await store.close(); - const result = createNullRecord>(); - result.stateDir = stateDir; - result.dbPath = join(stateDir, CAMPAIGN_SQLITE_FILENAME); - result.campaignId = verified.campaign.campaignId; - result.snapshotDigest = verified.manifestDigest; - result.individualCount = verified.individuals.length; - result.receiptCount = verified.receiptBytes.size; - result.blobCount = verified.blobByteLengths.size; - return result as unknown as ImportCampaignSnapshotResult; + return Object.freeze({ + stateDir, + dbPath: join(stateDir, CAMPAIGN_SQLITE_FILENAME), + campaignId: verified.campaign.campaignId, + snapshotDigest: verified.manifestDigest, + individualCount: verified.individuals.length, + receiptCount: verified.receiptBytes.size, + blobCount: verified.blobByteLengths.size, + }); } diff --git a/packages/evolution/src/store.ts b/packages/evolution/src/store.ts index f05e4b08..1ece13b4 100644 --- a/packages/evolution/src/store.ts +++ b/packages/evolution/src/store.ts @@ -11,6 +11,7 @@ import type { HardwareProvenance, StructuredFinding, } from '@loopwright/core'; +import { sortTeamConfigsTopologically } from './bundle-fs.js'; import { canonicalizeJson, parseArtifactRefsJson, @@ -650,23 +651,23 @@ export class EvolutionCampaignStore { } } // Stores created before campaign snapshots have no provenance table; add it idempotently. - const tableRows = db - .prepare("SELECT name FROM pragma_table_list WHERE schema = 'main' AND name = 'snapshot_provenance';") - .all() as SqlRow[]; - if (tableRows.length === 0) { - db.exec('BEGIN IMMEDIATE;'); - try { - db.exec(`CREATE TABLE snapshot_provenance ( + db.exec('BEGIN IMMEDIATE;'); + try { + const tableRows = db + .prepare("SELECT name FROM pragma_table_list WHERE schema = 'main' AND name = 'snapshot_provenance';") + .all() as SqlRow[]; + if (tableRows.length === 0) { + db.exec(`CREATE TABLE IF NOT EXISTS snapshot_provenance ( campaign_id TEXT PRIMARY KEY, snapshot_digest_hex TEXT NOT NULL, imported_wall_ms INTEGER NOT NULL CHECK (imported_wall_ms >= 0), FOREIGN KEY (campaign_id) REFERENCES campaigns(campaign_id) ON DELETE RESTRICT ) STRICT;`); - db.exec('COMMIT;'); - } catch (err) { - if (db.isTransaction) db.exec('ROLLBACK;'); - throw err; } + db.exec('COMMIT;'); + } catch (err) { + if (db.isTransaction) db.exec('ROLLBACK;'); + throw err; } } @@ -2173,20 +2174,24 @@ export class EvolutionCampaignStore { assertDriverConstraint(campaign.driverConstraint, '/driverConstraint'); const manifest = parseEvolutionCampaignDocument(campaign.manifest); - const teamConfigRows = [...input.teamConfigs] - .sort((a, b) => a.createdGeneration - b.createdGeneration || (a.teamConfigId < b.teamConfigId ? -1 : 1)) - .map(tc => { - assertSafeId(tc.teamConfigId, 'teamConfigId'); - if (tc.parentTeamConfigId !== null) assertSafeId(tc.parentTeamConfigId, 'parentTeamConfigId'); - if (tc.patchCasDigest !== null) assertDigest(tc.patchCasDigest, 'patchCasDigest'); - const diagnosisJson = tc.diagnosis === null - ? null - : canonicalizeJson(parseTeamDiagnosisValue( - sanitizeUntrustedValue(tc.diagnosis, { maxBytes: 4_096, path: '/diagnosis' }), - '/diagnosis', - )); - return { tc, diagnosisJson }; - }); + for (const tc of input.teamConfigs) { + assertSafeId(tc.teamConfigId, 'teamConfigId'); + if (tc.parentTeamConfigId !== null) assertSafeId(tc.parentTeamConfigId, 'parentTeamConfigId'); + if (tc.patchCasDigest !== null) assertDigest(tc.patchCasDigest, 'patchCasDigest'); + } + const teamConfigRows = sortTeamConfigsTopologically( + input.teamConfigs, + 'EVOLUTION_SCHEMA_INVALID', + '/teamConfigs', + ).map(tc => { + const diagnosisJson = tc.diagnosis === null + ? null + : canonicalizeJson(parseTeamDiagnosisValue( + sanitizeUntrustedValue(tc.diagnosis, { maxBytes: 4_096, path: '/diagnosis' }), + '/diagnosis', + )); + return { tc, diagnosisJson }; + }); const individualRows = [...input.individuals] .sort((a, b) => a.generation - b.generation || (a.individualId < b.individualId ? -1 : 1)) diff --git a/packages/evolution/test/snapshot.test.ts b/packages/evolution/test/snapshot.test.ts index 65f9534a..54116684 100644 --- a/packages/evolution/test/snapshot.test.ts +++ b/packages/evolution/test/snapshot.test.ts @@ -1,12 +1,13 @@ import assert from 'node:assert/strict'; import { createHash } from 'node:crypto'; -import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; -import { join } from 'node:path'; +import { dirname, join } from 'node:path'; import { DatabaseSync } from 'node:sqlite'; import test from 'node:test'; import { API_VERSION, + SecretScrubber, validateDocument, type BucketMetricEntry, type Digest, @@ -514,8 +515,42 @@ function readJsonlMember(bundleDir: string, relPath: string): readonly Record JSON.parse(line) as Record); } +function rewriteManifestMember( + bundleDir: string, + relPath: string, + content: Buffer | string, + mediaType?: string, +): void { + const bytes = typeof content === 'string' ? Buffer.from(content, 'utf8') : content; + const fullPath = join(bundleDir, relPath); + mkdirSync(dirname(fullPath), { recursive: true }); + writeFileSync(fullPath, bytes); + const manifestPath = join(bundleDir, 'manifest.json'); + const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as { + members: Array<{ path: string; digest: Digest; byteLength: number; mediaType?: string }>; + }; + const nextEntry = { + path: relPath, + digest: { algorithm: 'sha256' as const, hex: sha256Hex(bytes) }, + byteLength: bytes.byteLength, + ...(mediaType !== undefined ? { mediaType } : {}), + }; + const existingIdx = manifest.members.findIndex(m => m.path === relPath); + if (existingIdx >= 0) { + manifest.members[existingIdx] = { + ...manifest.members[existingIdx]!, + digest: nextEntry.digest, + byteLength: nextEntry.byteLength, + }; + } else { + manifest.members.push(nextEntry); + manifest.members.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0)); + } + writeFileSync(manifestPath, JSON.stringify(manifest)); +} + // --------------------------------------------------------------------------- -// isolation: optional HardwareProvenance field (landed first; T11 produces it) +// isolation: optional HardwareProvenance field // --------------------------------------------------------------------------- test('isolation: parseHardwareProvenanceJson accepts the optional key, both values, and refuses others', () => { @@ -791,9 +826,6 @@ test('snapshot: export, verify, import on a lower-clock host, and continue the c assert.deepEqual(bundle.exportedIndividualIds, ['ind-win-1', 'ind-win-2']); // Continue the campaign under a new lease: no EVOLUTION_CLOCK_DRIFT. - // shortcut: continuation is proven at store level plus a bundle export from the restored CAS; the - // real `evolve run` continuation needs a repository and taskpack and is asserted by T10's CLI test. - // Revisit here only if the store-level proof stops covering a path `evolve run` depends on. const lease = await resumed.acquireLease('resume-owner'); assert.equal(lease.fenceEpoch, 2); await resumed.recordIndividual(lease, { @@ -1054,3 +1086,700 @@ test('snapshot: import refuses a non-empty state directory without touching it a rmSync(tempDir, { recursive: true, force: true }); } }); + +test('snapshot: SecretScrubber rejects secrets on export, verify, and import across scratchpads and textual blobs', async () => { + const tempDir = mkdtempSync(join(tmpdir(), 'evo-snapshot-secrets-')); + try { + const customSecret = 'my-snapshot-custom-secret-value-998877'; + const customScrubber = new SecretScrubber(); + customScrubber.register(customSecret); + + // 1. Secret in scratchpad markdown is refused on writeCampaignSnapshot + const scratchpadRoot = join(tempDir, 'camp-scratchpad-secret'); + const seededScratchpad = await seedSnapshotCampaign(scratchpadRoot, { clock: makeSteppingClock(HIGH_MONO_MS) }); + try { + const lease = await seededScratchpad.store.acquireLease('secret-scratchpad-owner'); + const leakBytes = Buffer.from('# Scratchpad\nleaked token ghp_1234567890abcdefghijklmnopqrstuvwxyz\n', 'utf8'); + const leakCas = await seededScratchpad.store.writeCasBlob(leakBytes); + await seededScratchpad.store.recordScratchpadSnapshot(lease, { + snapshotId: 'snap-leak', + campaignId: seededScratchpad.campaignId, + generation: 2, + casDigest: leakCas.digest, + byteLength: leakCas.byteLength, + casRelPath: leakCas.casRelPath, + topGainsCount: 0, + failurePatternsCount: 1, + }); + await seededScratchpad.store.releaseLease(lease); + + const outLeak = join(tempDir, 'out-scratchpad-leak'); + await assertEvolutionErrorAsync( + () => writeCampaignSnapshot({ + store: seededScratchpad.store, + campaignId: seededScratchpad.campaignId, + outDir: outLeak, + receiptSigningSecret: TEST_HMAC_SECRET, + }), + 'SECRET_LEAK_DETECTED', + ); + assert.equal(existsSync(outLeak), false); + } finally { + await seededScratchpad.store.close(); + } + + // 2. Secret in codeSliceCasDigest blob is refused on writeCampaignSnapshot + const codeRoot = join(tempDir, 'camp-code-secret'); + const seededCode = await seedSnapshotCampaign(codeRoot, { clock: makeSteppingClock(HIGH_MONO_MS) }); + try { + const lease = await seededCode.store.acquireLease('secret-code-owner'); + const leakCode = await seededCode.store.writeCasBlob(`// token=${customSecret}\n`); + await seededCode.store.recordIndividual(lease, { + individualId: 'ind-code-leak', + campaignId: seededCode.campaignId, + islandId: 0, + generation: 2, + bucketId: null, + teamConfigId: seededCode.source.islands[0]!.activeTeamConfigId, + modelId: 'model-a', + trackId: 'cute', + mutationKind: 'diff_tune', + status: 'failed', + failureReason: 'RUN_FAILED', + nicheKey: null, + paretoRank: null, + crowdingDistance: null, + scalarFitness: null, + codeSliceCasDigest: leakCode.digest, + evidenceDigest: null, + verdictReceiptCasDigest: null, + outputArtifacts: [], + metrics: {}, + }); + await seededCode.store.releaseLease(lease); + + // Default scrubber allows the custom token to export so we can also test verify/import refusal with customScrubber + const outWithCustom = join(tempDir, 'snapshot-with-custom'); + await writeCampaignSnapshot({ + store: seededCode.store, + campaignId: seededCode.campaignId, + outDir: outWithCustom, + receiptSigningSecret: TEST_HMAC_SECRET, + }); + + // Export with customScrubber refuses the textual code blob + await assertEvolutionErrorAsync( + () => writeCampaignSnapshot({ + store: seededCode.store, + campaignId: seededCode.campaignId, + outDir: join(tempDir, 'out-code-leak'), + receiptSigningSecret: TEST_HMAC_SECRET, + scrubber: customScrubber, + }), + 'SECRET_LEAK_DETECTED', + ); + + // Verify & import with customScrubber refuse the textual code blob + await assertEvolutionErrorAsync( + () => verifyCampaignSnapshot({ + bundleDir: outWithCustom, + receiptSigningSecret: TEST_HMAC_SECRET, + scrubber: customScrubber, + }), + 'SECRET_LEAK_DETECTED', + ); + await assertEvolutionErrorAsync( + () => importCampaignSnapshot({ + bundleDir: outWithCustom, + stateDir: join(tempDir, 'state-code-leak'), + receiptSigningSecret: TEST_HMAC_SECRET, + scrubber: customScrubber, + clock: makeSteppingClock(LOW_MONO_MS), + }), + 'SECRET_LEAK_DETECTED', + ); + assert.equal(existsSync(join(tempDir, 'state-code-leak')), false); + } finally { + await seededCode.store.close(); + } + + // 3. Secret injected into scratchpad/*.md in a snapshot bundle is refused on verify/import + const cleanRoot = join(tempDir, 'camp-clean-for-tamper'); + const clean = await seedSnapshotCampaign(cleanRoot, { clock: makeSteppingClock(HIGH_MONO_MS) }); + const bundleDir = join(tempDir, 'snapshot-clean'); + try { + await writeCampaignSnapshot({ + store: clean.store, + campaignId: clean.campaignId, + outDir: bundleDir, + receiptSigningSecret: TEST_HMAC_SECRET, + }); + } finally { + await clean.store.close(); + } + + const leakScratchBytes = Buffer.from('# Tampered\nghp_1234567890abcdefghijklmnopqrstuvwxyz\n', 'utf8'); + const leakScratchHex = sha256Hex(leakScratchBytes); + const oldScratchPath = `scratchpad/${clean.scratchpadDigest.hex}.md`; + const newScratchPath = `scratchpad/${leakScratchHex}.md`; + unlinkSync(join(bundleDir, oldScratchPath)); + const scratchIndex = readJsonlMember(bundleDir, 'scratchpad.jsonl').map(row => ({ + ...row, + casDigest: { algorithm: 'sha256', hex: leakScratchHex }, + byteLength: leakScratchBytes.byteLength, + })); + const manifestObj = JSON.parse(readFileSync(join(bundleDir, 'manifest.json'), 'utf8')) as { + members: Array<{ path: string; digest: Digest; byteLength: number; mediaType?: string }>; + }; + manifestObj.members = manifestObj.members.filter(m => m.path !== oldScratchPath); + writeFileSync(join(bundleDir, 'manifest.json'), JSON.stringify(manifestObj)); + rewriteManifestMember(bundleDir, newScratchPath, leakScratchBytes, 'text/markdown'); + rewriteManifestMember(bundleDir, 'scratchpad.jsonl', `${scratchIndex.map(r => JSON.stringify(r)).join('\n')}\n`); + + await assertEvolutionErrorAsync( + () => verifyCampaignSnapshot({ bundleDir, receiptSigningSecret: TEST_HMAC_SECRET }), + 'SECRET_LEAK_DETECTED', + ); + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } +}); + +test('snapshot: >512 manifest members and negative scalarFitness round-trip export, verify, and import', async () => { + const tempDir = mkdtempSync(join(tmpdir(), 'evo-snapshot-scale-negfit-')); + try { + const campaignRoot = join(tempDir, 'campaign'); + const store = await EvolutionCampaignStore.open({ campaignRoot, clock: makeSteppingClock(HIGH_MONO_MS) }); + const campaignId = 'camp-scale-1'; + const outDir = join(tempDir, 'snapshot'); + try { + const lease = await store.acquireLease('scale-owner'); + const bigYaml = SINGLE_TARGET_CAMPAIGN_YAML.replace('maxEvaluations: 40', 'maxEvaluations: 600'); + const manifest = parseEvolutionCampaignDocument(bigYaml); + await store.createCampaign(lease, { + campaignId, + manifest, + manifestDigest: makeDigest(bigYaml), + baseRevision: 'c'.repeat(40), + lockHash: makeDigest('lock-scale-1'), + modelIds: ['model-a'], + }); + const islands = await store.listIslands(campaignId); + const team0 = islands[0]!.activeTeamConfigId; + + // Record 520 individuals with distinct code slices -> 527 manifest members (>512), including negative scalarFitness + for (let i = 0; i < 520; i++) { + const codeCas = await store.writeCasBlob(`// candidate ${i}\n`); + await store.recordIndividual(lease, { + individualId: `ind-${String(i).padStart(4, '0')}`, + campaignId, + islandId: 0, + generation: Math.floor(i / 100), + bucketId: null, + teamConfigId: team0, + modelId: 'model-a', + trackId: 'cute', + mutationKind: i === 0 ? 'baseline' : 'diff_tune', + status: 'passed', + failureReason: null, + nicheKey: 'bound_pipeline=hbm', + paretoRank: 1, + crowdingDistance: i === 0 ? Number.POSITIVE_INFINITY : 0.25, + scalarFitness: i === 0 ? -42.5 : -0.5 * (i + 1), + codeSliceCasDigest: codeCas.digest, + evidenceDigest: null, + verdictReceiptCasDigest: null, + outputArtifacts: [], + metrics: { latency_us_p50: 40 + i, goodput_rps: 2000 }, + }); + } + await store.releaseLease(lease); + + const written = await writeCampaignSnapshot({ store, campaignId, outDir }); + assert.equal(written.individualCount, 520); + assert.equal(written.blobCount, 520); + + const verified = await verifyCampaignSnapshot({ bundleDir: outDir }); + assert.ok(verified.manifest.members.length >= 527); + assert.equal(verified.manifestDigest.hex, written.manifestDigest.hex); + } finally { + await store.close(); + } + + const stateDir = join(tempDir, 'state'); + const importClock = makeSteppingClock(LOW_MONO_MS); + const imported = await importCampaignSnapshot({ + bundleDir: outDir, + stateDir, + clock: importClock, + }); + assert.equal(imported.individualCount, 520); + assert.equal(imported.blobCount, 520); + + const resumed = await EvolutionCampaignStore.open({ campaignRoot: stateDir, createIfMissing: false, clock: importClock }); + try { + const ind0 = await resumed.getIndividual('ind-0000'); + assert.equal(ind0?.scalarFitness, -42.5); + const ind519 = await resumed.getIndividual('ind-0519'); + assert.equal(ind519?.scalarFitness, -260); + } finally { + await resumed.close(); + } + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } +}); + +test('snapshot: rejects tampered individual metrics, unreceipted hardwareProvenance, and unreferenced manifest members', async () => { + const tempDir = mkdtempSync(join(tmpdir(), 'evo-snapshot-binding-')); + try { + const campaignRoot = join(tempDir, 'campaign'); + const seeded = await seedSnapshotCampaign(campaignRoot, { clock: makeSteppingClock(HIGH_MONO_MS) }); + const cleanBundle = join(tempDir, 'snapshot-clean'); + try { + await writeCampaignSnapshot({ + store: seeded.store, + campaignId: seeded.campaignId, + outDir: cleanBundle, + receiptSigningSecret: TEST_HMAC_SECRET, + }); + } finally { + await seeded.store.close(); + } + + // 1. Tampered metrics on receipt-bearing individual with updated manifest digest is rejected + const tamperMetricsDir = join(tempDir, 'tamper-metrics'); + cpSync(cleanBundle, tamperMetricsDir, { recursive: true }); + const rows1 = readJsonlMember(tamperMetricsDir, 'individuals.jsonl').map(r => + r['individualId'] === 'ind-win-1' + ? { ...r, metrics: { latency_us_p50: 1.0, goodput_rps: 999_999 } } + : r, + ); + rewriteManifestMember(tamperMetricsDir, 'individuals.jsonl', `${rows1.map(r => JSON.stringify(r)).join('\n')}\n`); + await assertEvolutionErrorAsync( + () => verifyCampaignSnapshot({ bundleDir: tamperMetricsDir, receiptSigningSecret: TEST_HMAC_SECRET }), + 'ARTIFACT_INVALID', + ); + + // 2. Non-passed status on receipt-bearing individual with updated manifest digest is rejected + const tamperStatusDir = join(tempDir, 'tamper-status'); + cpSync(cleanBundle, tamperStatusDir, { recursive: true }); + const rowsStatus = readJsonlMember(tamperStatusDir, 'individuals.jsonl').map(r => + r['individualId'] === 'ind-win-1' + ? { ...r, status: 'failed' } + : r, + ); + rewriteManifestMember(tamperStatusDir, 'individuals.jsonl', `${rowsStatus.map(r => JSON.stringify(r)).join('\n')}\n`); + await assertEvolutionErrorAsync( + () => verifyCampaignSnapshot({ bundleDir: tamperStatusDir, receiptSigningSecret: TEST_HMAC_SECRET }), + 'ARTIFACT_INVALID', + ); + + // 3. Unreceipted individual (receipt: null) declaring hardwareProvenance is rejected + const smuggleProvDir = join(tempDir, 'smuggle-provenance'); + cpSync(cleanBundle, smuggleProvDir, { recursive: true }); + const rows2 = readJsonlMember(smuggleProvDir, 'individuals.jsonl').map(r => + r['individualId'] === 'ind-fail-1' + ? { ...r, hardwareProvenance: makeProvenance({ probeKind: 'synthetic_fixture', isolation: 'host_attested' }) } + : r, + ); + rewriteManifestMember(smuggleProvDir, 'individuals.jsonl', `${rows2.map(r => JSON.stringify(r)).join('\n')}\n`); + await assertEvolutionErrorAsync( + () => verifyCampaignSnapshot({ bundleDir: smuggleProvDir, receiptSigningSecret: TEST_HMAC_SECRET }), + 'ARTIFACT_INVALID', + ); + + // 4. Unreferenced blob listed in manifest.json is rejected + const unrefBlobDir = join(tempDir, 'unref-blob'); + cpSync(cleanBundle, unrefBlobDir, { recursive: true }); + const rogueBlob = Buffer.from('rogue-unreferenced-payload\n', 'utf8'); + rewriteManifestMember(unrefBlobDir, `blobs/sha256/${sha256Hex(rogueBlob)}`, rogueBlob, 'application/octet-stream'); + await assertEvolutionErrorAsync( + () => verifyCampaignSnapshot({ bundleDir: unrefBlobDir, receiptSigningSecret: TEST_HMAC_SECRET }), + 'ARTIFACT_INVALID', + ); + + // 5. Unreferenced receipt listed in manifest.json is rejected + const unrefReceiptDir = join(tempDir, 'unref-receipt'); + cpSync(cleanBundle, unrefReceiptDir, { recursive: true }); + rewriteManifestMember(unrefReceiptDir, 'receipts/ind-rogue.verdict.json', '{"status":"denied"}\n', 'application/vnd.loopwright.benchmark-verdict.v1+json'); + await assertEvolutionErrorAsync( + () => verifyCampaignSnapshot({ bundleDir: unrefReceiptDir, receiptSigningSecret: TEST_HMAC_SECRET }), + 'ARTIFACT_INVALID', + ); + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } +}); + +test('snapshot: topological team_configs import handles out-of-order same-generation child IDs and rejects parent cycles', async () => { + const tempDir = mkdtempSync(join(tmpdir(), 'evo-snapshot-team-topo-')); + try { + const campaignRoot = join(tempDir, 'campaign'); + const seeded = await seedSnapshotCampaign(campaignRoot, { clock: makeSteppingClock(HIGH_MONO_MS) }); + const bundleDir = join(tempDir, 'snapshot'); + try { + const lease = await seeded.store.acquireLease('topo-owner'); + const baseTeam0 = seeded.source.islands[0]!.activeTeamConfigId; + // Same generation (gen 2), where child ID ('team-alpha-child') sorts alphabetically BEFORE parent ID ('team-zeta-parent') + await seeded.store.createTrialTeamConfig(lease, { + teamConfigId: 'team-zeta-parent', + campaignId: seeded.campaignId, + islandId: 0, + parentTeamConfigId: baseTeam0, + createdGeneration: 2, + trialBudgetGenerations: 2, + diagnosis: { summary: 'parent team', plateauCategory: 'other', rationale: 'parent rationale' }, + patchCasDigest: seeded.patchDigest, + }); + await seeded.store.createTrialTeamConfig(lease, { + teamConfigId: 'team-alpha-child', + campaignId: seeded.campaignId, + islandId: 0, + parentTeamConfigId: 'team-zeta-parent', + createdGeneration: 2, + trialBudgetGenerations: 2, + diagnosis: { summary: 'child team', plateauCategory: 'other', rationale: 'child rationale' }, + patchCasDigest: seeded.patchDigest, + }); + await seeded.store.releaseLease(lease); + + await writeCampaignSnapshot({ + store: seeded.store, + campaignId: seeded.campaignId, + outDir: bundleDir, + receiptSigningSecret: TEST_HMAC_SECRET, + }); + } finally { + await seeded.store.close(); + } + + // Export -> verify -> import succeeds despite child ID < parent ID in the same generation + const stateDir = join(tempDir, 'state-ok'); + const importClock = makeSteppingClock(LOW_MONO_MS); + const imported = await importCampaignSnapshot({ + bundleDir, + stateDir, + receiptSigningSecret: TEST_HMAC_SECRET, + clock: importClock, + }); + assert.equal(imported.campaignId, seeded.campaignId); + const resumed = await EvolutionCampaignStore.open({ campaignRoot: stateDir, createIfMissing: false, clock: importClock }); + try { + const teams = await resumed.listTeamConfigs(seeded.campaignId); + assert.equal(teams.find(t => t.teamConfigId === 'team-alpha-child')?.parentTeamConfigId, 'team-zeta-parent'); + } finally { + await resumed.close(); + } + + // Parent cycle in team_configs.jsonl is rejected on verifyCampaignSnapshot + const cycleDir = join(tempDir, 'snapshot-cycle'); + cpSync(bundleDir, cycleDir, { recursive: true }); + const cyclicRows = readJsonlMember(cycleDir, 'team_configs.jsonl').map(r => + r['teamConfigId'] === 'team-zeta-parent' + ? { ...r, parentTeamConfigId: 'team-alpha-child' } + : r, + ); + rewriteManifestMember(cycleDir, 'team_configs.jsonl', `${cyclicRows.map(r => JSON.stringify(r)).join('\n')}\n`); + await assertEvolutionErrorAsync( + () => verifyCampaignSnapshot({ bundleDir: cycleDir, receiptSigningSecret: TEST_HMAC_SECRET }), + 'ARTIFACT_INVALID', + ); + + // Direct store.importCampaignState also rejects a parent cycle with EVOLUTION_SCHEMA_INVALID + const directRoot = join(tempDir, 'direct-cycle-store'); + const directStore = await EvolutionCampaignStore.open({ campaignRoot: directRoot, clock: makeSteppingClock(LOW_MONO_MS) }); + try { + const lease = await directStore.acquireLease('direct-cycle'); + const manifest = parseEvolutionCampaignDocument(SINGLE_TARGET_CAMPAIGN_YAML); + await assertEvolutionErrorAsync( + () => directStore.importCampaignState(lease, { + campaign: { + campaignId: 'camp-cycle', + name: manifest.metadata.name, + status: 'paused', + stagePhase: 'single-target', + activeBucketId: null, + manifest, + manifestDigest: makeDigest(SINGLE_TARGET_CAMPAIGN_YAML), + baseRevision: 'a'.repeat(40), + lockHash: makeDigest('lock-cycle'), + driverConstraint: null, + currentGeneration: 0, + evaluationsUsed: 0, + preemptionsCount: 0, + }, + islands: [], + teamConfigs: [ + { + teamConfigId: 'team-a', + campaignId: 'camp-cycle', + islandId: 0, + parentTeamConfigId: 'team-b', + createdGeneration: 0, + status: 'trial', + trialBudgetGenerations: 2, + trialUsedGenerations: 0, + diagnosis: null, + patchCasDigest: null, + paretoAdvances: 0, + nicheDiscoveries: 0, + }, + { + teamConfigId: 'team-b', + campaignId: 'camp-cycle', + islandId: 0, + parentTeamConfigId: 'team-a', + createdGeneration: 0, + status: 'trial', + trialBudgetGenerations: 2, + trialUsedGenerations: 0, + diagnosis: null, + patchCasDigest: null, + paretoAdvances: 0, + nicheDiscoveries: 0, + }, + ], + individuals: [], + lineageEdges: [], + modelBanditArms: [], + scratchpadSnapshots: [], + snapshotDigest: makeDigest('snap-cycle'), + }), + 'EVOLUTION_SCHEMA_INVALID', + ); + await directStore.releaseLease(lease); + } finally { + await directStore.close(); + } + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } +}); + +test('snapshot & bundle: host_attested refusal/opt-in across snapshot APIs and mixed isolation refusal in bundle export', async () => { + const tempDir = mkdtempSync(join(tmpdir(), 'evo-snapshot-host-attested-')); + try { + const attestedRoot = join(tempDir, 'camp-attested'); + const attested = await seedSnapshotCampaign(attestedRoot, { + clock: makeSteppingClock(HIGH_MONO_MS), + winReceipt: individualId => ({ operationId: `op-${individualId}`, isolation: 'host_attested' }), + }); + const outDir = join(tempDir, 'snapshot-attested'); + try { + await assertEvolutionErrorAsync( + () => writeCampaignSnapshot({ + store: attested.store, + campaignId: attested.campaignId, + outDir, + receiptSigningSecret: TEST_HMAC_SECRET, + }), + 'EXPORT_UNVERIFIED_FORBIDDEN', + ); + assert.equal(existsSync(outDir), false); + + const written = await writeCampaignSnapshot({ + store: attested.store, + campaignId: attested.campaignId, + outDir, + allowHostAttested: true, + receiptSigningSecret: TEST_HMAC_SECRET, + }); + assert.equal(written.receiptCount, 2); + + await assertEvolutionErrorAsync( + () => verifyCampaignSnapshot({ bundleDir: outDir, receiptSigningSecret: TEST_HMAC_SECRET }), + 'EXPORT_UNVERIFIED_FORBIDDEN', + ); + const verified = await verifyCampaignSnapshot({ + bundleDir: outDir, + allowHostAttested: true, + receiptSigningSecret: TEST_HMAC_SECRET, + }); + assert.equal(verified.receiptCount, 2); + + await assertEvolutionErrorAsync( + () => importCampaignSnapshot({ + bundleDir: outDir, + stateDir: join(tempDir, 'state-refused'), + receiptSigningSecret: TEST_HMAC_SECRET, + clock: makeSteppingClock(LOW_MONO_MS), + }), + 'EXPORT_UNVERIFIED_FORBIDDEN', + ); + assert.equal(existsSync(join(tempDir, 'state-refused')), false); + + const imported = await importCampaignSnapshot({ + bundleDir: outDir, + stateDir: join(tempDir, 'state-allowed'), + allowHostAttested: true, + receiptSigningSecret: TEST_HMAC_SECRET, + clock: makeSteppingClock(LOW_MONO_MS), + }); + assert.equal(imported.receiptCount, 2); + } finally { + await attested.store.close(); + } + + // Mixing docker and host_attested receipts in a single bundle export is refused + const mixedRoot = join(tempDir, 'camp-mixed-isolation'); + const mixed = await seedSnapshotCampaign(mixedRoot, { + clock: makeSteppingClock(HIGH_MONO_MS), + winReceipt: individualId => ({ + operationId: `op-${individualId}`, + isolation: individualId === 'ind-win-1' ? 'docker' : 'host_attested', + }), + }); + try { + await assertEvolutionErrorAsync( + () => exportEvolutionBundle({ + store: mixed.store, + campaignId: mixed.campaignId, + outputDir: join(tempDir, 'bundle-mixed'), + allowHostAttested: true, + receiptSigningSecret: TEST_HMAC_SECRET, + }), + 'ARTIFACT_INVALID', + ); + } finally { + await mixed.store.close(); + } + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } +}); + +test('snapshot: symlink refusal on outDir, bundleDir, stateDir, and snapshot members', async () => { + const tempDir = mkdtempSync(join(tmpdir(), 'evo-snapshot-symlink-')); + try { + const campaignRoot = join(tempDir, 'campaign'); + const seeded = await seedSnapshotCampaign(campaignRoot, { clock: makeSteppingClock(HIGH_MONO_MS) }); + const bundleDir = join(tempDir, 'snapshot-real'); + try { + const realOut = join(tempDir, 'real-out'); + mkdirSync(realOut); + const outLink = join(tempDir, 'out-link'); + symlinkSync(realOut, outLink); + await assertEvolutionErrorAsync( + () => writeCampaignSnapshot({ + store: seeded.store, + campaignId: seeded.campaignId, + outDir: outLink, + receiptSigningSecret: TEST_HMAC_SECRET, + }), + 'EVOLUTION_SYMLINK_FORBIDDEN', + ); + + await writeCampaignSnapshot({ + store: seeded.store, + campaignId: seeded.campaignId, + outDir: bundleDir, + receiptSigningSecret: TEST_HMAC_SECRET, + }); + } finally { + await seeded.store.close(); + } + + const bundleLink = join(tempDir, 'bundle-link'); + symlinkSync(bundleDir, bundleLink); + await assertEvolutionErrorAsync( + () => verifyCampaignSnapshot({ bundleDir: bundleLink, receiptSigningSecret: TEST_HMAC_SECRET }), + 'EVOLUTION_SYMLINK_FORBIDDEN', + ); + + const realState = join(tempDir, 'real-state'); + mkdirSync(realState); + const stateLink = join(tempDir, 'state-link'); + symlinkSync(realState, stateLink); + await assertEvolutionErrorAsync( + () => importCampaignSnapshot({ + bundleDir, + stateDir: stateLink, + receiptSigningSecret: TEST_HMAC_SECRET, + clock: makeSteppingClock(LOW_MONO_MS), + }), + 'EVOLUTION_SYMLINK_FORBIDDEN', + ); + + // Symlinked snapshot member (manifest.json and campaign.json) + const memberSymlinkDir = join(tempDir, 'snapshot-member-symlink'); + cpSync(bundleDir, memberSymlinkDir, { recursive: true }); + const outsideCampaign = join(tempDir, 'outside-campaign.json'); + writeFileSync(outsideCampaign, readFileSync(join(memberSymlinkDir, 'campaign.json'))); + unlinkSync(join(memberSymlinkDir, 'campaign.json')); + symlinkSync(outsideCampaign, join(memberSymlinkDir, 'campaign.json')); + await assertEvolutionErrorAsync( + () => verifyCampaignSnapshot({ bundleDir: memberSymlinkDir, receiptSigningSecret: TEST_HMAC_SECRET }), + 'EVOLUTION_SYMLINK_FORBIDDEN', + ); + + const manifestSymlinkDir = join(tempDir, 'snapshot-manifest-symlink'); + cpSync(bundleDir, manifestSymlinkDir, { recursive: true }); + const outsideManifest = join(tempDir, 'outside-manifest.json'); + writeFileSync(outsideManifest, readFileSync(join(manifestSymlinkDir, 'manifest.json'))); + unlinkSync(join(manifestSymlinkDir, 'manifest.json')); + symlinkSync(outsideManifest, join(manifestSymlinkDir, 'manifest.json')); + await assertEvolutionErrorAsync( + () => verifyCampaignSnapshot({ bundleDir: manifestSymlinkDir, receiptSigningSecret: TEST_HMAC_SECRET }), + 'EVOLUTION_SYMLINK_FORBIDDEN', + ); + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } +}); + +test('snapshot: prototype-pollution keys and forbidden modelId labels are rejected in snapshot JSON and JSONL', async () => { + const tempDir = mkdtempSync(join(tmpdir(), 'evo-snapshot-proto-')); + try { + const campaignRoot = join(tempDir, 'campaign'); + const seeded = await seedSnapshotCampaign(campaignRoot, { clock: makeSteppingClock(HIGH_MONO_MS) }); + const cleanBundle = join(tempDir, 'snapshot-clean'); + try { + await writeCampaignSnapshot({ + store: seeded.store, + campaignId: seeded.campaignId, + outDir: cleanBundle, + receiptSigningSecret: TEST_HMAC_SECRET, + }); + } finally { + await seeded.store.close(); + } + + for (const badKey of ['__proto__', 'constructor', 'prototype']) { + // 1. Forbidden key in manifest.json + const badManifestDir = join(tempDir, `proto-manifest-${badKey}`); + cpSync(cleanBundle, badManifestDir, { recursive: true }); + const rawManifest = readFileSync(join(badManifestDir, 'manifest.json'), 'utf8'); + const pollutedManifest = `{"${badKey}":{"polluted":true},${rawManifest.slice(1)}`; + writeFileSync(join(badManifestDir, 'manifest.json'), pollutedManifest); + await assertEvolutionErrorAsync( + () => verifyCampaignSnapshot({ bundleDir: badManifestDir, receiptSigningSecret: TEST_HMAC_SECRET }), + 'ARTIFACT_INVALID', + ); + + // 2. Forbidden key in individuals.jsonl + const badIndDir = join(tempDir, `proto-ind-${badKey}`); + cpSync(cleanBundle, badIndDir, { recursive: true }); + const rawLines = readFileSync(join(badIndDir, 'individuals.jsonl'), 'utf8').split('\n').filter(Boolean); + rawLines[0] = `{"${badKey}":1,${rawLines[0]!.slice(1)}`; + rewriteManifestMember(badIndDir, 'individuals.jsonl', `${rawLines.join('\n')}\n`); + await assertEvolutionErrorAsync( + () => verifyCampaignSnapshot({ bundleDir: badIndDir, receiptSigningSecret: TEST_HMAC_SECRET }), + 'ARTIFACT_INVALID', + ); + } + + // 3. Forbidden prototype key as bandit.json modelId + const badBanditDir = join(tempDir, 'proto-bandit-model'); + cpSync(cleanBundle, badBanditDir, { recursive: true }); + const arms = JSON.parse(readFileSync(join(badBanditDir, 'bandit.json'), 'utf8')) as Array>; + arms[0] = { ...arms[0]!, modelId: '__proto__' }; + rewriteManifestMember(badBanditDir, 'bandit.json', JSON.stringify(arms)); + await assertEvolutionErrorAsync( + () => verifyCampaignSnapshot({ bundleDir: badBanditDir, receiptSigningSecret: TEST_HMAC_SECRET }), + 'ARTIFACT_INVALID', + ); + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } +}); From 5b6b21146a8b49e55fb0b8226656dabcd255a56f Mon Sep 17 00:00:00 2001 From: thxCode Date: Tue, 1 Dec 2026 18:28:35 +0800 Subject: [PATCH 15/26] test(hardware-runner): track sanitized probe evidence and refine namespace diagnostics Relocate sanitized probe JSONL transcripts into tracked fixture evidence under packages/hardware-runner/test/fixtures/bwrap-namespace-probe/evidence/, remove agent scratch paths and internal task tags from tracked files, replace the nonexistent /sys/kernel/security/landlock/abi sysfs read with unprobed, fix the SECCOMP_RET_ERRNO | EPERM comment, and align the Ubuntu 6.8+ AppArmor unprivileged_userns differential notes. Signed-off-by: thxCode --- .../test/bwrap-namespace-probe.test.ts | 37 ++++++++++++------- .../evidence/diag-a-seccomp-unconfined.jsonl | 13 +++++++ .../diag-b-seccomp-apparmor-unconfined.jsonl | 13 +++++++ .../evidence/restricted-probe-output.jsonl | 13 +++++++ .../fixtures/bwrap-namespace-probe/pod.yaml | 16 ++++---- .../fixtures/bwrap-namespace-probe/probe.sh | 26 ++++++++----- 6 files changed, 86 insertions(+), 32 deletions(-) create mode 100644 packages/hardware-runner/test/fixtures/bwrap-namespace-probe/evidence/diag-a-seccomp-unconfined.jsonl create mode 100644 packages/hardware-runner/test/fixtures/bwrap-namespace-probe/evidence/diag-b-seccomp-apparmor-unconfined.jsonl create mode 100644 packages/hardware-runner/test/fixtures/bwrap-namespace-probe/evidence/restricted-probe-output.jsonl diff --git a/packages/hardware-runner/test/bwrap-namespace-probe.test.ts b/packages/hardware-runner/test/bwrap-namespace-probe.test.ts index bac43c9f..48f29200 100644 --- a/packages/hardware-runner/test/bwrap-namespace-probe.test.ts +++ b/packages/hardware-runner/test/bwrap-namespace-probe.test.ts @@ -3,13 +3,13 @@ import assert from 'node:assert/strict'; import { spawnSync } from 'node:child_process'; import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; -import { join } from 'node:path'; +import { basename, join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { parseYamlDocument } from '@loopwright/taskpack'; import { compileStrictSocketDenySeccompBpf } from '../src/evaluator.js'; /** - * T11 feasibility probe for `native_os` under `deviceOwnership: host`. The fixture is the + * Feasibility probe for `native_os` under `deviceOwnership: host`. The fixture is the * deliverable: probe.sh (JSON lines) and pod.yaml (the target Pod profile). This file proves the * probe's own fidelity, holds the measured cluster outcome, and runs the probe locally on Linux * hosts that have bubblewrap as local evidence only. The cluster run is the qualification. @@ -58,13 +58,13 @@ export const RECORDED_PROBE_OUTCOME: Readonly<{ verdict: 'namespaces_blocked', measuredAt: '2026-12-01', environment: Object.freeze({ - cluster: 'kind v0.33.0 cluster lw-t11-probe on a developer Linux host (not the production GPU node)', + cluster: 'kind v0.33.0 cluster lw-bwrap-probe on a developer Linux host (not the production GPU node)', hostKernel: '6.17.0-23-generic (Ubuntu-family sysctls: kernel.unprivileged_userns_clone=1, kernel.apparmor_restrict_unprivileged_userns=1)', kubernetes: 'v1.37.0', containerRuntime: 'containerd 2.3.4 (kind node image Debian 13)', - podSecurityAdmission: 'namespace lw-t11-probe enforces pod-security.kubernetes.io/enforce=restricted (+audit, +warn, version latest); pod.yaml admitted unchanged', + podSecurityAdmission: 'namespace lw-bwrap-probe enforces pod-security.kubernetes.io/enforce=restricted (+audit, +warn, version latest); pod.yaml admitted unchanged', pod: 'phase Succeeded, probe exit 0, 13 JSON lines', - containerContext: 'uid/gid 65532, x86_64, CapEff=0 CapBnd=0, NoNewPrivs=1, Seccomp=2 (1 filter), apparmor_profile=unconfined, user.max_user_namespaces=124231, landlock abi absent, bwrap 0.8.0 via the apt bootstrap', + containerContext: 'uid/gid 65532, x86_64, CapEff=0 CapBnd=0, NoNewPrivs=1, Seccomp=2 (1 filter), apparmor_profile=unconfined, user.max_user_namespaces=124231, landlock abi unprobed (sysfs path does not exist; syscall not probed), bwrap 0.8.0 via the apt bootstrap', }), firstFailingAttempt: Object.freeze({ attempt: 'negotiate-probe', @@ -77,15 +77,15 @@ export const RECORDED_PROBE_OUTCOME: Readonly<{ ]), differential: Object.freeze([ 'Variant A, same manifest with seccompProfile Unconfined (pod + container) in a namespace without PodSecurity enforcement: namespace creation proceeds; bwrap then fails at "loopback: Failed RTM_NEWADDR: Operation not permitted" (negotiate-probe and every seccomp/stage attempt, EPERM) and "setting up uid map: Permission denied" (unshare-all-share-net and userns-mount-proc-dev, EACCES); summary still namespaces_blocked.', - 'Variant B, A plus container appArmorProfile.type Unconfined: identical to A, so the host AppArmor unprivileged-userns restriction is not what blocks the restricted run.', - 'The restricted namespace refused variant A (PodSecurity restricted:latest forbids seccompProfile.type Unconfined), so a restricted Pod cannot relax seccomp.', - 'Conclusion: RuntimeDefault seccomp is the first barrier; without it the drop-ALL bounding set (CapBnd=0, inherited into any user namespace the process creates) still stops bwrap at uid mapping. native_os cannot run under the restricted profile; stage 2 (deviceOwnership, relay block, runner inline, isolation producer) is not implemented.', + 'Variant B, A plus container appArmorProfile.type Unconfined: identical to A. On Ubuntu 6.8+ with kernel.apparmor_restrict_unprivileged_userns=1, unconfined processes creating a user namespace are restricted by the host unprivileged_userns AppArmor transition, so Variant B remained identical to Variant A.', + 'The restricted namespace refused variant A (PodSecurity restricted:latest forbids seccompProfile.type Unconfined), so a restricted Pod cannot relax seccomp to Unconfined (though PSA restricted permits a node-installed Localhost seccomp profile if evaluated on a bare-metal GPU node in the future).', + 'Conclusion: RuntimeDefault seccomp is the PSA restricted-enforced barrier that blocks clone(CLONE_NEWUSER); even when seccomp is relaxed, the host unprivileged_userns AppArmor transition on Ubuntu 6.8+ still blocks bwrap user-namespace setup. native_os cannot run under the restricted profile; stage 2 (deviceOwnership, relay block, runner inline, isolation producer) is not implemented.', ]), caveat: 'Measured on a kind cluster on a developer Linux host; the production GPU node was not measured.', evidence: Object.freeze([ - '.claude/handoffs/2026-11-30-t11-probe-output.jsonl', - '.claude/handoffs/2026-11-30-t11-probe-diag-a-seccomp-unconfined.jsonl', - '.claude/handoffs/2026-11-30-t11-probe-diag-b-seccomp-apparmor-unconfined.jsonl', + 'packages/hardware-runner/test/fixtures/bwrap-namespace-probe/evidence/restricted-probe-output.jsonl', + 'packages/hardware-runner/test/fixtures/bwrap-namespace-probe/evidence/diag-a-seccomp-unconfined.jsonl', + 'packages/hardware-runner/test/fixtures/bwrap-namespace-probe/evidence/diag-b-seccomp-apparmor-unconfined.jsonl', ]), }); @@ -149,7 +149,7 @@ test('probe fixture: pod.yaml applies the target profile and nothing that would volumes: readonly Record[]; }; }; - assert.equal(pod.metadata.name, 't11-bwrap-probe'); + assert.equal(pod.metadata.name, 'bwrap-namespace-probe'); assert.equal(pod.metadata.labels['pod-security.kubernetes.io/enforce'], 'restricted'); const spec = pod.spec; assert.equal(spec.automountServiceAccountToken, false); @@ -198,7 +198,7 @@ test('probe fixture: without an executable bwrap the probe records bwrap_unavail test('probe fixture: the recorded cluster outcome is consistent with the probe vocabulary and complete', t => { if (RECORDED_PROBE_OUTCOME.status === 'pending') { - t.diagnostic('T11 probe not yet run in the target cluster: RECORDED_PROBE_OUTCOME.status is pending'); + t.diagnostic('bwrap-namespace-probe not yet run in the target cluster: RECORDED_PROBE_OUTCOME.status is pending'); assert.equal(RECORDED_PROBE_OUTCOME.verdict, undefined); return; } @@ -207,6 +207,15 @@ test('probe fixture: the recorded cluster outcome is consistent with the probe v assert.match(measuredAt ?? '', /^\d{4}-\d{2}-\d{2}$/); assert.ok(environment && Object.keys(environment).length > 0, 'the measurement environment must be recorded'); assert.ok(evidence && evidence.length > 0, 'the evidence files must be named'); + for (const evidencePath of evidence) { + const resolvedPath = join(PROBE_DIR, 'evidence', basename(evidencePath)); + assert.ok(existsSync(resolvedPath), `missing recorded evidence file: ${evidencePath}`); + const parsedLines = readFileSync(resolvedPath, 'utf8') + .split('\n') + .filter(line => line.length > 0) + .map(line => JSON.parse(line) as ProbeAttemptLine); + assert.equal(verdictOf(summaryOf(parsedLines)), verdict, `${evidencePath} must match recorded verdict`); + } if (verdict === 'namespaces_ok') { assert.equal(firstFailingAttempt, undefined); return; @@ -220,7 +229,7 @@ test('probe fixture: the recorded cluster outcome is consistent with the probe v assert.ok(differential?.length && differential.length > 0, 'the seccomp-versus-appArmor differential must be recorded'); assert.ok(caveat?.includes('not measured'), 'the caveat must say what was not measured'); } - t.diagnostic(`T11 probe verdict=${verdict} at ${firstFailingAttempt.attempt} (${firstFailingAttempt.errno}): ${firstFailingAttempt.message}`); + t.diagnostic(`bwrap-namespace-probe verdict=${verdict} at ${firstFailingAttempt.attempt} (${firstFailingAttempt.errno}): ${firstFailingAttempt.message}`); }); test('probe fixture: local Linux run with bubblewrap is local evidence only (cluster run is the qualification)', { diff --git a/packages/hardware-runner/test/fixtures/bwrap-namespace-probe/evidence/diag-a-seccomp-unconfined.jsonl b/packages/hardware-runner/test/fixtures/bwrap-namespace-probe/evidence/diag-a-seccomp-unconfined.jsonl new file mode 100644 index 00000000..f3fdd70b --- /dev/null +++ b/packages/hardware-runner/test/fixtures/bwrap-namespace-probe/evidence/diag-a-seccomp-unconfined.jsonl @@ -0,0 +1,13 @@ +{"attempt":"context","ok":true,"uid":65532,"gid":65532,"arch":"x86_64","kernel":"6.17.0-23-generic","bwrap_arch":"x64","cap_eff":"0000000000000000","cap_bnd":"0000000000000000","no_new_privs":"1","seccomp":"0","seccomp_filters":"0","userns_max":"124231","unprivileged_userns_clone":"1","apparmor_restrict_userns":"1","apparmor_profile":"unconfined","lsm":"na","selinuxfs":"absent","landlock_abi":"na","bwrap":"pending","bwrap_version":"pending"} +{"attempt":"bootstrap","ok":true,"exit":0,"errno":"-","message":"fetched bubblewrap and libcap2 into the emptyDir (user-space copy; the controller image must ship a root-owned /usr/bin/bwrap)"} +{"attempt":"bwrap-found","ok":true,"exit":0,"errno":"-","message":"path=/probe-out/root/usr/bin/bwrap version=bubblewrap 0.8.0"} +{"attempt":"negotiate-probe","ok":false,"exit":1,"errno":"EPERM","message":"bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted"} +{"attempt":"unshare-all-share-net","ok":false,"exit":1,"errno":"EACCES","message":"bwrap: setting up uid map: Permission denied"} +{"attempt":"userns-mount-proc-dev","ok":false,"exit":1,"errno":"EACCES","message":"bwrap: setting up uid map: Permission denied"} +{"attempt":"seccomp-fd3-allowall","ok":false,"exit":1,"errno":"EPERM","message":"bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted"} +{"attempt":"seccomp-fd3-strict","ok":false,"exit":1,"errno":"EPERM","message":"bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted"} +{"attempt":"stage-a-exact-shape","ok":false,"exit":1,"errno":"EPERM","message":"bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted"} +{"attempt":"stage-b-exact-shape","ok":false,"exit":1,"errno":"EPERM","message":"bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted"} +{"attempt":"stage-a-host-checks","ok":false,"exit":1,"errno":"EINVAL","message":"stage-a-out bind did not persist the write, or the candidate tree changed"} +{"attempt":"stage-b-host-checks","ok":false,"exit":1,"errno":"EINVAL","message":"Stage B wrote into stage-a-out or the workload snapshot changed"} +{"attempt":"summary","ok":false,"exit":0,"errno":"-","message":"verdict=namespaces_blocked feature=stop"} diff --git a/packages/hardware-runner/test/fixtures/bwrap-namespace-probe/evidence/diag-b-seccomp-apparmor-unconfined.jsonl b/packages/hardware-runner/test/fixtures/bwrap-namespace-probe/evidence/diag-b-seccomp-apparmor-unconfined.jsonl new file mode 100644 index 00000000..f3fdd70b --- /dev/null +++ b/packages/hardware-runner/test/fixtures/bwrap-namespace-probe/evidence/diag-b-seccomp-apparmor-unconfined.jsonl @@ -0,0 +1,13 @@ +{"attempt":"context","ok":true,"uid":65532,"gid":65532,"arch":"x86_64","kernel":"6.17.0-23-generic","bwrap_arch":"x64","cap_eff":"0000000000000000","cap_bnd":"0000000000000000","no_new_privs":"1","seccomp":"0","seccomp_filters":"0","userns_max":"124231","unprivileged_userns_clone":"1","apparmor_restrict_userns":"1","apparmor_profile":"unconfined","lsm":"na","selinuxfs":"absent","landlock_abi":"na","bwrap":"pending","bwrap_version":"pending"} +{"attempt":"bootstrap","ok":true,"exit":0,"errno":"-","message":"fetched bubblewrap and libcap2 into the emptyDir (user-space copy; the controller image must ship a root-owned /usr/bin/bwrap)"} +{"attempt":"bwrap-found","ok":true,"exit":0,"errno":"-","message":"path=/probe-out/root/usr/bin/bwrap version=bubblewrap 0.8.0"} +{"attempt":"negotiate-probe","ok":false,"exit":1,"errno":"EPERM","message":"bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted"} +{"attempt":"unshare-all-share-net","ok":false,"exit":1,"errno":"EACCES","message":"bwrap: setting up uid map: Permission denied"} +{"attempt":"userns-mount-proc-dev","ok":false,"exit":1,"errno":"EACCES","message":"bwrap: setting up uid map: Permission denied"} +{"attempt":"seccomp-fd3-allowall","ok":false,"exit":1,"errno":"EPERM","message":"bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted"} +{"attempt":"seccomp-fd3-strict","ok":false,"exit":1,"errno":"EPERM","message":"bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted"} +{"attempt":"stage-a-exact-shape","ok":false,"exit":1,"errno":"EPERM","message":"bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted"} +{"attempt":"stage-b-exact-shape","ok":false,"exit":1,"errno":"EPERM","message":"bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted"} +{"attempt":"stage-a-host-checks","ok":false,"exit":1,"errno":"EINVAL","message":"stage-a-out bind did not persist the write, or the candidate tree changed"} +{"attempt":"stage-b-host-checks","ok":false,"exit":1,"errno":"EINVAL","message":"Stage B wrote into stage-a-out or the workload snapshot changed"} +{"attempt":"summary","ok":false,"exit":0,"errno":"-","message":"verdict=namespaces_blocked feature=stop"} diff --git a/packages/hardware-runner/test/fixtures/bwrap-namespace-probe/evidence/restricted-probe-output.jsonl b/packages/hardware-runner/test/fixtures/bwrap-namespace-probe/evidence/restricted-probe-output.jsonl new file mode 100644 index 00000000..d6369daf --- /dev/null +++ b/packages/hardware-runner/test/fixtures/bwrap-namespace-probe/evidence/restricted-probe-output.jsonl @@ -0,0 +1,13 @@ +{"attempt":"context","ok":true,"uid":65532,"gid":65532,"arch":"x86_64","kernel":"6.17.0-23-generic","bwrap_arch":"x64","cap_eff":"0000000000000000","cap_bnd":"0000000000000000","no_new_privs":"1","seccomp":"2","seccomp_filters":"1","userns_max":"124231","unprivileged_userns_clone":"1","apparmor_restrict_userns":"1","apparmor_profile":"unconfined","lsm":"na","selinuxfs":"absent","landlock_abi":"na","bwrap":"pending","bwrap_version":"pending"} +{"attempt":"bootstrap","ok":true,"exit":0,"errno":"-","message":"fetched bubblewrap and libcap2 into the emptyDir (user-space copy; the controller image must ship a root-owned /usr/bin/bwrap)"} +{"attempt":"bwrap-found","ok":true,"exit":0,"errno":"-","message":"path=/probe-out/root/usr/bin/bwrap version=bubblewrap 0.8.0"} +{"attempt":"negotiate-probe","ok":false,"exit":1,"errno":"EPERM","message":"bwrap: No permissions to create new namespace, likely because the kernel does not allow non-privileged user namespaces. See or ."} +{"attempt":"unshare-all-share-net","ok":false,"exit":1,"errno":"EPERM","message":"bwrap: No permissions to create new namespace, likely because the kernel does not allow non-privileged user namespaces. See or ."} +{"attempt":"userns-mount-proc-dev","ok":false,"exit":1,"errno":"EPERM","message":"bwrap: No permissions to create new namespace, likely because the kernel does not allow non-privileged user namespaces. See or ."} +{"attempt":"seccomp-fd3-allowall","ok":false,"exit":1,"errno":"EPERM","message":"bwrap: No permissions to create new namespace, likely because the kernel does not allow non-privileged user namespaces. See or ."} +{"attempt":"seccomp-fd3-strict","ok":false,"exit":1,"errno":"EPERM","message":"bwrap: No permissions to create new namespace, likely because the kernel does not allow non-privileged user namespaces. See or ."} +{"attempt":"stage-a-exact-shape","ok":false,"exit":1,"errno":"EPERM","message":"bwrap: No permissions to create new namespace, likely because the kernel does not allow non-privileged user namespaces. See or ."} +{"attempt":"stage-b-exact-shape","ok":false,"exit":1,"errno":"EPERM","message":"bwrap: No permissions to create new namespace, likely because the kernel does not allow non-privileged user namespaces. See or ."} +{"attempt":"stage-a-host-checks","ok":false,"exit":1,"errno":"EINVAL","message":"stage-a-out bind did not persist the write, or the candidate tree changed"} +{"attempt":"stage-b-host-checks","ok":false,"exit":1,"errno":"EINVAL","message":"Stage B wrote into stage-a-out or the workload snapshot changed"} +{"attempt":"summary","ok":false,"exit":0,"errno":"-","message":"verdict=namespaces_blocked feature=stop"} diff --git a/packages/hardware-runner/test/fixtures/bwrap-namespace-probe/pod.yaml b/packages/hardware-runner/test/fixtures/bwrap-namespace-probe/pod.yaml index 6d38bae8..eee18e4f 100644 --- a/packages/hardware-runner/test/fixtures/bwrap-namespace-probe/pod.yaml +++ b/packages/hardware-runner/test/fixtures/bwrap-namespace-probe/pod.yaml @@ -1,4 +1,4 @@ -# T11 feasibility probe Pod: runs probe.sh under the TARGET profile, exactly. +# bwrap-namespace-probe Pod: runs probe.sh under the TARGET profile, exactly. # # Profile (the F5 "host profile" from the spec Notes): non-root, ALL capabilities dropped, # allowPrivilegeEscalation: false, RuntimeDefault seccomp, no service account token, no host paths @@ -12,13 +12,13 @@ # The script comes from a ConfigMap created with --from-file so it is not duplicated here: # # NS= -# kubectl -n "$NS" create configmap t11-bwrap-probe-script \ +# kubectl -n "$NS" create configmap bwrap-namespace-probe-script \ # --from-file=probe.sh=packages/hardware-runner/test/fixtures/bwrap-namespace-probe/probe.sh \ # --dry-run=client -o yaml | kubectl apply -f - # kubectl -n "$NS" apply -f packages/hardware-runner/test/fixtures/bwrap-namespace-probe/pod.yaml -# kubectl -n "$NS" wait --for=jsonpath='{.status.phase}'=Succeeded pod/t11-bwrap-probe --timeout=15m \ -# || kubectl -n "$NS" wait --for=jsonpath='{.status.phase}'=Failed pod/t11-bwrap-probe --timeout=15m -# kubectl -n "$NS" logs pod/t11-bwrap-probe > t11-bwrap-probe.jsonl +# kubectl -n "$NS" wait --for=jsonpath='{.status.phase}'=Succeeded pod/bwrap-namespace-probe --timeout=15m \ +# || kubectl -n "$NS" wait --for=jsonpath='{.status.phase}'=Failed pod/bwrap-namespace-probe --timeout=15m +# kubectl -n "$NS" logs pod/bwrap-namespace-probe > bwrap-namespace-probe.jsonl # # The image ships no bubblewrap, so probe.sh fetches a user-space copy of bubblewrap and libcap2 # into /probe-out with apt-get download (non-root, redirected apt state). That needs egress to @@ -29,9 +29,9 @@ apiVersion: v1 kind: Pod metadata: - name: t11-bwrap-probe + name: bwrap-namespace-probe labels: - app.kubernetes.io/name: t11-bwrap-probe + app.kubernetes.io/name: bwrap-namespace-probe pod-security.kubernetes.io/enforce: restricted pod-security.kubernetes.io/enforce-version: latest pod-security.kubernetes.io/audit: restricted @@ -86,7 +86,7 @@ spec: volumes: - name: script configMap: - name: t11-bwrap-probe-script + name: bwrap-namespace-probe-script defaultMode: 0555 - name: out emptyDir: {} diff --git a/packages/hardware-runner/test/fixtures/bwrap-namespace-probe/probe.sh b/packages/hardware-runner/test/fixtures/bwrap-namespace-probe/probe.sh index 6515a3ba..efca3ac4 100755 --- a/packages/hardware-runner/test/fixtures/bwrap-namespace-probe/probe.sh +++ b/packages/hardware-runner/test/fixtures/bwrap-namespace-probe/probe.sh @@ -1,5 +1,5 @@ #!/bin/sh -# bwrap-namespace-probe: feasibility probe for T11 / F5 (`native_os` under `deviceOwnership: host`). +# bwrap-namespace-probe: feasibility probe for `native_os` under `deviceOwnership: host`. # # What it measures: whether bubblewrap can create the user, pid, mount, and network namespaces, # mount --proc / --dev, bind --ro-bind / --bind paths, chdir, and install the Stage B socket-denial @@ -30,11 +30,16 @@ # with this file as evidence. # Measured (a kind cluster on a developer Linux host, not a GPU node): under # this profile every attempt fails with EPERM before any namespace exists. -# RuntimeDefault seccomp is the first barrier; with seccomp Unconfined the -# drop-ALL bounding set (CapBnd=0, inherited into any user namespace the -# process creates) still stops bwrap (uid map EACCES, RTM_NEWADDR EPERM), and -# relaxing the host AppArmor userns rule changes nothing. A restricted Pod -# cannot relax seccomp (PodSecurity refuses type Unconfined). +# RuntimeDefault seccomp is the PSA restricted-enforced barrier that blocks +# clone(CLONE_NEWUSER) with EPERM before any namespace exists. With seccomp +# Unconfined, namespace creation proceeds, and on Ubuntu 6.8+ with +# kernel.apparmor_restrict_unprivileged_userns=1, unconfined processes +# creating a user namespace are restricted by the host's unprivileged_userns +# AppArmor transition (so Variant B with appArmorProfile.type: Unconfined +# remained identical to Variant A: uid map EACCES, RTM_NEWADDR EPERM). A +# restricted Pod cannot relax seccomp to Unconfined (PodSecurity refuses it), +# though PSA restricted permits a node-installed Localhost seccomp profile if +# evaluated on a bare-metal GPU node in the future. # netns_blocked User and mount namespaces work but --unshare-net fails. buildStrictLinuxBwrapArgs # always emits --unshare-all, so the feature is blocked unless the lead accepts # a --share-net variant (a design change: seccomp socket denial would become @@ -56,9 +61,9 @@ # attempt "negotiate-probe" runs exactly that command. The bootstrap below fetches a user-space # copy into the emptyDir so the probe measures the kernel, not the image; the controller image # must still ship a root-owned /usr/bin/bwrap. -# - The strict filter returns SECCOMP_RET_KILL_PROCESS, so a socket() call inside the sandbox is -# expected to kill the calling process with SIGSYS ("Bad system call"), not to fail with EPERM. -# Both observations count as "socket denied"; ENETUNREACH or ECONNREFUSED do not. +# - The strict filter returns SECCOMP_RET_ERRNO | EPERM (0x00050001), so a socket() call inside +# the sandbox is expected to fail with EPERM ("Operation not permitted"), not ENETUNREACH or +# ECONNREFUSED. (SIGSYS / "Bad system call" would also count as socket denied if a filter killed.) # - bwrap always creates a mount namespace; "userns-mount-proc-dev" is therefore the smallest # namespace set it can attempt. set -u @@ -217,6 +222,7 @@ bootstrap_apt() { # user-space bubblewrap + libcap2 into the emptyDir (needs egr ARCH="$(uname -m)"; KERNEL="$(uname -r)" BWRAP_ARCH="" case "$ARCH" in x86_64) BWRAP_ARCH=x64 ;; aarch64|arm64) BWRAP_ARCH=arm64 ;; esac +# Landlock ABI is queried via landlock_create_ruleset(NULL, 0, LANDLOCK_CREATE_RULESET_VERSION) syscall, not sysfs. printf '{"attempt":"context","ok":true,"uid":%s,"gid":%s,"arch":"%s","kernel":"%s","bwrap_arch":"%s","cap_eff":"%s","cap_bnd":"%s","no_new_privs":"%s","seccomp":"%s","seccomp_filters":"%s","userns_max":"%s","unprivileged_userns_clone":"%s","apparmor_restrict_userns":"%s","apparmor_profile":"%s","lsm":"%s","selinuxfs":"%s","landlock_abi":"%s","bwrap":"%s","bwrap_version":"%s"}\n' \ "$(id -u)" "$(id -g)" "$ARCH" "$KERNEL" "$BWRAP_ARCH" \ "$(status_field CapEff)" "$(status_field CapBnd)" "$(status_field NoNewPrivs)" \ @@ -227,7 +233,7 @@ printf '{"attempt":"context","ok":true,"uid":%s,"gid":%s,"arch":"%s","kernel":"% "$(read_or_na /proc/self/attr/current)" \ "$(read_or_na /sys/kernel/security/lsm)" \ "$([ -d /sys/fs/selinux ] && echo present || echo absent)" \ - "$(read_or_na /sys/kernel/security/landlock/abi)" \ + "unprobed" \ "pending" "pending" | tee -a "$LOG" # ---------------------------------------------------------------- bwrap From bc3b09038ffc67df1e95a7cfd0d720f4832b3006 Mon Sep 17 00:00:00 2001 From: thxCode Date: Tue, 1 Dec 2026 18:28:35 +0800 Subject: [PATCH 16/26] docs(specs): align pre-T6 fixes, T7 usage ledger, and operator/forgevo boundaries Update specs/2026-11-30-managed-controller-in-process-execution.md with the pre-T6 design review findings and confirmed gpustack-operator <-> loopwright <-> forgevo alignment: - Clarify exec.env literal values, 3,600,000 ms exec.timeoutMs ceiling, same-UID trust boundary, T6 DAG/recovery/cleanup requirements, and T7 usage aggregation from settled exec-outcome artifacts without mutating frozen LocalRunStore.requests. - Align F4/T10 snapshot continuation on evolve resume with optional --receipt-secret-env when no individual carries a signed receipt, and correct T11 Landlock/AppArmor diagnostic wording. - Record the three-layer boundary and explicitly deferred/rejected items in Alternatives (decoupled snapshot manifests, single-archive packing in forgevo, F5 blocked_external under PSA restricted, and evolve CLI composition boundary). Signed-off-by: thxCode --- ...managed-controller-in-process-execution.md | 101 ++++++++++++++---- 1 file changed, 78 insertions(+), 23 deletions(-) diff --git a/specs/2026-11-30-managed-controller-in-process-execution.md b/specs/2026-11-30-managed-controller-in-process-execution.md index 165a6661..ca86a0da 100644 --- a/specs/2026-11-30-managed-controller-in-process-execution.md +++ b/specs/2026-11-30-managed-controller-in-process-execution.md @@ -185,8 +185,10 @@ controller's own environment on a host whose isolation the registry attests. { command, args?, env?, credentialRefs?, timeoutMs, captureBytes? }`. `context` is not required and not read for `exec` roles. `command` is 1..64 entries; `command[0]` is an absolute path without NUL, newline, or a trailing slash, and no entry starts with `-` unless it is an - argument after `command[0]`. `env` holds non-secret values; `${NAME}` templates resolve - through `environmentBindings` as today. + argument after `command[0]`. `env` holds literal non-secret string values (the digest-pinned + `TrustedRegistry` is never template-interpolated; dynamic or secret values flow through + `credentialRefs` with `consumer: exec`). `timeoutMs` is bounded `1..3600000` so every dispatch + fits inside the `3_700_000 ms` state dispatch permit ceiling and 32-bit timer limit. - **Credentials.** `credentialBindings[]` gains `consumer: exec`. For a bound credential, the child receives one variable per name in `environmentNames`, each set to the resolved template value; the names in the template and in the child are the same. Values resolve in memory @@ -215,11 +217,20 @@ controller's own environment on a host whose isolation the registry attests. synthesizes it today ([step.ts](../packages/controller/src/step.ts)); `completeCapture` never parses the child's free text, and no `exec` step enters format repair. - Exit `0` is `completed`. Exit `3` is `blocked` with the last non-empty stderr line as the - reason. Any other exit is `failed`. A run past `timeoutMs` is `failed` with reason - `exec_timeout` and the process group killed. + reason (halting the DAG so downstream required checks, `onRework`, and implementation repair + do not run or overwrite `blocked` into `failed`). Any other exit is `failed` (pruning + downstream agent steps). A run past `timeoutMs` is `failed` with reason + `exec_timeout` and the process group killed. On normal exit, the controller still kills and + confirms the process group gone before overlay capture so no background grandchild mutates + `candidateDir`. - After the exit, the controller writes the proof marker and captures the overlay through the - `adoptRoleCapture` path that `step submit` uses: `scope.v1`, overlay limits, symlink and - hard-link refusal, protected-path invariance. + same `scanCandidateDirectory` -> `captureDelegatedRole` -> `completeCapture` path that + `step submit` uses: `scope.v1`, overlay limits, symlink and hard-link refusal, protected-path + invariance. +- **Same-UID trust boundary.** Like `command.v1` under `direct`, an `exec` command runs under the + controller's own user ID inside an already isolated host (a restricted Pod with network policy, + such as `forgevo`). Do not pair an `exec` command that executes untrusted model-generated shell + commands with unrelated host secrets or publication tokens in the same UID. - **Unknown outcomes.** The child's model calls are invisible to the store, so a re-dispatch would repeat an uncertain external effect. On recovery, an `exec` operation without a proof marker is settled as unknown: the run requires recovery (`RECOVERY_REQUIRED`), the recorded @@ -228,23 +239,30 @@ controller's own environment on a host whose isolation the registry attests. - **Compilation.** [compile.ts](../packages/controller/src/compile.ts) branches on `exec`: no runtime profile, no provider credential, no `context` guard; `PlannedRole.policy` for an `exec` role is `{ tools: the declared tools, mcp: empty, limits: profile.limits or the role - defaults }`; the credential set must equal the vault references named by `credentialRefs`. + defaults }`; the credential set must equal the vault references named by `credentialRefs`; + steps with `purpose: 'review'` are refused (`CONFIG_SCHEMA`). [budget-observations.ts](../packages/controller/src/budget-observations.ts) counts an `exec` dispatch as one model call; [recovery.ts](../packages/controller/src/recovery.ts) handles `exec` nodes as this section says. - **Admission.** `run` and `resume` admit plans whose agent roles are all `exec`. A plan that mixes `exec` with `pi` or `delegated` roles fails admission (`CONFIG_SCHEMA`), and `step next` - refuses `exec` plans. Consequence: in a Pod without Docker, no reviewer step exists in this - version; the measured check is the reviewer. + refuses `exec` plans (`CAPABILITY_UNSUPPORTED`). Consequence: in a Pod without Docker, no + reviewer step exists in this version; the measured check is the reviewer. - **Budgets and usage.** `wallTime`, `modelCalls` (one per dispatch), and `concurrency` enforce as hard admission; admission is per dispatch and happens before the spawn. `check` refuses an `exec` `timeoutMs` that cannot fit between `controls.drainReserveMs` and `budgets.wallTimeMs`, the same rule as `command.v1` `timeoutMs`. Provider calls made inside one dispatch are the command's responsibility. Optional usage file: the controller sets `LOOPWRIGHT_USAGE_OUT` to a - path inside the attempt scratch directory; if the command wrote that file, the controller reads - `{ requests: [{ requestId, inputTokens, outputTokens, costMicrousd }] }` (bounded, scrubbed) - into the usage ledger with `provenance: 'reported'`; without the file, usage records - `provenance: 'unknown'`, never zero ([usage.ts](../packages/core/src/usage.ts)). + path inside the attempt scratch directory; if the command wrote that file (`usageReported: true`), + the controller reads `{ requests: [{ requestId, inputTokens, outputTokens, costMicrousd }] }` + (bounded up to `LIMITS.requests`, scrubbed, namespaced per attempt as `:` + to prevent cross-rework collisions) into settled `exec-outcome` artifacts with + `provenance: 'reported'`; without the file (`usageReported: false`), usage records + `provenance: 'unknown'`, never zero ([usage.ts](../packages/core/src/usage.ts)). Because + `@loopwright/state` is frozen and treats any `provenance: 'unknown'` entry in + `LocalRunStore.requests` as `unresolvedRequests` (`reconcile_required`), `exec` usage records + are aggregated from settled `exec-outcome` artifacts in `acceptance.ts` and `inspect.ts` rather + than inserted into `LocalRunStore.requests`. - Acceptance: - `loopwright check` accepts an `exec` profile and refuses a missing `exec` block, a non-null `runtimeRef`, a relative `command[0]`, a `credentialRefs` entry whose binding is @@ -306,10 +324,13 @@ controller's own environment on a host whose isolation the registry attests. individuals, lineage, islands, bandit arms, scratchpad, and team configs copied verbatim, and the snapshot digest recorded in a new `snapshot_provenance` table. Clock and fence columns are never copied. A tampered member or receipt fails the import. -- Acceptance: export, import, and `evolve run` continue the campaign on a host whose monotonic +- Acceptance: export, import, and `evolve resume` continue the campaign on a host whose monotonic clock is lower than the exporter's, with the Pareto archive, lineage, and bandit state intact and no `EVOLUTION_CLOCK_DRIFT`; a snapshot with failed or preempted individuals imports with - their status and `receipt: null`; a tampered receipt fails. + their status and `receipt: null`; a tampered receipt or tampered `individuals.jsonl` metric + fails. Note: `loopwright evolve` CLI currently drives Taskpack + Pi; consumers running Managed + Controller `exec` + `command.v1` invoke `loopwright run` or the `@loopwright/controller` + + `@loopwright/evolution` library APIs directly. #### F5. In-process `benchmark-gate.v1` (phase 2, feasibility first) @@ -566,14 +587,14 @@ and T11 have disjoint `Owns:` and start together; T5 follows T2. Verify: `node scripts/run-tests.mjs --pkg controller` - [ ] **T6 · `exec` controller integration** Blocked by: T4, T5 - Owns: `packages/controller/src/controller.ts`, `packages/controller/src/compile.ts`, `packages/controller/src/step.ts`, `packages/controller/src/credentials.ts`, `packages/controller/src/budget-observations.ts`, `packages/controller/src/recovery.ts`, `packages/controller/src/capture.ts`, `packages/controller/test/delegated-compile.test.ts`, `packages/controller/test/exec-role-integration.test.ts`, `packages/controller/test/recovery-owner.test.ts` + Owns: `packages/controller/src/controller.ts`, `packages/controller/src/compile.ts`, `packages/controller/src/step.ts`, `packages/controller/src/credentials.ts`, `packages/controller/src/budget-observations.ts`, `packages/controller/src/recovery.ts`, `packages/controller/src/capture.ts`, `packages/controller/src/retained.ts`, `packages/controller/test/delegated-compile.test.ts`, `packages/controller/test/exec-role-integration.test.ts`, `packages/controller/test/recovery-owner.test.ts` Gate: review - Acceptance: compile branches on `exec` (no runtime profile, provider credential, or context guard; the F2 `policy`; credentials equal the named refs); `role()` records the intent and binding marker, takes the task prompt from the bound `pi.agent.v1` handler, sets `LOOPWRIGHT_USAGE_OUT` to a path inside the attempt scratch directory, runs the T5 runner, synthesizes the submission as `step submit` does, captures through `adoptRoleCapture`, and never enters format repair; recovery settles an `exec` operation without a proof marker as `RECOVERY_REQUIRED`, kills the recorded group, and discards the attempt directory; `run` and `resume` admit all-`exec` plans and refuse mixes with `pi` or `delegated`; `step next` refuses `exec` plans; `consumer: exec` bindings resolve through the vault. Tests: in-scope write settles `completed` with the file exported; out-of-scope write fails `scope.v1`; exit `3` settles `blocked`; free-text stdout never repairs; a mid-exec kill resumes as `RECOVERY_REQUIRED` without re-dispatch; a bound credential appears in no `inspect` output. + Acceptance: compile branches on `exec` (no runtime profile, provider credential, or context guard; the F2 `policy`; credentials equal the named refs; refuses `purpose: 'review'`); `role()` records the intent (`effect: 'local_write'`) and binding marker, takes the task prompt from the bound `pi.agent.v1` handler, sets `LOOPWRIGHT_USAGE_OUT` to a path inside the attempt scratch directory, runs the T5 runner, synthesizes the submission as `step submit` does, captures through `scanCandidateDirectory -> captureDelegatedRole -> completeCapture`, and never enters format repair; exit `3` halts the DAG (no downstream checks or rework) and settles `blocked`; `CLEANUP_FAILED` leaves the operation `dispatch_uncertain` without releasing `holdLocalActivity()` or deleting `attemptDir`; `DEADLINE` aborts settle receipt after `store.renew` and rethrow `DEADLINE`; recovery settles an `exec` operation without a proof marker as `RECOVERY_REQUIRED`, kills the recorded group, verifies `binding.workspaceDir`, and discards the attempt directory; `run` and `resume` admit all-`exec` plans and refuse mixes with `pi` or `delegated` (`CONFIG_SCHEMA`); `step next` refuses `exec` plans (`CAPABILITY_UNSUPPORTED`); `consumer: exec` bindings resolve through the vault. Tests: in-scope write settles `completed` with the file exported; out-of-scope write fails `scope.v1`; exit `3` settles `blocked` even when a required check would fail; free-text stdout never repairs; a mid-exec kill resumes as `RECOVERY_REQUIRED` without re-dispatch; a bound credential appears in no `inspect` output. Verify: `node scripts/run-tests.mjs --pkg controller` - [ ] **T7 · `exec` budgets and usage ledger** Blocked by: T6 - Owns: `packages/controller/src/budget-observations.ts`, `packages/controller/src/controller.ts`, `packages/core/src/usage.ts`, `packages/core/test/usage.test.ts`, `packages/controller/test/exec-usage.test.ts` - Acceptance: each `exec` dispatch charges one model call under `maxModelCalls` hard admission before the spawn; the usage file named by the controller-set `LOOPWRIGHT_USAGE_OUT` lands in the ledger as request records with `provenance: 'reported'`; without it, usage records `provenance: 'unknown'`; `usage.json` exports both. + Owns: `packages/controller/src/budget-observations.ts`, `packages/controller/src/controller.ts`, `packages/controller/src/acceptance.ts`, `packages/controller/src/inspect.ts`, `packages/controller/src/run-eval.ts`, `packages/controller/src/exec-role.ts`, `packages/core/src/usage.ts`, `packages/core/test/usage.test.ts`, `packages/controller/test/exec-usage.test.ts` + Acceptance: each `exec` dispatch charges one model call under `maxModelCalls` hard admission before the spawn; settled `exec-outcome` artifacts carry reported request records (namespaced per attempt as `:`, `provenance: 'reported'`) or `usageReported: false` (`provenance: 'unknown'`) without inserting `unknown` entries into frozen `LocalRunStore.requests`; `acceptance.ts` and `inspect.ts` aggregate them into `RunResult` and `usage.json`; `run-eval.ts` classifies `exec` honestly instead of counting it as `piAttempts` with `toolTelemetry: 'available'`. Verify: `node scripts/run-tests.mjs --pkg controller && node scripts/run-tests.mjs --pkg core` - [ ] **T8 · Closure matrix, ADR, and documentation** Blocked by: T4, T6, T7 @@ -589,13 +610,13 @@ and T11 have disjoint `Owns:` and start together; T5 follows T2. - [ ] **T10 · Snapshot CLI and documentation (phase 2)** Blocked by: T8, T9 Owns: `packages/cli/src/evolve.ts`, `packages/cli/src/main.ts`, `packages/cli/src/arguments.ts`, `packages/cli/test/evolve-snapshot.test.ts`, `docs/configuration/campaign-snapshots.md`, `docs/contribute/internals.md`, `docs/operations/cli.md`, `docs/README.md`, `site/data/navigation.yaml` - Acceptance: `evolve export --snapshot`, `evolve check --bundle`, and `evolve import` exist with `--receipt-secret-env`, `--allow-synthetic-probe`, and `--allow-host-attested`, and exit codes consistent with the other `evolve` commands; `evolve-snapshot.test.ts` asserts the real `evolve run` continuation on a host with a lower monotonic clock; `docs/contribute/internals.md` lists the `snapshot_provenance` table; `docs/README.md` and the site navigation index the new page; `lint:docs` and `site` pass. + Acceptance: `evolve export --snapshot`, `evolve check --bundle`, and `evolve import` exist with `--receipt-secret-env` (optional when the snapshot contains no signed receipts, required fail-closed when any individual has a non-null receipt), `--allow-synthetic-probe`, and `--allow-host-attested`, and exit codes consistent with the other `evolve` commands; `evolve-snapshot.test.ts` asserts the real `evolve resume` continuation on a host with a lower monotonic clock; `docs/contribute/internals.md` lists the `snapshot_provenance` table; `docs/README.md` and the site navigation index the new page; `lint:docs` and `site` pass. Verify: `node scripts/run-tests.mjs --pkg cli && npm run lint:docs && npm run site` - [ ] **T11 · In-process benchmark gate, feasibility first (phase 2)** Blocked by: None Owns: `packages/hardware-runner/src/config.ts`, `packages/hardware-runner/src/worker.ts`, `packages/hardware-runner/src/evaluator.ts`, `packages/hardware-runner/src/provenance.ts`, `packages/hardware-runner/src/relay-server.ts`, `packages/hardware-runner/src/index.ts`, `packages/hardware-runner/test/**`, `packages/cli/src/main.ts`, `packages/cli/src/arguments.ts`, `packages/cli/test/runner-inline.test.ts` Gate: review - Status: blocked_external (2026-12-01). The probe ran under PSA `restricted` on kind v0.33 (Kubernetes 1.37, containerd 2.3.4, kernel 6.17) and settled `namespaces_blocked`: RuntimeDefault seccomp denies namespace creation, the drop-ALL bounding set stops bubblewrap at uid mapping even with seccomp relaxed (which `restricted` forbids), and the node has no Landlock ABI. Stage 1 is delivered (`packages/hardware-runner/test/bwrap-namespace-probe.test.ts` holds `RECORDED_PROBE_OUTCOME`); no feature code was written and the stage-2 `Owns:` widenings are void. + Status: blocked_external (2026-12-01). The probe ran under PSA `restricted` on kind v0.33 (Kubernetes 1.37, containerd 2.3.4, kernel 6.17) and settled `namespaces_blocked`: RuntimeDefault seccomp denies namespace creation (`clone(CLONE_NEWUSER)` -> `EPERM`), and even with seccomp relaxed (which PSA `restricted` forbids) the host's Ubuntu `kernel.apparmor_restrict_unprivileged_userns=1` transition kept `unconfined` processes from setting up userns uid mapping/loopback; Landlock ABI was not probed via syscall. Stage 1 is delivered (`packages/hardware-runner/test/bwrap-namespace-probe.test.ts` holds `RECORDED_PROBE_OUTCOME`); no feature code was written and the stage-2 `Owns:` widenings are void. Acceptance: first, a recorded probe decides whether `native_os` can create its namespaces under the target Pod profile (RuntimeDefault seccomp, all capabilities dropped); if it cannot, the task reports that and stops before any feature code. Then `deviceOwnership: host` permits `sandboxBackend: native_os` with `probeMode: physical`, `hardwareProvenance.isolation` (the optional T9 field) records `docker` or `host_attested`, and `loopwright runner inline --config worker.yaml` serves relay and worker in one process on loopback; a loopback end-to-end test runs `benchmark-gate.v1` through the inline runner on `synthetic_fixture`; the physical evidence row stays `blocked_external`. Verify: `node scripts/run-tests.mjs --pkg hardware-runner && node scripts/run-tests.mjs --pkg cli` - [ ] **T12 · In-process gate documentation (phase 2)** @@ -706,6 +727,39 @@ with the exact error code asserted. - **Binding controller and worker identities in-process for the inline runner, without HMAC.** Rejected: a second trust path that exists in one mode only. The relay's HMAC and bearer authentication stay unchanged. +- **Coupling `campaign-snapshot.v1` (`manifest.json`) to `gpustack-forge-snapshot/v1` (`snapshot-manifest.json`), or adding a single-file archive mode inside Loopwright.** + Rejected: Loopwright stays agnostic to Kubernetes CRDs and `gpustack-operator` ingest rules, and + `gpustack-operator` stays agnostic to Loopwright's internal schema. The thin `forgevo` adapter + packs Loopwright's `campaign-snapshot.v1` directory into a single deterministic archive + (`campaign-snapshot.tar` / `.tar.zst`) alongside a 1-entry `snapshot-manifest.json` inside + `GPUSTACK_FORGE_STATE_DIR` (keeping well below the operator's `MaxFiles = 1024` limit and + avoiding small-file Peer Sync amplification), and unpacks to `/tmp` on the next Pod before + `evolve import`. +- **Running F5 (`benchmark-gate.v1` + `sandboxBackend: native_os` / `bubblewrap` + `runner inline`) inside a PSA `restricted` Pod.** + Deferred / `blocked_external`: the recorded feasibility probe (`bwrap-namespace-probe.test.ts`) + proved `RuntimeDefault` seccomp blocks `clone(CLONE_NEWUSER)` (`EPERM`). In a `restricted` Pod + (`gpustack-operator` `ForgeSandbox`), `forgevo` closes the online forge loop through F1 + (`command.v1` under `host.localChecks.backend: direct`) and F2 (`adapter: exec`) without + `bubblewrap`, user namespaces, or a loopback relay. +- **Requiring a shared HMAC receipt secret for direct-mode campaign snapshot import.** + Rejected: when a campaign evaluates candidates via `command.v1 (direct)` rather than signed + `benchmark-gate.v1` receipts, individuals carry `receipt: null`; cross-Pod tamper resistance is + provided by the host's content-addressed read-only volume (`manifestDigest`), and `evolve + import` / `check` do not require `--receipt-secret-env` when no individual carries a non-null + receipt. +- **Driving Managed Controller `exec` + `command.v1` directly from `loopwright evolve` CLI in this spec.** + Deferred: `loopwright evolve` CLI currently drives Taskpack + Pi. In the three-layer split + (`gpustack-operator` = Pod/GPU/PSA/NetworkPolicy/independent `forge-verifier`/state persistence; + `loopwright` = Managed Controller `command.v1` + `exec` + `@loopwright/evolution` store and + `campaign-snapshot.v1`; `forgevo` = thin domain orchestrator inside the runner container), + `forgevo` composes `loopwright run` (or `@loopwright/controller`) with `@loopwright/evolution` + directly. Bridging `loopwright evolve` CLI to Managed Controller is left for a dedicated follow-up + spec if needed. +- **Writing `exec` usage records into frozen `LocalRunStore.requests`.** + Rejected: `@loopwright/state` is frozen and treats any `provenance: 'unknown'` request in + `LocalRunStore.requests` as `unresolvedRequests` (`reconcile_required`), and counts + `maxModelCalls` as `requests.length`. `exec` usage is instead aggregated from settled + `exec-outcome` artifacts in `acceptance.ts` and `inspect.ts` (T7). ## Open Questions @@ -715,8 +769,9 @@ with the exact error code asserted. on stdout as a trailing JSON line? 3. Does the inline runner (F5) need its own relay authentication, or may it bind the controller and worker identities in-process without HMAC? Resolved: unchanged HMAC and bearer, see F5. -4. Can `native_os` create its namespaces under the target Pod profile at all? T11's probe - answers this before any feature code. +4. Can `native_os` create its namespaces under the target Pod profile at all? Resolved (2026-12-01): + `namespaces_blocked` under PSA `restricted` (`RuntimeDefault` seccomp denies `clone(CLONE_NEWUSER)`); + F5 stays `blocked_external` in this version (see T11 and Alternatives). 5. Which analytics export format (Parquet or JSONL) would operators read, and is it worth a dependency on a Parquet writer? 6. Should the Taskpack reference page's `command.v1` parameter table gain the `networkMode` From c719a0a79b32b2d86590760add742b283692390e Mon Sep 17 00:00:00 2001 From: thxCode Date: Tue, 1 Dec 2026 22:35:39 +0800 Subject: [PATCH 17/26] feat(controller): integrate exec role adapter across compile, dispatch, capture, and recovery - Add exec compilation branch in compile.ts (no runtime profile, provider credential, or context guard; refuses mixed exec+pi/delegated plans and exec review/compaction steps; validates exec credentialRefs strictly against vault bindings). - Add CredentialVault.resolveExecCredential for consumer: exec bindings and include exec timeoutMs in resolveStoreLeaseMs and exec dispatches in countDelegatedBudgets. - Share synthesizedStepOutput and removeTree across step, capture, local-check, controller, and recovery; extend captureDelegatedRole and add captureExecRole for single confirmed exec local_write operations. - Implement Cycle.#execDispatch with binding/proof markers, holdLocalActivity, process-group confirmation, CLEANUP_FAILED invariants, DEADLINE vs CANCELLED mapping with pre-receipt store.renew, exit-3 blocked DAG halt (guarded by scope.v1), upstream failed pruning, and no format repair. - Refuse exec plans in stepNext/reopenStepContext (CAPABILITY_UNSUPPORTED) and settle interrupted exec operations fail-closed as exec_unknown / RECOVERY_REQUIRED in recovery.ts while discarding attempt directories. - Add compile, end-to-end integration, and crash-recovery tests (417/417 controller tests passing) and check off T6 in the spec. Signed-off-by: thxCode --- .../controller/src/budget-observations.ts | 7 +- packages/controller/src/capture.ts | 157 +++- packages/controller/src/compile.ts | 101 +- packages/controller/src/controller.ts | 633 ++++++++++++- packages/controller/src/credentials.ts | 7 + packages/controller/src/files.ts | 29 +- packages/controller/src/local-check.ts | 17 +- packages/controller/src/recovery.ts | 225 ++++- packages/controller/src/retained.ts | 7 +- packages/controller/src/step.ts | 47 +- .../controller/test/delegated-compile.test.ts | 368 +++++++- .../test/exec-role-integration.test.ts | 867 ++++++++++++++++++ .../controller/test/recovery-owner.test.ts | 366 +++++++- ...managed-controller-in-process-execution.md | 2 +- 14 files changed, 2708 insertions(+), 125 deletions(-) create mode 100644 packages/controller/test/exec-role-integration.test.ts diff --git a/packages/controller/src/budget-observations.ts b/packages/controller/src/budget-observations.ts index b8117b8c..95c7f53e 100644 --- a/packages/controller/src/budget-observations.ts +++ b/packages/controller/src/budget-observations.ts @@ -11,19 +11,20 @@ import { overlayManifestBounds } from './source.js'; import type { ByteInventory } from './verification.js'; import type { CompiledPlan, ControllerProgress } from './types.js'; +/** Counts non-Pi (`delegated` and `exec`) attempts toward parent budget observations; each non-compaction dispatch counts as one model call. */ export function countDelegatedBudgets(plan: CompiledPlan, attempts: ControllerProgress['attempts']): { readonly modelCalls: number; readonly formatRepairs: number; readonly implementationRepairs: number; } { - const isDelegated = (nodeId: string): boolean => { + const isDelegatedOrExec = (nodeId: string): boolean => { const node = plan.orderedDAG.find(item => item.id === nodeId); const role = node?.roleId ? plan.roles.find(item => item.roleId === node.roleId) : undefined; - return role?.adapter === 'delegated'; + return role?.adapter === 'delegated' || role?.adapter === 'exec'; }; let modelCalls = 0, formatRepairs = 0, implementationRepairs = 0; for (const attempt of attempts) { - if (!isDelegated(attempt.nodeId)) continue; + if (!isDelegatedOrExec(attempt.nodeId)) continue; if (attempt.purpose !== 'compaction') modelCalls++; if (attempt.repair === 'format') formatRepairs++; if (attempt.repair === 'implementation') implementationRepairs++; diff --git a/packages/controller/src/capture.ts b/packages/controller/src/capture.ts index b131e83a..e67b9e96 100644 --- a/packages/controller/src/capture.ts +++ b/packages/controller/src/capture.ts @@ -20,10 +20,14 @@ import { type ArtifactReader, } from './storage.js'; import { canonical, hash, integer, isRecord, list, record, same, text } from './schema.js'; +import { scanCandidateDirectory } from './candidate-workspace.js'; +import type { CycleContext } from './controller.js'; import { parsePrivateJson } from './parser.js'; -import { journal, phaseCheckpointId } from './progress.js'; +import { journal, phaseCheckpointId, type ProgressHead } from './progress.js'; import { formatPolicy } from './repair.js'; import { refuse, type ControllerDiagnostic } from './errors.js'; +import { resolveCurrentFileModes } from './step.js'; +import type { Submission } from './submission.js'; import { assertCanonicalMinimalOverlay, canonicalizeCandidateManifest, @@ -40,7 +44,9 @@ import type { ControllerAttempt, PlannedRole, RawCandidateFile, + StepVerdict, } from './types.js'; +import type { ByteInventory } from './verification.js'; export interface CapturedRole { readonly checkpointId: string; @@ -479,6 +485,7 @@ export async function captureDelegatedRole( readonly submissionBytes: Uint8Array | null; }, hostProtection: boolean | HostPathProtectionOptions = false, + dispatchedOperation?: { readonly operationId: string }, ): Promise { const bounds = overlayManifestBounds(lock.spec.contract.spec.budgets.overlay); const checkpointId = phaseCheckpointId(lock.spec.runId, 'role.' + attempt.ordinal + '.native'); @@ -489,8 +496,27 @@ export async function captureDelegatedRole( assertNoUnauthorizedModeMutations(input.candidateFiles, input.payload.overlay, source, lock.spec.contract, hostProtection, 'execution'); const wsMaxBytes = input.payload.version === 2 ? bounds.v2WorkspaceJsonMaxBytes : bounds.workspaceMaxBytes; const workspace = await artifacts.json('workspace', input.payload, wsMaxBytes); - const current = stateValue(store.inspect()); - if (current.counts.requests !== attempt.before.requests || current.counts.operations !== attempt.before.operations) refuse('RECOVERY_REQUIRED', '', 'execution'); + const records = journal(store); + const current = records.view; + let operationIds: readonly string[] = []; + if (dispatchedOperation !== undefined) { + if (current.counts.requests !== attempt.before.requests || current.counts.operations !== attempt.before.operations + 1) { + refuse('RECOVERY_REQUIRED', '', 'execution'); + } + const intervalOps = records.operations.filter(item => item.sequence > attempt.before.operations); + if ( + intervalOps.length !== 1 + || intervalOps[0]!.intent.operationId !== dispatchedOperation.operationId + || intervalOps[0]!.state !== 'confirmed' + || intervalOps[0]!.intent.effect !== 'local_write' + || !intervalOps[0]!.intent.targetIdentity.startsWith('exec:') + ) { + refuse('RECOVERY_REQUIRED', '', 'execution'); + } + operationIds = [dispatchedOperation.operationId]; + } else if (current.counts.requests !== attempt.before.requests || current.counts.operations !== attempt.before.operations) { + refuse('RECOVERY_REQUIRED', '', 'execution'); + } stateValue(store.writeCheckpoint(authority, { checkpointId, expectedRevision: current.revision, @@ -516,7 +542,7 @@ export async function captureDelegatedRole( workspace, session: null, submission, - journal: { requestIds: [], operationIds: [] }, + journal: { requestIds: [], operationIds }, }, 1_048_576); return { checkpointId, @@ -531,6 +557,129 @@ export async function captureDelegatedRole( }; } +export function synthesizedStepOutput( + task: TaskContract, + verdictStep: boolean, + status: 'completed' | 'no_change' | 'failed' | 'blocked', + reason: string | null, +): { readonly assistantText: string; readonly submissionBytes: Uint8Array } { + if (verdictStep) { + const syntheticVerdict: StepVerdict = { + verdict: status === 'failed' ? 'fail' : status === 'blocked' ? 'human' : 'pass', + summary: reason ?? 'Passed via step submit.', + findings: [], + }; + const assistantText = canonical(syntheticVerdict); + return { assistantText, submissionBytes: new Uint8Array(Buffer.from(assistantText, 'utf8')) }; + } + const checkStatus = + status === 'completed' || status === 'no_change' + ? ('passed' as const) + : status === 'blocked' + ? ('blocked' as const) + : ('failed' as const); + const checkReason = checkStatus === 'passed' ? null : (reason ?? 'check_not_satisfied'); + const synthetic: Submission = { + version: 1, + status, + checks: task.spec.acceptance.checks.map(check => ({ + checkId: check.id, + status: checkStatus, + evidenceId: null, + reason: checkReason, + })), + reason, + }; + const assistantText = canonical(synthetic); + return { assistantText, submissionBytes: new Uint8Array(Buffer.from(assistantText, 'utf8')) }; +} + +export async function captureExecRole( + context: CycleContext, + head: ProgressHead, + role: PlannedRole, + attempt: ControllerAttempt, + candidate: ByteInventory, + candidateDir: string, + verdictStep: boolean, + outcome: { + readonly status: 'completed' | 'blocked' | 'failed'; + readonly reason: string | null; + readonly operationId: string; + }, + hostProtection: HostPathProtectionOptions, +): Promise<{ readonly captured: CapturedRole; readonly ignoreArtifactPath: true }> { + const disallowMutations = + attempt.repair === 'format' + || !role.policy.tools.some(tool => tool === 'write' || tool === 'edit' || tool === 'delete' || tool === 'bash'); + const previousModes = await resolveCurrentFileModes(context, head, candidate.files); + const scanned = await scanCandidateDirectory( + candidateDir, + context.source, + context.plan.task, + head.progress.candidate.digest, + previousModes, + disallowMutations, + context.plan.budgets.overlay, + context.artifacts, + hostProtection, + ); + const { assistantText, submissionBytes } = synthesizedStepOutput( + context.plan.task, + verdictStep, + outcome.status, + outcome.reason, + ); + const payload: DelegatedCapturePayloadV2 = { + format: 'delegated-capture.v2', + version: 2, + baseRevision: context.plan.task.spec.target.baseRevision, + sourceRevision: context.plan.task.spec.target.sourceRevision, + overlay: scanned.overlay, + deleted: scanned.deleted, + assistantText, + status: outcome.status, + reason: outcome.reason, + }; + const bounds = overlayManifestBounds(context.plan.budgets.overlay); + const canonicalManifest = identifyManifest(canonicalizeCandidateManifest(scanned.manifest), bounds.options); + if (!canonicalManifest.ok || Buffer.byteLength(canonical(canonicalManifest.value.manifest), 'utf8') > bounds.manifestMaxBytes) { + refuse('OUTPUT_LIMIT', '', 'execution'); + } + await assertCanonicalMinimalOverlay(canonicalManifest.value.manifest, scanned.files, context.source, 'execution'); + const subject = bindSubject(context.lock, canonicalManifest.value.manifest, bounds.options); + if (!subject.ok) refuse('ARTIFACT_INVALID', '', 'execution'); + const changed = !same(subject.value.candidateDigest, head.progress.candidate.digest); + if (!changed && scanned.overlay.some(entry => (previousModes.get(entry.name) ?? '100644') !== entry.mode)) { + refuse('ARTIFACT_INVALID', '', 'execution'); + } + const nextGeneration = head.progress.candidate.generation + (changed ? 1 : 0); + if (nextGeneration >= context.plan.capacity.V) refuse('ATTEMPT_LIMIT', '', 'execution'); + const payloadBytes = Buffer.from(canonical(payload), 'utf8'); + if (payloadBytes.byteLength > bounds.v2WorkspaceJsonMaxBytes) refuse('OUTPUT_LIMIT', '', 'execution'); + context.artifacts.vault.assertClean(payloadBytes); + if (submissionBytes.byteLength > 1_048_576) refuse('OUTPUT_LIMIT', '', 'execution'); + context.artifacts.vault.assertClean(submissionBytes); + const captured = await captureDelegatedRole( + context.store, + context.authority, + context.artifacts, + context.lock, + role, + attempt, + context.source, + { + candidateManifest: scanned.manifest, + candidateFiles: scanned.files, + payload, + submissionBytes, + }, + hostProtection, + { operationId: outcome.operationId }, + ); + return { captured, ignoreArtifactPath: true }; +} + export async function adoptDelegatedCapture( store: LocalRunStore, artifacts: ArtifactStore, diff --git a/packages/controller/src/compile.ts b/packages/controller/src/compile.ts index 0f5ad305..7780dbe1 100644 --- a/packages/controller/src/compile.ts +++ b/packages/controller/src/compile.ts @@ -14,7 +14,31 @@ import { refuse, result } from './errors.js'; import { compactionTarget, descendants, reworkSubgraph } from './scheduler.js'; import { isScriptDirectoryProtected, localCheckScriptDirectoryDigest, type LocalCheckRecorded, type LocalCheckScriptEntry } from './local-check.js'; import { matchesScopePattern, type FrozenSource } from './source.js'; -import { CONTROLLER_LIMITS, type CheckpointCapacity, type CompiledPlan, type LoadedConfiguration, type PlannedNode, type PlannedRole, type RuntimeProfile, type StepHandoffSelect, type StepHandoffSelector, type StepHandoffSource, type VerifierSlot } from './types.js'; +import { CONTROLLER_LIMITS, type CheckpointCapacity, type CompiledPlan, type ExecPlannedRole, type LoadedConfiguration, type PlannedNode, type PlannedRole, type RuntimeProfile, type StepHandoffSelect, type StepHandoffSelector, type StepHandoffSource, type VerifierSlot } from './types.js'; + +export function isExecRole(role: PlannedRole): role is ExecPlannedRole { + return role.adapter === 'exec' && 'exec' in role; +} + +function placeholderRuntime( + id: string, + dockerPrefix: string, + files: { readonly sdkIntegrity: RuntimeProfile['identity']['sdkIntegrity']; readonly restrictionDigest: Digest }, + graphDigest: Digest, +): RuntimeProfile { + return { + id, + dockerExecutable: dockerPrefix, + dockerSocket: dockerPrefix + '.sock', + identity: { + sdkIntegrity: files.sdkIntegrity, + graphDigest, + configDigest: files.restrictionDigest, + imageDigest: 'sha256:' + '0'.repeat(64), + profile: 'linux/arm64', + }, + }; +} function cloneHandoffSelector(item: StepHandoffSelector): StepHandoffSelector { const source: StepHandoffSource = item.source.kind === 'artifact' ? { kind: 'artifact', path: item.source.path } @@ -122,6 +146,8 @@ export function compilePlan(loaded: LoadedConfiguration, admission?: SlotAdmissi } if (registry.resourceVersion !== task.spec.trustedContext.revision) refuse('CONFIG_REFERENCE', '/spec/task/spec/trustedContext', 'compile'); if (config.spec.profiles.roles.length !== task.spec.roles.length || config.spec.profiles.steps.length !== task.spec.steps.length) refuse('CONFIG_REFERENCE', '/spec/profiles', 'compile'); + const adapters = new Set(task.spec.roles.map(role => role.adapter)); + if (adapters.has('exec') && adapters.size > 1) refuse('CONFIG_SCHEMA', '/spec/task/spec/roles', 'compile'); const installed = await installedHandlerDigests(); for (const handler of registry.handlers) if (!same(handler.digest, installed[handler.implementation])) refuse('CONFIG_REFERENCE', '/registry/spec/handlers', 'compile'); const pending = [...task.spec.steps], orderedDAG: PlannedNode[] = [], done = new Set(); @@ -178,11 +204,26 @@ export function compilePlan(loaded: LoadedConfiguration, admission?: SlotAdmissi } } } + if (node.kind === 'agent' && node.handler.parameters.purpose === 'review') { + const reviewRole = task.spec.roles.find(item => item.id === node.roleId); + const reviewSelected = config.spec.profiles.roles.find(item => item.roleId === node.roleId); + const reviewProfile = registry.roleProfiles.find(item => item.id === reviewSelected?.profileRef); + if (reviewRole?.adapter === 'exec' || reviewProfile?.adapter === 'exec') { + refuse('CONFIG_SCHEMA', '/spec/profiles/steps', 'compile'); + } + } if (node.handler.implementation === 'pi.compact.v1') { const compactRole = task.spec.roles.find(item => item.id === node.roleId); const compactSelected = config.spec.profiles.roles.find(item => item.roleId === node.roleId); const compactProfile = registry.roleProfiles.find(item => item.id === compactSelected?.profileRef); - if (compactRole?.adapter === 'delegated' || compactProfile?.adapter === 'delegated') refuse('CAPABILITY_UNSUPPORTED', '/spec/profiles/steps', 'compile'); + if ( + compactRole?.adapter === 'delegated' + || compactProfile?.adapter === 'delegated' + || compactRole?.adapter === 'exec' + || compactProfile?.adapter === 'exec' + ) { + refuse('CAPABILITY_UNSUPPORTED', '/spec/profiles/steps', 'compile'); + } compactionTarget({ orderedDAG }, node.id); } } @@ -305,12 +346,12 @@ export function compilePlan(loaded: LoadedConfiguration, admission?: SlotAdmissi refuse('CONFIG_REFERENCE', '/spec/profiles/roles', 'compile'); } const active = orderedDAG.some(node => node.roleId === role.id); - if (active && (task.spec.budgets.enforcement.tokens !== 'soft_accounting' || profile.context.mode !== 'estimated_guard' || task.spec.budgets.perCallOutputTokens > profile.context.maxOutputTokens)) { + if (adapter !== 'exec' && active && (task.spec.budgets.enforcement.tokens !== 'soft_accounting' || profile.context.mode !== 'estimated_guard' || task.spec.budgets.perCallOutputTokens > profile.context.maxOutputTokens)) { refuse('CAPABILITY_UNSUPPORTED', '/registry/spec/roleProfiles', 'compile'); } const mcpEnabled = role.tools.includes('mcp__workspace__read_file'); let mcp: PlannedRole['policy']['mcp']; - if (adapter === 'delegated' && profile.mcp === null) { + if ((adapter === 'delegated' || adapter === 'exec') && profile.mcp === null) { if (role.tools.some(tool => tool === 'codemode' || tool === 'mcp__workspace__read_file')) { refuse('CAPABILITY_UNSUPPORTED', '/spec/profiles/roles', 'compile'); } @@ -347,22 +388,50 @@ export function compilePlan(loaded: LoadedConfiguration, admission?: SlotAdmissi const roleResources = selectRoleResources(task.spec.trustedContext.resources, role.resourceIds, 'compile').map( item => ({ id: item.id, kind: item.kind, path: item.path, digest: item.digest }), ); + if (adapter === 'exec') { + if (profile.providerCredentialRef !== null || profile.runtimeRef !== null || profile.mcp !== null || !profile.exec) { + refuse('CONFIG_SCHEMA', '/registry/spec/roleProfiles', 'compile'); + } + for (const ref of profile.exec.credentialRefs ?? []) { + const binding = registry.credentialBindings.find(item => item.id === ref); + if (!binding || binding.consumer !== 'exec') refuse('CONFIG_REFERENCE', '/registry/spec/roleProfiles', 'compile'); + neededCredentials.add(binding.id); + } + const runtime = placeholderRuntime('exec.none', '/nonexistent/exec.none', files, graphDigest); + const execRole: ExecPlannedRole = { + roleId: role.id, + adapter: 'exec', + profileRef: profile.id, + providerCredentialRef: null, + runtime, + policy: { + version: 2, + policyId: 'controller.' + loaded.registryDigest.hex.slice(0, 32), + resourceVersion: registry.resourceVersion, + adapterId: 'pi', + adapterVersion: '0.0.0', + runtime: runtime.identity, + selection: { provider: role.provider, model: role.model, thinking: role.thinking, api: 'openai-responses' }, + resources: [files.preamble, ...roleResources], + tools: role.tools, + mcp, + context: profile.context, + accounting: 'soft_only', + retry: 'sender_only', + extensions: [], + privateArtifacts: true, + limits: roleLimits, + }, + exec: profile.exec, + }; + roles.push(execRole); + continue; + } if (adapter === 'delegated') { if (profile.providerCredentialRef !== null) refuse('CONFIG_SCHEMA', '/registry/spec/roleProfiles', 'compile'); let runtime: RuntimeProfile; if (profile.runtimeRef === null) { - runtime = { - id: 'delegated.none', - dockerExecutable: '/nonexistent/delegated', - dockerSocket: '/nonexistent/delegated.sock', - identity: { - sdkIntegrity: files.sdkIntegrity, - graphDigest, - configDigest: files.restrictionDigest, - imageDigest: 'sha256:' + '0'.repeat(64), - profile: 'linux/arm64', - }, - }; + runtime = placeholderRuntime('delegated.none', '/nonexistent/delegated', files, graphDigest); } else { const found = registry.runtimeProfiles.find(item => item.id === profile.runtimeRef); if (!found || found.identity.sdkIntegrity !== files.sdkIntegrity || !same(found.identity.graphDigest, graphDigest) || !same(found.identity.configDigest, files.restrictionDigest)) { diff --git a/packages/controller/src/controller.ts b/packages/controller/src/controller.ts index 7884f7b7..ad425280 100644 --- a/packages/controller/src/controller.ts +++ b/packages/controller/src/controller.ts @@ -4,17 +4,21 @@ import { dirname, join, resolve } from 'node:path'; import { randomBytes } from 'node:crypto'; import { openPiAdapterV2, type PiAdapterV2, type PiCandidateArtifactInput, type PiHostV2, type PiOpenInputV2, type PiOutcomeV2 } from '@loopwright/agent-pi'; import { LIMITS, admitTask, bindSubject, identifyManifest, validateRelativePath, type ArtifactManifest, type ArtifactRef, type Digest, type StepHandoffSelector, type StructuredFinding, type TaskLock } from '@loopwright/core'; -import { createLocalRun, type Authority, type LocalRunIdentity, type LocalRunStore } from '@loopwright/state'; +import { createLocalRun, type Authority, type LocalRunIdentity, type LocalRunStore, type OperationReceipt } from '@loopwright/state'; +import { materializeAttemptWorkspace } from './candidate-workspace.js'; import { approvedState, selectRoleResources } from './config.js'; -import { compilePlan, recordedLocalCheck } from './compile.js'; +import { compilePlan, isExecRole, recordedLocalCheck } from './compile.js'; import { ControllerFailure, refuse, result, safeDiagnostic, type ControllerDiagnostic } from './errors.js'; +import { runExecRole } from './exec-role.js'; +import { readBoundedFile, removeTree } from './files.js'; import { privateDirectory, ArtifactStore, checkedRef, stateValue, streamVerifiedCasBlob } from './storage.js'; import { ControllerOwner, bootIdentity } from './ownership.js'; +import { confirmProcessGroupGone } from './process-group.js'; import { effectiveRunHostPolicy, hostProtectionFromPolicy, resolveStoreLeaseMs, validatePortPolicyFields } from './retained.js'; export { resolveStoreLeaseMs }; import { compareUtf16, freezeSource, gitObjectOid, materializeBaseline, overlayManifestBounds, verifySource, type FrozenSource, type HostPathProtectionOptions } from './source.js'; import { ProgressStore, stableId, journal, type ProgressHead } from './progress.js'; -import { captureRole, adoptRoleCapture, decodeCandidateCapture, nativeSessionId, type CapturedRole } from './capture.js'; +import { captureExecRole, captureRole, adoptRoleCapture, decodeCandidateCapture, nativeSessionId, type CapturedRole } from './capture.js'; import { appendHandoffPromptBlock, evaluateStepHandoffSelectors, @@ -79,9 +83,11 @@ import { type ControllerProgress, type CycleAlignmentRoute, type CycleExecution, + type ExecPlannedRole, type LoadedConfiguration, type NodeCandidateSnapshot, type PersistedHostPolicy, + type PlannedNode, type PlannedRole, type RoleModelOverride, type StepMcpServerMetadata, @@ -99,6 +105,47 @@ const VALID_ADVISORY_SOURCES: ReadonlySet = new Set = new Set(['continue', 'revise', 'needs_review', 'blocked']); const VALID_CAPABILITY_TIERS: ReadonlySet = new Set(['fast', 'balanced', 'strongest']); const VALID_SOFT_COMPACTION_DECISIONS: ReadonlySet = new Set(['compact', 'defer']); +export const EXEC_ROLE_PRODUCER_ID = 'loopwright.exec-role.v1'; +export const EXEC_ROLE_METHOD = 'exec_command'; +export const EXEC_MARKER_BYTES = 1_048_576; +const EXEC_OUTCOME_MAX_BYTES = 8_388_608; + +export function execOperationId(runId: string, attemptId: string): string { + return 'exec.' + hash('loopwright.dev/controller/exec/v1\0' + canonical({ runId, attemptId })).hex.slice(0, 40); +} + +export function execMarkerPath(artifactsDirectory: string, operationId: string, kind: 'binding' | 'proof'): string { + return join(artifactsDirectory, 'exec-role-producer-' + hash(operationId).hex + '.' + kind + '.json'); +} + +export async function writeExecMarker( + artifacts: ArtifactStore, + operationId: string, + kind: 'binding' | 'proof', + value: unknown, + phase: ControllerDiagnostic['phase'] = 'execution', +): Promise { + await artifacts.owner.assertCurrent(); + const path = execMarkerPath(artifacts.directory, operationId, kind); + const bytes = Buffer.from(canonical(value)); + if (bytes.byteLength > EXEC_MARKER_BYTES) refuse('OUTPUT_LIMIT', '', phase); + artifacts.vault.assertClean(bytes); + let file: Awaited>; + try { + file = await open(path, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'EEXIST' || !Buffer.from(await readBoundedFile(path, EXEC_MARKER_BYTES, true)).equals(bytes)) { + refuse('RECOVERY_REQUIRED', '', phase); + } + return; + } + try { + await file.writeFile(bytes); + await file.sync(); + } finally { + await file.close(); + } +} export function isHaltedByVerdict(progress: ControllerProgress | null | undefined): 'blocked' | 'failed' | null { const verdicts = progress?.stepVerdicts; @@ -401,6 +448,20 @@ export class Cycle { haltedVerdictStatus(): 'blocked' | 'failed' | null { return isHaltedByVerdict(this.head?.progress); } + haltedExecStatus(): 'blocked' | 'failed' | null { + const progress = this.head?.progress; + if (!progress) return null; + let hasFailed = false; + for (const item of progress.nodes) { + if (item.state !== 'blocked' && item.state !== 'failed') continue; + const dagNode = this.context.plan.orderedDAG.find(node => node.id === item.id); + const role = dagNode?.roleId ? this.context.plan.roles.find(r => r.roleId === dagNode.roleId) : undefined; + if (dagNode?.kind !== 'agent' || role?.adapter !== 'exec') continue; + if (item.state === 'blocked') return 'blocked'; + hasFailed = true; + } + return hasFailed ? 'failed' : null; + } async activeReworkForNode(nodeId: string): Promise { const epoch = this.reworkEpoch; if (epoch === 0) return null; @@ -1053,6 +1114,7 @@ export class Cycle { ); } } else { + const execStatus = role.adapter === 'exec' && stepOutput?.kind === 'submission' ? stepOutput.retained.value.status : null; if (stepOutput?.kind === 'submission') { const retained = stepOutput.retained; const priorNodeSub = this.draft.nodeSubmissions?.[nodeId]; @@ -1064,12 +1126,17 @@ export class Cycle { this.submission.value.checks.length > 0 && retained.value.status === 'completed' && retained.value.checks.length === 0; - if (!keepPriorRicherAuthorClaims) { + const keepPriorExecFailure = + role.adapter === 'exec' && + this.submission !== null && + (this.submission.value.status === 'blocked' || this.submission.value.status === 'failed') && + retained.value.status === 'completed'; + if (!keepPriorRicherAuthorClaims && !keepPriorExecFailure) { this.submission = retained; } nextSubmissionRef = this.submission!.raw; } - if (purpose !== 'compaction' && isArtifactHandoffSourceStep(plan, nodeId)) { + if (purpose !== 'compaction' && execStatus !== 'blocked' && execStatus !== 'failed' && isArtifactHandoffSourceStep(plan, nodeId)) { nextNodeCandidates = freeze({ ...(this.draft.nodeCandidates ?? {}), [nodeId]: freeze({ @@ -1081,7 +1148,24 @@ export class Cycle { }), }); } - nextNodes = nextNodes.map(item => (item.id === nodeId ? { ...item, state: 'completed' as const } : item)); + if (execStatus === 'blocked') { + verdictHalted = true; + nextNodes = nextNodes.map(item => + item.id === nodeId ? { ...item, state: 'blocked' as const } : item.state === 'pending' ? { ...item, state: 'not_run' as const } : item, + ); + } else if (execStatus === 'failed') { + verdictHalted = true; + const downstream = new Set(descendants(plan, nodeId)); + nextNodes = nextNodes.map(item => + item.id === nodeId + ? { ...item, state: 'failed' as const } + : downstream.has(item.id) && item.state === 'pending' + ? { ...item, state: 'not_run' as const } + : item, + ); + } else { + nextNodes = nextNodes.map(item => (item.id === nodeId ? { ...item, state: 'completed' as const } : item)); + } } const generation = this.generation + (changed || reworked ? 1 : 0); @@ -1628,36 +1712,38 @@ export class Cycle { const originalSubmission = this.draft.failures.at(-1)?.evidence ?? this.draft.submission, before = journal(store).view.counts, oldDigest = this.draft.candidate.digest; const originalState = await schedulingSnapshot(store, authority, lock, artifacts, this.candidate, this.draft.candidate); observeParentExhaustion(this.deadline.assert(), lock, delegatedCounts.modelCalls); - // Native Pi adapter materializes files using baseline-derived modes in tree_overlay (v2) and 0o444 (100644) - // for every file in classic (v1); fail closed with zero effect before launching a native role whenever a - // candidate overlay/mutation carries an effective mode that Pi cannot faithfully materialize. - const baselineByPath = new Map( - this.context.source.version === 2 - ? (this.context.source.baselineEntries ?? []).map(entry => [ - entry.name, - { mode: entry.mode, bytes: null as Uint8Array | null, sha256: null as string | null }, - ]) - : this.context.source.artifacts.map(entry => [ - entry.name, - { mode: entry.mode ?? ('100644' as const), bytes: entry.bytes, sha256: hash(entry.bytes).hex }, - ]), - ); - for (const file of this.candidate.files) { - const base = baselineByPath.get(file.name); - const baselineMode = base?.mode ?? '100644'; - const effectiveMode = file.mode ?? baselineMode; - const piMaterializedMode = this.context.source.version === 2 ? baselineMode : '100644'; - if (this.context.source.version === 1 && base !== undefined) { - const bytesUnchanged = - 'bytes' in file - ? Buffer.from(file.bytes).equals(Buffer.from(base.bytes!)) - : file.byteLength === base.bytes!.byteLength && file.digest.hex === base.sha256; - if (bytesUnchanged && effectiveMode === baselineMode) { - continue; + if (originalRole.adapter !== 'exec') { + // Native Pi adapter materializes files using baseline-derived modes in tree_overlay (v2) and 0o444 (100644) + // for every file in classic (v1); fail closed with zero effect before launching a native role whenever a + // candidate overlay/mutation carries an effective mode that Pi cannot faithfully materialize. + const baselineByPath = new Map( + this.context.source.version === 2 + ? (this.context.source.baselineEntries ?? []).map(entry => [ + entry.name, + { mode: entry.mode, bytes: null as Uint8Array | null, sha256: null as string | null }, + ]) + : this.context.source.artifacts.map(entry => [ + entry.name, + { mode: entry.mode ?? ('100644' as const), bytes: entry.bytes, sha256: hash(entry.bytes).hex }, + ]), + ); + for (const file of this.candidate.files) { + const base = baselineByPath.get(file.name); + const baselineMode = base?.mode ?? '100644'; + const effectiveMode = file.mode ?? baselineMode; + const piMaterializedMode = this.context.source.version === 2 ? baselineMode : '100644'; + if (this.context.source.version === 1 && base !== undefined) { + const bytesUnchanged = + 'bytes' in file + ? Buffer.from(file.bytes).equals(Buffer.from(base.bytes!)) + : file.byteLength === base.bytes!.byteLength && file.digest.hex === base.sha256; + if (bytesUnchanged && effectiveMode === baselineMode) { + continue; + } + } + if (effectiveMode !== piMaterializedMode) { + refuse('CAPABILITY_UNSUPPORTED', '', 'execution', { effect: 'none' }); } - } - if (effectiveMode !== piMaterializedMode) { - refuse('CAPABILITY_UNSUPPORTED', '', 'execution', { effect: 'none' }); } } const attempt: ControllerAttempt = retained ?? { @@ -1674,6 +1760,11 @@ export class Cycle { await this.events.push(repair === 'none' ? 'role' : 'repair', null, nodeId, commandId); await this.publish({ ...this.draft, stage: { ...this.draft.stage, kind: 'role_pre' }, attempts: [...this.draft.attempts, attempt], nodes: this.draft.nodes.map(item => item.id === nodeId ? { ...item, state: 'running' } : item) }, 'role.' + ordinal + '.pre'); } + if (isExecRole(originalRole)) { + const execRole: ExecPlannedRole = repair === 'format' ? { ...originalRole, policy: formatPolicy(originalRole.policy) } : originalRole; + await this.#execDispatch(execRole, node, attempt, commandText, activeResources, attempt.handoffExtracts ?? []); + return; + } let restore: PiOpenInputV2['restore'] = null, nativeManifest = this.candidate.manifest; if (purpose === 'compaction' || repair === 'implementation') { const prior = this.draft.attempts.slice(0, -1).filter(item => item.nativeStepId === nativeStepId && item.sessionId === sessionId && item.finished?.nativeCheckpointId).at(-1); @@ -1782,11 +1873,7 @@ let cleanupKnown = false, reader: Promise | null = null, nativeOutcome: Ar }); } } - if (this.head?.progress.attempts.at(-1)?.id === commandId && this.head.progress.attempts.at(-1)!.finished === null) { - const diagnostic = safeDiagnostic(failure, 'execution'), after = stateValue(store.inspect()).counts; - const outcome = await artifacts.json('role-refusal', { version: 1, attemptId: commandId, command, diagnostic, nativeOutcome, currentCandidate: this.#candidateKnown ? this.draft.candidate.manifest : null, unavailable: this.#candidateKnown ? [] : ['current_candidate', 'submission'], localCleanup: cleanupKnown ? 'complete' : 'pending' }, 65536); - await this.publish({ ...this.draft, stage: { ...this.draft.stage, kind: 'role_post' }, attempts: this.draft.attempts.map(item => item.id === commandId ? { ...item, finished: { after: { requests: after.requests, operations: after.operations }, outcome, nativeCheckpointId: null } } : item), nodes: this.draft.nodes.map(item => item.id === nodeId ? { ...item, state: 'failed' } : descendants(plan, nodeId).includes(item.id) && item.state === 'pending' ? { ...item, state: 'not_run' } : item) }, 'role.' + ordinal + '.post'); - } + await this.#publishRoleRefusal(attempt, nodeId, failure, nativeOutcome, cleanupKnown); throw failure; } finally { await closeLocal(); @@ -1795,10 +1882,447 @@ let cleanupKnown = false, reader: Promise | null = null, nativeOutcome: Ar if (structureFailure === 'SUBMISSION_AMBIGUOUS') refuse(structureFailure, '', 'verification'); if (structureFailure === 'SUBMISSION_INVALID') await this.repairFormat(nodeId); } + #stopCode(): 'DEADLINE' | 'CANCELLED' { + return this.deadline.reason === 'DEADLINE' ? 'DEADLINE' : 'CANCELLED'; + } + #mapDeadlineError(error: unknown): unknown { + if (error instanceof ControllerFailure && error.diagnostic.code === 'CANCELLED' && this.deadline.reason === 'DEADLINE') { + return new ControllerFailure({ ...error.diagnostic, code: 'DEADLINE' }); + } + return error; + } + #hasActiveStoreAuthority(): boolean { + const inspected = this.context.store.inspect(); + return ( + inspected.ok + && inspected.value.clockStatus === 'trusted' + && inspected.value.owner.mode === 'active' + && inspected.value.owner.ownerId === this.context.authority.ownerId + && inspected.value.owner.generation === this.context.authority.generation + ); + } + async #publishRoleRefusal( + attempt: ControllerAttempt, + nodeId: string, + failure: unknown, + nativeOutcome: ArtifactRef | null, + cleanupKnown: boolean, + ): Promise { + const { plan, store, artifacts } = this.context; + if (this.head?.progress.attempts.at(-1)?.id === attempt.id && this.head.progress.attempts.at(-1)!.finished === null) { + const diagnostic = safeDiagnostic(failure, 'execution'); + const after = stateValue(store.inspect()).counts; + const outcome = await artifacts.json( + 'role-refusal', + { + version: 1, + attemptId: attempt.id, + command: attempt.command, + diagnostic, + nativeOutcome, + currentCandidate: this.#candidateKnown ? this.draft.candidate.manifest : null, + unavailable: this.#candidateKnown ? [] : ['current_candidate', 'submission'], + localCleanup: cleanupKnown ? 'complete' : 'pending', + }, + 65_536, + ); + await this.publish( + { + ...this.draft, + stage: { ...this.draft.stage, kind: 'role_post' }, + attempts: this.draft.attempts.map(item => + item.id === attempt.id + ? { ...item, finished: { after: { requests: after.requests, operations: after.operations }, outcome, nativeCheckpointId: null } } + : item, + ), + nodes: this.draft.nodes.map(item => + item.id === nodeId + ? { ...item, state: 'failed' } + : descendants(plan, nodeId).includes(item.id) && item.state === 'pending' + ? { ...item, state: 'not_run' } + : item, + ), + }, + 'role.' + attempt.ordinal + '.post', + ); + } + } + async #execDispatch( + role: ExecPlannedRole, + node: PlannedNode, + attempt: ControllerAttempt, + promptText: string, + activeResources: ReturnType, + handoffExtracts: readonly AttemptHandoffExtract[], + ): Promise { + const { plan, lock, store, artifacts, authority, loaded, directory, owner } = this.context; + const runRoot = dirname(directory); + const hostProtection = cycleHostProtection(this.context); + const attemptDir = join(runRoot, 'workspaces', lock.spec.runId, attempt.id); + const scratchDir = join(attemptDir, 'scratch'); + const promptFile = join(scratchDir, 'prompt.md'); + const usageOut = join(scratchDir, 'usage.json'); + const done = await owner.holdLocalActivity(); + let groupClean = true; + let workspacePresent = false; + let dispatchedOperation = false; + let operationSettled = false; + let bindingWritten = false; + let proofWritten = false; + let spawnedPgid: number | null = null; + let recordedOutcomeRef: ArtifactRef | null = null; + const savedCandidate = this.candidate; + + try { + const bindings = (role.exec.credentialRefs ?? []).map(ref => { + const binding = loaded.registry.spec.credentialBindings.find(item => item.id === ref); + if (!binding || binding.consumer !== 'exec') refuse('CONFIG_REFERENCE', '/registry/spec/roleProfiles', 'execution'); + return binding; + }); + if (this.deadline.abort.signal.aborted) refuse(this.#stopCode(), '', 'execution'); + workspacePresent = true; + let candidateDir: string; + let contextFiles: readonly string[]; + try { + const materialized = await materializeAttemptWorkspace( + this, + runRoot, + attempt.id, + role, + attempt.repair, + hostProtection, + activeResources, + handoffExtracts, + 'execution', + ); + candidateDir = materialized.candidateDir; + contextFiles = materialized.contextFiles; + await mkdir(scratchDir, { mode: 0o700 }); + const promptBytes = Buffer.from(promptText, 'utf8'); + const promptHandle = await open( + promptFile, + constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, + 0o400, + ); + try { + await promptHandle.writeFile(promptBytes); + await promptHandle.chmod(0o400); + await promptHandle.sync(); + } finally { + await promptHandle.close(); + } + } catch (error) { + await removeTree(attemptDir, 'execution'); + workspacePresent = false; + throw this.#mapDeadlineError(error); + } + + this.deadline.assert(); + const operationId = execOperationId(lock.spec.runId, attempt.id); + const candidateDigest = this.draft.candidate.digest; + const target = 'exec:' + node.id + ':' + attempt.ordinal + ':' + candidateDigest.hex; + const requestDigest = hash( + 'loopwright.dev/controller/exec-request/v1\0' + + canonical({ + planDigest: plan.planDigest, + attemptId: attempt.id, + nodeId: node.id, + roleId: role.roleId, + promptDigest: attempt.command.digest, + candidateDigest, + }), + ); + stateValue( + store.putIntent(authority, { + operationId, + nodeId: node.id, + attemptId: attempt.id, + effect: 'local_write', + requestDigest, + targetIdentity: target, + }), + ); + const dispatched = stateValue(store.authorizeOperationDispatch(authority, operationId)); + if (dispatched.kind !== 'new_dispatch') refuse('RECOVERY_REQUIRED', '', 'execution'); + dispatchedOperation = true; + const permit = dispatched.permit; + const intentDigest = stateValue(store.getOperation(operationId)).intentDigest; + const dispatchReceipt = { + generation: permit.generation, + dispatchId: permit.dispatchId, + revision: permit.authorizedRevision, + clockEpoch: permit.clockEpoch, + }; + + const settleRefused = async (failure: unknown): Promise => { + if (operationSettled) return; + if (!this.#hasActiveStoreAuthority()) refuse('AUTHORITY_REFUSED', '', 'execution'); + await artifacts.owner.assertCurrent(); + stateValue(store.renew(authority)); + const view = stateValue(store.inspect()); + const op = stateValue(store.getOperation(operationId)); + if (op.dispatch?.dispatchId !== permit.dispatchId || op.intent.targetIdentity !== target) { + refuse('AUTHORITY_REFUSED', '', 'execution'); + } + if (!recordedOutcomeRef) { + const diagnostic = safeDiagnostic(failure, 'execution'); + recordedOutcomeRef = await artifacts.json( + 'exec-outcome', + { + version: 1, + attemptId: attempt.id, + operationId, + status: null, + reason: null, + diagnostic, + pgid: spawnedPgid, + timedOut: null, + exitCode: null, + exitSignal: null, + stdout: '', + stderr: '', + stdoutTruncated: false, + stderrTruncated: false, + usage: [], + usageReported: false, + }, + EXEC_OUTCOME_MAX_BYTES, + ); + } + if (!proofWritten) { + await writeExecMarker(artifacts, operationId, 'proof', { + version: 1, + operationId, + attemptId: attempt.id, + pgid: spawnedPgid, + outcome: recordedOutcomeRef, + capture: null, + settled: 'refused', + }); + proofWritten = true; + } + const suffix = hash(operationId).hex.slice(0, 40); + const receipt: OperationReceipt = { + receiptId: 'receipt.' + suffix, + outcome: bindingWritten || spawnedPgid !== null ? 'failed' : 'not_executed', + evidence: { + evidenceId: 'receipt-evidence.' + suffix, + producerId: EXEC_ROLE_PRODUCER_ID, + method: EXEC_ROLE_METHOD, + subject: { + storeId: view.storeId, + runId: view.runId, + lockHash: view.lockHash, + operationId, + requestId: null, + intentDigest, + dispatchGeneration: dispatchReceipt.generation, + dispatchId: dispatchReceipt.dispatchId, + }, + artifact: recordedOutcomeRef, + }, + }; + stateValue(store.recordOperationReceipt(authority, operationId, receipt)); + operationSettled = true; + }; + + try { + this.#candidateKnown = false; + let outcome: Awaited>; + try { + outcome = await runExecRole( + { exec: role.exec, tools: role.policy.tools, credentials: bindings }, + { + runId: lock.spec.runId, + stepId: node.id, + roleId: role.roleId, + attemptId: attempt.id, + scopeWritable: plan.scope.writable, + contextFiles, + scratchDir, + promptFile, + candidateDir, + usageOut, + secrets: approvedState(loaded).vault, + signal: this.deadline.abort.signal, + onSpawned: async pgid => { + spawnedPgid = pgid; + groupClean = false; + await writeExecMarker(artifacts, operationId, 'binding', { + version: 1, + planDigest: plan.planDigest, + operationId, + attemptId: attempt.id, + nodeId: node.id, + roleId: role.roleId, + promptDigest: attempt.command.digest, + intentDigest, + dispatchReceipt, + pgid, + workspaceDir: attemptDir, + }); + bindingWritten = true; + }, + }, + ); + } catch (runError) { + if (!(runError instanceof ControllerFailure && runError.diagnostic.code === 'CLEANUP_FAILED')) { + groupClean = true; + } + throw this.#mapDeadlineError(runError); + } + + await confirmProcessGroupGone(outcome.pgid, 'execution'); + groupClean = true; + + if (!this.#hasActiveStoreAuthority()) refuse('AUTHORITY_REFUSED', '', 'execution'); + await artifacts.owner.assertCurrent(); + stateValue(store.renew(authority)); + if (this.deadline.abort.signal.aborted) refuse(this.#stopCode(), '', 'execution'); + + const view = stateValue(store.inspect()); + const op = stateValue(store.getOperation(operationId)); + if ( + view.storeId !== permit.storeId + || view.runId !== permit.runId + || !same(view.lockHash, permit.lockHash) + || permit.generation !== authority.generation + || permit.clockEpoch !== view.clock.basis.clockEpoch + || op.state !== 'dispatch_uncertain' + || op.dispatch?.dispatchId !== permit.dispatchId + || op.intent.targetIdentity !== target + ) { + refuse('AUTHORITY_REFUSED', '', 'execution'); + } + + recordedOutcomeRef = await artifacts.json( + 'exec-outcome', + { + version: 1, + attemptId: attempt.id, + operationId, + status: outcome.status, + reason: outcome.reason, + exitCode: outcome.exitCode, + exitSignal: outcome.exitSignal, + timedOut: outcome.timedOut, + stdout: outcome.stdout, + stderr: outcome.stderr, + stdoutTruncated: outcome.stdoutTruncated, + stderrTruncated: outcome.stderrTruncated, + usage: outcome.usage, + usageReported: outcome.usageReported, + pgid: outcome.pgid, + }, + EXEC_OUTCOME_MAX_BYTES, + ); + await writeExecMarker(artifacts, operationId, 'proof', { + version: 1, + operationId, + attemptId: attempt.id, + pgid: outcome.pgid, + outcome: recordedOutcomeRef, + capture: null, + settled: 'observed', + }); + proofWritten = true; + + const suffix = hash(operationId).hex.slice(0, 40); + const receipt: OperationReceipt = { + receiptId: 'receipt.' + suffix, + outcome: outcome.status === 'completed' ? 'succeeded' : 'failed', + evidence: { + evidenceId: 'receipt-evidence.' + suffix, + producerId: EXEC_ROLE_PRODUCER_ID, + method: EXEC_ROLE_METHOD, + subject: { + storeId: view.storeId, + runId: view.runId, + lockHash: view.lockHash, + operationId, + requestId: null, + intentDigest, + dispatchGeneration: dispatchReceipt.generation, + dispatchId: dispatchReceipt.dispatchId, + }, + artifact: recordedOutcomeRef, + }, + }; + stateValue(store.recordOperationReceipt(authority, operationId, receipt)); + operationSettled = true; + this.#candidateKnown = true; + + if (BigInt(view.clock.sampledNow.monotonicMs) >= BigInt(view.clock.basis.taskDeadlineMonotonicMs) || this.deadline.reason === 'DEADLINE') { + refuse('DEADLINE', '', 'execution'); + } + if (BigInt(view.clock.sampledNow.monotonicMs) >= BigInt(permit.notAfterMonotonicMs)) { + refuse('AUTHORITY_REFUSED', '', 'execution'); + } + + const { captured, ignoreArtifactPath } = await captureExecRole( + this.context, + this.head!, + role, + attempt, + this.candidate, + candidateDir, + isVerdictStep(node), + { status: outcome.status, reason: outcome.reason, operationId }, + hostProtection, + ); + await this.completeCapture(attempt, captured, { ignoreArtifactPath }); + } catch (dispatchError) { + this.candidate = savedCandidate; + const failure = this.#mapDeadlineError(dispatchError); + if (failure instanceof ControllerFailure && failure.diagnostic.code === 'CLEANUP_FAILED') { + this.#cleanup = 'pending'; + this.#candidateKnown = false; + if (this.#hasActiveStoreAuthority()) { + await this.#publishRoleRefusal(attempt, node.id, failure, null, false); + } + throw failure; + } + if (groupClean && dispatchedOperation && !operationSettled) { + try { + await settleRefused(failure); + this.#candidateKnown = true; + } catch (settleError) { + this.#candidateKnown = false; + throw settleError; + } + } + if (this.#hasActiveStoreAuthority()) { + await this.#publishRoleRefusal(attempt, node.id, failure, recordedOutcomeRef, groupClean); + } + throw failure; + } + } catch (outerError) { + if (outerError instanceof ControllerFailure && outerError.diagnostic.code === 'CLEANUP_FAILED') { + this.#cleanup = 'pending'; + this.#candidateKnown = false; + } + if (!dispatchedOperation && this.#hasActiveStoreAuthority()) { + await this.#publishRoleRefusal(attempt, node.id, outerError, null, groupClean && !workspacePresent); + } + throw outerError; + } finally { + if (groupClean && workspacePresent) { + await removeTree(attemptDir, 'execution'); + workspacePresent = false; + } + if (groupClean && !workspacePresent) { + done(); + } else if (this.#cleanup === 'complete') { + this.#cleanup = 'pending'; + } + } + } async resumeAttempt(adopt: boolean): Promise { const attempt = this.draft.attempts.at(-1); if (!attempt || attempt.finished !== null) return; - if (!adopt) { await this.role(attempt.nodeId, attempt.repair, undefined, attempt); return; } const original = this.context.plan.roles.find(role => role.roleId === this.context.plan.orderedDAG.find(node => node.id === attempt.nodeId)!.roleId)!; + // shortcut: an interrupted exec attempt (including the narrow checkpoint-to-role_post window) never re-runs or re-adopts; fail closed. + if (original.adapter === 'exec') refuse('RECOVERY_REQUIRED', '', 'recovery'); + if (!adopt) { await this.role(attempt.nodeId, attempt.repair, undefined, attempt); return; } const role = attempt.repair === 'format' ? { ...original, policy: formatPolicy(original.policy) } : original; const captured = await adoptRoleCapture(this.context.store, this.context.artifacts, this.context.lock, role, attempt, undefined, this.context.source, cycleHostProtection(this.context)); const failure = await this.completeCapture(attempt, captured); @@ -1827,13 +2351,18 @@ let cleanupKnown = false, reader: Promise | null = null, nativeOutcome: Ar return formatPrompt(bytes, allowedCheckIds, maxPromptBytes); } async repairFormat(nodeId: string): Promise { + const node = this.context.plan.orderedDAG.find(item => item.id === nodeId); + const role = this.context.plan.roles.find(item => item.roleId === node?.roleId); + if (role?.adapter === 'exec') refuse('CAPABILITY_UNSUPPORTED', '', 'execution'); const prompt = await this.formatRepairPrompt(nodeId); await this.role(nodeId, 'format', prompt); } currentChecks(): readonly VerifiedCheck[] { return [...this.checks.values()].filter(check => check.generation === this.generation); } currentRefusals(): readonly PreflightRefusal[] { return [...this.refusals.values()].filter(item => item.generation === this.generation); } async verifyEligible(): Promise { + const execBlocked = this.haltedExecStatus() === 'blocked'; for (const slot of this.context.plan.verifierSlots) { + if (execBlocked && slot.implicit === null) continue; const nodes = this.context.plan.orderedDAG.filter(node => node.kind === 'check' && node.handler.id === slot.handler.id); if (nodes.some(node => this.draft.nodes.find(item => item.id === node.id)?.state !== 'completed')) continue; await this.runVerifier(slot.id); @@ -1861,7 +2390,7 @@ let cleanupKnown = false, reader: Promise | null = null, nativeOutcome: Ar await this.verifyEligible(); } async prepareImplementationRepair(): Promise<{ readonly targetNodeId: string; readonly role: PlannedRole; readonly prompt: string } | null> { - const { plan } = this.context; if (plan.budgets.maxImplementationRepairs === 0) return null; + const { plan } = this.context; if (plan.budgets.maxImplementationRepairs === 0 || this.haltedExecStatus() !== null) return null; const checks = this.currentChecks(), required = plan.verifierSlots.filter(slot => slot.implicit === null && plan.task.spec.acceptance.required.includes(slot.checkId)); const failed = checks.filter(check => { if (check.status !== 'failed') return false; @@ -1963,7 +2492,16 @@ let cleanupKnown = false, reader: Promise | null = null, nativeOutcome: Ar if (attempt?.finished?.nativeCheckpointId === null) { await refuseFromRoleOutcome(this.context.artifacts, attempt.finished.outcome, this.draft.candidate.manifest, () => { this.#candidateKnown = false; }); } - if (attempt?.finished?.nativeCheckpointId && attempt.purpose !== 'compaction' && !this.haltedVerdictStatus() && this.draft.nodes.find(node => node.id === attempt.nodeId)?.state === 'failed') { + const attemptRole = attempt + ? this.context.plan.roles.find(r => r.roleId === this.context.plan.orderedDAG.find(n => n.id === attempt.nodeId)?.roleId) + : undefined; + if ( + attempt?.finished?.nativeCheckpointId + && attempt.purpose !== 'compaction' + && attemptRole?.adapter !== 'exec' + && !this.haltedVerdictStatus() + && this.draft.nodes.find(node => node.id === attempt.nodeId)?.state === 'failed' + ) { await this.repairFormat(attempt.nodeId); } } @@ -1979,6 +2517,11 @@ let cleanupKnown = false, reader: Promise | null = null, nativeOutcome: Ar }, }); const verdictHalt = this.haltedVerdictStatus(); + const execHalt = this.haltedExecStatus(); + const scopeFailed = checks.some( + check => this.context.plan.verifierSlots.find(slot => slot.id === check.slotId)?.implicit === 'scope' && check.status === 'failed', + ); + const forcedHalt = verdictHalt ?? (execHalt === 'blocked' && scopeFailed ? 'failed' : execHalt); const acceptance = evaluateControllerAcceptance( this.context.plan, this.context.lock, @@ -1988,13 +2531,13 @@ let cleanupKnown = false, reader: Promise | null = null, nativeOutcome: Ar checks, this.submission!.value, this.context.store, - verdictHalt, + forcedHalt, this.draft.nodes.every(node => node.state === 'completed'), this.currentRefusals(), null, preverified, ); - if (verdictHalt === null && acceptance.result.spec.status === 'failed' && await this.implementationRepair()) { + if (forcedHalt === null && acceptance.result.spec.status === 'failed' && await this.implementationRepair()) { await this.graph(); continue; } diff --git a/packages/controller/src/credentials.ts b/packages/controller/src/credentials.ts index 0b61ad54..72e89555 100644 --- a/packages/controller/src/credentials.ts +++ b/packages/controller/src/credentials.ts @@ -20,6 +20,8 @@ export interface CredentialVault { readonly createStreamChecker: () => CredentialStreamChecker; /** Gate and publisher signing/auth secrets only; provider and mcp consumers stay behind their bound resolvers. */ readonly resolveNetworkCredential: (ref: string) => string; + /** Expanded template value of the `consumer: exec` binding `ref`; refuses when `ref` names no such binding. */ + readonly resolveExecCredential: (ref: string) => string; readonly bind: (scope: { readonly runId: string; readonly roleId: string; @@ -176,6 +178,11 @@ export function createVault(expanded: unknown, registry: TrustedRegistry): Crede if (!binding || binding.consumer !== 'gate' && binding.consumer !== 'publisher') refuse('CONFIG_CREDENTIAL_INVALID', '/spec/credentials'); const token = tokens.get(ref); if (!token) refuse('CONFIG_CREDENTIAL_INVALID', '/spec/credentials'); return token; }, + resolveExecCredential: (ref: string): string => { + const binding = registry.spec.credentialBindings.find(item => item.id === ref); + if (!binding || binding.consumer !== 'exec') refuse('CONFIG_CREDENTIAL_INVALID', '/spec/credentials', 'execution'); + const token = tokens.get(ref); if (!token) refuse('CONFIG_CREDENTIAL_INVALID', '/spec/credentials', 'execution'); return token; + }, bind: (scope: Parameters[0]) => { const provider: PiHost['resolveCredential'] = async binding => { const approved = registry.spec.credentialBindings.find(item => item.id === scope.providerCredentialRef); diff --git a/packages/controller/src/files.ts b/packages/controller/src/files.ts index fd82338c..f3b63cc6 100644 --- a/packages/controller/src/files.ts +++ b/packages/controller/src/files.ts @@ -1,6 +1,6 @@ import { createHash, randomBytes } from 'node:crypto'; import { constants } from 'node:fs'; -import { link, lstat, open, realpath, unlink } from 'node:fs/promises'; +import { chmod, link, lstat, open, readdir, realpath, rm, unlink } from 'node:fs/promises'; import { dirname, isAbsolute, join, resolve, sep } from 'node:path'; import { ControllerFailure, refuse, type ControllerDiagnostic } from './errors.js'; @@ -438,3 +438,30 @@ export async function copyVerifiedFileReadOnly( } } } + +/** Directories of a read-only tree refuse `rm`; restore owner write on every directory, never following links. A tree that vanishes mid-walk was discarded by someone else. */ +export async function removeTree(root: string, phase: ControllerDiagnostic['phase']): Promise { + const missing = (error: unknown) => (error as NodeJS.ErrnoException).code === 'ENOENT'; + try { + const openUp = async (abs: string): Promise => { + const info = await lstat(abs).catch(error => { + if (missing(error)) return null; + throw error; + }); + if (!info || info.isSymbolicLink() || !info.isDirectory()) return; + await chmod(abs, 0o700).catch(error => { + if (!missing(error)) throw error; + }); + for (const name of await readdir(abs).catch(error => { + if (missing(error)) return [] as string[]; + throw error; + })) { + await openUp(join(abs, name)); + } + }; + await openUp(root); + await rm(root, { recursive: true, force: true }); + } catch { + refuse('CLEANUP_FAILED', '', phase); + } +} diff --git a/packages/controller/src/local-check.ts b/packages/controller/src/local-check.ts index 3b36c62a..b47b74e9 100644 --- a/packages/controller/src/local-check.ts +++ b/packages/controller/src/local-check.ts @@ -1,5 +1,5 @@ import { constants } from 'node:fs'; -import { chmod, lstat, mkdir, open, readdir, rm } from 'node:fs/promises'; +import { chmod, lstat, mkdir, open, readdir } from 'node:fs/promises'; import { spawn, type ChildProcess } from 'node:child_process'; import { dirname, join } from 'node:path'; import { @@ -12,7 +12,7 @@ import { materializeAttemptWorkspace } from './candidate-workspace.js'; import type { Cycle } from './controller.js'; import { approvedState } from './config.js'; import { ControllerFailure, refuse, type ControllerDiagnostic } from './errors.js'; -import { readBoundedFile } from './files.js'; +import { readBoundedFile, removeTree } from './files.js'; import { parsePrivateJson } from './parser.js'; import { confirmProcessGroupGone, drainStream, killProcessGroup } from './process-group.js'; import { verifierOperationId } from './progress.js'; @@ -246,19 +246,6 @@ function createRollingTail(maxBytes: number): RollingTail { }; } -/** Directories of a read-only tree refuse `rm`; restore owner write on every directory, never following links. A tree that vanishes mid-walk was discarded by someone else. */ -async function removeTree(root: string, phase: ControllerDiagnostic['phase']): Promise { - const missing = (error: unknown) => (error as NodeJS.ErrnoException).code === 'ENOENT'; - try { - const openUp = async (abs: string): Promise => { - const info = await lstat(abs).catch(error => { if (missing(error)) return null; throw error; }); if (!info || info.isSymbolicLink() || !info.isDirectory()) return; - await chmod(abs, 0o700).catch(error => { if (!missing(error)) throw error; }); - for (const name of await readdir(abs).catch(error => { if (missing(error)) return []; throw error; })) await openUp(join(abs, name)); - }; - await openUp(root); - await rm(root, { recursive: true, force: true }); - } catch { refuse('CLEANUP_FAILED', '', phase); } -} async function makeReadOnlyTree(root: string): Promise { const visit = async (abs: string): Promise => { const info = await lstat(abs); diff --git a/packages/controller/src/recovery.ts b/packages/controller/src/recovery.ts index a8271fce..b6f31653 100644 --- a/packages/controller/src/recovery.ts +++ b/packages/controller/src/recovery.ts @@ -1,10 +1,13 @@ +import { lstat } from 'node:fs/promises'; import { dirname, join, resolve } from 'node:path'; import { validateDocument } from '@loopwright/core'; -import { reopenLocalRun, type Authority, type LocalRunStore } from '@loopwright/state'; +import { reopenLocalRun, type Authority, type LocalRunStore, type OperationReceipt, type OperationRecord } from '@loopwright/state'; import { approvedState } from './config.js'; import { recordedLocalCheck } from './compile.js'; import { ControllerFailure, refuse, result } from './errors.js'; +import { readBoundedFile, removeTree } from './files.js'; import { ControllerOwner } from './ownership.js'; +import { confirmProcessGroupGone } from './process-group.js'; import { admitRetainedRun, effectiveRunHostPolicy, @@ -20,7 +23,7 @@ import { ControllerEvents } from './events.js'; import { Finalizer, type ControllerIncident } from './finalize.js'; import { parsePrivateJson } from './parser.js'; import { boundFindingsForObservations, hydrateStepVerdicts, normalizeSubmission, type RetainedSubmission } from './submission.js'; -import { freeze, record, same } from './schema.js'; +import { digestValue, freeze, hash, id, isRecord, record, same } from './schema.js'; import { Verifier, prepareVerification, verifierProofPaths, type ByteInventory } from './verification.js'; import { Gate, GATE_OUTPUT_BYTES, prepareGate, validateGateUrlOverrides } from './gate.js'; import { LOCAL_CHECK_OUTPUT_BYTES, LocalCheck, prepareLocalCheck } from './local-check.js'; @@ -34,7 +37,18 @@ import { } from './benchmark-gate.js'; import { Publication, preparePublication } from './publication.js'; import { countDelegatedBudgets } from './budget-observations.js'; -import { executeCycleContext, isHaltedByVerdict, type CycleContext, type ControllerPorts, type RunCycleInput } from './controller.js'; +import { + EXEC_MARKER_BYTES, + EXEC_ROLE_PRODUCER_ID, + execMarkerPath, + execOperationId, + executeCycleContext, + isHaltedByVerdict, + writeExecMarker, + type CycleContext, + type ControllerPorts, + type RunCycleInput, +} from './controller.js'; import type { CycleExecution, PlannedRole } from './types.js'; export async function restoredCandidate(context: CycleContext, head: ProgressHead | null): Promise { @@ -115,8 +129,205 @@ export async function retainedPrimary(context: CycleContext, head: ProgressHead) if (incident.version !== 1 || incident.runId !== context.lock.spec.runId || !same(incident.lockHash, context.lock.spec.lockHash) || incident.code !== intent.primary) refuse('RECOVERY_REQUIRED', '', 'recovery'); return freeze({ kind: 'incident', version: 1, incident: incident as unknown as ControllerIncident }); } +async function settleInterruptedExec(context: CycleContext, operation: OperationRecord): Promise { + const { plan, lock, store, authority, artifacts, directory } = context; + const dispatch = operation.dispatch; + if (!dispatch || operation.linkedRequestId !== null) refuse('RECOVERY_REQUIRED', '', 'recovery'); + let attemptId: string; + try { + attemptId = id(operation.intent.attemptId); + } catch { + refuse('RECOVERY_REQUIRED', '', 'recovery'); + } + if (operation.intent.operationId !== execOperationId(lock.spec.runId, attemptId)) { + refuse('RECOVERY_REQUIRED', '', 'recovery'); + } + const expectedAttemptDir = join(dirname(directory), 'workspaces', lock.spec.runId, attemptId); + await artifacts.owner.assertCurrent(); + stateValue(store.renew(authority)); + const view = stateValue(store.inspect()); + if (view.clockStatus !== 'trusted') refuse('RECOVERY_REQUIRED', '', 'recovery'); + + const bindingPath = execMarkerPath(artifacts.directory, operation.intent.operationId, 'binding'); + const hasBinding = await lstat(bindingPath).then( + () => true, + error => { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false; + throw error; + }, + ); + let binding: Record | null = null; + let pgid: number | null = null; + if (hasBinding) { + let bindingBytes: Buffer; + try { + bindingBytes = await readBoundedFile(bindingPath, EXEC_MARKER_BYTES, true); + } catch (error) { + if (error instanceof ControllerFailure && (error.diagnostic.code === 'REGISTRY_UNTRUSTED' || error.diagnostic.code === 'CONFIG_LIMIT')) { + refuse('RECOVERY_REQUIRED', '', 'recovery'); + } + throw error; + } + let raw: Record; + let receipt: Record; + let promptDigest: unknown; + try { + raw = record(parsePrivateJson(bindingBytes, EXEC_MARKER_BYTES), [ + 'version', + 'planDigest', + 'operationId', + 'attemptId', + 'nodeId', + 'roleId', + 'promptDigest', + 'intentDigest', + 'dispatchReceipt', + 'pgid', + 'workspaceDir', + ]); + receipt = record(raw.dispatchReceipt, ['generation', 'dispatchId', 'revision', 'clockEpoch']); + promptDigest = digestValue(raw.promptDigest); + } catch { + refuse('RECOVERY_REQUIRED', '', 'recovery'); + } + if ( + raw.version !== 1 + || !same(raw.planDigest, plan.planDigest) + || raw.operationId !== operation.intent.operationId + || raw.attemptId !== attemptId + || raw.nodeId !== operation.intent.nodeId + || typeof raw.roleId !== 'string' + || !plan.roles.some(r => r.roleId === raw.roleId && r.adapter === 'exec') + || !promptDigest + || !same(raw.intentDigest, operation.intentDigest) + || !(raw.pgid === null || (typeof raw.pgid === 'number' && Number.isSafeInteger(raw.pgid) && raw.pgid > 0)) + || raw.workspaceDir !== expectedAttemptDir + || !same(receipt, { + generation: dispatch.generation, + dispatchId: dispatch.dispatchId, + revision: dispatch.revision, + clockEpoch: view.clock.basis.clockEpoch, + }) + ) { + refuse('RECOVERY_REQUIRED', '', 'recovery'); + } + pgid = raw.pgid as number | null; + binding = raw; + } + + if (pgid !== null) { + await confirmProcessGroupGone(pgid, 'recovery'); + } + await removeTree(expectedAttemptDir, 'recovery'); + + const proofPath = execMarkerPath(artifacts.directory, operation.intent.operationId, 'proof'); + const hasProof = await lstat(proofPath).then( + () => true, + error => { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false; + throw error; + }, + ); + if (hasProof) { + try { + const proofBytes = await readBoundedFile(proofPath, EXEC_MARKER_BYTES, true); + const parsedProof = record(parsePrivateJson(proofBytes, EXEC_MARKER_BYTES), [ + 'version', + 'operationId', + 'attemptId', + 'pgid', + 'outcome', + 'capture', + 'settled', + ]); + if ( + parsedProof.version !== 1 + || parsedProof.operationId !== operation.intent.operationId + || parsedProof.attemptId !== attemptId + || !isRecord(parsedProof) + ) { + refuse('RECOVERY_REQUIRED', '', 'recovery'); + } + } catch (error) { + if (error instanceof ControllerFailure && ['RECOVERY_REQUIRED', 'REGISTRY_UNTRUSTED', 'CONFIG_LIMIT', 'CONFIG_SCHEMA', 'ARTIFACT_INVALID'].includes(error.diagnostic.code)) { + refuse('RECOVERY_REQUIRED', '', 'recovery'); + } + throw error; + } + } else { + await writeExecMarker( + artifacts, + operation.intent.operationId, + 'proof', + { + version: 1, + operationId: operation.intent.operationId, + attemptId, + pgid, + outcome: null, + capture: null, + settled: 'unknown', + }, + 'recovery', + ); + } + + stateValue(store.renew(authority)); + const latestView = stateValue(store.inspect()); + const settlementRef = await artifacts.json( + 'exec-settlement', + { + version: 1, + operationId: operation.intent.operationId, + attemptId, + binding, + settled: 'unknown', + }, + 65_536, + ); + const suffix = hash(operation.intent.operationId).hex.slice(0, 40); + const receipt: OperationReceipt = { + receiptId: 'receipt.' + suffix, + outcome: 'failed', + evidence: { + evidenceId: 'receipt-evidence.' + suffix, + producerId: EXEC_ROLE_PRODUCER_ID, + method: 'exec_unknown', + subject: { + storeId: latestView.storeId, + runId: latestView.runId, + lockHash: latestView.lockHash, + operationId: operation.intent.operationId, + requestId: null, + intentDigest: operation.intentDigest, + dispatchGeneration: dispatch.generation, + dispatchId: dispatch.dispatchId, + }, + artifact: settlementRef, + }, + }; + stateValue(store.reconcileOperation(authority, operation.intent.operationId, receipt)); +} + export async function reconcileInterruptedOperations(context: CycleContext, head: ProgressHead | null, candidate: ByteInventory, storeId: string): Promise { const { plan, lock, store, authority, artifacts, loaded, source, descriptor, ports, directory } = context; + for (const operation of journal(store).operations) { + if ( + operation.intent.effect === 'local_write' + && operation.intent.targetIdentity.startsWith('exec:') + && operation.state === 'dispatch_uncertain' + ) { + await settleInterruptedExec(context, operation); + } + } + const activeAttempt = head?.progress.attempts.at(-1); + if (activeAttempt && activeAttempt.finished === null) { + const activeNode = plan.orderedDAG.find(node => node.id === activeAttempt.nodeId); + const activeRole = activeNode?.roleId ? plan.roles.find(role => role.roleId === activeNode.roleId) : undefined; + if (activeRole?.adapter === 'exec') { + await removeTree(join(dirname(directory), 'workspaces', lock.spec.runId, id(activeAttempt.id)), 'recovery'); + } + } if (head?.progress.stage.kind === 'verifier_pre') { const row = head.progress.verifierReceipts.find(item => item.generation === head.progress.candidate.generation && item.receipt === null); if (row) { @@ -239,6 +450,14 @@ export function resumeCycleWithPorts(input: RunCycleInput, ports: ControllerPort const activeNodes = head ? head.progress.nodes : plan.orderedDAG.map(node => ({ id: node.id, state: 'pending' as const })); const attempts = head?.progress.attempts ?? []; const lastAttempt = attempts.at(-1); + const isExecNode = (nodeId: string): boolean => { + const dagNode = plan.orderedDAG.find(item => item.id === nodeId); + const role = dagNode?.roleId ? plan.roles.find(item => item.roleId === dagNode.roleId) : undefined; + return dagNode?.kind === 'agent' && role?.adapter === 'exec'; + }; + if (lastAttempt !== undefined && lastAttempt.finished === null && isExecNode(lastAttempt.nodeId)) { + refuse('RECOVERY_REQUIRED', '', 'recovery'); + } const unfinishedDelegated = lastAttempt !== undefined && lastAttempt.finished === null && isDelegatedNode(lastAttempt.nodeId); const reachableDelegated = activeNodes.some(node => (node.state === 'pending' || node.state === 'running') && isDelegatedNode(node.id)); const formatRepairDelegated = Boolean(lastAttempt?.finished?.nativeCheckpointId) diff --git a/packages/controller/src/retained.ts b/packages/controller/src/retained.ts index 14c44066..9dfa1c8a 100644 --- a/packages/controller/src/retained.ts +++ b/packages/controller/src/retained.ts @@ -3,7 +3,7 @@ import { lstat } from 'node:fs/promises'; import { admitTask, validateDocument } from '@loopwright/core'; import type { LocalRunIdentity } from '@loopwright/state'; import { approvedState, loadConfiguration } from './config.js'; -import { compilePlan } from './compile.js'; +import { compilePlan, isExecRole } from './compile.js'; import { readBoundedFile, canonicalComponents } from './files.js'; import { checkedRef, readArtifact, type ArtifactReader } from './storage.js'; import { parsePrivateJson } from './parser.js'; @@ -101,6 +101,11 @@ export function resolveStoreLeaseMs(configuration: LoadedConfiguration, plan: Co const durationMs = slot.handler.implementation === 'benchmark-gate.v1' ? Math.max(ep.timeoutMs, ep.maxPollMs) : ep.timeoutMs; if (durationMs > maxEndpointDurationMs) maxEndpointDurationMs = durationMs; } + for (const role of plan.roles) { + if (isExecRole(role)) { + maxEndpointDurationMs = Math.max(maxEndpointDurationMs, role.exec.timeoutMs); + } + } return maxEndpointDurationMs > 30000 ? Math.min(3700000, maxEndpointDurationMs + 30000) : 60000; } diff --git a/packages/controller/src/step.ts b/packages/controller/src/step.ts index fc83df06..4b3210dd 100644 --- a/packages/controller/src/step.ts +++ b/packages/controller/src/step.ts @@ -29,6 +29,7 @@ import { adoptDelegatedCapture, captureDelegatedRole, nativeSessionId, + synthesizedStepOutput, type DelegatedCapturePayloadV2, } from './capture.js'; import { @@ -40,7 +41,7 @@ import { restoreSource, type HostPathProtectionOptions, } from './source.js'; -import { isVerdictStep, normalizeSubmission, validateStepVerdictObject, type RetainedSubmission, type Submission } from './submission.js'; +import { isVerdictStep, normalizeSubmission, validateStepVerdictObject, type RetainedSubmission } from './submission.js'; import { evaluateControllerAcceptance, verifyControllerVerifierCasDescriptors, @@ -855,6 +856,12 @@ async function runStepTickWithCycle( return settled; } +function refuseExecPlan(plan: CompiledPlan, phase: ControllerDiagnostic['phase']): void { + if (plan.roles.some(role => role.adapter === 'exec')) { + refuse('CAPABILITY_UNSUPPORTED', '/spec/profiles/roles', phase); + } +} + async function reopenStepContext(input: { readonly runRoot: string; readonly runId: string; @@ -883,6 +890,7 @@ async function reopenStepContext(input: { ...(input.environment ? { environment: input.environment } : {}), phase: input.phase, }); + refuseExecPlan(plan, input.phase); const meta = await readStepMeta(directory, effectiveRunHostPolicy(descriptor)); const effectivePorts = validatePortsAgainstHostPolicy(input.ports, meta.hostPolicy, input.phase); const effectiveDescriptor = descriptor.hostPolicy !== undefined ? descriptor : { ...descriptor, hostPolicy: meta.hostPolicy }; @@ -1157,6 +1165,7 @@ export function stepNext(input: StepNextInput, ports: ControllerPorts = {}) { if (!input.configuration || input.repository === undefined) refuse('CONFIG_SCHEMA', '', 'admission'); const compiled = await compilePlan(input.configuration); if (!compiled.ok) throw new ControllerFailure(compiled.error); + refuseExecPlan(compiled.value, 'admission'); validateGateUrlOverrides(ports.gateUrlOverrides, 'admission', input.configuration.registry.spec.gateEndpoints); if (input.mode === 'no-change' && !compiled.value.noChangeEligibility.available) { refuse('CAPABILITY_UNSUPPORTED', '/mode', 'admission'); @@ -1510,36 +1519,12 @@ export function stepSubmit(input: StepSubmitInput, ports: ControllerPorts = {}) assistantText = new TextDecoder('utf-8', { fatal: true }).decode(explicitSubmissionBytes); submissionBytes = explicitSubmissionBytes; } else if (artifactSubmissionFile === undefined || active.repair === 'format' || ignoreArtifactPath) { - if (isVerdictStep(activeNode)) { - const syntheticVerdict: StepVerdict = { - verdict: effectiveStatus === 'failed' ? 'fail' : effectiveStatus === 'blocked' ? 'human' : 'pass', - summary: effectiveReason ?? 'Passed via step submit.', - findings: [], - }; - assistantText = canonical(syntheticVerdict); - submissionBytes = new Uint8Array(Buffer.from(assistantText, 'utf8')); - } else { - const checkStatus = - effectiveStatus === 'completed' || effectiveStatus === 'no_change' - ? ('passed' as const) - : effectiveStatus === 'blocked' - ? ('blocked' as const) - : ('failed' as const); - const checkReason = checkStatus === 'passed' ? null : (effectiveReason ?? 'check_not_satisfied'); - const synthetic: Submission = { - version: 1, - status: effectiveStatus, - checks: context.plan.task.spec.acceptance.checks.map(check => ({ - checkId: check.id, - status: checkStatus, - evidenceId: null, - reason: checkReason, - })), - reason: effectiveReason, - }; - assistantText = canonical(synthetic); - submissionBytes = new Uint8Array(Buffer.from(assistantText, 'utf8')); - } + ({ assistantText, submissionBytes } = synthesizedStepOutput( + context.plan.task, + isVerdictStep(activeNode), + effectiveStatus, + effectiveReason, + )); } const payload: DelegatedCapturePayloadV2 = { diff --git a/packages/controller/test/delegated-compile.test.ts b/packages/controller/test/delegated-compile.test.ts index ec1c235b..0c64e048 100644 --- a/packages/controller/test/delegated-compile.test.ts +++ b/packages/controller/test/delegated-compile.test.ts @@ -1,13 +1,17 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import { writeFile } from 'node:fs/promises'; +import { lstat, mkdir, writeFile } from 'node:fs/promises'; +import { execFileSync } from 'node:child_process'; import { join } from 'node:path'; import { stringify } from 'yaml'; import { admitTask } from '@loopwright/core'; import { compilePlan } from '../src/compile.js'; import { loadConfiguration, approvedState } from '../src/config.js'; +import { runCycleWithPorts } from '../src/controller.js'; import { validateRegistry } from '../src/registry.js'; +import { stepNext } from '../src/step.js'; import { parseDocumentBytes } from '../src/parser.js'; +import { canonical } from '../src/schema.js'; import type { ControllerResult } from '../src/errors.js'; import type { RoleAdapterKind, @@ -15,6 +19,7 @@ import type { RoleSelectionOverride, RoleModelOverride, StepYield, + ExecPlannedRole, } from '../src/types.js'; import { configurationFixture, TOKEN } from './config-fixtures.js'; import { installedHandlerDigests } from '../src/handlers.js'; @@ -777,3 +782,364 @@ test('non-null profile.mcp on a delegated role validates scriptDigest and popula } }); +test('compilePlan compiles adapter: exec role without runtimeProfile, provider credential, or context guard, enforces credentialRefs parity, and refuses compaction and review steps', async () => { + const f = await configurationFixture(); + try { + const execSecret = 'EXEC_COMPILE_SECRET_Aa11Bb22Cc33'; + f.environment['LLM_TOKEN'] = execSecret; + set(f.registry, ['spec', 'runtimeProfiles'], []); + set(f.registry, ['spec', 'credentialBindings'], [{ + id: 'llm-token', + consumer: 'exec', + destinationRef: 'openai', + environmentNames: ['LLM_TOKEN'], + template: '${LLM_TOKEN}', + }]); + set(f.registry, ['spec', 'environmentBindings'], [{ + name: 'LLM_TOKEN', + classification: 'credential', + paths: ['/spec/credentials/0/template'], + }]); + set(f.registry, ['spec', 'roleProfiles'], [{ + id: 'author', + adapter: 'exec', + runtimeRef: null, + providerCredentialRef: null, + selection: { provider: 'openai', model: 'gpt-5', thinking: 'medium' }, + tools: ['read', 'write', 'edit'], + context: { + mode: 'estimated_guard', + estimator: 'lw-pi-final-json-bytes-v1', + proofId: null, + version: 1, + evidence: 'estimated', + workingWindowCeiling: 98304, + maxRequestBytes: 65536, + serviceMargin: 32768, + toolReserve: 16384, + maxOutputTokens: 1, + }, + mcp: null, + limits: { requests: 16 }, + exec: { + command: ['/usr/local/bin/forgevo-author'], + args: ['--strict'], + env: { FORGEVO_LLM_BASE_URL: 'https://api.example.com/v1' }, + credentialRefs: ['llm-token'], + timeoutMs: 60000, + captureBytes: 32768, + }, + }]); + set(f.config, ['spec', 'credentials'], [{ ref: 'llm-token', template: '${LLM_TOKEN}' }]); + set(f.config, ['spec', 'profiles', 'roles'], [{ roleId: 'author', profileRef: 'author' }]); + set(f.config, ['spec', 'task', 'spec', 'budgets', 'perCallOutputTokens'], 1024); + set(f.config, ['spec', 'task', 'spec', 'roles'], [{ + id: 'author', + adapter: 'exec', + provider: 'openai', + model: 'gpt-5', + thinking: 'medium', + tools: ['read', 'write'], + }]); + set(f.config, ['spec', 'task', 'spec', 'steps'], [ + { id: 'build', kind: 'agent', uses: 'package.patch', roleId: 'author', dependsOn: [] }, + ]); + await f.save(); + + const loaded = good(await f.load()); + const plan = good(await compilePlan(loaded)); + assert.equal(plan.roles.length, 1); + const planned = plan.roles[0]! as ExecPlannedRole; + assert.equal(planned.roleId, 'author'); + assert.equal(planned.adapter, 'exec'); + assert.equal(planned.providerCredentialRef, null); + assert.equal(planned.runtime.id, 'exec.none'); + assert.equal(planned.runtime.dockerExecutable, '/nonexistent/exec.none'); + assert.equal(planned.runtime.dockerSocket, '/nonexistent/exec.none.sock'); + assert.deepEqual(planned.policy.tools, ['read', 'write']); + assert.deepEqual(planned.policy.mcp.names, []); + assert.deepEqual(planned.policy.mcp.effects, []); + assert.equal(planned.policy.limits.requests, 16); + assert.equal(planned.exec.timeoutMs, 60000); + assert.equal(planned.exec.captureBytes, 32768); + assert.deepEqual(planned.exec.args, ['--strict']); + assert.deepEqual(plan.credentialReferences, [ + { ref: 'llm-token', consumer: 'exec', destinationRef: 'openai' }, + ]); + assert.equal(canonical(plan).includes(execSecret), false); + + // Unreferenced vault credential fails credential set equality at compile + f.environment['UNUSED_TOKEN'] = execSecret; + set(f.registry, ['spec', 'credentialBindings'], [ + f.registry.spec.credentialBindings[0]!, + { + id: 'unused-token', + consumer: 'exec', + destinationRef: 'openai', + environmentNames: ['UNUSED_TOKEN'], + template: '${UNUSED_TOKEN}', + }, + ]); + set(f.registry, ['spec', 'environmentBindings'], [ + { + name: 'LLM_TOKEN', + classification: 'credential', + paths: ['/spec/credentials/0/template'], + }, + { + name: 'UNUSED_TOKEN', + classification: 'credential', + paths: ['/spec/credentials/1/template'], + }, + ]); + set(f.config, ['spec', 'credentials'], [ + { ref: 'llm-token', template: '${LLM_TOKEN}' }, + { ref: 'unused-token', template: '${UNUSED_TOKEN}' }, + ]); + await f.save(); + const extraVaultLoaded = good(await f.load()); + const extraVaultPlan = await compilePlan(extraVaultLoaded); + assert.equal(extraVaultPlan.ok, false); + if (!extraVaultPlan.ok) { + assert.equal(extraVaultPlan.error.code, 'CONFIG_REFERENCE'); + assert.equal(extraVaultPlan.error.path, '/spec/credentials'); + } + + // Restore single credential, test purpose: 'review' refusal (CONFIG_SCHEMA) + set(f.registry, ['spec', 'credentialBindings'], [f.registry.spec.credentialBindings[0]!]); + set(f.registry, ['spec', 'environmentBindings'], [{ + name: 'LLM_TOKEN', + classification: 'credential', + paths: ['/spec/credentials/0/template'], + }]); + set(f.config, ['spec', 'credentials'], [{ ref: 'llm-token', template: '${LLM_TOKEN}' }]); + const installed = await installedHandlerDigests(); + set(f.registry, ['spec', 'handlers'], [ + ...f.registry.spec.handlers, + { + id: 'package.review', + kind: 'agent', + implementation: 'pi.agent.v1', + version: 1, + digest: installed['pi.agent.v1'], + parameters: { prompt: 'Review the candidate.', purpose: 'review' }, + capabilities: ['pi'], + }, + ]); + set(f.config, ['spec', 'task', 'spec', 'steps'], [ + { id: 'build', kind: 'agent', uses: 'package.patch', roleId: 'author', dependsOn: [] }, + { id: 'review', kind: 'agent', uses: 'package.review', roleId: 'author', dependsOn: ['build'] }, + ]); + set(f.config, ['spec', 'profiles', 'steps'], [ + { stepId: 'build', handlerRef: 'package.patch' }, + { stepId: 'review', handlerRef: 'package.review' }, + ]); + await f.save(); + const reviewLoaded = good(await f.load()); + const reviewPlan = await compilePlan(reviewLoaded); + assert.equal(reviewPlan.ok, false); + if (!reviewPlan.ok) { + assert.equal(reviewPlan.error.code, 'CONFIG_SCHEMA'); + assert.equal(reviewPlan.error.phase, 'compile'); + } + + // Test pi.compact.v1 targeting exec role refuses CAPABILITY_UNSUPPORTED + set(f.registry, ['spec', 'handlers'], [ + ...f.registry.spec.handlers.filter(h => h.id !== 'package.review'), + { + id: 'compact.step', + kind: 'agent', + implementation: 'pi.compact.v1', + version: 1, + digest: installed['pi.compact.v1'], + parameters: {}, + capabilities: ['pi', 'compaction'], + }, + ]); + set(f.config, ['spec', 'task', 'spec', 'steps'], [ + { id: 'build', kind: 'agent', uses: 'package.patch', roleId: 'author', dependsOn: [] }, + { id: 'compact', kind: 'agent', uses: 'compact.step', roleId: 'author', dependsOn: ['build'] }, + ]); + set(f.config, ['spec', 'profiles', 'steps'], [ + { stepId: 'build', handlerRef: 'package.patch' }, + { stepId: 'compact', handlerRef: 'compact.step' }, + ]); + await f.save(); + const compactLoaded = good(await f.load()); + const compactPlan = await compilePlan(compactLoaded); + assert.equal(compactPlan.ok, false); + if (!compactPlan.ok) { + assert.equal(compactPlan.error.code, 'CAPABILITY_UNSUPPORTED'); + assert.equal(compactPlan.error.path, '/spec/profiles/steps'); + assert.equal(compactPlan.error.phase, 'compile'); + } + } finally { + await f.cleanup(); + } +}); + +test('compilePlan and runCycleWithPorts refuse mixed exec + pi and exec + delegated plans with CONFIG_SCHEMA before creating runRoot', async () => { + for (const otherAdapter of ['pi', 'delegated'] as const) { + const f = await configurationFixture(); + try { + const otherProfile = + otherAdapter === 'pi' + ? f.registry.spec.roleProfiles[0]! + : { + id: 'builder', + adapter: 'delegated' as const, + runtimeRef: null, + providerCredentialRef: null, + selection: { provider: 'antigravity', model: 'gemini-4-argon', thinking: 'low' }, + tools: ['read'], + mcp: null, + }; + const otherRole = + otherAdapter === 'pi' + ? f.config.spec.task.spec.roles[0]! + : { + id: 'builder', + adapter: 'delegated' as const, + provider: 'antigravity', + model: 'gemini-4-argon', + thinking: 'low', + tools: ['read'], + }; + if (otherAdapter === 'delegated') { + set(f.registry, ['spec', 'runtimeProfiles'], []); + set(f.registry, ['spec', 'credentialBindings'], []); + set(f.registry, ['spec', 'environmentBindings'], []); + set(f.config, ['spec', 'credentials'], []); + } + set(f.registry, ['spec', 'roleProfiles'], [ + otherProfile, + { + id: 'author', + adapter: 'exec', + runtimeRef: null, + providerCredentialRef: null, + selection: { provider: 'openai', model: 'gpt-5', thinking: 'medium' }, + tools: ['read', 'write'], + mcp: null, + exec: { command: ['/usr/local/bin/forgevo-author'], timeoutMs: 60000 }, + }, + ]); + set(f.config, ['spec', 'task', 'spec', 'roles'], [ + otherRole, + { + id: 'author', + adapter: 'exec', + provider: 'openai', + model: 'gpt-5', + thinking: 'medium', + tools: ['read', 'write'], + }, + ]); + set(f.config, ['spec', 'profiles', 'roles'], [ + { roleId: 'builder', profileRef: 'builder' }, + { roleId: 'author', profileRef: 'author' }, + ]); + await f.save(); + + const loaded = good(await f.load()); + const compiled = await compilePlan(loaded); + assert.equal(compiled.ok, false, `exec + ${otherAdapter} compile`); + if (!compiled.ok) { + assert.equal(compiled.error.code, 'CONFIG_SCHEMA'); + assert.equal(compiled.error.path, '/spec/task/spec/roles'); + assert.equal(compiled.error.phase, 'compile'); + } + + const runRoot = join(f.root, 'runs-never-created'); + const repository = join(f.root, 'repo'); + await mkdir(repository, { mode: 0o700 }); + const ran = await runCycleWithPorts({ + configuration: loaded, + repository, + runRoot, + runId: 'mixed-plan-run', + }); + assert.equal(ran.ok, false, `exec + ${otherAdapter} run`); + if (!ran.ok) { + assert.equal(ran.error.code, 'CONFIG_SCHEMA'); + assert.equal(ran.error.path, '/spec/task/spec/roles'); + } + assert.equal(await lstat(runRoot).then(() => true, () => false), false, 'runRoot not created'); + } finally { + await f.cleanup(); + } + } +}); + +test('stepNext refuses an all-exec plan with CAPABILITY_UNSUPPORTED at admission without creating the run directory', async () => { + const f = await configurationFixture(); + try { + const repository = join(f.root, 'repository'); + const runRoot = join(f.root, 'runs'); + await mkdir(repository, { mode: 0o700 }); + const gitEnv = { + PATH: '/usr/bin:/bin', + LANG: 'C', + LC_ALL: 'C', + GIT_CONFIG_NOSYSTEM: '1', + GIT_CONFIG_GLOBAL: '/dev/null', + HOME: '/nonexistent', + GIT_TERMINAL_PROMPT: '0', + }; + const git = (args: string[]) => execFileSync('/usr/bin/git', ['-c', 'core.hooksPath=/dev/null', ...args], { cwd: repository, env: gitEnv, encoding: 'utf8' }); + git(['init', '-q']); + await writeFile(join(repository, 'result.json'), JSON.stringify({ ok: true }), { mode: 0o600 }); + git(['add', 'result.json']); + git(['-c', 'user.name=Fixture', '-c', 'user.email=fixture@localhost.invalid', 'commit', '-qm', 'init']); + const revision = git(['rev-parse', 'HEAD']).trim(); + + set(f.registry, ['spec', 'runtimeProfiles'], []); + set(f.registry, ['spec', 'credentialBindings'], []); + set(f.registry, ['spec', 'environmentBindings'], []); + set(f.registry, ['spec', 'roleProfiles'], [{ + id: 'author', + adapter: 'exec', + runtimeRef: null, + providerCredentialRef: null, + selection: { provider: 'openai', model: 'gpt-5', thinking: 'medium' }, + tools: ['read', 'write'], + mcp: null, + exec: { command: ['/usr/local/bin/forgevo-author'], timeoutMs: 60000 }, + }]); + set(f.config, ['spec', 'credentials'], []); + set(f.config, ['spec', 'profiles', 'roles'], [{ roleId: 'author', profileRef: 'author' }]); + set(f.config, ['spec', 'task', 'spec', 'target', 'baseRevision'], revision); + set(f.config, ['spec', 'task', 'spec', 'target', 'sourceRevision'], revision); + set(f.config, ['spec', 'task', 'spec', 'roles'], [{ + id: 'author', + adapter: 'exec', + provider: 'openai', + model: 'gpt-5', + thinking: 'medium', + tools: ['read', 'write'], + }]); + set(f.config, ['spec', 'task', 'spec', 'steps'], [ + { id: 'build', kind: 'agent', uses: 'package.patch', roleId: 'author', dependsOn: [] }, + ]); + await f.save(); + + const loaded = good(await f.load()); + const res = await stepNext({ + configuration: loaded, + repository, + runRoot, + runId: 'exec-step-next-refused', + }); + assert.equal(res.ok, false); + if (!res.ok) { + assert.equal(res.error.code, 'CAPABILITY_UNSUPPORTED'); + assert.equal(res.error.path, '/spec/profiles/roles'); + assert.equal(res.error.phase, 'admission'); + } + assert.equal(await lstat(join(runRoot, 'exec-step-next-refused')).then(() => true, () => false), false, 'run directory not created'); + } finally { + await f.cleanup(); + } +}); + + diff --git a/packages/controller/test/exec-role-integration.test.ts b/packages/controller/test/exec-role-integration.test.ts new file mode 100644 index 00000000..8506af5d --- /dev/null +++ b/packages/controller/test/exec-role-integration.test.ts @@ -0,0 +1,867 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import { chmod, lstat, mkdir, readFile, readdir, writeFile } from 'node:fs/promises'; +import { join } from 'node:path'; +import { reopenLocalRun } from '@loopwright/state'; +import type { ArtifactRef } from '@loopwright/core'; +import { inspectRun, runCycleWithPorts, stepCancel, stepNext, stepSubmit, type CycleExecution } from '../src/index.js'; +import type { RunDescriptor } from '../src/controller.js'; +import { ControllerFailure, type ControllerDiagnostic } from '../src/errors.js'; +import { installedHandlerDigests } from '../src/handlers.js'; +import { ControllerOwner } from '../src/ownership.js'; +import { parsePrivateJson } from '../src/parser.js'; +import { journal, phaseCheckpointId, ProgressStore } from '../src/progress.js'; +import { hash } from '../src/schema.js'; +import { stateValue } from '../src/storage.js'; +import { normalizeSubmission } from '../src/submission.js'; +import { configurationFixture } from './config-fixtures.js'; +import { setFixture } from './progress-fixtures.js'; + +const CANARY_SECRET = 'EXEC_INTEGRATION_CANARY_Zz99Yy88Xx77'; +const GIT_ENV = Object.freeze({ + PATH: '/usr/bin:/bin', + LANG: 'C', + LC_ALL: 'C', + GIT_CONFIG_NOSYSTEM: '1', + GIT_CONFIG_GLOBAL: '/dev/null', + HOME: '/nonexistent', + GIT_TERMINAL_PROMPT: '0', +}); + +const STUB_SOURCE = `import { spawn } from 'node:child_process'; +import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; + +const mode = process.argv[2] ?? ''; +const promptFile = process.argv.at(-2) ?? ''; +const candidateDir = process.argv.at(-1) ?? ''; + +function writeCandidate(relPath, content) { + const full = join(candidateDir, relPath); + mkdirSync(dirname(full), { recursive: true, mode: 0o700 }); + writeFileSync(full, content, { mode: 0o600 }); +} + +if (mode === 'write-inside') { + writeCandidate('packages/hello.txt', 'hello\\n'); + process.stdout.write('Plain free-text commentary, not JSON at all!\\n'); + process.exit(0); +} +if (mode === 'write-inside-with-usage') { + writeCandidate('packages/hello.txt', 'hello\\n'); + writeFileSync( + process.env.LOOPWRIGHT_USAGE_OUT, + JSON.stringify({ requests: [{ requestId: 'req_1', inputTokens: 80, outputTokens: 20, costMicrousd: 900 }] }), + { mode: 0o600 }, + ); + process.exit(0); +} +if (mode === 'write-outside') { + writeCandidate('docs/outside.txt', 'outside\\n'); + process.exit(0); +} +if (mode === 'exit-3') { + process.stderr.write('diagnostic context\\nneed a human decision\\n'); + process.exit(3); +} +if (mode === 'exit-7') { + process.stderr.write('step failed hard\\n'); + process.exit(7); +} +if (mode === 'print-env') { + writeCandidate('packages/hello.txt', 'hello\\n'); + const prompt = readFileSync(promptFile, 'utf8'); + process.stdout.write(JSON.stringify({ env: process.env, argv: process.argv, cwd: process.cwd(), prompt })); + process.exit(0); +} +if (mode === 'print-secret') { + writeCandidate('packages/hello.txt', 'hello\\n'); + const secret = process.env.LLM_TOKEN ?? ''; + process.stdout.write('out=' + secret + '\\n'); + process.stderr.write('err=' + secret + '\\n'); + process.exit(0); +} +if (mode === 'fork-bg-exit-0') { + const bg = spawn(process.execPath, ['-e', 'setTimeout(() => {}, 60_000)'], { stdio: 'ignore' }); + bg.unref(); + process.exit(0); +} +if (mode === 'sleep') { + setTimeout(() => {}, 60_000); +} else { + process.stderr.write('unknown mode: ' + mode + '\\n'); + process.exit(2); +} +`; + +function assertOk(res: { readonly ok: boolean; readonly value?: T; readonly error?: ControllerDiagnostic }, msg = ''): T { + assert.equal(res.ok, true, `${msg}: ${JSON.stringify(res.error)}`); + if (!res.ok) throw new Error('expected ok'); + return res.value as T; +} + +function groupGone(pgid: number): boolean { + try { + process.kill(-pgid, 0); + return false; + } catch (error) { + return (error as NodeJS.ErrnoException).code === 'ESRCH'; + } +} + +async function waitForJsonFile(path: string, timeoutMs = 10_000): Promise> { + const deadline = Date.now() + timeoutMs; + for (;;) { + try { + return JSON.parse(await readFile(path, 'utf8')) as Record; + } catch { + if (Date.now() >= deadline) throw new Error('Timed out waiting for ' + path); + await new Promise(resolve => setTimeout(resolve, 20)); + } + } +} + +async function findBindingMarker(artifactsDir: string, timeoutMs = 10_000): Promise<{ readonly path: string; readonly data: Record }> { + const deadline = Date.now() + timeoutMs; + for (;;) { + const names = await readdir(artifactsDir).catch(() => [] as string[]); + const found = names.find(name => /^exec-role-producer-[0-9a-f]{64}\.binding\.json$/.test(name)); + if (found) { + const full = join(artifactsDir, found); + const data = await waitForJsonFile(full, 5_000); + return { path: full, data }; + } + if (Date.now() >= deadline) throw new Error('Timed out waiting for exec binding marker in ' + artifactsDir); + await new Promise(resolve => setTimeout(resolve, 20)); + } +} + +async function cleanupFixtureRoot(root: string): Promise { + const openUp = async (abs: string): Promise => { + const st = await lstat(abs).catch(() => null); + if (!st || st.isSymbolicLink() || !st.isDirectory()) return; + await chmod(abs, 0o700).catch(() => undefined); + for (const entry of await readdir(abs).catch(() => [] as string[])) { + await openUp(join(abs, entry)); + } + }; + await openUp(root); +} + +interface ExecFixtureOptions { + readonly mode?: string; + readonly timeoutMs?: number; + readonly resultOk?: boolean; + readonly verifyOnRework?: number; + readonly maxImplementationRepairs?: number; + readonly withResource?: boolean; + readonly wallTimeMs?: number; + readonly drainReserveMs?: number; + readonly multiAgentSecondMode?: string; + readonly parallelFailingCheck?: boolean; +} + +async function execIntegrationFixture(options: ExecFixtureOptions = {}) { + const f = await configurationFixture(); + const repository = join(f.root, 'repository'); + const runRoot = join(f.root, 'runs'); + const stubPath = join(f.operator, 'exec-stub.mjs'); + await mkdir(repository, { mode: 0o700 }); + await writeFile(stubPath, STUB_SOURCE, { mode: 0o600 }); + + const resultOk = options.resultOk ?? true; + await writeFile(join(repository, 'result.json'), JSON.stringify({ ok: resultOk }), { mode: 0o600 }); + await mkdir(join(repository, 'packages'), { mode: 0o700 }); + await writeFile(join(repository, 'packages', 'seed.txt'), 'seed\n', { mode: 0o600 }); + + const git = (args: string[]) => execFileSync('/usr/bin/git', ['-c', 'core.hooksPath=/dev/null', ...args], { cwd: repository, env: GIT_ENV, encoding: 'utf8' }); + git(['init', '-q']); + git(['add', '.']); + git(['-c', 'user.name=Controller Fixture', '-c', 'user.email=fixture@localhost.invalid', 'commit', '-qm', 'initial baseline']); + const revision = git(['rev-parse', 'HEAD']).trim(); + + f.environment['LLM_TOKEN'] = CANARY_SECRET; + + const resources: { id: string; kind: 'instruction'; path: string; digest: ReturnType }[] = []; + if (options.withResource) { + const docBytes = Buffer.from('# Author Context\nFollow scope rules.\n', 'utf8'); + await writeFile(join(f.operator, 'guide.md'), docBytes, { mode: 0o600 }); + resources.push({ id: 'author-guide', kind: 'instruction', path: 'guide.md', digest: hash(docBytes) }); + } + + const installed = await installedHandlerDigests(); + const extraHandlers = options.parallelFailingCheck + ? [{ + id: 'early-check', + kind: 'check' as const, + implementation: 'json-artifact.v1' as const, + version: 1 as const, + digest: installed['json-artifact.v1'], + parameters: { checkId: 'early', path: 'result.json', required: ['ok'], equals: { ok: true } }, + capabilities: ['inert_bytes', 'read_only'], + }] + : []; + + const secondRoleProfile = options.multiAgentSecondMode !== undefined + ? [{ + id: 'finisher', + adapter: 'exec' as const, + runtimeRef: null, + providerCredentialRef: null, + selection: { provider: 'openai', model: 'gpt-5', thinking: 'medium' }, + tools: ['read', 'write', 'edit'], + mcp: null, + exec: { + command: [process.execPath, stubPath], + args: [options.multiAgentSecondMode], + env: { FORGEVO_LLM_BASE_URL: 'https://api.example.com/v1' }, + credentialRefs: ['llm-token'], + timeoutMs: options.timeoutMs ?? 20_000, + }, + }] + : []; + + setFixture(f.registry, ['spec', 'runtimeProfiles'], []); + setFixture(f.registry, ['spec', 'resources'], resources); + setFixture(f.registry, ['spec', 'handlers'], [...f.registry.spec.handlers, ...extraHandlers]); + setFixture(f.registry, ['spec', 'credentialBindings'], [{ + id: 'llm-token', + consumer: 'exec', + destinationRef: 'openai', + environmentNames: ['LLM_TOKEN'], + template: '${LLM_TOKEN}', + }]); + setFixture(f.registry, ['spec', 'environmentBindings'], [{ + name: 'LLM_TOKEN', + classification: 'credential', + paths: ['/spec/credentials/0/template'], + }]); + setFixture(f.registry, ['spec', 'roleProfiles'], [ + { + id: 'author', + adapter: 'exec', + runtimeRef: null, + providerCredentialRef: null, + selection: { provider: 'openai', model: 'gpt-5', thinking: 'medium' }, + tools: ['read', 'write', 'edit'], + mcp: null, + exec: { + command: [process.execPath, stubPath], + args: [options.mode ?? 'write-inside'], + env: { FORGEVO_LLM_BASE_URL: 'https://api.example.com/v1' }, + credentialRefs: ['llm-token'], + timeoutMs: options.timeoutMs ?? 20_000, + }, + }, + ...secondRoleProfile, + ]); + + setFixture(f.config, ['spec', 'credentials'], [{ ref: 'llm-token', template: '${LLM_TOKEN}' }]); + if (options.drainReserveMs !== undefined) { + setFixture(f.config, ['spec', 'controls', 'drainReserveMs'], options.drainReserveMs); + } + if (options.wallTimeMs !== undefined) { + setFixture(f.config, ['spec', 'task', 'spec', 'budgets', 'wallTimeMs'], options.wallTimeMs); + } + if (options.maxImplementationRepairs !== undefined) { + setFixture(f.config, ['spec', 'task', 'spec', 'budgets', 'maxImplementationRepairs'], options.maxImplementationRepairs); + } + setFixture(f.config, ['spec', 'task', 'spec', 'target', 'baseRevision'], revision); + setFixture(f.config, ['spec', 'task', 'spec', 'target', 'sourceRevision'], revision); + if (resources.length > 0) { + setFixture(f.config, ['spec', 'task', 'spec', 'trustedContext', 'resources'], resources); + } + setFixture(f.config, ['spec', 'task', 'spec', 'roles'], [ + { + id: 'author', + adapter: 'exec', + provider: 'openai', + model: 'gpt-5', + thinking: 'medium', + tools: ['read', 'write'], + ...(resources.length > 0 ? { resourceIds: resources.map(r => r.id) } : {}), + }, + ...(options.multiAgentSecondMode !== undefined + ? [{ + id: 'finisher', + adapter: 'exec' as const, + provider: 'openai', + model: 'gpt-5', + thinking: 'medium', + tools: ['read', 'write'], + }] + : []), + ]); + setFixture(f.config, ['spec', 'profiles', 'roles'], [ + { roleId: 'author', profileRef: 'author' }, + ...(options.multiAgentSecondMode !== undefined ? [{ roleId: 'finisher', profileRef: 'finisher' }] : []), + ]); + + if (options.parallelFailingCheck) { + setFixture(f.config, ['spec', 'task', 'spec', 'acceptance'], { + required: ['early', 'tests'], + checks: [ + { id: 'early', allowedEvidenceLevels: ['local_execution'] }, + { id: 'tests', allowedEvidenceLevels: ['local_execution'] }, + ], + }); + setFixture(f.config, ['spec', 'task', 'spec', 'steps'], [ + { id: 'a-early', kind: 'check', uses: 'early-check', roleId: null, dependsOn: [] }, + { id: 'implement', kind: 'agent', uses: 'package.patch', roleId: 'author', dependsOn: [] }, + { id: 'verify', kind: 'check', uses: 'tests', roleId: null, dependsOn: ['implement'] }, + ]); + setFixture(f.config, ['spec', 'profiles', 'steps'], [ + { stepId: 'a-early', handlerRef: 'early-check' }, + { stepId: 'implement', handlerRef: 'package.patch' }, + { stepId: 'verify', handlerRef: 'tests' }, + ]); + } else if (options.multiAgentSecondMode !== undefined) { + setFixture(f.config, ['spec', 'task', 'spec', 'steps'], [ + { id: 'implement', kind: 'agent', uses: 'package.patch', roleId: 'author', dependsOn: [] }, + { id: 'finish', kind: 'agent', uses: 'package.patch', roleId: 'finisher', dependsOn: ['implement'] }, + { id: 'verify', kind: 'check', uses: 'tests', roleId: null, dependsOn: ['finish'] }, + ]); + setFixture(f.config, ['spec', 'profiles', 'steps'], [ + { stepId: 'implement', handlerRef: 'package.patch' }, + { stepId: 'finish', handlerRef: 'package.patch' }, + { stepId: 'verify', handlerRef: 'tests' }, + ]); + } else { + setFixture(f.config, ['spec', 'task', 'spec', 'steps'], [ + { id: 'implement', kind: 'agent', uses: 'package.patch', roleId: 'author', dependsOn: [] }, + { + id: 'verify', + kind: 'check', + uses: 'tests', + roleId: null, + dependsOn: ['implement'], + ...(options.verifyOnRework !== undefined ? { onRework: { rejectTo: 'implement', maxReworks: options.verifyOnRework } } : {}), + }, + ]); + setFixture(f.config, ['spec', 'profiles', 'steps'], [ + { stepId: 'implement', handlerRef: 'package.patch' }, + { stepId: 'verify', handlerRef: 'tests' }, + ]); + } + + await f.save(); + const loaded = assertOk(await f.load(), 'load exec fixture'); + return { + ...f, + repository, + runRoot, + stubPath, + loaded, + closeFixture: async () => { + await cleanupFixtureRoot(f.root); + await f.cleanup(); + }, + }; +} + +async function readHeadAndStore(runRoot: string, runId: string) { + const runDir = join(runRoot, runId); + const descriptor = JSON.parse(await readFile(join(runDir, 'run.json'), 'utf8')) as RunDescriptor; + const artifactsDir = join(runDir, 'artifacts'); + const reader = { read: async (ref: ArtifactRef) => new Uint8Array(await readFile(join(artifactsDir, ref.name))) }; + const plan = parsePrivateJson(await reader.read(descriptor.plan), 4_194_304) as unknown as import('../src/types.js').CompiledPlan; + const store = stateValue(reopenLocalRun(descriptor.identity)); + try { + const progress = new ProgressStore(store, null, reader, plan, descriptor.identity.lock, descriptor.plan, descriptor.source); + const head = await progress.read(); + const records = journal(store); + return { descriptor, artifactsDir, plan, head, records }; + } finally { + stateValue(store.close()); + } +} + +test('in-scope write with free-text stdout settles completed without format repair, exports overlay via inspect, records local_write operation and markers, preserves usageReported, and refuses step reopen', async () => { + const f = await execIntegrationFixture({ mode: 'write-inside' }); + const runId = 'run-exec-write-inside'; + try { + const execution: CycleExecution = assertOk( + await runCycleWithPorts({ configuration: f.loaded, repository: f.repository, runRoot: f.runRoot, runId }), + 'runCycleWithPorts', + ); + assert.equal(execution.kind, 'result', JSON.stringify(execution)); + if (execution.kind !== 'result') return; + assert.equal(execution.result.spec.status, 'completed'); + assert.deepEqual(execution.secondary, []); + + const { artifactsDir, head, records } = await readHeadAndStore(f.runRoot, runId); + assert.ok(head); + assert.equal(head.progress.attempts.length, 1, 'free-text stdout never triggers format repair'); + assert.equal(head.progress.attempts.every(a => a.repair !== 'format'), true); + assert.equal( + head.progress.failures.every(failure => failure.evidence?.name.startsWith('verifier-output-') === true), + true, + 'only implicit controller.no-change verifier failure, zero submission format failures', + ); + + const artifactNames = await readdir(artifactsDir); + assert.equal(artifactNames.some(name => name.startsWith('format-intent-')), false, 'no format-intent artifact'); + const bindings = artifactNames.filter(name => /^exec-role-producer-[0-9a-f]{64}\.binding\.json$/.test(name)); + const proofs = artifactNames.filter(name => /^exec-role-producer-[0-9a-f]{64}\.proof\.json$/.test(name)); + assert.equal(bindings.length, 1); + assert.equal(proofs.length, 1); + + const proof = JSON.parse(await readFile(join(artifactsDir, proofs[0]!), 'utf8')) as { + readonly settled: string; + readonly outcome: ArtifactRef; + }; + assert.equal(proof.settled, 'observed'); + const execOutcome = parsePrivateJson(await readFile(join(artifactsDir, proof.outcome.name)), 1_048_576) as { + readonly status: string; + readonly usageReported: boolean; + readonly usage: readonly unknown[]; + }; + assert.equal(execOutcome.status, 'completed'); + assert.equal(execOutcome.usageReported, false); + assert.deepEqual(execOutcome.usage, []); + + const execOps = records.operations.filter(op => op.intent.targetIdentity.startsWith('exec:')); + assert.equal(execOps.length, 1); + assert.equal(execOps[0]!.state, 'confirmed'); + assert.equal(execOps[0]!.intent.effect, 'local_write'); + assert.equal(execOps[0]!.initialReceipt?.outcome, 'succeeded'); + + const nativeId = phaseCheckpointId(runId, 'role.1.native'); + assert.ok(records.checkpoints.some(cp => cp.checkpointId === nativeId), 'native checkpoint recorded'); + + const inspectDir = join(f.root, 'inspected'); + const inspected = assertOk(await inspectRun({ runRoot: f.runRoot, runId, output: inspectDir }), 'inspectRun'); + assert.ok(inspected.manifest); + assert.equal(inspected.status.currentState?.ledger.admittedCalls, 1, 'exec dispatch counted as one model call'); + const exported = JSON.parse(await readFile(join(inspectDir, 'candidate.files.json'), 'utf8')) as { + readonly files: readonly ({ readonly name: string; readonly sha256: string } | { readonly name: string; readonly body: string })[]; + }; + const byName = new Map( + exported.files.map(entry => [ + entry.name, + 'sha256' in entry ? entry.sha256 : hash(Buffer.from(entry.body, 'base64')).hex, + ]), + ); + assert.equal(byName.get('packages/hello.txt'), hash('hello\n').hex); + assert.equal(byName.get('result.json'), hash(JSON.stringify({ ok: true })).hex); + assert.deepEqual(await readdir(join(f.runRoot, 'workspaces', runId)), [], 'attempt workspace cleaned up'); + + // Reopening a retained exec run via step APIs refuses CAPABILITY_UNSUPPORTED + const envLookup = (name: string) => f.environment[name]; + for (const reopen of [ + () => stepNext({ runRoot: f.runRoot, runId, environment: envLookup }), + () => stepSubmit({ runRoot: f.runRoot, runId, leaseToken: 'a'.repeat(64), environment: envLookup }), + () => stepCancel({ runRoot: f.runRoot, runId, environment: envLookup }), + ]) { + const res = await reopen(); + assert.equal(res.ok, false); + if (!res.ok) { + assert.equal(res.error.code, 'CAPABILITY_UNSUPPORTED'); + assert.equal(res.error.path, '/spec/profiles/roles'); + } + } + } finally { + await f.closeFixture(); + } + + // Verify usageReported: true is preserved in exec-outcome when child writes LOOPWRIGHT_USAGE_OUT + const fUsage = await execIntegrationFixture({ mode: 'write-inside-with-usage' }); + const runIdUsage = 'run-exec-usage-reported'; + try { + const execution = assertOk( + await runCycleWithPorts({ configuration: fUsage.loaded, repository: fUsage.repository, runRoot: fUsage.runRoot, runId: runIdUsage }), + 'run with usage', + ); + assert.equal(execution.kind, 'result'); + const { artifactsDir } = await readHeadAndStore(fUsage.runRoot, runIdUsage); + const proofName = (await readdir(artifactsDir)).find(name => name.endsWith('.proof.json'))!; + const proof = JSON.parse(await readFile(join(artifactsDir, proofName), 'utf8')) as { readonly outcome: ArtifactRef }; + const execOutcome = parsePrivateJson(await readFile(join(artifactsDir, proof.outcome.name)), 1_048_576) as { + readonly usageReported: boolean; + readonly usage: readonly { readonly requestId: string; readonly inputTokens: number; readonly outputTokens: number; readonly costMicrousd: number }[]; + }; + assert.equal(execOutcome.usageReported, true); + assert.deepEqual(execOutcome.usage, [{ requestId: 'req_1', inputTokens: 80, outputTokens: 20, costMicrousd: 900 }]); + } finally { + await fUsage.closeFixture(); + } +}); + +test('out-of-scope write fails implicit scope.v1 check with outside_scope', async () => { + const f = await execIntegrationFixture({ mode: 'write-outside' }); + const runId = 'run-exec-write-outside'; + try { + const execution = assertOk( + await runCycleWithPorts({ configuration: f.loaded, repository: f.repository, runRoot: f.runRoot, runId }), + 'run outside scope', + ); + assert.equal(execution.kind, 'result', JSON.stringify(execution)); + if (execution.kind !== 'result') return; + assert.equal(execution.result.spec.status, 'failed'); + const observed = JSON.parse( + await readFile(join(f.runRoot, runId, 'artifacts', execution.observations!.name), 'utf8'), + ) as { readonly verifierMatrix: readonly { readonly slotId: string; readonly status: string; readonly reason: string | null }[] }; + const scopeRow = observed.verifierMatrix.find(row => row.slotId === 'controller.scope'); + assert.deepEqual(scopeRow, { + slotId: 'controller.scope', + checkId: 'controller.scope', + status: 'failed', + reason: 'outside_scope', + implicit: 'scope', + }); + } finally { + await f.closeFixture(); + } +}); + +test('exit 3 halts the DAG as blocked with exact stderr reason, skips downstream checks, onRework, and implementation repair, and never overwrites blocked into failed even when a required check fails', async () => { + // 1. Downstream failing check + onRework + maxImplementationRepairs: verify is pruned to not_run + const f = await execIntegrationFixture({ + mode: 'exit-3', + resultOk: false, + verifyOnRework: 2, + maxImplementationRepairs: 2, + }); + const runId = 'run-exec-exit-3-downstream'; + try { + const execution = assertOk( + await runCycleWithPorts({ configuration: f.loaded, repository: f.repository, runRoot: f.runRoot, runId }), + 'run exit-3', + ); + assert.equal(execution.kind, 'result', JSON.stringify(execution)); + if (execution.kind !== 'result') return; + assert.equal(execution.result.spec.status, 'blocked'); + + const { artifactsDir, plan, head } = await readHeadAndStore(f.runRoot, runId); + assert.ok(head); + assert.equal(head.progress.attempts.length, 1, 'no rework or implementation repair dispatched'); + assert.equal(head.progress.reworkEpoch ?? 0, 0); + assert.equal(head.progress.nodes.find(n => n.id === 'implement')?.state, 'blocked'); + assert.equal(head.progress.nodes.find(n => n.id === 'verify')?.state, 'not_run'); + assert.ok(head.progress.submission); + const sub = normalizeSubmission(await readFile(join(artifactsDir, head.progress.submission.name)), plan.task); + assert.equal(sub.status, 'blocked'); + assert.equal(sub.reason, 'need a human decision'); + } finally { + await f.closeFixture(); + } + + // 2. Parallel upstream required check already ran and failed before exec step exited 3 -> still settles blocked! + const fParallel = await execIntegrationFixture({ + mode: 'exit-3', + resultOk: false, + parallelFailingCheck: true, + maxImplementationRepairs: 2, + }); + const runIdParallel = 'run-exec-exit-3-forced-blocked'; + try { + const execution = assertOk( + await runCycleWithPorts({ configuration: fParallel.loaded, repository: fParallel.repository, runRoot: fParallel.runRoot, runId: runIdParallel }), + 'run exit-3 with failed check', + ); + assert.equal(execution.kind, 'result', JSON.stringify(execution)); + if (execution.kind !== 'result') return; + const earlyRow = execution.result.spec.verification.spec.required.find(r => r.checkId === 'early'); + assert.equal(earlyRow?.status, 'failed', 'parallel required check did run and fail'); + assert.equal(execution.result.spec.status, 'blocked', 'forced blocked prevents failed check from overwriting blocked'); + } finally { + await fParallel.closeFixture(); + } +}); + +test('multi-step DAG prunes downstream agent steps when an upstream exec step fails', async () => { + const f = await execIntegrationFixture({ + mode: 'exit-7', + multiAgentSecondMode: 'write-inside', + maxImplementationRepairs: 2, + }); + const runId = 'run-exec-multistep-prune'; + try { + const execution = assertOk( + await runCycleWithPorts({ configuration: f.loaded, repository: f.repository, runRoot: f.runRoot, runId }), + 'run multi-step failure', + ); + assert.equal(execution.kind, 'result', JSON.stringify(execution)); + if (execution.kind !== 'result') return; + assert.equal(execution.result.spec.status, 'failed'); + + const { artifactsDir, plan, head } = await readHeadAndStore(f.runRoot, runId); + assert.ok(head); + assert.equal(head.progress.attempts.length, 1, 'downstream agent step was pruned and never dispatched'); + assert.equal(head.progress.nodes.find(n => n.id === 'implement')?.state, 'failed'); + assert.equal(head.progress.nodes.find(n => n.id === 'finish')?.state, 'not_run'); + assert.equal(head.progress.nodes.find(n => n.id === 'verify')?.state, 'not_run'); + const sub = normalizeSubmission(await readFile(join(artifactsDir, head.progress.submission!.name)), plan.task); + assert.equal(sub.status, 'failed'); + assert.equal(sub.reason, 'exec_exit_7'); + } finally { + await f.closeFixture(); + } +}); + +test('child environment equals the exact allowlist plus configured env, scrubbed exec credential, and contract variables without inheriting process.env', async () => { + const f = await execIntegrationFixture({ mode: 'print-env', withResource: true }); + const runId = 'run-exec-print-env'; + process.env['LOOPWRIGHT_HOST_SENTINEL'] = 'must-not-leak'; + try { + const execution = assertOk( + await runCycleWithPorts({ configuration: f.loaded, repository: f.repository, runRoot: f.runRoot, runId }), + 'run print-env', + ); + assert.equal(execution.kind, 'result'); + const { artifactsDir, head } = await readHeadAndStore(f.runRoot, runId); + assert.ok(head); + const attempt = head.progress.attempts[0]!; + const expectedAttemptDir = join(f.runRoot, 'workspaces', runId, attempt.id); + const expectedScratchDir = join(expectedAttemptDir, 'scratch'); + + const proofName = (await readdir(artifactsDir)).find(name => /^exec-role-producer-[0-9a-f]{64}\.proof\.json$/.test(name))!; + const proof = JSON.parse(await readFile(join(artifactsDir, proofName), 'utf8')) as { readonly outcome: ArtifactRef }; + const execOutcome = parsePrivateJson(await readFile(join(artifactsDir, proof.outcome.name)), 1_048_576) as { + readonly stdout: string; + }; + const report = JSON.parse(execOutcome.stdout) as { + readonly env: Record; + readonly argv: readonly string[]; + readonly cwd: string; + readonly prompt: string; + }; + // Measured on darwin: CoreFoundation sets __CF_USER_TEXT_ENCODING inside every newly started node process. + delete report.env['__CF_USER_TEXT_ENCODING']; + + assert.equal(report.cwd, join(expectedAttemptDir, 'candidate')); + assert.deepEqual(report.argv.slice(-2), [join(expectedScratchDir, 'prompt.md'), join(expectedAttemptDir, 'candidate')]); + assert.equal(report.prompt, 'Produce one structured submission for the frozen candidate.'); + assert.equal(report.env['LOOPWRIGHT_CONTEXT_FILES']?.startsWith(join(expectedAttemptDir, 'context') + '/'), true); + + const expectedEnv: Record = { + PATH: '/usr/local/bin:/usr/bin:/bin', + HOME: expectedScratchDir, + TMPDIR: expectedScratchDir, + LANG: 'C.UTF-8', + LC_ALL: 'C.UTF-8', + TERM: 'dumb', + FORGEVO_LLM_BASE_URL: 'https://api.example.com/v1', + LLM_TOKEN: '[scrubbed]', + LOOPWRIGHT_RUN_ID: runId, + LOOPWRIGHT_STEP_ID: 'implement', + LOOPWRIGHT_ROLE_ID: 'author', + LOOPWRIGHT_ATTEMPT_ID: attempt.id, + LOOPWRIGHT_SCOPE_WRITABLE: 'packages/**', + LOOPWRIGHT_ALLOWED_TOOLS: 'read,write', + LOOPWRIGHT_CONTEXT_FILES: report.env['LOOPWRIGHT_CONTEXT_FILES']!, + LOOPWRIGHT_USAGE_OUT: join(expectedScratchDir, 'usage.json'), + }; + const sorted = (rec: Record) => Object.entries(rec).sort(([a], [b]) => a.localeCompare(b)); + assert.deepEqual(sorted(report.env), sorted(expectedEnv)); + } finally { + delete process.env['LOOPWRIGHT_HOST_SENTINEL']; + await f.closeFixture(); + } +}); + +test('bound exec credential is scrubbed from exec-outcome and absent from every inspect output and retained run file', async () => { + const f = await execIntegrationFixture({ mode: 'print-secret' }); + const runId = 'run-exec-scrub-secret'; + try { + const execution = assertOk( + await runCycleWithPorts({ configuration: f.loaded, repository: f.repository, runRoot: f.runRoot, runId }), + 'run print-secret', + ); + assert.equal(execution.kind, 'result'); + + const { artifactsDir } = await readHeadAndStore(f.runRoot, runId); + const proofName = (await readdir(artifactsDir)).find(name => /^exec-role-producer-[0-9a-f]{64}\.proof\.json$/.test(name))!; + const proof = JSON.parse(await readFile(join(artifactsDir, proofName), 'utf8')) as { readonly outcome: ArtifactRef }; + const execOutcome = parsePrivateJson(await readFile(join(artifactsDir, proof.outcome.name)), 1_048_576) as { + readonly stdout: string; + readonly stderr: string; + }; + assert.equal(execOutcome.stdout, 'out=[scrubbed]\n'); + assert.equal(execOutcome.stderr, 'err=[scrubbed]\n'); + + const inspectDir = join(f.root, 'inspect-clean'); + assertOk(await inspectRun({ runRoot: f.runRoot, runId, output: inspectDir }), 'inspectRun'); + + const assertTreeClean = async (dir: string): Promise => { + for (const name of await readdir(dir)) { + const full = join(dir, name); + const st = await lstat(full); + if (st.isDirectory()) { + await assertTreeClean(full); + } else if (st.isFile()) { + const text = (await readFile(full)).toString('utf8'); + assert.equal(text.includes(CANARY_SECRET), false, `${name} must not contain secret`); + } + } + }; + await assertTreeClean(inspectDir); + await assertTreeClean(join(f.runRoot, runId)); + } finally { + await f.closeFixture(); + } +}); + +test('sleeping exec child killed at timeoutMs settles failed with exec_timeout and leaves the process group gone', { timeout: 30_000 }, async () => { + const f = await execIntegrationFixture({ mode: 'sleep', timeoutMs: 1_200, maxImplementationRepairs: 2 }); + const runId = 'run-exec-timeout'; + try { + const execution = assertOk( + await runCycleWithPorts({ configuration: f.loaded, repository: f.repository, runRoot: f.runRoot, runId }), + 'run timeout', + ); + assert.equal(execution.kind, 'result', JSON.stringify(execution)); + if (execution.kind !== 'result') return; + assert.equal(execution.result.spec.status, 'failed'); + + const { artifactsDir, plan, head } = await readHeadAndStore(f.runRoot, runId); + assert.ok(head); + assert.equal(head.progress.attempts.length, 1); + const sub = normalizeSubmission(await readFile(join(artifactsDir, head.progress.submission!.name)), plan.task); + assert.equal(sub.status, 'failed'); + assert.equal(sub.reason, 'exec_timeout'); + + const bindingName = (await readdir(artifactsDir)).find(name => /^exec-role-producer-[0-9a-f]{64}\.binding\.json$/.test(name))!; + const binding = JSON.parse(await readFile(join(artifactsDir, bindingName), 'utf8')) as { readonly pgid: number }; + assert.ok(binding.pgid > 1); + assert.equal(groupGone(binding.pgid), true); + } finally { + await f.closeFixture(); + } +}); + +test('cancelling or hitting the work deadline mid-exec kills the process group, renews and settles the operation receipt, and finalizes cancelled or expired instead of reconcile_required', { timeout: 30_000 }, async () => { + // 1. Operator abort -> cancelled + const fCancel = await execIntegrationFixture({ mode: 'sleep', timeoutMs: 60_000 }); + const runIdCancel = 'run-exec-cancel'; + try { + const abort = new AbortController(); + const running = runCycleWithPorts({ + configuration: fCancel.loaded, + repository: fCancel.repository, + runRoot: fCancel.runRoot, + runId: runIdCancel, + signal: abort.signal, + }); + const { data: binding } = await findBindingMarker(join(fCancel.runRoot, runIdCancel, 'artifacts')); + const pgid = Number(binding.pgid); + assert.ok(pgid > 1); + abort.abort(); + + const execution = assertOk(await running, 'cancelled exec run'); + assert.equal(execution.kind, 'result', JSON.stringify(execution)); + if (execution.kind === 'result') { + assert.equal(execution.result.spec.status, 'cancelled'); + } + assert.equal(groupGone(pgid), true); + const { records } = await readHeadAndStore(fCancel.runRoot, runIdCancel); + assert.equal(records.view.counts.unresolvedOperations, 0); + assert.deepEqual(await readdir(join(fCancel.runRoot, 'workspaces', runIdCancel)), []); + } finally { + await fCancel.closeFixture(); + } + + // 2. Work deadline firing mid-exec -> expired (mapped from CANCELLED when deadline.reason === 'DEADLINE') + const fExpire = await execIntegrationFixture({ + mode: 'sleep', + timeoutMs: 5_500, + drainReserveMs: 120_000, + wallTimeMs: 126_000, + }); + const runIdExpire = 'run-exec-expire'; + try { + // With wallTimeMs=126000 and drainReserveMs=120000, work cutoff is 6000ms from Cycle creation while timeoutMs=5500 fits budget; + // pausing 2000ms at bootstrap leaves ~4000ms to materialize and spawn so cutoff fires mid-exec (~1500ms before exec timeoutMs). + const execution = assertOk( + await runCycleWithPorts( + { configuration: fExpire.loaded, repository: fExpire.repository, runRoot: fExpire.runRoot, runId: runIdExpire }, + { + afterCheckpoint: async phase => { + if (phase === 'bootstrap') await new Promise(resolve => setTimeout(resolve, 2_000)); + }, + }, + ), + 'expired exec run', + ); + assert.equal(execution.kind, 'result', JSON.stringify(execution)); + if (execution.kind === 'result') { + assert.equal(execution.result.spec.status, 'expired'); + } + const { artifactsDir, records } = await readHeadAndStore(fExpire.runRoot, runIdExpire); + assert.equal(records.view.counts.unresolvedOperations, 0); + const bindingName = (await readdir(artifactsDir)).find(name => /^exec-role-producer-[0-9a-f]{64}\.binding\.json$/.test(name)); + assert.ok(bindingName, 'exec child must have spawned before work deadline fired'); + const binding = JSON.parse(await readFile(join(artifactsDir, bindingName), 'utf8')) as { readonly pgid: number }; + assert.equal(groupGone(binding.pgid), true); + assert.deepEqual(await readdir(join(fExpire.runRoot, 'workspaces', runIdExpire)), []); + } finally { + await fExpire.closeFixture(); + } +}); + +test('CLEANUP_FAILED when process group survives SIGKILL leaves operation dispatch_uncertain, writes no proof marker, keeps holdLocalActivity held, and preserves attemptDir', { timeout: 30_000 }, async () => { + const f = await execIntegrationFixture({ mode: 'fork-bg-exit-0', timeoutMs: 20_000 }); + const runId = 'run-exec-cleanup-failed'; + const realKill = process.kill.bind(process); + let targetPgid = 0; + (process as { kill: typeof process.kill }).kill = ((pid: number, signal?: string | number) => { + if (pid < 0 && (signal === 'SIGKILL' || signal === 9)) { + targetPgid = -pid; + return true; + } + return realKill(pid, signal as NodeJS.Signals | number | undefined); + }) as typeof process.kill; + + try { + const execution = assertOk( + await runCycleWithPorts({ configuration: f.loaded, repository: f.repository, runRoot: f.runRoot, runId }), + 'cleanup failed run', + ); + assert.equal(execution.kind, 'incident', JSON.stringify(execution)); + if (execution.kind === 'incident') { + assert.equal(execution.incident.code, 'CLEANUP_FAILED'); + assert.equal(execution.incident.cleanup, 'pending'); + } + assert.ok(targetPgid > 1, 'attempted SIGKILL on process group'); + assert.equal(groupGone(targetPgid), false, 'child group still alive'); + + const runDir = join(f.runRoot, runId); + const artifactsDir = join(runDir, 'artifacts'); + const artifactNames = await readdir(artifactsDir); + assert.equal(artifactNames.some(name => name.endsWith('.proof.json')), false, 'no proof marker written on CLEANUP_FAILED'); + + const descriptor = JSON.parse(await readFile(join(runDir, 'run.json'), 'utf8')) as RunDescriptor; + const store = stateValue(reopenLocalRun(descriptor.identity)); + try { + const ops = stateValue(store.listOperations({ limit: 100, cursor: null })).items; + const execOp = ops.find(op => op.intent.targetIdentity.startsWith('exec:'))!; + assert.equal(execOp.state, 'dispatch_uncertain', 'operation must remain dispatch_uncertain for recovery'); + const attemptDir = join(f.runRoot, 'workspaces', runId, execOp.intent.attemptId); + assert.equal(await lstat(attemptDir).then(() => true, () => false), true, 'attemptDir preserved while writer is alive'); + } finally { + stateValue(store.close()); + } + + // Owner lock was NOT released because holdLocalActivity remained held + const plan = parsePrivateJson(await readFile(join(artifactsDir, descriptor.plan.name)), 4_194_304) as { readonly planDigest: import('@loopwright/core').Digest }; + await assert.rejects( + ControllerOwner.acquire(runDir, runId, plan.planDigest), + (err: unknown) => err instanceof ControllerFailure && err.diagnostic.code === 'OWNER_BUSY', + ); + } finally { + (process as { kill: typeof process.kill }).kill = realKill; + if (targetPgid > 1) { + try { + realKill(-targetPgid, 'SIGKILL'); + } catch { + // ignore if already exited + } + const waitEnd = Date.now() + 3_000; + while (!groupGone(targetPgid) && Date.now() < waitEnd) { + await new Promise(resolve => setTimeout(resolve, 20)); + } + } + await f.closeFixture(); + } +}); diff --git a/packages/controller/test/recovery-owner.test.ts b/packages/controller/test/recovery-owner.test.ts index f1d10f91..f7b5cc33 100644 --- a/packages/controller/test/recovery-owner.test.ts +++ b/packages/controller/test/recovery-owner.test.ts @@ -1,15 +1,18 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import { spawn, type ChildProcess } from 'node:child_process'; -import { open, readFile, writeFile, lstat } from 'node:fs/promises'; +import { execFileSync, spawn, type ChildProcess } from 'node:child_process'; +import { chmod, mkdir, open, readFile, readdir, writeFile, lstat } from 'node:fs/promises'; import { setTimeout as delay } from 'node:timers/promises'; import { join } from 'node:path'; import { randomBytes } from 'node:crypto'; import { fileURLToPath } from 'node:url'; -import { reopenLocalRun, type RunView } from '@loopwright/state'; -import { retainedFixture } from './progress-fixtures.js'; +import { reopenLocalRun, type Authority, type RunView } from '@loopwright/state'; +import { configurationFixture } from './config-fixtures.js'; +import { retainedFixture, setFixture } from './progress-fixtures.js'; +import { createCycle, Cycle } from '../src/controller.js'; import { ControllerOwner, processBirth, bootIdentity } from '../src/ownership.js'; import { ProgressStore } from '../src/progress.js'; +import { reconcileInterruptedOperations, resumeCycle } from '../src/recovery.js'; import { stateValue } from '../src/storage.js'; import { GIT_ENVIRONMENT } from '../src/git-reader.js'; import { canonical, hash } from '../src/schema.js'; @@ -100,3 +103,358 @@ test('crash fixture boundaries cover concurrent_resume_probe refusal, pre_intent } } }); + +test('mid-exec controller crash settles exec_unknown on recovery, kills the recorded process group, validates workspaceDir, discards expectedAttemptDir even without binding, and refuses resumeCycle with RECOVERY_REQUIRED without re-dispatch', { timeout: 30_000 }, async () => { + const execStub = fileURLToPath(new URL('./exec-role-fixtures.js', import.meta.url)); + const makeExecCrashFixture = async (mode: string) => { + const f = await configurationFixture(); + const repository = join(f.root, 'repository'); + const runRoot = join(f.root, 'runs'); + await mkdir(repository, { mode: 0o700 }); + await writeFile(join(repository, 'result.json'), JSON.stringify({ ok: true }), { mode: 0o600 }); + const git = (args: string[]) => execFileSync('/usr/bin/git', ['-c', 'core.hooksPath=/dev/null', ...args], { + cwd: repository, + env: { PATH: '/usr/bin:/bin', LANG: 'C', LC_ALL: 'C', GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null', HOME: '/nonexistent', GIT_TERMINAL_PROMPT: '0' }, + encoding: 'utf8', + }); + git(['init', '-q']); + git(['add', 'result.json']); + git(['-c', 'user.name=Fixture', '-c', 'user.email=fixture@localhost.invalid', 'commit', '-qm', 'init']); + const revision = git(['rev-parse', 'HEAD']).trim(); + + setFixture(f.registry, ['spec', 'runtimeProfiles'], []); + setFixture(f.registry, ['spec', 'credentialBindings'], []); + setFixture(f.registry, ['spec', 'environmentBindings'], []); + setFixture(f.registry, ['spec', 'roleProfiles'], [{ + id: 'author', + adapter: 'exec', + runtimeRef: null, + providerCredentialRef: null, + selection: { provider: 'openai', model: 'gpt-5', thinking: 'medium' }, + tools: ['read', 'write'], + mcp: null, + exec: { + command: [process.execPath, execStub], + args: [mode], + timeoutMs: 60_000, + }, + }]); + setFixture(f.config, ['spec', 'credentials'], []); + setFixture(f.config, ['spec', 'profiles', 'roles'], [{ roleId: 'author', profileRef: 'author' }]); + setFixture(f.config, ['spec', 'task', 'spec', 'target', 'baseRevision'], revision); + setFixture(f.config, ['spec', 'task', 'spec', 'target', 'sourceRevision'], revision); + setFixture(f.config, ['spec', 'task', 'spec', 'roles'], [{ + id: 'author', + adapter: 'exec', + provider: 'openai', + model: 'gpt-5', + thinking: 'medium', + tools: ['read', 'write'], + }]); + setFixture(f.config, ['spec', 'task', 'spec', 'steps'], [ + { id: 'implement', kind: 'agent', uses: 'package.patch', roleId: 'author', dependsOn: [] }, + ]); + setFixture(f.config, ['spec', 'profiles', 'steps'], [ + { stepId: 'implement', handlerRef: 'package.patch' }, + ]); + await f.save(); + const loaded = await f.load(); + assert.equal(loaded.ok, true); + if (!loaded.ok) throw new Error('fixture'); + return { ...f, repository, runRoot, loaded: loaded.value }; + }; + + const exists = (p: string) => lstat(p).then(() => true, () => false); + const groupGone = (pgid: number) => { + try { + process.kill(-pgid, 0); + return false; + } catch (err) { + return (err as NodeJS.ErrnoException).code === 'ESRCH'; + } + }; + + // Part 1: Live sleeping exec child crashed between .binding.json and .proof.json + { + const f = await makeExecCrashFixture('sleep'); + const input = { configuration: f.loaded, repository: f.repository, runRoot: f.runRoot, runId: 'exec-crash-live' }; + const context = await createCycle(input, {}); + const original = stateValue(context.store.inspect()); + let cycle: Cycle | null = null; + let recoveryAuth: Authority | null = null; + try { + cycle = new Cycle(context); + await cycle.bootstrap(); + const continuation = cycle.role('implement').then( + () => assert.fail('dead controller continuation must not complete'), + err => { + assert.ok(err instanceof ControllerFailure); + }, + ); + + let bindingPath = ''; + let binding: Record | null = null; + const waitDeadline = Date.now() + 10_000; + while (Date.now() < waitDeadline) { + const names = await readdir(context.artifacts.directory).catch(() => [] as string[]); + const found = names.find(name => /^exec-role-producer-[0-9a-f]{64}\.binding\.json$/.test(name)); + if (found) { + bindingPath = join(context.artifacts.directory, found); + try { + binding = JSON.parse(await readFile(bindingPath, 'utf8')) as Record; + break; + } catch { + // retry until fsync completes + } + } + await delay(20); + } + assert.ok(binding, 'binding marker written'); + const pgid = Number(binding.pgid); + const attemptDir = String(binding.workspaceDir); + const proofPath = bindingPath.replace(/\.binding\.json$/, '.proof.json'); + const operationId = String(binding.operationId); + + assert.equal(groupGone(pgid), false, 'exec child group alive'); + assert.equal(await exists(proofPath), false, 'no proof marker yet'); + assert.equal(await exists(attemptDir), true, 'attemptDir materialized'); + + await cycle.deadline.dispose(); + stateValue(context.store.release(context.authority)); + const crashedHead = await context.progress.read(); + const view = stateValue(context.store.inspect()); + assert.equal(stateValue(context.store.getOperation(operationId)).state, 'dispatch_uncertain'); + + recoveryAuth = stateValue( + context.store.claim({ + ownerId: 'controller.' + context.owner.nonce, + expectedGeneration: view.owner.generation, + expectedRevision: view.revision, + mode: 'recovery', + }), + ).authority; + await reconcileInterruptedOperations({ ...context, authority: recoveryAuth }, crashedHead, cycle.candidate, original.storeId); + await continuation; + + const settled = stateValue(context.store.getOperation(operationId)); + assert.equal(settled.state, 'confirmed'); + assert.equal(settled.reconciliation?.outcome, 'failed'); + assert.equal(settled.reconciliation?.evidence.method, 'exec_unknown'); + assert.equal(settled.reconciliation?.evidence.producerId, 'loopwright.exec-role.v1'); + assert.equal(groupGone(pgid), true, 'process group killed on recovery'); + assert.equal(await exists(attemptDir), false, 'expectedAttemptDir removed'); + assert.equal(await exists(proofPath), true, 'unknown proof marker written'); + const proof = JSON.parse(await readFile(proofPath, 'utf8')) as { readonly settled: string }; + assert.equal(proof.settled, 'unknown'); + assert.equal(stateValue(context.store.inspect()).counts.operations, 1); + + await cycle.events.close(); + stateValue(context.store.release(recoveryAuth)); + recoveryAuth = null; + stateValue(context.store.close()); + await context.owner.release(); + cycle = null; + + const resumed = await resumeCycle(input); + assert.equal(resumed.ok, false, JSON.stringify(resumed)); + if (!resumed.ok) { + assert.equal(resumed.error.code, 'RECOVERY_REQUIRED'); + } + + const reopened = stateValue(reopenLocalRun(context.descriptor.identity)); + try { + const ops = stateValue(reopened.listOperations({ limit: 100, cursor: null })).items; + const execOps = ops.filter(op => op.intent.targetIdentity.startsWith('exec:')); + assert.equal(execOps.length, 1, 'never re-dispatched'); + assert.equal(execOps[0]!.state, 'confirmed'); + const retained = new ProgressStore(reopened, null, context.artifacts, context.plan, context.lock, context.descriptor.plan, context.descriptor.source); + const finalHead = await retained.read(); + assert.equal(finalHead?.progress.attempts.length, 1); + } finally { + stateValue(reopened.close()); + } + } finally { + if (cycle) { + await cycle.deadline.dispose().catch(() => {}); + await cycle.events.close().catch(() => {}); + if (recoveryAuth) stateValue(context.store.release(recoveryAuth)); + try { stateValue(context.store.close()); } catch { /* already closed */ } + await context.owner.release().catch(() => {}); + } + await f.cleanup(); + } + } + + // Part 2: Mismatched binding.workspaceDir refuses RECOVERY_REQUIRED without deleting tampered target; + // absent binding still idempotently removes expectedAttemptDir (including read-only 0o500 context dir) + { + const f = await makeExecCrashFixture('print-env'); + const input = { configuration: f.loaded, repository: f.repository, runRoot: f.runRoot, runId: 'exec-crash-validation' }; + const context = await createCycle(input, {}); + const decoyDir = join(f.root, 'do-not-delete'); + await mkdir(decoyDir, { mode: 0o700 }); + try { + const cycle = new Cycle(context); + await cycle.bootstrap(); + const attemptId = 'attempt.' + hash('loopwright.dev/controller/attempt/v1\0' + canonical({ runId: input.runId, nodeId: 'implement', purpose: 'task', repair: 'none', ordinal: 1 })).hex.slice(0, 40); + const operationId = 'exec.' + hash('loopwright.dev/controller/exec/v1\0' + canonical({ runId: input.runId, attemptId })).hex.slice(0, 40); + const expectedAttemptDir = join(f.runRoot, 'workspaces', input.runId, attemptId); + await mkdir(join(expectedAttemptDir, 'context'), { recursive: true, mode: 0o700 }); + await writeFile(join(expectedAttemptDir, 'context', 'doc.md'), 'readonly\n', { mode: 0o400 }); + await chmod(join(expectedAttemptDir, 'context'), 0o500); + + const cmdRef = await context.artifacts.put('command', Buffer.from('prompt', 'utf8'), 65_536); + await cycle.publish( + { + ...cycle.draft, + stage: { ...cycle.draft.stage, kind: 'role_pre' }, + attempts: [{ + ordinal: 1, + id: attemptId, + nodeId: 'implement', + nativeStepId: 'implement', + sessionId: 'session.' + 'a'.repeat(40), + purpose: 'task', + repair: 'none', + command: cmdRef, + before: { requests: 0, operations: 0 }, + finished: null, + }], + nodes: [{ id: 'implement', state: 'running' }], + }, + 'role.1.pre', + ); + stateValue(context.store.putIntent(context.authority, { + operationId, + nodeId: 'implement', + attemptId, + effect: 'local_write', + requestDigest: hash('req'), + targetIdentity: 'exec:implement:1:' + cycle.draft.candidate.digest.hex, + })); + const dispatched = stateValue(context.store.authorizeOperationDispatch(context.authority, operationId)); + assert.equal(dispatched.kind, 'new_dispatch'); + if (dispatched.kind !== 'new_dispatch') throw new Error('expected new_dispatch'); + const opRecord = stateValue(context.store.getOperation(operationId)); + const view = stateValue(context.store.inspect()); + + // Write tampered binding pointing at decoyDir + const bindingPath = join(context.artifacts.directory, 'exec-role-producer-' + hash(operationId).hex + '.binding.json'); + await writeFile( + bindingPath, + canonical({ + version: 1, + planDigest: context.plan.planDigest, + operationId, + attemptId, + nodeId: 'implement', + roleId: 'author', + promptDigest: cmdRef.digest, + intentDigest: opRecord.intentDigest, + dispatchReceipt: { + generation: dispatched.permit.generation, + dispatchId: dispatched.permit.dispatchId, + revision: dispatched.permit.authorizedRevision, + clockEpoch: view.clock.basis.clockEpoch, + }, + pgid: null, + workspaceDir: decoyDir, + }), + { mode: 0o600 }, + ); + + await cycle.deadline.dispose(); + await cycle.events.close(); + stateValue(context.store.release(context.authority)); + stateValue(context.store.close()); + await context.owner.release(); + + const badResume = await resumeCycle(input); + assert.equal(badResume.ok, false); + if (!badResume.ok) assert.equal(badResume.error.code, 'RECOVERY_REQUIRED'); + assert.equal(await exists(decoyDir), true, 'tampered workspaceDir never deleted'); + assert.equal(await exists(expectedAttemptDir), true, 'refused before settlement'); + + // Remove binding marker -> absent-binding recovery removes read-only expectedAttemptDir and settles operation + const { unlink } = await import('node:fs/promises'); + await unlink(bindingPath); + const absentBindingResume = await resumeCycle(input); + assert.equal(absentBindingResume.ok, false); + if (!absentBindingResume.ok) assert.equal(absentBindingResume.error.code, 'RECOVERY_REQUIRED'); + assert.equal(await exists(expectedAttemptDir), false, 'expectedAttemptDir removed even without binding marker'); + } finally { + await chmod(join(f.runRoot, 'workspaces', input.runId), 0o700).catch(() => {}); + await f.cleanup(); + } + } + + // Part 3: Crash in native checkpoint -> role_post window refuses RECOVERY_REQUIRED and removes expectedAttemptDir + { + const f = await makeExecCrashFixture('print-env'); + const input = { configuration: f.loaded, repository: f.repository, runRoot: f.runRoot, runId: 'exec-crash-adopt-window' }; + const context = await createCycle(input, {}); + try { + const cycle = new Cycle(context); + await cycle.bootstrap(); + const attemptId = 'attempt.' + hash('loopwright.dev/controller/attempt/v1\0' + canonical({ runId: input.runId, nodeId: 'implement', purpose: 'task', repair: 'none', ordinal: 1 })).hex.slice(0, 40); + const expectedAttemptDir = join(f.runRoot, 'workspaces', input.runId, attemptId); + await mkdir(join(expectedAttemptDir, 'context'), { recursive: true, mode: 0o700 }); + await chmod(join(expectedAttemptDir, 'context'), 0o500); + + const cmdRef = await context.artifacts.put('command', Buffer.from('prompt', 'utf8'), 65_536); + await cycle.publish( + { + ...cycle.draft, + stage: { ...cycle.draft.stage, kind: 'role_pre' }, + attempts: [{ + ordinal: 1, + id: attemptId, + nodeId: 'implement', + nativeStepId: 'implement', + sessionId: 'session.' + 'a'.repeat(40), + purpose: 'task', + repair: 'none', + command: cmdRef, + before: { requests: 0, operations: 0 }, + finished: null, + }], + nodes: [{ id: 'implement', state: 'running' }], + }, + 'role.1.pre', + ); + const nativeId = 'pi.' + hash('loopwright.dev/controller/checkpoint/v1\0' + canonical({ runId: input.runId, phase: 'role.1.native' })).hex.slice(0, 40); + stateValue(context.store.writeCheckpoint(context.authority, { + checkpointId: nativeId, + expectedRevision: stateValue(context.store.inspect()).revision, + candidateManifest: context.source.manifest, + workspace: context.source.workspace, + privateSession: null, + additionalArtifacts: [], + })); + + await assert.rejects( + cycle.resumeAttempt(true), + (err: unknown) => err instanceof ControllerFailure && err.diagnostic.code === 'RECOVERY_REQUIRED', + ); + await assert.rejects( + cycle.resumeAttempt(false), + (err: unknown) => err instanceof ControllerFailure && err.diagnostic.code === 'RECOVERY_REQUIRED', + ); + + await cycle.deadline.dispose(); + await cycle.events.close(); + stateValue(context.store.release(context.authority)); + stateValue(context.store.close()); + await context.owner.release(); + + const adoptResume = await resumeCycle(input); + assert.equal(adoptResume.ok, false); + if (!adoptResume.ok) assert.equal(adoptResume.error.code, 'RECOVERY_REQUIRED'); + assert.equal(await exists(expectedAttemptDir), false, 'expectedAttemptDir removed in adopt window'); + } finally { + await chmod(join(f.runRoot, 'workspaces', input.runId), 0o700).catch(() => {}); + await f.cleanup(); + } + } +}); + diff --git a/specs/2026-11-30-managed-controller-in-process-execution.md b/specs/2026-11-30-managed-controller-in-process-execution.md index ca86a0da..8193b6dd 100644 --- a/specs/2026-11-30-managed-controller-in-process-execution.md +++ b/specs/2026-11-30-managed-controller-in-process-execution.md @@ -585,7 +585,7 @@ and T11 have disjoint `Owns:` and start together; T5 follows T2. Gate: review Acceptance: `runExecRole(spec, context)` validates an absolute `command[0]`, spawns `[...command, ...args, promptFile, candidateDir]` in its own process group with `cwd = candidateDir` and closed stdin, builds the F2 environment from an allowlist plus the configured `env` and the credentials supplied through a `SecretResolver` interface, captures stdout and stderr up to `captureBytes` and scrubs them, maps exit `0`, `3`, other, and timeout as F2 says, kills the group on timeout, exports the usage-file path from its context as `LOOPWRIGHT_USAGE_OUT`, and reads that file after exit into scrubbed request records. Tests cover each mapping, an environment diff against the allowlist, scrubbing, and process-group cleanup. Verify: `node scripts/run-tests.mjs --pkg controller` -- [ ] **T6 · `exec` controller integration** +- [x] **T6 · `exec` controller integration** Blocked by: T4, T5 Owns: `packages/controller/src/controller.ts`, `packages/controller/src/compile.ts`, `packages/controller/src/step.ts`, `packages/controller/src/credentials.ts`, `packages/controller/src/budget-observations.ts`, `packages/controller/src/recovery.ts`, `packages/controller/src/capture.ts`, `packages/controller/src/retained.ts`, `packages/controller/test/delegated-compile.test.ts`, `packages/controller/test/exec-role-integration.test.ts`, `packages/controller/test/recovery-owner.test.ts` Gate: review From fe92783df1fdbcc364afa75bdf3ed78d46de3693 Mon Sep 17 00:00:00 2001 From: thxCode Date: Tue, 1 Dec 2026 23:04:54 +0800 Subject: [PATCH 18/26] feat(controller): aggregate exec usage ledger and classify exec runs in run-eval - Add collectExecUsage and deterministic core-identifier-safe request ID namespacing in exec-role.ts, reading settled exec-outcome artifacts without mutating frozen LocalRunStore.requests. - Preserve provenance: 'unknown' (never zero) when usageReported is false, artifacts are unreadable, or exec settles as exec_unknown; preserve complete reported zero for explicit empty usage files; enforce LIMITS.requests bounds. - Wire exec usage aggregation into evaluateControllerAcceptance (acceptance.ts), Cycle acceptance paths (controller.ts), and inspectRun / usage.json (inspect.ts). - Update run-eval.ts to exclude exec operations from tool ops, classify exec attempts separately from pi/delegated, keep toolTelemetry and circuitBreaker honestly unavailable for pure-exec runs, and aggregate exec tokens/cost into step, role, and total breakdowns. - Add core usage boundary tests and controller exec-usage integration tests (146/146 core, 424/424 controller passing) and check off T7 in the spec. Signed-off-by: thxCode --- packages/controller/src/acceptance.ts | 9 +- packages/controller/src/controller.ts | 14 +- packages/controller/src/exec-role.ts | 148 ++- packages/controller/src/inspect.ts | 25 +- packages/controller/src/run-eval.ts | 146 ++- packages/controller/test/exec-usage.test.ts | 892 ++++++++++++++++++ packages/core/test/usage.test.ts | 40 + ...managed-controller-in-process-execution.md | 2 +- 8 files changed, 1253 insertions(+), 23 deletions(-) create mode 100644 packages/controller/test/exec-usage.test.ts diff --git a/packages/controller/src/acceptance.ts b/packages/controller/src/acceptance.ts index 82be18e6..d251e103 100644 --- a/packages/controller/src/acceptance.ts +++ b/packages/controller/src/acceptance.ts @@ -3,6 +3,7 @@ import { closeSync, constants, fstatSync, lstatSync, openSync } from 'node:fs'; import { lstat, open } from 'node:fs/promises'; import { dirname, isAbsolute, join, resolve } from 'node:path'; import { + LIMITS, VERIFIER_ARTIFACT_LIMITS, bindSubject, constructRunResult, @@ -25,6 +26,8 @@ import { authenticatedCheck, authenticatedRefusal, type PreflightRefusal, type V import { authenticatedGate } from './gate.js'; import { authenticatedBenchmarkGate } from './benchmark-gate.js'; import { LOCAL_CHECK_PRODUCER_ID, authenticatedLocalCheck } from './local-check.js'; +import { collectExecUsage, type CollectedExecUsage, type ExecUsageEntry } from './exec-role.js'; +export { collectExecUsage, type CollectedExecUsage, type ExecUsageEntry }; import { STREAM_CHUNK_BYTES, inside } from './files.js'; import { journal } from './progress.js'; import { canonical, freeze, hash, same } from './schema.js'; @@ -363,7 +366,7 @@ function expectedProducerByImpl(impl: string | undefined): string { return 'loopwright.byte-verifier.v1'; } export function evaluateControllerAcceptance(plan: CompiledPlan, lock: TaskLock, candidate: ArtifactManifest, candidateFiles: readonly (ResolvedArtifactInput | CandidateFileEntry)[], generation: number, - checks: readonly VerifiedCheck[], submission: Submission | null, store: LocalRunStore, forced: 'reconcile_required' | 'expired' | 'cancelled' | 'exhausted' | 'blocked' | 'failed' | null = null, graphComplete = true, refusals: readonly PreflightRefusal[] = [], forcedDiagnostic: ControllerDiagnostic['code'] | null = null, preverified?: PreverifiedVerifierArtifacts): AcceptanceObservation { + checks: readonly VerifiedCheck[], submission: Submission | null, store: LocalRunStore, forced: 'reconcile_required' | 'expired' | 'cancelled' | 'exhausted' | 'blocked' | 'failed' | null = null, graphComplete = true, refusals: readonly PreflightRefusal[] = [], forcedDiagnostic: ControllerDiagnostic['code'] | null = null, preverified?: PreverifiedVerifierArtifacts, execUsage: readonly RequestUsage[] = []): AcceptanceObservation { if (!same(plan.task, lock.spec.contract)) refuse('ARTIFACT_INVALID', '', 'verification'); let authenticatedStamps: ReadonlyMap | undefined; if (preverified !== undefined) { @@ -485,6 +488,10 @@ export function evaluateControllerAcceptance(plan: CompiledPlan, lock: TaskLock, const observed = item.resolution?.kind === 'terminal_usage' ? item.resolution.observation : item.initialObservation; usage.push(observed?.usage ?? { requestId: item.admission.requestId, inputTokens: { provenance: 'unknown' }, outputTokens: { provenance: 'unknown' }, costMicrousd: { provenance: 'unknown' } }); } + for (const item of execUsage) { + usage.push(item); + } + if (usage.length > LIMITS.requests) refuse('OUTPUT_LIMIT', '', 'verification'); const external = records.operations.filter(item => item.intent.effect === 'external_write'); let externalEffects: 'none' | 'possible' | 'confirmed' | 'unknown' = 'none', publicationNotExecuted = false; for (const item of external) { diff --git a/packages/controller/src/controller.ts b/packages/controller/src/controller.ts index ad425280..6afe2d8a 100644 --- a/packages/controller/src/controller.ts +++ b/packages/controller/src/controller.ts @@ -9,7 +9,8 @@ import { materializeAttemptWorkspace } from './candidate-workspace.js'; import { approvedState, selectRoleResources } from './config.js'; import { compilePlan, isExecRole, recordedLocalCheck } from './compile.js'; import { ControllerFailure, refuse, result, safeDiagnostic, type ControllerDiagnostic } from './errors.js'; -import { runExecRole } from './exec-role.js'; +import { EXEC_OUTCOME_MAX_BYTES, EXEC_ROLE_METHOD, EXEC_ROLE_PRODUCER_ID, collectExecUsage, runExecRole } from './exec-role.js'; +export { EXEC_ROLE_METHOD, EXEC_ROLE_PRODUCER_ID }; import { readBoundedFile, removeTree } from './files.js'; import { privateDirectory, ArtifactStore, checkedRef, stateValue, streamVerifiedCasBlob } from './storage.js'; import { ControllerOwner, bootIdentity } from './ownership.js'; @@ -105,10 +106,7 @@ const VALID_ADVISORY_SOURCES: ReadonlySet = new Set = new Set(['continue', 'revise', 'needs_review', 'blocked']); const VALID_CAPABILITY_TIERS: ReadonlySet = new Set(['fast', 'balanced', 'strongest']); const VALID_SOFT_COMPACTION_DECISIONS: ReadonlySet = new Set(['compact', 'defer']); -export const EXEC_ROLE_PRODUCER_ID = 'loopwright.exec-role.v1'; -export const EXEC_ROLE_METHOD = 'exec_command'; export const EXEC_MARKER_BYTES = 1_048_576; -const EXEC_OUTCOME_MAX_BYTES = 8_388_608; export function execOperationId(runId: string, attemptId: string): string { return 'exec.' + hash('loopwright.dev/controller/exec/v1\0' + canonical({ runId, attemptId })).hex.slice(0, 40); @@ -2522,6 +2520,7 @@ let cleanupKnown = false, reader: Promise | null = null, nativeOutcome: Ar check => this.context.plan.verifierSlots.find(slot => slot.id === check.slotId)?.implicit === 'scope' && check.status === 'failed', ); const forcedHalt = verdictHalt ?? (execHalt === 'blocked' && scopeFailed ? 'failed' : execHalt); + const execUsage = (await collectExecUsage(journal(this.context.store).operations, this.context.artifacts)).requests; const acceptance = evaluateControllerAcceptance( this.context.plan, this.context.lock, @@ -2536,6 +2535,7 @@ let cleanupKnown = false, reader: Promise | null = null, nativeOutcome: Ar this.currentRefusals(), null, preverified, + execUsage, ); if (forcedHalt === null && acceptance.result.spec.status === 'failed' && await this.implementationRepair()) { await this.graph(); @@ -2585,7 +2585,8 @@ let cleanupKnown = false, reader: Promise | null = null, nativeOutcome: Ar await this.context.owner.assertCurrent(); }, }); - return evaluateControllerAcceptance(plan, lock, this.candidate.manifest, this.candidate.files, this.generation, checks, this.submission!.value, store, null, this.draft.nodes.every(node => node.state === 'completed'), this.currentRefusals(), null, preverified); + const execUsage = (await collectExecUsage(journal(store).operations, this.context.artifacts)).requests; + return evaluateControllerAcceptance(plan, lock, this.candidate.manifest, this.candidate.files, this.generation, checks, this.submission!.value, store, null, this.draft.nodes.every(node => node.state === 'completed'), this.currentRefusals(), null, preverified, execUsage); } async terminal(primary: AcceptanceObservation | ControllerIncident, drainWindowMs = 0): Promise { const { store, artifacts, lock } = this.context, secondary: ControllerDiagnostic['code'][] = []; @@ -2667,7 +2668,8 @@ let cleanupKnown = false, reader: Promise | null = null, nativeOutcome: Ar const preverified = await verifyControllerVerifierCasDescriptors(this.context.plan, checks, { checkAuthority: () => this.context.owner.assertCurrent(), }); - primary = evaluateControllerAcceptance(this.context.plan, this.context.lock, this.candidate.manifest, this.candidate.files, this.generation, checks, this.submission?.value ?? null, this.context.store, forced, this.draft.nodes.every(node => node.state === 'completed'), this.currentRefusals(), forcedDiagnostic, preverified); + const execUsage = (await collectExecUsage(journal(this.context.store).operations, this.context.artifacts)).requests; + primary = evaluateControllerAcceptance(this.context.plan, this.context.lock, this.candidate.manifest, this.candidate.files, this.generation, checks, this.submission?.value ?? null, this.context.store, forced, this.draft.nodes.every(node => node.state === 'completed'), this.currentRefusals(), forcedDiagnostic, preverified, execUsage); } catch { primary = incident(diagnostic, this.context.lock.spec.runId, this.context.lock.spec.lockHash, [this.context.descriptor.plan, this.context.source.inventory], ['authoritative_result'], this.#cleanup); } } else primary = incident(diagnostic, this.context.lock.spec.runId, this.context.lock.spec.lockHash, [this.context.descriptor.plan, this.context.source.inventory], this.#candidateKnown ? ['authoritative_result'] : ['current_candidate', 'submission', 'authoritative_result'], this.#cleanup); diff --git a/packages/controller/src/exec-role.ts b/packages/controller/src/exec-role.ts index abc58273..aac84874 100644 --- a/packages/controller/src/exec-role.ts +++ b/packages/controller/src/exec-role.ts @@ -1,14 +1,156 @@ import { spawn, type ChildProcess } from 'node:child_process'; import { lstat } from 'node:fs/promises'; import { isAbsolute, resolve } from 'node:path'; -import { EXEC_LIMITS, LIMITS, LOCAL_CHECK_LIMITS, SecretScrubber } from '@loopwright/core'; +import { EXEC_LIMITS, LIMITS, LOCAL_CHECK_LIMITS, SecretScrubber, type RequestUsage } from '@loopwright/core'; +import type { OperationReceipt, OperationRecord } from '@loopwright/state'; import { ControllerFailure, refuse, type ControllerDiagnostic } from './errors.js'; import { inside, readBoundedFile } from './files.js'; -import { parseDocumentBytes } from './parser.js'; +import { parseDocumentBytes, parsePrivateJson } from './parser.js'; import { confirmProcessGroupGone, drainStream, killProcessGroup } from './process-group.js'; -import { id, integer, list, record } from './schema.js'; +import { canonical, hash, id, integer, isRecord, list, record } from './schema.js'; +import type { ArtifactReader } from './storage.js'; import type { CredentialBinding, ExecProfileCommand } from './types.js'; +export const EXEC_ROLE_PRODUCER_ID = 'loopwright.exec-role.v1'; +export const EXEC_ROLE_METHOD = 'exec_command'; +export const EXEC_OUTCOME_MAX_BYTES = 8_388_608; + +const ATTEMPT_ID_RE = /^attempt\.[0-9a-f]{40}$/; +const IDENTIFIER_RE = /^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/; + +export interface ExecUsageEntry { + readonly operationId: string; + readonly attemptId: string; + readonly nodeId: string; + readonly state: OperationRecord['state']; + readonly outcome: OperationReceipt['outcome'] | null; + readonly usageReported: boolean; + readonly requests: readonly RequestUsage[]; +} + +export interface CollectedExecUsage { + readonly entries: readonly ExecUsageEntry[]; + readonly requests: readonly RequestUsage[]; +} + +export function isExecOperation(op: OperationRecord): boolean { + return op.intent.effect === 'local_write' && op.intent.targetIdentity.startsWith('exec:'); +} + +/** Deterministic valid `identifier` namespaced per attempt so repeated requestIds across rework/multi-step attempts never collide. */ +export function execUsageRequestId(attemptId: string, requestId: string): string { + if (ATTEMPT_ID_RE.test(attemptId) && IDENTIFIER_RE.test(requestId)) { + const candidate = `${attemptId}.${requestId}`; + if (candidate.length <= LIMITS.identifier && IDENTIFIER_RE.test(candidate)) { + return candidate; + } + } + return 'exec.r.' + hash('loopwright.dev/controller/exec-usage-id/v1\0' + canonical({ attemptId, requestId })).hex.slice(0, 40); +} + +/** Deterministic valid `identifier` representing unreported or unknown usage for one `exec` attempt. */ +export function execUnknownUsageRequestId(operationId: string, attemptId: string): string { + return 'exec.unknown.' + hash('loopwright.dev/controller/exec-usage-unknown/v1\0' + canonical({ operationId, attemptId })).hex.slice(0, 32); +} + +function unknownExecRequest(operationId: string, attemptId: string): RequestUsage { + return { + requestId: execUnknownUsageRequestId(operationId, attemptId), + inputTokens: { provenance: 'unknown' }, + outputTokens: { provenance: 'unknown' }, + costMicrousd: { provenance: 'unknown' }, + }; +} + +function parseExecOutcomeUsage( + raw: unknown, + operationId: string, + attemptId: string, +): { readonly usageReported: boolean; readonly requests: readonly RequestUsage[] } { + if (!isRecord(raw)) refuse('ARTIFACT_INVALID', '', 'verification'); + if ( + !Object.hasOwn(raw, 'version') || raw['version'] !== 1 + || !Object.hasOwn(raw, 'operationId') || raw['operationId'] !== operationId + || !Object.hasOwn(raw, 'attemptId') || raw['attemptId'] !== attemptId + || !Object.hasOwn(raw, 'usageReported') || typeof raw['usageReported'] !== 'boolean' + || !Object.hasOwn(raw, 'usage') + ) { + refuse('ARTIFACT_INVALID', '', 'verification'); + } + if (!raw['usageReported']) { + return { usageReported: false, requests: [unknownExecRequest(operationId, attemptId)] }; + } + const rawItems = list(raw['usage'], '', LIMITS.requests); + const seen = new Set(); + const requests: RequestUsage[] = []; + for (const item of rawItems) { + const entry = record(item, ['requestId', 'inputTokens', 'outputTokens', 'costMicrousd']); + const rawRequestId = id(entry['requestId']); + if (seen.has(rawRequestId)) refuse('ARTIFACT_INVALID', '', 'verification'); + seen.add(rawRequestId); + requests.push({ + requestId: execUsageRequestId(attemptId, rawRequestId), + inputTokens: { provenance: 'reported', value: integer(entry['inputTokens'], 0, Number.MAX_SAFE_INTEGER) }, + outputTokens: { provenance: 'reported', value: integer(entry['outputTokens'], 0, Number.MAX_SAFE_INTEGER) }, + costMicrousd: { provenance: 'reported', value: integer(entry['costMicrousd'], 0, Number.MAX_SAFE_INTEGER) }, + }); + } + return { usageReported: true, requests }; +} + +/** Collects `exec` usage records from operation receipts and `exec-outcome` artifacts without writing into frozen `LocalRunStore.requests`. */ +export async function collectExecUsage( + operations: readonly OperationRecord[], + artifacts: ArtifactReader | undefined, +): Promise { + const sorted = [...operations].sort((a, b) => a.sequence - b.sequence); + const entries: ExecUsageEntry[] = []; + const allRequests: RequestUsage[] = []; + const maxBuffered = LIMITS.requests + 1; + + for (const op of sorted) { + if (!isExecOperation(op)) continue; + const receipt = op.reconciliation ?? op.initialReceipt; + if (op.state === 'confirmed' && receipt?.outcome === 'not_executed') continue; + if (op.dispatch === null && (op.state === 'intent' || op.state === 'abandoned') && receipt === null) continue; + + let parsed: { readonly usageReported: boolean; readonly requests: readonly RequestUsage[] } | null = null; + if ( + op.state === 'confirmed' + && receipt !== null + && receipt.evidence.producerId === EXEC_ROLE_PRODUCER_ID + && receipt.evidence.method === EXEC_ROLE_METHOD + && artifacts !== undefined + ) { + try { + const bytes = await artifacts.read(receipt.evidence.artifact, EXEC_OUTCOME_MAX_BYTES); + const doc = parsePrivateJson(bytes, EXEC_OUTCOME_MAX_BYTES, LIMITS.requests); + parsed = parseExecOutcomeUsage(doc, op.intent.operationId, op.intent.attemptId); + } catch { + parsed = null; + } + } + const resolved = parsed ?? { + usageReported: false, + requests: [unknownExecRequest(op.intent.operationId, op.intent.attemptId)], + }; + entries.push({ + operationId: op.intent.operationId, + attemptId: op.intent.attemptId, + nodeId: op.intent.nodeId, + state: op.state, + outcome: receipt?.outcome ?? null, + usageReported: resolved.usageReported, + requests: resolved.requests, + }); + for (const req of resolved.requests) { + if (allRequests.length < maxBuffered) allRequests.push(req); + } + } + + return { entries, requests: allRequests }; +} + /** The two vault operations the exec runner needs. The controller's `process.env` is never read or passed. */ export interface SecretResolver { /** Expanded template value of the `consumer: exec` binding `ref`; refuses when `ref` names no such binding. */ diff --git a/packages/controller/src/inspect.ts b/packages/controller/src/inspect.ts index 7e9c854e..dd92c1a5 100644 --- a/packages/controller/src/inspect.ts +++ b/packages/controller/src/inspect.ts @@ -7,6 +7,7 @@ import { readRetained, type RetainedRunInput } from './retained.js'; import { ProgressStore, journal, type ProgressHead } from './progress.js'; import { decodeCandidateCapture } from './capture.js'; import { countDelegatedBudgets } from './budget-observations.js'; +import { collectExecUsage } from './exec-role.js'; import { parseSourceTree } from './source.js'; import { resolveCanonicalCasBlobPath, stateValue, checkedRef, streamVerifiedCasBlob } from './storage.js'; import { parsePrivateJson } from './parser.js'; @@ -266,6 +267,7 @@ export function inspectRun(input: InspectRunInput): Promise ({ requestId: row.admission.requestId, state: row.state, usage: (row.resolution?.kind === 'terminal_usage' ? row.resolution.observation : row.initialObservation)?.usage ?? null })), summary: usage }); + const storeUsageRows = saved.records.requests.map(row => ({ requestId: row.admission.requestId, state: row.state, usage: (row.resolution?.kind === 'terminal_usage' ? row.resolution.observation : row.initialObservation)?.usage ?? null })); + const execUsageRows = execUsage.entries.flatMap(entry => + entry.requests.map(req => ({ + requestId: req.requestId, + state: entry.state, + source: 'exec' as const, + operationId: entry.operationId, + attemptId: entry.attemptId, + usageReported: entry.usageReported, + usage: req, + })), + ); + bundle.json('usage.json', { + version: 1, + ledger: saved.effectiveLedger, + requests: [...storeUsageRows, ...execUsageRows], + ...(execUsage.entries.length > 0 ? { exec: execUsage.entries } : {}), + summary: usage, + }); bundle.json('checkpoint.manifest.json', { version: 1, runId, lockHash: saved.lock.spec.lockHash, checkpoints: saved.records.checkpoints.map(cp => ({ checkpointId: cp.checkpointId, sequence: cp.sequence, subject: cp.subject, artifacts: cp.additionalArtifacts })) }); for (const name of ['review.json', 'memory.json']) bundle.absent(name, 'outside_scope', 'not_run'); let externalUrl: string | null = null; diff --git a/packages/controller/src/run-eval.ts b/packages/controller/src/run-eval.ts index 22b5bd0a..5cf6a5ba 100644 --- a/packages/controller/src/run-eval.ts +++ b/packages/controller/src/run-eval.ts @@ -8,6 +8,7 @@ import { } from '@loopwright/core'; import type { CheckpointRecord, OperationRecord, RequestRecord } from '@loopwright/state'; import { inside, streamRegularFile } from './files.js'; +import { EXEC_ROLE_PRODUCER_ID, collectExecUsage, type ExecUsageEntry } from './exec-role.js'; import { parsePrivateJson } from './parser.js'; import { phaseCheckpointId, type ProgressHead, type journal } from './progress.js'; import { sanitizeReportText } from './report.js'; @@ -546,6 +547,88 @@ function findAttemptForOperation(attempts: readonly ControllerAttempt[], sequenc return null; } +function addExecUsageEntryToBucket(bucket: MutableBucket, entry: ExecUsageEntry | undefined): void { + if (entry === undefined || !entry.usageReported) { + bucket.unknownCostCount += 1; + return; + } + if (entry.requests.length === 0) { + bucket.knownCostCount += 1; + return; + } + for (const req of entry.requests) { + bucket.inputTokens += addQuantityToTokens(req.inputTokens); + bucket.outputTokens += addQuantityToTokens(req.outputTokens); + if (req.costMicrousd.provenance === 'unknown') { + bucket.unknownCostCount += 1; + } else { + bucket.knownCostMicrousd += req.costMicrousd.value; + bucket.knownCostCount += 1; + } + } +} + +function createDirectoryArtifactReader(artifactsDirectory: string): ArtifactReader { + return { + async read(rawRef: ArtifactRef, maxBytes: number): Promise { + const ref = checkedRef(rawRef); + if (ref.byteLength > maxBytes) throw new Error('cap_exceeded'); + if (typeof ref.uri === 'string' && ref.uri.startsWith('cas://sha256/')) { + if (ref.uri !== `cas://sha256/${ref.digest.hex}`) throw new Error('invalid_uri'); + const chunks: Uint8Array[] = []; + let collected = 0; + await streamVerifiedCasBlob( + artifactsDirectory, + { name: ref.name, sha256: ref.digest.hex, byteLength: ref.byteLength, uri: ref.uri }, + chunk => { + collected += chunk.byteLength; + if (collected > maxBytes) throw new Error('cap_exceeded'); + chunks.push(new Uint8Array(chunk)); + }, + 'inspection', + ); + return new Uint8Array(Buffer.concat(chunks)); + } + if (ref.name.length === 0 || ref.name.startsWith('/') || ref.name.includes('\\') || /[\0\r\n]/.test(ref.name)) { + throw new Error('invalid_name'); + } + const segments = ref.name.split('/'); + if (segments.some(seg => seg.length === 0 || seg === '.' || seg === '..')) throw new Error('invalid_name'); + const targetPath = join(artifactsDirectory, ref.name); + if (!inside(targetPath, artifactsDirectory) || targetPath === artifactsDirectory) throw new Error('outside_root'); + let current = artifactsDirectory; + for (const seg of segments) { + current = join(current, seg); + const st = await lstat(current); + if (st.isSymbolicLink()) throw new Error('symlink'); + } + const chunks: Uint8Array[] = []; + let collected = 0; + await streamRegularFile( + targetPath, + { maxBytes, expectedBytes: ref.byteLength, owned: true, code: 'ARTIFACT_INVALID', limitCode: 'OUTPUT_LIMIT', phase: 'inspection' }, + chunk => { + collected += chunk.byteLength; + if (collected > maxBytes) throw new Error('cap_exceeded'); + chunks.push(new Uint8Array(chunk)); + }, + ); + const bytes = new Uint8Array(Buffer.concat(chunks)); + const actual = digestArtifact(ref.name, bytes); + if ( + !actual.ok + || actual.value.name !== ref.name + || actual.value.byteLength !== ref.byteLength + || actual.value.digest.algorithm !== ref.digest.algorithm + || actual.value.digest.hex !== ref.digest.hex + ) { + throw new Error('digest_mismatch'); + } + return bytes; + }, + }; +} + function isToolOperation(op: OperationRecord): boolean { if (op.intent.effect === 'model_call' || op.intent.effect === 'external_write') return false; const receipt = op.reconciliation ?? op.initialReceipt; @@ -554,9 +637,11 @@ function isToolOperation(op: OperationRecord): boolean { op.intent.targetIdentity.startsWith('verifier:') || op.intent.targetIdentity.startsWith('gate:') || op.intent.targetIdentity.startsWith('command:') || + op.intent.targetIdentity.startsWith('exec:') || receipt?.evidence.producerId === 'loopwright.byte-verifier.v1' || receipt?.evidence.producerId === 'loopwright.gate-verifier.v1' || - receipt?.evidence.producerId === 'loopwright.local-check.v1' + receipt?.evidence.producerId === 'loopwright.local-check.v1' || + receipt?.evidence.producerId === EXEC_ROLE_PRODUCER_ID ) { return false; } @@ -595,12 +680,22 @@ export async function evaluateRunHealth(input: EvaluateRunHealthInput): Promise< const checkpointById = new Map(records.checkpoints.map(cp => [cp.checkpointId, cp])); const requestById = new Map(records.requests.map(req => [req.admission.requestId, req])); - const isDelegatedStep = (stepId: string): boolean => { + const stepAdapter = (stepId: string): 'pi' | 'delegated' | 'exec' => { const node = dagById.get(stepId); - if (!node?.roleId) return false; - return roleById.get(node.roleId)?.adapter === 'delegated'; + if (!node?.roleId) return 'pi'; + const adapter = roleById.get(node.roleId)?.adapter; + if (adapter === 'delegated' || adapter === 'exec') return adapter; + return 'pi'; }; + const execReader: ArtifactReader | undefined = + input.artifacts ?? (input.artifactsDirectory !== undefined ? createDirectoryArtifactReader(input.artifactsDirectory) : undefined); + const execUsage = await collectExecUsage(records.operations, execReader); + const execEntryByAttemptId = new Map( + execUsage.entries.map(entry => [entry.attemptId, entry] as const), + ); + const handledExecAttemptIds = new Set(); + // 1. Attempts classification, circuit-breaker metadata, and unchanged-digest repair counting. let ordinaryAttempts = 0; let formatAttempts = 0; @@ -609,6 +704,7 @@ export async function evaluateRunHealth(input: EvaluateRunHealthInput): Promise< let unchangedDigestRepairs = 0; let piAttempts = 0; let delegatedAttempts = 0; + let execAttempts = 0; let readablePiOutcomeCount = 0; let unreadablePiOutcomeCount = 0; let trippedBreaker: RunEvalCircuitBreakerState | null = null; @@ -641,8 +737,9 @@ export async function evaluateRunHealth(input: EvaluateRunHealthInput): Promise< else if ((attempt.reworkEpoch ?? 0) > 0) reworkAttempts += 1; else ordinaryAttempts += 1; - const delegated = isDelegatedStep(attempt.nodeId); - if (delegated) delegatedAttempts += 1; + const adapter = stepAdapter(attempt.nodeId); + if (adapter === 'delegated') delegatedAttempts += 1; + else if (adapter === 'exec') execAttempts += 1; else piAttempts += 1; const stepNode = dagById.get(attempt.nodeId); @@ -650,7 +747,7 @@ export async function evaluateRunHealth(input: EvaluateRunHealthInput): Promise< const stepBucket = ensureStepBucket(attempt.nodeId, roleId); const roleBucket = roleId !== null ? ensureRoleBucket(roleId) : null; - if (delegated && attempt.purpose !== 'compaction') { + if (adapter === 'delegated' && attempt.purpose !== 'compaction') { stepBucket.modelCalls += 1; stepBucket.unknownCostCount += 1; if (roleBucket !== null) { @@ -659,6 +756,17 @@ export async function evaluateRunHealth(input: EvaluateRunHealthInput): Promise< } totalsBucket.modelCalls += 1; totalsBucket.unknownCostCount += 1; + } else if (adapter === 'exec' && attempt.purpose !== 'compaction') { + const execEntry = execEntryByAttemptId.get(attempt.id); + handledExecAttemptIds.add(attempt.id); + stepBucket.modelCalls += 1; + addExecUsageEntryToBucket(stepBucket, execEntry); + if (roleBucket !== null) { + roleBucket.modelCalls += 1; + addExecUsageEntryToBucket(roleBucket, execEntry); + } + totalsBucket.modelCalls += 1; + addExecUsageEntryToBucket(totalsBucket, execEntry); } const preCp = checkpointById.get(phaseCheckpointId(input.runId, `role.${attempt.ordinal}.pre`)); @@ -679,7 +787,7 @@ export async function evaluateRunHealth(input: EvaluateRunHealthInput): Promise< } } - if (!delegated && attempt.finished !== null) { + if (adapter === 'pi' && attempt.finished !== null) { const parsed = await reader.readJson(attempt.finished.outcome, RUN_EVAL_ARTIFACT_MAX_BYTES); if (!parsed.ok || !isRecord(parsed.value)) { unreadablePiOutcomeCount += 1; @@ -707,6 +815,22 @@ export async function evaluateRunHealth(input: EvaluateRunHealthInput): Promise< } } + for (const entry of execUsage.entries) { + if (handledExecAttemptIds.has(entry.attemptId)) continue; + execAttempts += 1; + const roleId = dagById.get(entry.nodeId)?.roleId ?? null; + const stepBucket = ensureStepBucket(entry.nodeId, roleId); + const roleBucket = roleId !== null ? ensureRoleBucket(roleId) : null; + stepBucket.modelCalls += 1; + addExecUsageEntryToBucket(stepBucket, entry); + if (roleBucket !== null) { + roleBucket.modelCalls += 1; + addExecUsageEntryToBucket(roleBucket, entry); + } + totalsBucket.modelCalls += 1; + addExecUsageEntryToBucket(totalsBucket, entry); + } + // 2. Model request tokens and cost breakdown. for (const req of records.requests) { const attempt = findAttemptForRequest(attempts, req.sequence); @@ -804,11 +928,11 @@ export async function evaluateRunHealth(input: EvaluateRunHealthInput): Promise< const allRolesDelegated = plan.roles.length > 0 && plan.roles.every(role => role.adapter === 'delegated'); let toolTelemetry: RunEvalToolTelemetryState; - if (delegatedAttempts > 0 && piAttempts === 0 && totalToolOps === 0) { + if (delegatedAttempts > 0 && piAttempts === 0 && execAttempts === 0 && totalToolOps === 0) { toolTelemetry = 'delegated_unavailable'; - } else if (piAttempts === 0 && delegatedAttempts === 0 && allRolesDelegated && totalToolOps === 0) { + } else if (piAttempts === 0 && delegatedAttempts === 0 && execAttempts === 0 && allRolesDelegated && totalToolOps === 0) { toolTelemetry = 'delegated_unavailable'; - } else if (delegatedAttempts > 0 && (piAttempts > 0 || totalToolOps > 0)) { + } else if ((delegatedAttempts > 0 || execAttempts > 0) && (piAttempts > 0 || totalToolOps > 0)) { toolTelemetry = 'partial'; } else if (totalToolOps > 0) { toolTelemetry = unreadableToolOps === 0 ? 'available' : parsedToolOps > 0 ? 'partial' : 'unavailable'; diff --git a/packages/controller/test/exec-usage.test.ts b/packages/controller/test/exec-usage.test.ts new file mode 100644 index 00000000..6fc796f5 --- /dev/null +++ b/packages/controller/test/exec-usage.test.ts @@ -0,0 +1,892 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import { chmod, lstat, mkdir, readFile, readdir, writeFile } from 'node:fs/promises'; +import { join } from 'node:path'; +import { reopenLocalRun, type Authority, type OperationRecord } from '@loopwright/state'; +import { aggregateUsage, LIMITS, type ArtifactRef, type UsageSummary } from '@loopwright/core'; +import { inspectRun, resumeCycle, runCycleWithPorts, type CycleExecution, type RunEvalReport } from '../src/index.js'; +import { createCycle, Cycle, type RunDescriptor } from '../src/controller.js'; +import { ControllerFailure, type ControllerDiagnostic } from '../src/errors.js'; +import { collectExecUsage, EXEC_ROLE_METHOD, EXEC_ROLE_PRODUCER_ID, execUnknownUsageRequestId, execUsageRequestId } from '../src/exec-role.js'; +import { installedHandlerDigests } from '../src/handlers.js'; +import { parsePrivateJson } from '../src/parser.js'; +import { journal, ProgressStore } from '../src/progress.js'; +import { reconcileInterruptedOperations } from '../src/recovery.js'; +import { stateValue } from '../src/storage.js'; +import { configurationFixture } from './config-fixtures.js'; +import { setFixture } from './progress-fixtures.js'; + +const CANARY_SECRET = 'EXEC_USAGE_CANARY_Aa11Bb22Cc33'; +const GIT_ENV = Object.freeze({ + PATH: '/usr/bin:/bin', + LANG: 'C', + LC_ALL: 'C', + GIT_CONFIG_NOSYSTEM: '1', + GIT_CONFIG_GLOBAL: '/dev/null', + HOME: '/nonexistent', + GIT_TERMINAL_PROMPT: '0', +}); + +const STUB_SOURCE = `import { appendFileSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; + +const mode = process.argv[2] ?? ''; +const candidateDir = process.argv.at(-1) ?? ''; + +function writeCandidate(relPath, content) { + const full = join(candidateDir, relPath); + mkdirSync(dirname(full), { recursive: true, mode: 0o700 }); + writeFileSync(full, content, { mode: 0o600 }); +} + +function recordSpawn() { + const sentinel = process.env.SENTINEL_FILE; + if (sentinel) appendFileSync(sentinel, (process.env.LOOPWRIGHT_STEP_ID ?? '') + '\\n', { mode: 0o600 }); +} + +function nextCounter() { + const counterFile = process.env.COUNTER_FILE; + if (!counterFile) return 1; + let count = 0; + try { + count = Number.parseInt(readFileSync(counterFile, 'utf8').trim(), 10) || 0; + } catch { + count = 0; + } + const next = count + 1; + writeFileSync(counterFile, String(next), { mode: 0o600 }); + return next; +} + +recordSpawn(); + +if (mode === 'reported-multi') { + writeCandidate('packages/hello.txt', 'hello\\n'); + writeFileSync( + process.env.LOOPWRIGHT_USAGE_OUT, + JSON.stringify({ + requests: [ + { requestId: 'req-1', inputTokens: 120, outputTokens: 30, costMicrousd: 1500 }, + { requestId: 'req-2', inputTokens: 80, outputTokens: 20, costMicrousd: 900 }, + ], + }), + { mode: 0o600 }, + ); + process.exit(0); +} + +if (mode === 'reported-large-stdio') { + writeCandidate('packages/hello.txt', 'hello\\n'); + process.stdout.write('x'.repeat(100_000)); + process.stderr.write('y'.repeat(100_000)); + writeFileSync( + process.env.LOOPWRIGHT_USAGE_OUT, + JSON.stringify({ + requests: [ + { requestId: 'req-large', inputTokens: 45, outputTokens: 15, costMicrousd: 300 }, + ], + }), + { mode: 0o600 }, + ); + process.exit(0); +} + +if (mode === 'no-usage') { + writeCandidate('packages/hello.txt', 'no-usage\\n'); + process.exit(0); +} + +if (mode === 'empty-usage') { + writeCandidate('packages/hello.txt', 'empty-usage\\n'); + writeFileSync(process.env.LOOPWRIGHT_USAGE_OUT, JSON.stringify({ requests: [] }), { mode: 0o600 }); + process.exit(0); +} + +if (mode === 'rework-collide') { + const attempt = nextCounter(); + if (attempt === 1) { + writeCandidate('packages/result.json', JSON.stringify({ ok: false })); + writeFileSync( + process.env.LOOPWRIGHT_USAGE_OUT, + JSON.stringify({ + requests: [ + { requestId: 'req-1', inputTokens: 50, outputTokens: 10, costMicrousd: 400 }, + { requestId: 'a-very-long-request-id-exceeding-fifteen-chars', inputTokens: 25, outputTokens: 5, costMicrousd: 200 }, + ], + }), + { mode: 0o600 }, + ); + } else { + writeCandidate('packages/result.json', JSON.stringify({ ok: true })); + writeFileSync( + process.env.LOOPWRIGHT_USAGE_OUT, + JSON.stringify({ + requests: [ + { requestId: 'req-1', inputTokens: 70, outputTokens: 15, costMicrousd: 600 }, + { requestId: 'a-very-long-request-id-exceeding-fifteen-chars', inputTokens: 35, outputTokens: 10, costMicrousd: 300 }, + ], + }), + { mode: 0o600 }, + ); + } + process.exit(0); +} + +if (mode === 'reported-step-one') { + writeCandidate('packages/step1.txt', 'step1\\n'); + writeFileSync( + process.env.LOOPWRIGHT_USAGE_OUT, + JSON.stringify({ + requests: [{ requestId: 'req-1', inputTokens: 100, outputTokens: 40, costMicrousd: 1200 }], + }), + { mode: 0o600 }, + ); + process.exit(0); +} + +if (mode === 'reported-step-two') { + writeCandidate('packages/step2.txt', 'step2\\n'); + writeFileSync( + process.env.LOOPWRIGHT_USAGE_OUT, + JSON.stringify({ + requests: [{ requestId: 'req-1', inputTokens: 60, outputTokens: 20, costMicrousd: 800 }], + }), + { mode: 0o600 }, + ); + process.exit(0); +} + +if (mode === 'sleep') { + setTimeout(() => {}, 60_000); +} else { + process.stderr.write('unknown mode: ' + mode + '\\n'); + process.exit(2); +} +`; + +function assertUsageEqual(actual: UsageSummary | null, expected: UsageSummary | null): void { + assert.deepEqual(JSON.parse(JSON.stringify(actual)), JSON.parse(JSON.stringify(expected))); +} + +function assertOk(res: { readonly ok: boolean; readonly value?: T; readonly error?: ControllerDiagnostic }, msg = ''): T { + assert.equal(res.ok, true, `${msg}: ${JSON.stringify(res.error)}`); + if (!res.ok) throw new Error('expected ok'); + return res.value as T; +} + +async function cleanupFixtureRoot(root: string): Promise { + const openUp = async (abs: string): Promise => { + const st = await lstat(abs).catch(() => null); + if (!st || st.isSymbolicLink() || !st.isDirectory()) return; + await chmod(abs, 0o700).catch(() => undefined); + for (const entry of await readdir(abs).catch(() => [] as string[])) { + await openUp(join(abs, entry)); + } + }; + await openUp(root); +} + +interface ExecUsageFixtureOptions { + readonly mode: string; + readonly secondMode?: string; + readonly checkPath?: string; + readonly initialResultOk?: boolean; + readonly verifyOnRework?: number; + readonly maxModelCalls?: number; + readonly captureBytes?: number; + readonly timeoutMs?: number; + readonly extraEnv?: Readonly>; +} + +async function execUsageFixture(options: ExecUsageFixtureOptions) { + const f = await configurationFixture(); + const repository = join(f.root, 'repository'); + const runRoot = join(f.root, 'runs'); + const stubPath = join(f.operator, 'exec-usage-stub.mjs'); + const sentinelPath = join(f.root, 'spawn-sentinel.log'); + const counterPath = join(f.root, 'rework-counter.txt'); + await mkdir(repository, { mode: 0o700 }); + await writeFile(stubPath, STUB_SOURCE, { mode: 0o600 }); + + const checkPath = options.checkPath ?? 'result.json'; + const checkAbs = join(repository, checkPath); + await mkdir(join(repository, 'packages'), { recursive: true, mode: 0o700 }); + await writeFile(checkAbs, JSON.stringify({ ok: options.initialResultOk ?? true }), { mode: 0o600 }); + await writeFile(join(repository, 'packages', 'seed.txt'), 'seed\n', { mode: 0o600 }); + + const git = (args: string[]) => execFileSync('/usr/bin/git', ['-c', 'core.hooksPath=/dev/null', ...args], { cwd: repository, env: GIT_ENV, encoding: 'utf8' }); + git(['init', '-q']); + git(['add', '.']); + git(['-c', 'user.name=Controller Fixture', '-c', 'user.email=fixture@localhost.invalid', 'commit', '-qm', 'initial baseline']); + const revision = git(['rev-parse', 'HEAD']).trim(); + + f.environment['LLM_TOKEN'] = CANARY_SECRET; + + const installed = await installedHandlerDigests(); + const baseHandlers = f.registry.spec.handlers.map(handler => + handler.id === 'tests' + ? { + ...handler, + digest: installed['json-artifact.v1'], + parameters: { ...handler.parameters, path: checkPath }, + } + : handler, + ); + + const envMap = { + FORGEVO_LLM_BASE_URL: 'https://api.example.com/v1', + SENTINEL_FILE: sentinelPath, + COUNTER_FILE: counterPath, + ...(options.extraEnv ?? {}), + }; + + const secondRoleProfile = options.secondMode !== undefined + ? [{ + id: 'finisher', + adapter: 'exec' as const, + runtimeRef: null, + providerCredentialRef: null, + selection: { provider: 'openai', model: 'gpt-5', thinking: 'medium' }, + tools: ['read', 'write', 'edit'], + mcp: null, + exec: { + command: [process.execPath, stubPath], + args: [options.secondMode], + env: envMap, + credentialRefs: ['llm-token'], + timeoutMs: options.timeoutMs ?? 20_000, + ...(options.captureBytes !== undefined ? { captureBytes: options.captureBytes } : {}), + }, + }] + : []; + + setFixture(f.registry, ['spec', 'runtimeProfiles'], []); + setFixture(f.registry, ['spec', 'resources'], []); + setFixture(f.registry, ['spec', 'handlers'], baseHandlers); + setFixture(f.registry, ['spec', 'credentialBindings'], [{ + id: 'llm-token', + consumer: 'exec', + destinationRef: 'openai', + environmentNames: ['LLM_TOKEN'], + template: '${LLM_TOKEN}', + }]); + setFixture(f.registry, ['spec', 'environmentBindings'], [{ + name: 'LLM_TOKEN', + classification: 'credential', + paths: ['/spec/credentials/0/template'], + }]); + setFixture(f.registry, ['spec', 'roleProfiles'], [ + { + id: 'author', + adapter: 'exec', + runtimeRef: null, + providerCredentialRef: null, + selection: { provider: 'openai', model: 'gpt-5', thinking: 'medium' }, + tools: ['read', 'write', 'edit'], + mcp: null, + exec: { + command: [process.execPath, stubPath], + args: [options.mode], + env: envMap, + credentialRefs: ['llm-token'], + timeoutMs: options.timeoutMs ?? 20_000, + ...(options.captureBytes !== undefined ? { captureBytes: options.captureBytes } : {}), + }, + }, + ...secondRoleProfile, + ]); + + setFixture(f.config, ['spec', 'credentials'], [{ ref: 'llm-token', template: '${LLM_TOKEN}' }]); + setFixture(f.config, ['spec', 'task', 'spec', 'target', 'baseRevision'], revision); + setFixture(f.config, ['spec', 'task', 'spec', 'target', 'sourceRevision'], revision); + if (options.maxModelCalls !== undefined) { + setFixture(f.config, ['spec', 'task', 'spec', 'budgets', 'maxModelCalls'], options.maxModelCalls); + setFixture(f.config, ['spec', 'task', 'spec', 'budgets', 'maxConcurrency'], Math.min(1, options.maxModelCalls)); + setFixture(f.config, ['spec', 'task', 'spec', 'budgets', 'maxFormatRepairs'], Math.min(1, options.maxModelCalls)); + setFixture(f.config, ['spec', 'task', 'spec', 'budgets', 'maxImplementationRepairs'], Math.min(1, options.maxModelCalls)); + setFixture(f.config, ['spec', 'task', 'spec', 'budgets', 'maxTransportRetries'], Math.min(1, options.maxModelCalls)); + } + setFixture(f.config, ['spec', 'task', 'spec', 'roles'], [ + { + id: 'author', + adapter: 'exec', + provider: 'openai', + model: 'gpt-5', + thinking: 'medium', + tools: ['read', 'write'], + }, + ...(options.secondMode !== undefined + ? [{ + id: 'finisher', + adapter: 'exec' as const, + provider: 'openai', + model: 'gpt-5', + thinking: 'medium', + tools: ['read', 'write'], + }] + : []), + ]); + setFixture(f.config, ['spec', 'profiles', 'roles'], [ + { roleId: 'author', profileRef: 'author' }, + ...(options.secondMode !== undefined ? [{ roleId: 'finisher', profileRef: 'finisher' }] : []), + ]); + + if (options.secondMode !== undefined) { + setFixture(f.config, ['spec', 'task', 'spec', 'steps'], [ + { id: 'implement', kind: 'agent', uses: 'package.patch', roleId: 'author', dependsOn: [] }, + { id: 'finish', kind: 'agent', uses: 'package.patch', roleId: 'finisher', dependsOn: ['implement'] }, + { id: 'verify', kind: 'check', uses: 'tests', roleId: null, dependsOn: ['finish'] }, + ]); + setFixture(f.config, ['spec', 'profiles', 'steps'], [ + { stepId: 'implement', handlerRef: 'package.patch' }, + { stepId: 'finish', handlerRef: 'package.patch' }, + { stepId: 'verify', handlerRef: 'tests' }, + ]); + } else { + setFixture(f.config, ['spec', 'task', 'spec', 'steps'], [ + { id: 'implement', kind: 'agent', uses: 'package.patch', roleId: 'author', dependsOn: [] }, + { + id: 'verify', + kind: 'check', + uses: 'tests', + roleId: null, + dependsOn: ['implement'], + ...(options.verifyOnRework !== undefined ? { onRework: { rejectTo: 'implement', maxReworks: options.verifyOnRework } } : {}), + }, + ]); + setFixture(f.config, ['spec', 'profiles', 'steps'], [ + { stepId: 'implement', handlerRef: 'package.patch' }, + { stepId: 'verify', handlerRef: 'tests' }, + ]); + } + + await f.save(); + const loaded = assertOk(await f.load(), 'load exec usage fixture'); + return { + ...f, + repository, + runRoot, + sentinelPath, + counterPath, + loaded, + closeFixture: async () => { + await cleanupFixtureRoot(f.root); + await f.cleanup(); + }, + }; +} + +async function readStoreJournal(runRoot: string, runId: string) { + const runDir = join(runRoot, runId); + const descriptor = JSON.parse(await readFile(join(runDir, 'run.json'), 'utf8')) as RunDescriptor; + const artifactsDir = join(runDir, 'artifacts'); + const reader = { read: async (ref: ArtifactRef) => new Uint8Array(await readFile(join(artifactsDir, ref.name))) }; + const plan = parsePrivateJson(await reader.read(descriptor.plan), 4_194_304) as unknown as import('../src/types.js').CompiledPlan; + const store = stateValue(reopenLocalRun(descriptor.identity)); + try { + const progress = new ProgressStore(store, null, reader, plan, descriptor.identity.lock, descriptor.plan, descriptor.source); + const head = await progress.read(); + const records = journal(store); + return { descriptor, artifactsDir, plan, head, records }; + } finally { + stateValue(store.close()); + } +} + +test('reported exec usage aggregates into RunResult, inspectRun, usage.json, and run-eval without writing LocalRunStore.requests', async () => { + const f = await execUsageFixture({ mode: 'reported-multi' }); + const runId = 'exec-usage-reported-multi'; + try { + const execution: CycleExecution = assertOk( + await runCycleWithPorts({ configuration: f.loaded, repository: f.repository, runRoot: f.runRoot, runId }), + 'runCycleWithPorts', + ); + assert.equal(execution.kind, 'result', JSON.stringify(execution)); + if (execution.kind !== 'result') return; + assert.equal(execution.result.spec.status, 'completed'); + + const usage = execution.result.spec.usage; + assert.equal(usage.requests.length, 2); + assert.deepEqual(usage.inputTokens, { knownSubtotal: 200, unknownCount: 0, completeness: 'complete', provenance: 'reported' }); + assert.deepEqual(usage.outputTokens, { knownSubtotal: 50, unknownCount: 0, completeness: 'complete', provenance: 'reported' }); + assert.deepEqual(usage.totalTokens, { knownSubtotal: 250, unknownCount: 0, completeness: 'complete', provenance: 'reported' }); + assert.deepEqual(usage.costMicrousd, { knownSubtotal: 2400, unknownCount: 0, completeness: 'complete', provenance: 'reported' }); + + const { records } = await readStoreJournal(f.runRoot, runId); + assert.equal(records.requests.length, 0, 'LocalRunStore.requests stays empty for exec runs'); + + const outputDir = join(f.root, 'inspect-reported'); + const inspected = assertOk(await inspectRun({ runRoot: f.runRoot, runId, output: outputDir }), 'inspectRun'); + assertUsageEqual(inspected.usage, usage); + assert.equal(inspected.status.currentState?.ledger.admittedCalls, 1); + + const usageDoc = JSON.parse(await readFile(join(outputDir, 'usage.json'), 'utf8')) as { + readonly ledger: { readonly admittedCalls: number }; + readonly requests: readonly { readonly requestId: string; readonly source?: string; readonly usageReported?: boolean }[]; + readonly summary: UsageSummary | null; + }; + assert.equal(usageDoc.ledger.admittedCalls, 1); + assert.equal(usageDoc.requests.length, 2); + assert.equal(usageDoc.requests.every(r => r.source === 'exec' && r.usageReported === true), true); + assertUsageEqual(usageDoc.summary, usage); + + const runEval = JSON.parse(await readFile(join(outputDir, 'run-eval.json'), 'utf8')) as RunEvalReport; + assert.equal(runEval.toolTelemetry, 'unavailable'); + assert.equal(runEval.toolRepeats.circuitBreaker, 'unavailable'); + assert.equal(runEval.breakdown.totals.modelCalls, 1); + assert.equal(runEval.breakdown.totals.toolCalls, 0); + assert.deepEqual(runEval.breakdown.totals.tokens, { input: 200, output: 50, total: 250 }); + assert.equal(runEval.breakdown.totals.costMicrousd, 2400); + assert.equal(runEval.breakdown.totals.costCompleteness, 'complete'); + const implStep = runEval.breakdown.byStep.find(s => s.stepId === 'implement'); + assert.ok(implStep); + assert.equal(implStep.modelCalls, 1); + assert.equal(implStep.costMicrousd, 2400); + assert.equal(implStep.costCompleteness, 'complete'); + assert.deepEqual(implStep.tokens, { input: 200, output: 50, total: 250 }); + const authorRole = runEval.breakdown.byRole.find(r => r.roleId === 'author'); + assert.ok(authorRole); + assert.equal(authorRole.modelCalls, 1); + assert.equal(authorRole.costMicrousd, 2400); + assert.equal(authorRole.costCompleteness, 'complete'); + } finally { + await f.closeFixture(); + } + + // Also verify large exec-outcome (> 65_536 bytes of captured stdout/stderr) parses cleanly with EXEC_OUTCOME_MAX_BYTES + const fLarge = await execUsageFixture({ mode: 'reported-large-stdio', captureBytes: 262_144 }); + const runIdLarge = 'exec-usage-large-stdio'; + try { + const execution = assertOk( + await runCycleWithPorts({ configuration: fLarge.loaded, repository: fLarge.repository, runRoot: fLarge.runRoot, runId: runIdLarge }), + 'run large stdio', + ); + assert.equal(execution.kind, 'result'); + if (execution.kind !== 'result') return; + assert.deepEqual(execution.result.spec.usage.costMicrousd, { + knownSubtotal: 300, + unknownCount: 0, + completeness: 'complete', + provenance: 'reported', + }); + const inspected = assertOk(await inspectRun({ runRoot: fLarge.runRoot, runId: runIdLarge }), 'inspect large stdio'); + assert.equal(inspected.runEval?.breakdown.totals.costMicrousd, 300); + assert.equal(inspected.runEval?.breakdown.totals.costCompleteness, 'complete'); + } finally { + await fLarge.closeFixture(); + } +}); + +test('missing usage file records unknown provenance and unavailable cost rather than reported zero', async () => { + const f = await execUsageFixture({ mode: 'no-usage' }); + const runId = 'exec-usage-missing'; + try { + const execution = assertOk( + await runCycleWithPorts({ configuration: f.loaded, repository: f.repository, runRoot: f.runRoot, runId }), + 'runCycleWithPorts', + ); + assert.equal(execution.kind, 'result'); + if (execution.kind !== 'result') return; + assert.equal(execution.result.spec.status, 'completed'); + + const usage = execution.result.spec.usage; + assert.equal(usage.requests.length, 1); + assert.deepEqual(usage.inputTokens, { knownSubtotal: 0, unknownCount: 1, completeness: 'partial', provenance: 'unknown' }); + assert.deepEqual(usage.outputTokens, { knownSubtotal: 0, unknownCount: 1, completeness: 'partial', provenance: 'unknown' }); + assert.deepEqual(usage.totalTokens, { knownSubtotal: 0, unknownCount: 2, completeness: 'partial', provenance: 'unknown' }); + assert.deepEqual(usage.costMicrousd, { knownSubtotal: 0, unknownCount: 1, completeness: 'partial', provenance: 'unknown' }); + + const { records } = await readStoreJournal(f.runRoot, runId); + assert.equal(records.requests.length, 0); + + const outputDir = join(f.root, 'inspect-missing'); + const inspected = assertOk(await inspectRun({ runRoot: f.runRoot, runId, output: outputDir }), 'inspectRun'); + assertUsageEqual(inspected.usage, usage); + assert.ok(inspected.runEval !== null); + assert.equal(inspected.runEval!.toolTelemetry, 'unavailable'); + assert.equal(inspected.runEval!.toolRepeats.circuitBreaker, 'unavailable'); + assert.equal(inspected.runEval!.breakdown.totals.modelCalls, 1); + assert.equal(inspected.runEval!.breakdown.totals.costMicrousd, null); + assert.equal(inspected.runEval!.breakdown.totals.costCompleteness, 'unavailable'); + } finally { + await f.closeFixture(); + } +}); + +test('explicit empty usage file reports complete reported zero usage', async () => { + const f = await execUsageFixture({ mode: 'empty-usage' }); + const runId = 'exec-usage-empty'; + try { + const execution = assertOk( + await runCycleWithPorts({ configuration: f.loaded, repository: f.repository, runRoot: f.runRoot, runId }), + 'runCycleWithPorts', + ); + assert.equal(execution.kind, 'result'); + if (execution.kind !== 'result') return; + assert.equal(execution.result.spec.status, 'completed'); + + const usage = execution.result.spec.usage; + assert.equal(usage.requests.length, 0); + assert.deepEqual(usage.inputTokens, { knownSubtotal: 0, unknownCount: 0, completeness: 'complete', provenance: 'reported' }); + assert.deepEqual(usage.outputTokens, { knownSubtotal: 0, unknownCount: 0, completeness: 'complete', provenance: 'reported' }); + assert.deepEqual(usage.totalTokens, { knownSubtotal: 0, unknownCount: 0, completeness: 'complete', provenance: 'reported' }); + assert.deepEqual(usage.costMicrousd, { knownSubtotal: 0, unknownCount: 0, completeness: 'complete', provenance: 'reported' }); + + const outputDir = join(f.root, 'inspect-empty'); + const inspected = assertOk(await inspectRun({ runRoot: f.runRoot, runId, output: outputDir }), 'inspectRun'); + assertUsageEqual(inspected.usage, usage); + assert.equal(inspected.runEval?.toolTelemetry, 'unavailable'); + assert.equal(inspected.runEval?.toolRepeats.circuitBreaker, 'unavailable'); + assert.equal(inspected.runEval?.breakdown.totals.modelCalls, 1); + assert.equal(inspected.runEval?.breakdown.totals.costMicrousd, 0); + assert.equal(inspected.runEval?.breakdown.totals.costCompleteness, 'complete'); + } finally { + await f.closeFixture(); + } +}); + +test('rework attempts namespace colliding requestIds cleanly and mixed reported plus unknown yields partial totals', async () => { + // Part A: check onRework triggers two attempts both emitting identical requestIds (short and long) + const fRework = await execUsageFixture({ + mode: 'rework-collide', + checkPath: 'packages/result.json', + initialResultOk: false, + verifyOnRework: 1, + }); + try { + const execution = assertOk( + await runCycleWithPorts({ + configuration: fRework.loaded, + repository: fRework.repository, + runRoot: fRework.runRoot, + runId: 'exec-usage-rework-collide', + }), + 'rework run', + ); + assert.equal(execution.kind, 'result', JSON.stringify(execution)); + if (execution.kind !== 'result') return; + assert.equal(execution.result.spec.status, 'completed'); + + const usage = execution.result.spec.usage; + assert.equal(usage.requests.length, 4, 'all 4 reported requests across 2 attempts preserved'); + assert.equal(new Set(usage.requests.map(r => r.requestId)).size, 4, 'namespaced requestIds are distinct'); + assert.deepEqual(usage.inputTokens, { knownSubtotal: 180, unknownCount: 0, completeness: 'complete', provenance: 'reported' }); + assert.deepEqual(usage.outputTokens, { knownSubtotal: 40, unknownCount: 0, completeness: 'complete', provenance: 'reported' }); + assert.deepEqual(usage.totalTokens, { knownSubtotal: 220, unknownCount: 0, completeness: 'complete', provenance: 'reported' }); + assert.deepEqual(usage.costMicrousd, { knownSubtotal: 1500, unknownCount: 0, completeness: 'complete', provenance: 'reported' }); + + const inspected = assertOk( + await inspectRun({ runRoot: fRework.runRoot, runId: 'exec-usage-rework-collide' }), + 'inspect rework', + ); + assert.equal(inspected.runEval?.breakdown.totals.modelCalls, 2); + assert.equal(inspected.runEval?.breakdown.totals.costMicrousd, 1500); + assert.equal(inspected.runEval?.breakdown.totals.costCompleteness, 'complete'); + } finally { + await fRework.closeFixture(); + } + + // Part B: 2-step DAG where step 1 reports usage and step 2 omits usage -> partial totals + const fMixed = await execUsageFixture({ mode: 'reported-step-one', secondMode: 'no-usage' }); + const runIdMixed = 'exec-usage-mixed-partial'; + try { + const execution = assertOk( + await runCycleWithPorts({ + configuration: fMixed.loaded, + repository: fMixed.repository, + runRoot: fMixed.runRoot, + runId: runIdMixed, + }), + 'mixed run', + ); + assert.equal(execution.kind, 'result', JSON.stringify(execution)); + if (execution.kind !== 'result') return; + assert.equal(execution.result.spec.status, 'completed'); + + const usage = execution.result.spec.usage; + assert.equal(usage.requests.length, 2); + assert.deepEqual(usage.inputTokens, { knownSubtotal: 100, unknownCount: 1, completeness: 'partial', provenance: 'reported' }); + assert.deepEqual(usage.outputTokens, { knownSubtotal: 40, unknownCount: 1, completeness: 'partial', provenance: 'reported' }); + assert.deepEqual(usage.totalTokens, { knownSubtotal: 140, unknownCount: 2, completeness: 'partial', provenance: 'reported' }); + assert.deepEqual(usage.costMicrousd, { knownSubtotal: 1200, unknownCount: 1, completeness: 'partial', provenance: 'reported' }); + + const inspected = assertOk(await inspectRun({ runRoot: fMixed.runRoot, runId: runIdMixed }), 'inspect mixed'); + assert.ok(inspected.runEval !== null); + assert.equal(inspected.runEval!.breakdown.totals.modelCalls, 2); + assert.equal(inspected.runEval!.breakdown.totals.costMicrousd, 1200); + assert.equal(inspected.runEval!.breakdown.totals.costCompleteness, 'partial'); + assert.equal(inspected.runEval!.breakdown.byStep.find(s => s.stepId === 'implement')?.costCompleteness, 'complete'); + assert.equal(inspected.runEval!.breakdown.byStep.find(s => s.stepId === 'finish')?.costCompleteness, 'unavailable'); + } finally { + await fMixed.closeFixture(); + } +}); + +test('maxModelCalls enforces hard admission before spawning a second exec step and settles exhausted', async () => { + const f = await execUsageFixture({ + mode: 'reported-step-one', + secondMode: 'reported-step-two', + maxModelCalls: 1, + }); + const runId = 'exec-usage-max-model-calls'; + try { + const execution = assertOk( + await runCycleWithPorts({ configuration: f.loaded, repository: f.repository, runRoot: f.runRoot, runId }), + 'run with maxModelCalls=1', + ); + assert.equal(execution.kind, 'result', JSON.stringify(execution)); + if (execution.kind !== 'result') return; + assert.equal(execution.result.spec.status, 'exhausted'); + + const spawns = (await readFile(f.sentinelPath, 'utf8')).trim().split('\n').filter(Boolean); + assert.deepEqual(spawns, ['implement'], 'second exec step never spawned'); + + const { artifactsDir, records } = await readStoreJournal(f.runRoot, runId); + const execOps = records.operations.filter(op => op.intent.effect === 'local_write' && op.intent.targetIdentity.startsWith('exec:')); + assert.equal(execOps.length, 1, 'zero second exec operation in SQLite store'); + const bindings = (await readdir(artifactsDir)).filter(name => /^exec-role-producer-[0-9a-f]{64}\.binding\.json$/.test(name)); + assert.equal(bindings.length, 1, 'only one exec binding marker'); + + const outputDir = join(f.root, 'inspect-exhausted'); + const inspected = assertOk(await inspectRun({ runRoot: f.runRoot, runId, output: outputDir }), 'inspect exhausted'); + assert.equal(inspected.status.currentState?.ledger.admittedCalls, 1); + assertUsageEqual(inspected.usage, execution.result.spec.usage); + const usageDoc = JSON.parse(await readFile(join(outputDir, 'usage.json'), 'utf8')) as { + readonly ledger: { readonly admittedCalls: number }; + readonly requests: readonly unknown[]; + readonly summary: UsageSummary | null; + }; + assert.equal(usageDoc.ledger.admittedCalls, 1); + assert.equal(usageDoc.requests.length, 1); + assert.deepEqual(usageDoc.summary?.costMicrousd, { + knownSubtotal: 1200, + unknownCount: 0, + completeness: 'complete', + provenance: 'reported', + }); + } finally { + await f.closeFixture(); + } +}); + +test('fallback inspectRun without result.json reports unknown provenance for interrupted exec settled as exec_unknown', { timeout: 30_000 }, async () => { + const f = await execUsageFixture({ mode: 'sleep', timeoutMs: 20_000 }); + const runId = 'exec-usage-crash-unknown'; + const input = { configuration: f.loaded, repository: f.repository, runRoot: f.runRoot, runId }; + const context = await createCycle(input, {}); + const original = stateValue(context.store.inspect()); + let cycle: Cycle | null = null; + let recoveryAuth: Authority | null = null; + try { + cycle = new Cycle(context); + await cycle.bootstrap(); + const continuation = cycle.role('implement').then( + () => assert.fail('interrupted exec continuation must not complete'), + err => { + assert.ok(err instanceof ControllerFailure); + }, + ); + + let binding: Record | null = null; + const deadline = Date.now() + 10_000; + while (Date.now() < deadline) { + const names = await readdir(context.artifacts.directory).catch(() => [] as string[]); + const found = names.find(name => /^exec-role-producer-[0-9a-f]{64}\.binding\.json$/.test(name)); + if (found) { + try { + binding = JSON.parse(await readFile(join(context.artifacts.directory, found), 'utf8')) as Record; + break; + } catch { + // wait for fsync + } + } + await new Promise(resolve => setTimeout(resolve, 20)); + } + assert.ok(binding, 'binding marker written'); + + await cycle.deadline.dispose(); + stateValue(context.store.release(context.authority)); + const crashedHead = await context.progress.read(); + const view = stateValue(context.store.inspect()); + + recoveryAuth = stateValue( + context.store.claim({ + ownerId: 'controller.' + context.owner.nonce, + expectedGeneration: view.owner.generation, + expectedRevision: view.revision, + mode: 'recovery', + }), + ).authority; + await reconcileInterruptedOperations({ ...context, authority: recoveryAuth }, crashedHead, cycle.candidate, original.storeId); + await continuation; + + await cycle.events.close(); + stateValue(context.store.release(recoveryAuth)); + recoveryAuth = null; + stateValue(context.store.close()); + await context.owner.release(); + cycle = null; + + const resumed = await resumeCycle(input); + assert.equal(resumed.ok, false); + if (!resumed.ok) assert.equal(resumed.error.code, 'RECOVERY_REQUIRED'); + + const outputDir = join(f.root, 'inspect-crashed'); + const inspected = assertOk(await inspectRun({ runRoot: f.runRoot, runId, output: outputDir }), 'inspect crashed run'); + assert.equal(inspected.manifest?.entries.find(e => e.name === 'result.json')?.presence, 'absent'); + assert.ok(inspected.usage !== null, 'fallback usage summary is populated'); + assert.equal(inspected.usage!.requests.length, 1); + assert.deepEqual(inspected.usage!.inputTokens, { knownSubtotal: 0, unknownCount: 1, completeness: 'partial', provenance: 'unknown' }); + assert.deepEqual(inspected.usage!.outputTokens, { knownSubtotal: 0, unknownCount: 1, completeness: 'partial', provenance: 'unknown' }); + assert.deepEqual(inspected.usage!.totalTokens, { knownSubtotal: 0, unknownCount: 2, completeness: 'partial', provenance: 'unknown' }); + assert.deepEqual(inspected.usage!.costMicrousd, { knownSubtotal: 0, unknownCount: 1, completeness: 'partial', provenance: 'unknown' }); + + const usageDoc = JSON.parse(await readFile(join(outputDir, 'usage.json'), 'utf8')) as { + readonly ledger: { readonly admittedCalls: number }; + readonly requests: readonly { readonly usageReported?: boolean }[]; + readonly summary: UsageSummary | null; + }; + assert.equal(usageDoc.ledger.admittedCalls, 1); + assert.equal(usageDoc.requests.length, 1); + assert.equal(usageDoc.requests[0]!.usageReported, false); + assertUsageEqual(usageDoc.summary, inspected.usage); + + assert.equal(inspected.runEval?.toolTelemetry, 'unavailable'); + assert.equal(inspected.runEval?.toolRepeats.circuitBreaker, 'unavailable'); + assert.equal(inspected.runEval?.breakdown.totals.modelCalls, 1); + assert.equal(inspected.runEval?.breakdown.totals.costMicrousd, null); + assert.equal(inspected.runEval?.breakdown.totals.costCompleteness, 'unavailable'); + } finally { + if (cycle) { + await cycle.deadline.dispose().catch(() => undefined); + await cycle.events.close().catch(() => undefined); + if (recoveryAuth) { + try { stateValue(context.store.release(recoveryAuth)); } catch { /* ignore */ } + } + try { stateValue(context.store.close()); } catch { /* ignore */ } + await context.owner.release().catch(() => undefined); + } + await f.closeFixture(); + } +}); + +test('collectExecUsage namespaces ids unambiguously, skips not_executed, handles unreadable outcomes as unknown, and bounds LIMITS.requests', async () => { + const idPattern = /^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/; + const attemptA = 'attempt.' + 'a'.repeat(40); + const attemptB = 'attempt.' + 'b'.repeat(40); + const shortA = execUsageRequestId(attemptA, 'req-1'); + const shortB = execUsageRequestId(attemptB, 'req-1'); + const longA = execUsageRequestId(attemptA, 'request-id-exceeding-fifteen-characters'); + const ambig1 = execUsageRequestId('a.b', 'c'); + const ambig2 = execUsageRequestId('a', 'b.c'); + const unkA = execUnknownUsageRequestId('exec.' + '1'.repeat(40), attemptA); + + for (const candidate of [shortA, shortB, longA, ambig1, ambig2, unkA]) { + assert.ok(candidate.length <= LIMITS.identifier, `id within limit: ${candidate}`); + assert.match(candidate, idPattern, `valid identifier: ${candidate}`); + } + assert.notEqual(shortA, shortB); + assert.notEqual(ambig1, ambig2); + assert.notEqual(shortA, unkA); + + const digest = { algorithm: 'sha256' as const, hex: '0'.repeat(64) }; + const makeExecOp = ( + sequence: number, + attemptId: string, + state: OperationRecord['state'], + outcome: 'succeeded' | 'failed' | 'not_executed' | null, + artifactName = 'exec-outcome-' + sequence + '.json', + ): OperationRecord => ({ + sequence, + intent: { + operationId: 'exec.' + String(sequence).padStart(40, '0'), + nodeId: 'implement', + attemptId, + effect: 'local_write', + requestDigest: digest, + targetIdentity: 'exec:implement:' + sequence + ':' + '0'.repeat(64), + }, + intentDigest: digest, + intentGeneration: 1, + state, + dispatch: { + generation: 1, + dispatchId: 'dispatch.' + sequence, + revision: sequence, + }, + linkedRequestId: null, + initialReceipt: outcome === null + ? null + : { + receiptId: 'receipt.' + sequence, + outcome, + evidence: { + evidenceId: 'ev.' + sequence, + producerId: EXEC_ROLE_PRODUCER_ID, + method: EXEC_ROLE_METHOD, + subject: { + storeId: 'store.1', + runId: 'run-1', + lockHash: digest, + operationId: 'exec.' + String(sequence).padStart(40, '0'), + requestId: null, + intentDigest: digest, + dispatchGeneration: 1, + dispatchId: 'dispatch.' + sequence, + }, + artifact: { name: artifactName, digest, byteLength: 32 }, + }, + }, + reconciliation: null, + unresolvedReason: null, + }); + + const opNotExecuted = makeExecOp(1, attemptA, 'confirmed', 'not_executed'); + const opUnreadable = makeExecOp(2, attemptA, 'confirmed', 'succeeded', 'missing.json'); + const opUncertain = makeExecOp(3, attemptB, 'dispatch_uncertain', null); + const opCorrupt = makeExecOp(4, 'attempt.' + 'c'.repeat(40), 'confirmed', 'succeeded', 'corrupt.json'); + + const fakeArtifacts = { + async read(ref: ArtifactRef): Promise { + if (ref.name === 'corrupt.json') return Buffer.from('{"version":1,"usageReported":true,"usage":"not-array"}'); + throw new Error('ENOENT'); + }, + }; + + const collected = await collectExecUsage([opNotExecuted, opUnreadable, opUncertain, opCorrupt], fakeArtifacts); + assert.equal(collected.entries.length, 3, 'not_executed skipped; 3 remaining ops emitted'); + assert.equal(collected.entries.every(e => e.usageReported === false), true); + assert.equal(collected.requests.length, 3); + const summary = aggregateUsage(collected.requests); + assert.equal(summary.ok, true); + if (summary.ok) { + assert.equal(summary.value.costMicrousd.provenance, 'unknown'); + assert.equal(summary.value.costMicrousd.unknownCount, 3); + } + + const bigReqs = Array.from({ length: 600 }, (_, i) => ({ + requestId: 'req-' + i, + inputTokens: 1, + outputTokens: 1, + costMicrousd: 1, + })); + const opBig1 = makeExecOp(10, 'attempt.' + '1'.repeat(40), 'confirmed', 'succeeded', 'big-1.json'); + const opBig2 = makeExecOp(11, 'attempt.' + '2'.repeat(40), 'confirmed', 'succeeded', 'big-2.json'); + const bigArtifacts = { + async read(ref: ArtifactRef): Promise { + const op = ref.name === 'big-1.json' ? opBig1 : opBig2; + return Buffer.from(JSON.stringify({ + version: 1, + operationId: op.intent.operationId, + attemptId: op.intent.attemptId, + usageReported: true, + usage: bigReqs, + })); + }, + }; + const bigCollected = await collectExecUsage([opBig1, opBig2], bigArtifacts); + assert.equal(bigCollected.requests.length, LIMITS.requests + 1); + const overflow = aggregateUsage(bigCollected.requests); + assert.equal(overflow.ok, false); +}); diff --git a/packages/core/test/usage.test.ts b/packages/core/test/usage.test.ts index 7215133b..ee2179da 100644 --- a/packages/core/test/usage.test.ts +++ b/packages/core/test/usage.test.ts @@ -51,3 +51,43 @@ test('review R2 direct usage diagnostics use the array input root', () => { assert.equal(code(malformed), 'VALUE_TYPE'); if (!malformed.ok) assert.equal(malformed.errors[0]!.path, '/0/inputTokens'); }); + +test('usage distinguishes all-unknown, mixed reported and unknown, and explicit empty reported sets', () => { + const allUnknown = value(aggregateUsage([ + { + requestId: 'exec.unknown.0123456789abcdef0123456789abcdef', + inputTokens: { provenance: 'unknown' }, + outputTokens: { provenance: 'unknown' }, + costMicrousd: { provenance: 'unknown' }, + }, + ])); + assert.deepEqual(allUnknown.inputTokens, { knownSubtotal: 0, unknownCount: 1, completeness: 'partial', provenance: 'unknown' }); + assert.deepEqual(allUnknown.outputTokens, { knownSubtotal: 0, unknownCount: 1, completeness: 'partial', provenance: 'unknown' }); + assert.deepEqual(allUnknown.totalTokens, { knownSubtotal: 0, unknownCount: 2, completeness: 'partial', provenance: 'unknown' }); + assert.deepEqual(allUnknown.costMicrousd, { knownSubtotal: 0, unknownCount: 1, completeness: 'partial', provenance: 'unknown' }); + + const mixed = value(aggregateUsage([ + { + requestId: 'exec.r.1111111111111111111111111111111111111111', + inputTokens: { provenance: 'reported', value: 80 }, + outputTokens: { provenance: 'reported', value: 20 }, + costMicrousd: { provenance: 'reported', value: 900 }, + }, + { + requestId: 'exec.unknown.22222222222222222222222222222222', + inputTokens: { provenance: 'unknown' }, + outputTokens: { provenance: 'unknown' }, + costMicrousd: { provenance: 'unknown' }, + }, + ])); + assert.deepEqual(mixed.inputTokens, { knownSubtotal: 80, unknownCount: 1, completeness: 'partial', provenance: 'reported' }); + assert.deepEqual(mixed.outputTokens, { knownSubtotal: 20, unknownCount: 1, completeness: 'partial', provenance: 'reported' }); + assert.deepEqual(mixed.totalTokens, { knownSubtotal: 100, unknownCount: 2, completeness: 'partial', provenance: 'reported' }); + assert.deepEqual(mixed.costMicrousd, { knownSubtotal: 900, unknownCount: 1, completeness: 'partial', provenance: 'reported' }); + + const empty = value(aggregateUsage([])); + assert.deepEqual(empty.inputTokens, { knownSubtotal: 0, unknownCount: 0, completeness: 'complete', provenance: 'reported' }); + assert.deepEqual(empty.outputTokens, { knownSubtotal: 0, unknownCount: 0, completeness: 'complete', provenance: 'reported' }); + assert.deepEqual(empty.totalTokens, { knownSubtotal: 0, unknownCount: 0, completeness: 'complete', provenance: 'reported' }); + assert.deepEqual(empty.costMicrousd, { knownSubtotal: 0, unknownCount: 0, completeness: 'complete', provenance: 'reported' }); +}); diff --git a/specs/2026-11-30-managed-controller-in-process-execution.md b/specs/2026-11-30-managed-controller-in-process-execution.md index 8193b6dd..01fe757d 100644 --- a/specs/2026-11-30-managed-controller-in-process-execution.md +++ b/specs/2026-11-30-managed-controller-in-process-execution.md @@ -591,7 +591,7 @@ and T11 have disjoint `Owns:` and start together; T5 follows T2. Gate: review Acceptance: compile branches on `exec` (no runtime profile, provider credential, or context guard; the F2 `policy`; credentials equal the named refs; refuses `purpose: 'review'`); `role()` records the intent (`effect: 'local_write'`) and binding marker, takes the task prompt from the bound `pi.agent.v1` handler, sets `LOOPWRIGHT_USAGE_OUT` to a path inside the attempt scratch directory, runs the T5 runner, synthesizes the submission as `step submit` does, captures through `scanCandidateDirectory -> captureDelegatedRole -> completeCapture`, and never enters format repair; exit `3` halts the DAG (no downstream checks or rework) and settles `blocked`; `CLEANUP_FAILED` leaves the operation `dispatch_uncertain` without releasing `holdLocalActivity()` or deleting `attemptDir`; `DEADLINE` aborts settle receipt after `store.renew` and rethrow `DEADLINE`; recovery settles an `exec` operation without a proof marker as `RECOVERY_REQUIRED`, kills the recorded group, verifies `binding.workspaceDir`, and discards the attempt directory; `run` and `resume` admit all-`exec` plans and refuse mixes with `pi` or `delegated` (`CONFIG_SCHEMA`); `step next` refuses `exec` plans (`CAPABILITY_UNSUPPORTED`); `consumer: exec` bindings resolve through the vault. Tests: in-scope write settles `completed` with the file exported; out-of-scope write fails `scope.v1`; exit `3` settles `blocked` even when a required check would fail; free-text stdout never repairs; a mid-exec kill resumes as `RECOVERY_REQUIRED` without re-dispatch; a bound credential appears in no `inspect` output. Verify: `node scripts/run-tests.mjs --pkg controller` -- [ ] **T7 · `exec` budgets and usage ledger** +- [x] **T7 · `exec` budgets and usage ledger** Blocked by: T6 Owns: `packages/controller/src/budget-observations.ts`, `packages/controller/src/controller.ts`, `packages/controller/src/acceptance.ts`, `packages/controller/src/inspect.ts`, `packages/controller/src/run-eval.ts`, `packages/controller/src/exec-role.ts`, `packages/core/src/usage.ts`, `packages/core/test/usage.test.ts`, `packages/controller/test/exec-usage.test.ts` Acceptance: each `exec` dispatch charges one model call under `maxModelCalls` hard admission before the spawn; settled `exec-outcome` artifacts carry reported request records (namespaced per attempt as `:`, `provenance: 'reported'`) or `usageReported: false` (`provenance: 'unknown'`) without inserting `unknown` entries into frozen `LocalRunStore.requests`; `acceptance.ts` and `inspect.ts` aggregate them into `RunResult` and `usage.json`; `run-eval.ts` classifies `exec` honestly instead of counting it as `piAttempts` with `toolTelemetry: 'available'`. From 88d92bd33129b29682ac23346ff8f8d9429c32c0 Mon Sep 17 00:00:00 2001 From: thxCode Date: Tue, 1 Dec 2026 23:24:18 +0800 Subject: [PATCH 19/26] docs(closure): expand closure ledger to 26 rows, add ADR 0003 and isolated-host docs - Expand CLOSURE_CAPABILITY_LEDGER to 26 rows (20 closed_local, 6 unprovisioned_external): add command.v1 direct and exec role adapter as closed_local and in-process benchmark-gate hardware as blocked_external with tracked probe evidence; update closureExitCode and CLI tests. - Add ADR 0003 (Linux SQLite profiles) superseding ADR 0001's darwin/arm64-only host sentence with CI runner evidence and Linux fullfsync semantics. - Add Managed Controller in Isolated Host public walkthrough (YAML verified via loopwright check) and update controller-and-registry, task-contract, cli, coding-agents, closure-matrix, docs/README.md, site navigation/index/home, check-docs.mjs, page-map.md, and docs/site CLI tests. - Check off T8 in the spec; all 36 docs pages, Hugo site exports, 100/100 CLI tests, and closure --verify-failures (14/14) pass. Signed-off-by: thxCode --- .../loopwright-docs/references/page-map.md | 27 +- docs/README.md | 9 +- docs/configuration/controller-and-registry.md | 10 +- docs/configuration/task-contract.md | 5 +- .../adr/0003-linux-sqlite-profiles.md | 54 +++ docs/contribute/closure-matrix.md | 11 +- docs/operations/cli.md | 5 +- docs/operations/coding-agents.md | 2 + .../managed-controller-in-isolated-host.md | 332 ++++++++++++++++++ packages/cli/src/closure.ts | 33 +- packages/cli/src/main.ts | 2 +- packages/cli/test/check-docs-rules.test.ts | 4 + .../test/closure-and-failure-matrix.test.ts | 69 +++- packages/cli/test/docs-and-site.test.ts | 19 +- scripts/check-docs.mjs | 4 +- site/content/docs/_index.md | 1 + site/data/navigation.yaml | 2 + site/layouts/index.html | 1 + ...managed-controller-in-process-execution.md | 2 +- 19 files changed, 537 insertions(+), 55 deletions(-) create mode 100644 docs/contribute/adr/0003-linux-sqlite-profiles.md create mode 100644 docs/walkthroughs/managed-controller-in-isolated-host.md diff --git a/.agents/skills/loopwright-docs/references/page-map.md b/.agents/skills/loopwright-docs/references/page-map.md index c6e2ad8c..ce086420 100644 --- a/.agents/skills/loopwright-docs/references/page-map.md +++ b/.agents/skills/loopwright-docs/references/page-map.md @@ -2,16 +2,16 @@ One file owns each technical fact, schema dictionary, or operational workflow. When multiple pages touch a subject, the owning file states the normative contract and every other page links to it within allowed zone boundaries. -## Three-Zone Architecture (`34` Markdown Files Under `docs/`) +## Three-Zone Architecture (`36` Markdown Files Under `docs/`) -Loopwright maintains **`34` Markdown files** under `docs/`: **`1` shared index** (`docs/README.md`) plus **`33` zone pages** partitioned into three strict zones: +Loopwright maintains **`36` Markdown files** under `docs/`: **`1` shared index** (`docs/README.md`) plus **`35` zone pages** partitioned into three strict zones: -- **15 Public Human Site Pages (`Site Published: yes`)**: Built into the Hugo static site (`site/public/`) across `4` groups (`Getting Started`, `Operations`, `Walkthroughs`, `Configuration`), registered under `docs/README.md` `## All pages`, listed in `site/data/navigation.yaml`, `site/content/docs/_index.md`, and `site/layouts/index.html`, indexed in `index.json` and `sitemap.xml`, and exported to `site/public/llms.txt` topic sections. +- **16 Public Human Site Pages (`Site Published: yes`)**: Built into the Hugo static site (`site/public/`) across `4` groups (`Getting Started`, `Operations`, `Walkthroughs`, `Configuration`), registered under `docs/README.md` `## All pages`, listed in `site/data/navigation.yaml`, `site/content/docs/_index.md`, and `site/layouts/index.html`, indexed in `index.json` and `sitemap.xml`, and exported to `site/public/llms.txt` topic sections. - **6 Flat LLM Reference Pages (`Site Published: static /references/*.md`)**: Flat `docs/references/*.md` files (`README.md` hub + `5` topic references; `0` subdirectories) excluded from HTML navigation, `index.json`, and `sitemap.xml`, staged with rewritten links by `scripts/site.mjs` (`stageReferenceDocs()`) into `site/resources/references/` → `site/public/references/*.md`, and dynamically emitted under `## Reference` in `docs/README.md` and `site/public/llms.txt`. -- **12 Repo-Only `Contribute` Pages (`Site Published: no (repo-only)`)**: `docs/development.md`, `docs/contribute/{internals,identity,evidence,state,pi-adapter,runner-taskpack,memory,github-app-internals,closure-matrix}.md`, and `docs/contribute/adr/{0001-local-state-authority,0002-isolated-pi-sdk}.md` excluded from Hugo HTML, `index.json`, and `sitemap.xml`, registered under `docs/README.md` `## Contribute`, and emitted under `site/public/llms.txt` `## Optional` as GitHub `blob/` URLs. -- **One-Way Public Link Isolation**: None of the `15` public `docs/` pages or `site/content/**` files may link to `development.md`, `contribute/**`, or `references/**` (via relative, root-relative, or same-origin URLs). `docs/references/*.md` and `docs/contribute/**` may freely link inward to public pages. +- **13 Repo-Only `Contribute` Pages (`Site Published: no (repo-only)`)**: `docs/development.md`, `docs/contribute/{internals,identity,evidence,state,pi-adapter,runner-taskpack,memory,github-app-internals,closure-matrix}.md`, and `docs/contribute/adr/{0001-local-state-authority,0002-isolated-pi-sdk,0003-linux-sqlite-profiles}.md` excluded from Hugo HTML, `index.json`, and `sitemap.xml`, registered under `docs/README.md` `## Contribute`, and emitted under `site/public/llms.txt` `## Optional` as GitHub `blob/` URLs. +- **One-Way Public Link Isolation**: None of the `16` public `docs/` pages or `site/content/**` files may link to `development.md`, `contribute/**`, or `references/**` (via relative, root-relative, or same-origin URLs). `docs/references/*.md` and `docs/contribute/**` may freely link inward to public pages. -## Zone 1: Public Human Site Inventory (`15` Pages Across `4` Groups) +## Zone 1: Public Human Site Inventory (`16` Pages Across `4` Groups) Every public page (`Site Published: yes`) obeys strict **1:1:1 alignment**: `docs//.md`, with `Exact # H1 Title === docs/README.md All pages Label === navigation.yaml Label`, `<= 8` content `##` H2 sections, and both `**See also**` and `**Next**` reading footer lines. @@ -25,6 +25,7 @@ Every public page (`Site Published: yes`) obeys strict **1:1:1 alignment**: `doc | `operations/coding-agents.md` | Operations | `yes` | `Coding Agents` | `Coding Agents` | `<= 400` | Host coding agent operators | `@loopwright/controller`, `@loopwright/cli`, `@loopwright/taskpack`; `specs/2026-11-14-delegated-role-stepping-and-multi-model-routing.md` | | `walkthroughs/declarative-taskpack.md` | Walkthroughs | `yes` | `Declarative Taskpack` | `Declarative Taskpack` | `<= 400` | Repo maintainers | `@loopwright/taskpack`, `@loopwright/github-app`, `@loopwright/taskpack-runner` | | `walkthroughs/managed-controller.md` | Walkthroughs | `yes` | `Managed Controller` | `Managed Controller` | `<= 400` | Platform & CLI operators | `@loopwright/controller`, `@loopwright/cli`, `@loopwright/core` | +| `walkthroughs/managed-controller-in-isolated-host.md` | Walkthroughs | `yes` | `Managed Controller in Isolated Host` | `Managed Controller in Isolated Host` | `<= 400` | Platform & sandbox operators | `@loopwright/controller`, `@loopwright/cli`, `@loopwright/core`; `specs/2026-11-30-managed-controller-in-process-execution.md` | | `walkthroughs/evolutionary-campaign.md` | Walkthroughs | `yes` | `Evolutionary Campaign` | `Evolutionary Campaign` | `<= 400` | Kernel & optimization engineers | `@loopwright/evolution`, `@loopwright/hardware-runner`, `@loopwright/cli` | | `configuration/taskpack.md` | Configuration | `yes` | `Taskpack` | `Taskpack` | `<= 400` | Repo maintainers | `@loopwright/taskpack`; `specs/2026-11-20-decouple-taskpack-and-cas-blob-pointers.md` | | `configuration/task-contract.md` | Configuration | `yes` | `Task Contract` | `Task Contract` | `<= 400` | Integrators & engineers | `@loopwright/core`; `specs/2026-11-05-task-contracts-and-evidence.md` | @@ -46,7 +47,7 @@ Every flat reference file opens with `Evidence: contract.`, ends with `**See als | `references/cli-and-action-reference.md` | `static (/references/cli-and-action-reference.md)` | `CLI and Action Reference` | `<= 800` | `operations/{github-action,cli,github-app}.md` | Complete 44 `action.yml` inputs and 6 outputs, all 23 `@gpustack/loopwright` CLI subcommand actions and flags, CLI exit codes, and `GitHubAppConfig` bounds | | `references/coding-agent-protocol.md` | `static (/references/coding-agent-protocol.md)` | `Coding Agent Protocol Reference` | `<= 800` | `operations/coding-agents.md` | `StepYield` NDJSON schema, lease/confinement error codes, exit codes, and the verified `node -e` `candidate.files.json` overlay-apply script (kept identical to `loopwright-step/SKILL.md`) | -## Zone 3: Repo-Only `Contribute` Inventory (`12` Pages) +## Zone 3: Repo-Only `Contribute` Inventory (`13` Pages) Every contributor page (`Site Published: no (repo-only)`) is registered in `docs/README.md` `## Contribute` (`<= 10` content `##` H2 sections) and emitted under `llms.txt` `## Optional` as a GitHub `blob/` URL. @@ -64,17 +65,18 @@ Every contributor page (`Site Published: no (repo-only)`) is registered in `docs | `contribute/closure-matrix.md` | Contribute (Repo-Only) | `no (repo-only)` | `Capability Closure Matrix and Failure Semantics` | *(excluded from `site/`)* | `<= 400` | Release & audit operators | `@loopwright/cli`, `@loopwright/controller`; `specs/2026-11-11-capability-closure-matrix-and-failure-semantics.md` | | `contribute/adr/0001-local-state-authority.md` | Contribute (Repo-Only) | `no (repo-only)` | `ADR 0001: Local State Authority` | *(excluded from `site/`)* | `<= 220` | Architects & auditors | `@loopwright/state`; `specs/2026-11-05-persistent-state-and-admission.md` | | `contribute/adr/0002-isolated-pi-sdk.md` | Contribute (Repo-Only) | `no (repo-only)` | `ADR 0002: Isolated Pi SDK` | *(excluded from `site/`)* | `<= 220` | Architects & auditors | `@loopwright/agent-pi`; `specs/2026-11-05-isolated-pi-adapter.md` | +| `contribute/adr/0003-linux-sqlite-profiles.md` | Contribute (Repo-Only) | `no (repo-only)` | `ADR 0003: Linux SQLite Profiles` | *(excluded from `site/`)* | `<= 220` | Architects & auditors | `@loopwright/state`; `specs/2026-11-30-managed-controller-in-process-execution.md` | ## Per-Zone Scope & Boundary Rules ### `docs/README.md` (Shared Three-Zone Index) - **Owns**: `## Reading paths`, `## Module map` (all `9` module IDs: `contracts`, `state`, `pi-adapter`, `controller`, `taskpacks`, `memory`, `github-app`, `decisions`, `development`), `## Specs`, and three top-level zone tables: - - `## All pages` (`15` public pages grouped under `### Getting Started`, `### Operations`, `### Walkthroughs`, and `### Configuration` — never nesting `### Contribute` or `### Reference`). + - `## All pages` (`16` public pages grouped under `### Getting Started`, `### Operations`, `### Walkthroughs`, and `### Configuration` — never nesting `### Contribute` or `### Reference`). - `## Reference` (all flat `docs/references/*.md` files dynamically verified against disk). - - `## Contribute` (all `12` repo-only contributor pages). + - `## Contribute` (all `13` repo-only contributor pages). - **Must not absorb**: Narrative explanations or configuration snippets. -### Public `site/` Pages (`15` Pages Across `4` Groups, `<= 8` H2s) +### Public `site/` Pages (`16` Pages Across `4` Groups, `<= 8` H2s) - **`docs/getting-started/architecture.md` (`<= 200` lines)**: 4-stage execution lifecycle, operating modes, `architecture-flow.svg` + hidden Mermaid flowgraph comment, runtime baseline, and routing links to public guides. - **`docs/getting-started/installation.md` (`<= 400` lines)**: Choosing between GitHub Action, `@gpustack/loopwright` CLI (`npm`/`pnpm --ignore-scripts`), release tarballs, source checkouts, and `llms.txt` bootstrap prompts. - **`docs/operations/github-action.md` (`<= 400` lines)**: Reusable `action.yml` workflow setup, permissions, secret bindings, and common inputs (exhaustive 44-input catalog lives in `docs/references/cli-and-action-reference.md`). @@ -83,6 +85,7 @@ Every contributor page (`Site Published: no (repo-only)`) is registered in `docs - **`docs/operations/coding-agents.md` (`<= 400` lines)**: Human-first `loopwright step` workflow, multi-role `--role-model` routing, and 5-invariant overlay checklist (full `StepYield` schema and `node -e` overlay-apply script live in `docs/references/coding-agent-protocol.md`). - **`docs/walkthroughs/declarative-taskpack.md` (`<= 400` lines)**: End-to-end walkthrough of `.loopwright/taskpack.yaml` + GitHub Action/App + prompt migration. - **`docs/walkthroughs/managed-controller.md` (`<= 400` lines)**: End-to-end walkthrough of out-of-repo `TrustedRegistry` + `ControllerConfig` (`managed-controller-relations.svg`) and CLI governance. +- **`docs/walkthroughs/managed-controller-in-isolated-host.md` (`<= 400` lines)**: End-to-end walkthrough of unattended Managed Controller execution inside an isolated host using `command.v1` under `direct` and `adapter: exec`. - **`docs/walkthroughs/evolutionary-campaign.md` (`<= 400` lines)**: End-to-end walkthrough of evolutionary campaign mode (`EVOLVE-BLOCK`, `evolve-block-guard.v1`, `benchmark-gate.v1`, `runner relay|worker`, and `loopwright evolve`). - **`docs/configuration/{taskpack,task-contract,controller-and-registry,sandbox-backends,decision-routing,evolution-campaign}.md` (`<= 400` lines each)**: Human-first mental models, strict block-style Pretty YAML Macro manifests (`Taskpack`, `TaskpackSuite`, `TaskContract`, `ControllerConfig`, `TrustedRegistry`, `DecisionPolicy`, `EvolutionCampaign`), and focused Micro constraints (exhaustive field/bound dictionaries live in `docs/references/{taskpack-and-contract-schema,controller-and-registry-schema}.md`). @@ -90,7 +93,7 @@ Every contributor page (`Site Published: no (repo-only)`) is registered in `docs - **`docs/references/README.md`**: Task routing (pairing every reference lookup with its public owner), exact resource/CLI symbol aliases, and evidence labels (`contract`, `recorded capture`, `synthetic simulation`). - **`docs/references/{bootstrap-interview,taskpack-and-contract-schema,controller-and-registry-schema,cli-and-action-reference,coding-agent-protocol}.md`**: Machine-oriented interview protocols, complete schema/flag/exit-code tables, and verified protocol scripts fetched by coding agents via `llms.txt`. -### Repo-Only `Contribute` Pages (`12` Pages, `<= 10` H2s) +### Repo-Only `Contribute` Pages (`13` Pages, `<= 10` H2s) - **`docs/development.md` & `docs/contribute/internals.md` (`<= 400` lines each)**: Workspace build/test/lint/site commands, package dependency order, `.agents/skills/*` routing, and `.opencodereview/rule.json` invariants. - **`docs/contribute/{identity,evidence,state,pi-adapter,runner-taskpack,memory,github-app-internals,closure-matrix}.md` (`<= 400` lines each)**: Subsystem implementation guides for JCS digests, HMAC `gate.v1` receipts, SQLite WAL fencing, isolated Pi sessions, runner parity, reviewed memory CAS compaction, GitHub App internals, and capability closure. -- **`docs/contribute/adr/{0001-local-state-authority,0002-isolated-pi-sdk}.md` (`<= 220` lines each)**: Architectural Decision Records. +- **`docs/contribute/adr/{0001-local-state-authority,0002-isolated-pi-sdk,0003-linux-sqlite-profiles}.md` (`<= 220` lines each)**: Architectural Decision Records. diff --git a/docs/README.md b/docs/README.md index bf1337ea..23079cd3 100644 --- a/docs/README.md +++ b/docs/README.md @@ -4,7 +4,7 @@ - [Installation](getting-started/installation.md) and [Architecture](getting-started/architecture.md) - [Declarative Taskpack](walkthroughs/declarative-taskpack.md), [Taskpack](configuration/taskpack.md), and [GitHub Action](operations/github-action.md) -- [Managed Controller](walkthroughs/managed-controller.md), [Task Contract](configuration/task-contract.md), and [Controller and Registry](configuration/controller-and-registry.md) +- [Managed Controller](walkthroughs/managed-controller.md), [Managed Controller in Isolated Host](walkthroughs/managed-controller-in-isolated-host.md), [Task Contract](configuration/task-contract.md), and [Controller and Registry](configuration/controller-and-registry.md) - [Evolutionary Campaign](walkthroughs/evolutionary-campaign.md) and [Evolution Campaign](configuration/evolution-campaign.md) - [GitHub App](operations/github-app.md), [CLI](operations/cli.md), and [Coding Agents](operations/coding-agents.md) - [Sandbox Backends](configuration/sandbox-backends.md) and [Decision Routing](configuration/decision-routing.md) @@ -51,8 +51,8 @@ - ID: controller - Use for: compile trusted configuration and coordinate bounded runs - Aliases: controller -- Guides: [getting-started/installation.md](getting-started/installation.md), [walkthroughs/managed-controller.md](walkthroughs/managed-controller.md), [walkthroughs/evolutionary-campaign.md](walkthroughs/evolutionary-campaign.md), [configuration/controller-and-registry.md](configuration/controller-and-registry.md), [configuration/evolution-campaign.md](configuration/evolution-campaign.md), [operations/cli.md](operations/cli.md), [operations/coding-agents.md](operations/coding-agents.md), [contribute/closure-matrix.md](contribute/closure-matrix.md) -- Specs: [Specification](../specs/2026-11-06-bounded-controller-and-trusted-config.md), [Delegated Stepping](../specs/2026-11-14-delegated-role-stepping-and-multi-model-routing.md), [Multi-Domain Suites, Handoffs, and RunEval](../specs/2026-11-21-multi-domain-suite-handoff-and-run-eval.md), [Hardware Execution and Remote Runner](../specs/2026-11-21-hardware-execution-benchmark-gate-and-remote-runner.md), [Evolutionary Campaigns, Pareto Archive, and Bundle Export](../specs/2026-11-23-evolutionary-campaigns-pareto-archive-and-bundle-export.md) +- Guides: [getting-started/installation.md](getting-started/installation.md), [walkthroughs/managed-controller.md](walkthroughs/managed-controller.md), [walkthroughs/managed-controller-in-isolated-host.md](walkthroughs/managed-controller-in-isolated-host.md), [walkthroughs/evolutionary-campaign.md](walkthroughs/evolutionary-campaign.md), [configuration/controller-and-registry.md](configuration/controller-and-registry.md), [configuration/evolution-campaign.md](configuration/evolution-campaign.md), [operations/cli.md](operations/cli.md), [operations/coding-agents.md](operations/coding-agents.md), [contribute/closure-matrix.md](contribute/closure-matrix.md) +- Specs: [Specification](../specs/2026-11-06-bounded-controller-and-trusted-config.md), [Delegated Stepping](../specs/2026-11-14-delegated-role-stepping-and-multi-model-routing.md), [Multi-Domain Suites, Handoffs, and RunEval](../specs/2026-11-21-multi-domain-suite-handoff-and-run-eval.md), [Hardware Execution and Remote Runner](../specs/2026-11-21-hardware-execution-benchmark-gate-and-remote-runner.md), [Evolutionary Campaigns, Pareto Archive, and Bundle Export](../specs/2026-11-23-evolutionary-campaigns-pareto-archive-and-bundle-export.md), [Managed Controller In-Process Execution](../specs/2026-11-30-managed-controller-in-process-execution.md) - Code: [controller](../packages/controller/), [hardware-runner](../packages/hardware-runner/), [evolution](../packages/evolution/), [cli](../packages/cli/) - Related: [contracts](#contracts-and-evidence), [state](#persistent-state-store) - Skills: [overview](../.agents/skills/loopwright-overview/SKILL.md), [step](../.agents/skills/loopwright-step/SKILL.md) @@ -139,6 +139,7 @@ | [2026-11-21-hardware-execution-benchmark-gate-and-remote-runner.md](../specs/2026-11-21-hardware-execution-benchmark-gate-and-remote-runner.md) | Hardware execution, benchmark-gate.v1, and outbound remote runner | | [2026-11-21-multi-domain-suite-handoff-and-run-eval.md](../specs/2026-11-21-multi-domain-suite-handoff-and-run-eval.md) | Multi-domain `TaskpackSuite`, compact handoffs, conditional rules, `RunEval`, and baseline alignment | | [2026-11-23-evolutionary-campaigns-pareto-archive-and-bundle-export.md](../specs/2026-11-23-evolutionary-campaigns-pareto-archive-and-bundle-export.md) | Evolutionary campaigns (`@loopwright/evolution`), `evolve-block-guard.v1`, plateau `teamEvolution`, `hardwareScope`, and `evolution-bundle.v1` | +| [2026-11-30-managed-controller-in-process-execution.md](../specs/2026-11-30-managed-controller-in-process-execution.md) | Managed Controller `command.v1` under `direct`, `exec` role adapter, and portable campaign state | ## All pages @@ -164,6 +165,7 @@ | --- | --- | | [Declarative Taskpack](walkthroughs/declarative-taskpack.md) | Author or migrate a single-file repository taskpack | | [Managed Controller](walkthroughs/managed-controller.md) | Configure out-of-repo registries, contracts, and CLI runs | +| [Managed Controller in Isolated Host](walkthroughs/managed-controller-in-isolated-host.md) | Run `command.v1` checks and `exec` roles unattended inside an isolated host | | [Evolutionary Campaign](walkthroughs/evolutionary-campaign.md) | Run bounded island optimization with hardware gates and bundle export | ### Configuration @@ -204,3 +206,4 @@ | [Capability Closure Matrix and Failure Semantics](contribute/closure-matrix.md) | Maintain capability closure ledger and failure injection suites | | [ADR 0001: Local State Authority](contribute/adr/0001-local-state-authority.md) | Record the fenced local SQLite authority decision | | [ADR 0002: Isolated Pi SDK](contribute/adr/0002-isolated-pi-sdk.md) | Record the isolated Pi runtime boundary decision | +| [ADR 0003: Linux SQLite Profiles](contribute/adr/0003-linux-sqlite-profiles.md) | Record Linux x64 and arm64 SQLite qualification and `fullfsync` semantics | diff --git a/docs/configuration/controller-and-registry.md b/docs/configuration/controller-and-registry.md index 27ab3dcf..8eaca6eb 100644 --- a/docs/configuration/controller-and-registry.md +++ b/docs/configuration/controller-and-registry.md @@ -275,11 +275,15 @@ Each `handlers[]` entry pins `id`, `version: 1`, `digest` (from `installedHandle | `pi.agent.v1` / `pi.compact.v1` | `agent` | `['pi']` / `['pi', 'compaction']` | | `scope.v1` / `no-change.v1` | `check` | `['inert_bytes', 'read_only']` | | `json-artifact.v1` / `json-keys-guard.v1` / `line-section-guard.v1` | `check` | `['inert_bytes', 'read_only']` | +| `command.v1` | `check` | `['host_execution']` | | `gate.v1` / `benchmark-gate.v1` | `check` | `['external_service', 'read_only']` / `['hardware_execution', 'read_only']` | +- **Direct check attestation (`spec.host.localChecks`)**: Registries declaring `command.v1` must set `host.localChecks.backend: direct` (`CONFIG_SCHEMA` otherwise). `command.v1` accepts `checkId`, `script` (executable file inside a `scope.protected` directory), `args` (`0..64`), `env` (`0..32`, uppercase, `LOOPWRIGHT_*` refused), `toolchainPaths` (`0..32`), and `timeoutMs` (`1000..3600000`, fitting inside `wallTimeMs - drainReserveMs`), producing `host_execution` evidence. + ### Role and runtime profiles -- **Adapter choice**: `roleProfiles[]` accepts `adapter: pi` (with `runtimeRef` and `mcp`) or `adapter: delegated` (`runtimeRef: null`, `mcp: null`). Unattended `run`/`resume` refuse delegated roles (`CAPABILITY_UNSUPPORTED`). +- **Adapter choice**: `roleProfiles[]` accepts `adapter: pi` (with `runtimeRef` and `mcp`), `adapter: delegated` (`runtimeRef: null`, `mcp: null`), or `adapter: exec` (`runtimeRef: null`, `providerCredentialRef: null`, `mcp: null`, and `exec.{command,args,env,credentialRefs,timeoutMs,captureBytes}`). +- **Plan mixing rules**: Unattended `run`/`resume` admit all-`pi` or all-`exec` plans (refusing `delegated` and mixed `exec` plans); `step` admits `delegated` only and refuses `exec` (`CAPABILITY_UNSUPPORTED`). - **Model selection**: Configure `selection` (see [Model configuration](taskpack.md#model-configuration)); CLI `--role-model` overrides take precedence and persist in `run.json`. - **Runtime identity**: `runtimeProfiles[]` locks `dockerExecutable`, `dockerSocket`, `sdkIntegrity`, `graphDigest`, `imageDigest`, `configDigest`, and `profile` via `describePiAdapterFiles()`. @@ -294,7 +298,7 @@ Secrets resolve exclusively in memory into a `CredentialVault` (`vault.assertCle - **Escape & safety**: Use `$$` for a literal `$`. Shell `$(...)`, `!command`, and `${NAME:-default}` fail closed (`CONFIG_ENV_SYNTAX`). - **JSON Pointer allowlist**: Every `${NAME}` must match `environmentBindings[]` at that exact pointer (`CONFIG_ENV_DENIED` / `CONFIG_ENV_MISSING`): `credential` only under `/spec/credentials//template`, `nonsecret` under task fields. -- **Scoped endpoints**: `gateEndpoints[]` (`consumer: gate`) and `publicationEndpoints[]` (`consumer: publisher`) require `https://` or loopback URLs with HMAC `signingCredentialRef` and optional bearer `authCredentialRef`. +- **Scoped consumers & endpoints**: `credentialBindings[]` binds `consumer` (`provider`, `mcp`, `gate`, `publisher`, or `exec` for `roleProfiles[].exec.credentialRefs`). `gateEndpoints[]` and `publicationEndpoints[]` require `https://` or loopback URLs with HMAC `signingCredentialRef` and optional bearer `authCredentialRef`. ## Controller controls @@ -317,6 +321,6 @@ Run `loopwright check` or `loopwright run --dry-run` before execution. When an e --- -**See also** — [Managed Controller](../walkthroughs/managed-controller.md) (relationship diagram, setup, and digest commands) · [Task Contract](task-contract.md) (`TaskContract` fields and budget rules) +**See also** — [Managed Controller](../walkthroughs/managed-controller.md) (relationship diagram, setup, and digest commands) · [Managed Controller in Isolated Host](../walkthroughs/managed-controller-in-isolated-host.md) (`direct` checks and `exec` roles) · [Task Contract](task-contract.md) (`TaskContract` fields and budget rules) **Next** → [CLI](../operations/cli.md) — run `check`, `run`, `inspect`, and `reconcile` with your controller files. diff --git a/docs/configuration/task-contract.md b/docs/configuration/task-contract.md index 53fc963f..f7353b6a 100644 --- a/docs/configuration/task-contract.md +++ b/docs/configuration/task-contract.md @@ -132,7 +132,7 @@ spec: ## Roles and steps -- **Roles (`1..64`)**: Bind `adapter` (`pi` or `delegated`), `provider`, `model`, `thinking`, `tools`, and optional `resourceIds` (see [Model configuration](taskpack.md#model-configuration)). +- **Roles (`1..64`)**: Bind `adapter` (`pi`, `delegated`, or `exec`), `provider`, `model`, `thinking`, `tools`, and optional `resourceIds` (see [Controller and Registry](controller-and-registry.md#role-and-runtime-profiles) and [Model configuration](taskpack.md#model-configuration)). Plans cannot mix `exec` with `pi` or `delegated` roles. - **Steps (`1..256` acyclic nodes)**: `agent` steps bind a `roleId`; `check` steps set `roleId: null`. Optional `onRework: { rejectTo, maxReworks }` resets an ancestor (`1..8` times). ### Handoff selectors @@ -163,7 +163,8 @@ Every retry and repair draws from one parent `budgets` envelope (`wallTimeMs` mu | --- | --- | --- | | `static_inspection` | Deterministic byte or AST parser | Inert file inspection only; executes no target code | | `synthetic_fixture` | Controlled local test fixture | Proves harness logic only; never qualifies live systems | -| `local_execution` | Isolated host verifier worker | Scoped to current host (`json-artifact.v1`, `scope.v1`, `command.v1`) | +| `local_execution` | Isolated host verifier worker | Scoped to current host (`json-artifact.v1`, `scope.v1`, Taskpack `command.v1`) | +| `host_execution` | Managed Controller `command.v1` (`direct`) | Host isolation attested by `TrustedRegistry`; runs under controller UID | | `external_service` | Signed `gate.v1` remote receipt | Requires trusted `gateEndpoints[]` URL and HMAC secret | | `hardware_execution` | Dedicated physical target runner | Must appear alone as `['hardware_execution']` with `benchmark-gate.v1` | diff --git a/docs/contribute/adr/0003-linux-sqlite-profiles.md b/docs/contribute/adr/0003-linux-sqlite-profiles.md new file mode 100644 index 00000000..db377f66 --- /dev/null +++ b/docs/contribute/adr/0003-linux-sqlite-profiles.md @@ -0,0 +1,54 @@ +# ADR 0003: Linux SQLite Profiles + +Date: 2026-12-01 +Status: Accepted (supersedes darwin/arm64-only host profile sentence in ADR 0001) + +## Contents + +- [Context](#context) +- [Decision](#decision) +- [Alternatives](#alternatives) +- [Consequences](#consequences) +- [Verification](#verification) + +## Context + +[ADR 0001](0001-local-state-authority.md) froze the initial local state store profile to one measured `darwin/arm64` host running Node `26.x` and bundled SQLite `3.x`. Since then, container and CI workloads run Loopwright on Linux `x64` and Linux `arm64`, and [Persistent Local State Store](../state.md) already documents both Linux architectures alongside macOS `arm64`. + +Because architectural decision records are superseded rather than edited, this record formally updates the qualified host profile with current CI evidence and states Linux `fullfsync` behavior explicitly. + +## Decision + +Qualify three local host profiles for `@loopwright/state` on Node `26.x` with bundled SQLite `3.x` and local locking filesystems: + +| Platform | Architecture | CI runner evidence | Storage profile | +| --- | --- | --- | --- | +| macOS | `arm64` | `macos-15` | `DELETE`, `EXTRA`, `fullfsync`, `checkpoint_fullfsync` | +| Linux | `x64` | `ubuntu-24.04` | `DELETE`, `EXTRA`, `fullfsync`, `checkpoint_fullfsync` | +| Linux | `arm64` | `ubuntu-24.04-arm` | `DELETE`, `EXTRA`, `fullfsync`, `checkpoint_fullfsync` | + +Keep all SQLite invariants from ADR 0001 unchanged: `4 KiB` pages, `DELETE` rollback journal, `synchronous = EXTRA`, `PRAGMA fullfsync = ON`, `PRAGMA checkpoint_fullfsync = ON`, `BEGIN IMMEDIATE` serialization, owner/generation/nonce fencing, and an immutable monotonic creation clock basis. Each store still records its exact host and runtime tuple at creation and rejects reopen on a different platform, architecture, Node major version, or SQLite version. + +Record Linux `fullfsync` semantics explicitly: SQLite maps `PRAGMA fullfsync = ON` to `fcntl(F_FULLFSYNC)` on Darwin and falls back to `fsync()` on Linux. Durability on Linux remains bounded by the local filesystem and storage controller write cache. + +## Alternatives + +- Edit ADR 0001 in place to list Linux profiles. Rejected because ADRs are immutable decision history and must be superseded by a new record. +- Require a remote database for Linux container runs. Rejected because local fenced SQLite remains the run authority and needs no external storage service. +- Disable `PRAGMA fullfsync = ON` on Linux. Rejected because keeping one uniform pragma profile lets SQLite apply platform-native sync behavior without per-OS divergence. + +## Consequences + +Unattended Linux `x64` and `arm64` containers and CI runners are covered by the qualified local SQLite profile without adding native addons or remote services. + +Linux `fsync()` durability depends on local filesystem mount options and underlying block-device cache behavior. This decision still does not qualify network filesystems (NFS, SMB, FUSE overlays), host suspension, power-loss testing, or cross-host store copying. + +## Verification + +`.github/workflows/test.yml` shards the full workspace unit and integration test suites on `ubuntu-24.04` (Linux `x64`, shards `1/3` through `3/3`) and `ubuntu-24.04-arm` (Linux `arm64`, shards `1/3` through `3/3`) on Node `26` alongside `macos-15`. + +These CI runs verify SQLite fencing, clock-drift refusal, lock contention, and SIGKILL recovery on all three qualified profiles. They do not establish power-loss durability, network-filesystem safety, or remote host-loss acceptance. + +--- + +**See also** — [ADR 0001: Local State Authority](0001-local-state-authority.md) (fenced SQLite authority decision) · [Persistent Local State Store](../state.md) (qualified profiles, clock guards, and storage bounds) diff --git a/docs/contribute/closure-matrix.md b/docs/contribute/closure-matrix.md index 2166d2df..1adaf6b9 100644 --- a/docs/contribute/closure-matrix.md +++ b/docs/contribute/closure-matrix.md @@ -21,9 +21,9 @@ Read each row as an evidence boundary. Local closure covers its stated criterion | `blocked_external` | External qualification remains blocked. | | `deferred_owned` | An owned external qualification remains deferred. | -`CLOSURE_CAPABILITY_LEDGER` is a deeply frozen array of exactly 23 `ClosureCapabilityEntry` rows across all 12 workspace packages (`@loopwright/hardware-runner` and `@loopwright/evolution` are registered in `OWNER_PACKAGES`; `@loopwright/taskpack` owns `qualified-host-clock-and-storage-profile` and `interactive-mcp-oauth-browser-flow`). +`CLOSURE_CAPABILITY_LEDGER` is a deeply frozen array of exactly 26 `ClosureCapabilityEntry` rows across all 12 workspace packages (`@loopwright/hardware-runner` and `@loopwright/evolution` are registered in `OWNER_PACKAGES`; `@loopwright/taskpack` owns `qualified-host-clock-and-storage-profile` and `interactive-mcp-oauth-browser-flow`). -Eighteen rows are `closed_local` with `verificationStatus: 'passed'` (`unit_and_integration`, `controlled_local_qualification`, or `frozen_offline_parity`). Five rows carry `evidenceLevel: 'unprovisioned_external'` and stay honestly blocked: +Twenty rows are `closed_local` with `verificationStatus: 'passed'` (`unit_and_integration`, `controlled_local_qualification`, or `frozen_offline_parity`), including `managed-controller-command-v1-direct` and `managed-controller-exec-role-adapter` under `@loopwright/controller`. Six rows carry `evidenceLevel: 'unprovisioned_external'` (`4` `blocked_external` and `2` `deferred_owned`) and stay honestly blocked: | Capability | Owner | Disposition | Status | | --- | --- | --- | --- | @@ -32,12 +32,15 @@ Eighteen rows are `closed_local` with `verificationStatus: 'passed'` (`unit_and_ | `interactive-mcp-oauth-browser-flow` | `@loopwright/taskpack` | `deferred_owned` | `blocked` | | `deployed-github-app-and-webhook-ingress` | `@loopwright/github-app` | `blocked_external` | `not_run` | | `live-provider-billing-and-effort-attestation` | `@loopwright/agent-pi` | `deferred_owned` | `not_run` | +| `in-process-benchmark-gate-hardware` | `@loopwright/hardware-runner` | `blocked_external` | `blocked` | Every row names a closure criterion, a residual boundary, and at least one `evidencePaths` entry that resolves to a committed regular file in the repository. Non-passed rows must carry a non-empty `unlockPrerequisite`; passed rows must not. -`external-build-and-accelerator-matrix` lists `@loopwright/hardware-runner` evidence paths (`relay-server.ts`, `worker.ts`, `evaluator.ts`, `e2e-nat-loopback.test.ts`, and `docs/configuration/sandbox-backends.md`), yet stays `blocked_external` (`18` `closedLocal`, `5` `unprovisionedExternal`) until signed `ExternalQualificationReceipt` records are attached (`CLOSURE_FALSIFICATION_FORBIDDEN`). +`external-build-and-accelerator-matrix` lists `@loopwright/hardware-runner` evidence paths (`relay-server.ts`, `worker.ts`, `evaluator.ts`, `e2e-nat-loopback.test.ts`, and `docs/configuration/sandbox-backends.md`). + +`in-process-benchmark-gate-hardware` records the `namespaces_blocked` probe (`packages/hardware-runner/test/bwrap-namespace-probe.test.ts` and `packages/hardware-runner/test/fixtures/bwrap-namespace-probe/evidence/restricted-probe-output.jsonl`). Both stay `blocked_external` (`20` `closedLocal`, `6` `unprovisionedExternal`) until signed `ExternalQualificationReceipt` records are attached (`CLOSURE_FALSIFICATION_FORBIDDEN`). ## Non-falsification invariant @@ -107,7 +110,7 @@ and refuses to overwrite an existing file. `--json` emits one `Envelope` (`kind: summary. Exit codes: `0` when integrity holds, no falsification is detected, the summary counts stay at -18 closed local and 5 unprovisioned external, and (under `--verify-failures`) all 14 scenarios pass; +20 closed local and 6 unprovisioned external, and (under `--verify-failures`) all 14 scenarios pass; `3` on falsification or a capability invariant violation; `4` when `--verify-failures` observes a failed scenario; `8` on missing or untrusted evidence; `2` on usage errors. diff --git a/docs/operations/cli.md b/docs/operations/cli.md index 59e28a2f..15b69184 100644 --- a/docs/operations/cli.md +++ b/docs/operations/cli.md @@ -39,6 +39,7 @@ loopwright resume --config CONFIG --registry REGISTRY --registry-sha256 DIGEST - ``` - **Local taskpack mode**: `--taskpack` accepts `--mode`, `--baseline-alignment`, `--source-revision`, and `--role-model`. PR publication or PR memory fails closed locally (`TASKPACK_HOST_BINDING_INVALID`). +- **Exec role plans**: `run` and `resume` admit all-`exec` plans (refusing mixed `exec` + `pi`/`delegated` plans with `CONFIG_SCHEMA`); `step` refuses `exec` plans (`CAPABILITY_UNSUPPORTED`). - **Dual-key privileges**: `run`, `resume`, `step next`, and `step submit` accept `--allow-privileged` and `--allow-workflow-writes`; `run` and `step` also accept `--allow-host-mounts `. - **Diagnostics & decisions**: `--output-format` (`json`, `github-step-summary`, `markdown`, `text`) and `--step-summary-file` emit `RunEval`. Enabled `spec.decisions` wires live adapters with fallback. @@ -56,7 +57,7 @@ loopwright inspect --run-root TRUSTED_ROOT --run-id demo --output INSPECTION_DIR loopwright reconcile --config CONFIG --registry REGISTRY --registry-sha256 DIGEST --repo REPO --run-root TRUSTED_ROOT --run-id demo --receipt RECEIPT --json ``` -Inspect state and `run-eval.json` offline before recovery. Settle any `unknown` external outcome with its matching authenticated receipt via `reconcile`; never silently retry uncertain remote effects. +Inspect state, `verifier-receipts.json`, `usage.json`, and `run-eval.json` offline before recovery. Settle any `unknown` external outcome with its matching authenticated receipt via `reconcile`; never silently retry uncertain remote effects. ## Step 4: Audit closure @@ -64,7 +65,7 @@ Inspect state and `run-eval.json` offline before recovery. Settle any `unknown` loopwright closure --verify-failures --json ``` -Closure audits the 23-capability matrix and 14-case failure suite, exiting `0` when valid, `3` on unsupported/falsified capability, `4` on failure-matrix failure, and `8` on integrity failure. +Closure audits the 26-capability matrix and 14-case failure suite, exiting `0` when valid, `3` on unsupported/falsified capability, `4` on failure-matrix failure, and `8` on integrity failure. | Disposition | Evidence scope | Meaning | | --- | --- | --- | diff --git a/docs/operations/coding-agents.md b/docs/operations/coding-agents.md index 0b1785ae..57559bbf 100644 --- a/docs/operations/coding-agents.md +++ b/docs/operations/coding-agents.md @@ -26,6 +26,8 @@ Zero Loopwright provider credentials, GitHub App keys, or workflow secrets are n | Declarative Taskpack | `--taskpack .loopwright/taskpack.yaml` | Compiles roles as `adapter: delegated` with `publication.mode: disabled` | | Managed Controller | `--config`, `--registry`, `--registry-sha256` | Uses `adapter: delegated` profiles with local `publication.mode: disabled` | +For unattended local command execution without a pull loop (`loopwright run` inside an isolated host), configure `adapter: exec` instead of `adapter: delegated` (see [Managed Controller in Isolated Host](../walkthroughs/managed-controller-in-isolated-host.md)); `loopwright step` refuses `exec` plans. + ## Skill and prompt ### Portable skill diff --git a/docs/walkthroughs/managed-controller-in-isolated-host.md b/docs/walkthroughs/managed-controller-in-isolated-host.md new file mode 100644 index 00000000..a5a000bf --- /dev/null +++ b/docs/walkthroughs/managed-controller-in-isolated-host.md @@ -0,0 +1,332 @@ +# Managed Controller in Isolated Host + +Run Managed Controller unattended inside an already isolated host, such as a single-accelerator restricted Pod with no Docker socket, no hardware relay, and no model calls from the Loopwright process. Protected repository scripts verify candidates via `command.v1` under `host.localChecks.backend: direct`, while local author commands execute via `adapter: exec`. + +For Docker-isolated Pi roles on a workstation or shared host, follow [Managed Controller](managed-controller.md). For interactive host coding agents over OAuth sessions, use [Coding Agents](../operations/coding-agents.md). + +## Contents + +- [Overview](#overview) +- [Step 1: Pin registry](#step-1-pin-registry) +- [Step 2: Author controller](#step-2-author-controller) +- [Step 3: Check and run](#step-3-check-and-run) +- [Step 4: Inspect evidence](#step-4-inspect-evidence) +- [Direct execution limits](#direct-execution-limits) +- [Verification](#verification) + +## Overview + +In an isolated single-tenant container or restricted Pod (`runAsNonRoot: true`, `allowPrivilegeEscalation: false`, `capabilities.drop: ALL`, `RuntimeDefault` seccomp, no host paths, and egress restricted to the model endpoint), the host boundary provides OS and network containment. Loopwright retains SQLite lease fencing, scope enforcement, digest pinning, output scrubbing, and verifiable receipts. + +| Component | Isolated-host choice | Boundary enforced | +| --- | --- | --- | +| Agent execution | `adapter: exec` with `consumer: exec` | Allowlisted env, overlay scan, unknown-outcome recovery | +| Verification check | `command.v1` under `direct` backend | Protected script dir, `host_execution` evidence, timeout kill | +| State authority | Local fenced SQLite store | Exclusive owner lease, monotonic clock, budget admission | + +## Step 1: Pin registry + +Keep `registry.yaml` (`0600`) outside `cwd`, outside `dirname(controller.yaml)`, and outside `--repo`. Compute the installed `pi.agent.v1` and `command.v1` handler digests first: + +```sh +node --input-type=module -e " +import { installedHandlerDigests } from '@loopwright/controller'; +console.log(await installedHandlerDigests()); +" +``` + +### TrustedRegistry + +Declare `host.localChecks.backend: direct`, the `command.v1` check handler with `host_execution`, the `adapter: exec` role profile, and a `consumer: exec` credential binding: + +```yaml +apiVersion: loopwright.dev/v1alpha1 +kind: TrustedRegistry +metadata: + name: isolated-pod-registry +spec: + version: 1 + resourceVersion: rev-2026-12 + host: + localChecks: + backend: direct + handlers: + - id: author-step + version: 1 + kind: agent + implementation: pi.agent.v1 + digest: + algorithm: sha256 + hex: + parameters: + prompt: Optimize kernels/rmsnorm.py and preserve numerical accuracy. + purpose: task + capabilities: + - pi + - id: evaluate-kernel + version: 1 + kind: check + implementation: command.v1 + digest: + algorithm: sha256 + hex: + parameters: + checkId: evaluate-kernel + script: scripts/evaluate.sh + args: [] + env: + KERNEL_ID: rmsnorm + toolchainPaths: [] + timeoutMs: 600000 + capabilities: + - host_execution + - id: scope + version: 1 + kind: check + implementation: scope.v1 + digest: + algorithm: sha256 + hex: + parameters: + checkId: null + capabilities: + - inert_bytes + - read_only + - id: no-change + version: 1 + kind: check + implementation: no-change.v1 + digest: + algorithm: sha256 + hex: + parameters: + checkId: null + capabilities: + - inert_bytes + - read_only + roleProfiles: + - id: author-exec + adapter: exec + selection: + provider: openai + model: gpt-5 + thinking: medium + tools: + - read + - write + - edit + runtimeRef: null + providerCredentialRef: null + mcp: null + exec: + command: + - /usr/local/bin/local-author + args: [] # Optional extra arguments before promptFile and candidateDir + env: # Optional literal non-secret environment variables + LLM_BASE_URL: "https://api.example.com/v1" + credentialRefs: # Optional consumer exec credential IDs + - llm-token + timeoutMs: 600000 + captureBytes: 65536 # Optional stdout/stderr byte cap (1024..1048576) + resources: [] + runtimeProfiles: [] + credentialBindings: + - id: llm-token + consumer: exec + destinationRef: openai + environmentNames: + - LLM_TOKEN + template: "${LLM_TOKEN}" + environmentBindings: + - name: LLM_TOKEN + classification: credential + paths: + - /spec/credentials/0/template +``` + +- **Attestation**: Omitting `host.localChecks.backend: direct` fails `CONFIG_SCHEMA`; Loopwright never auto-detects or falls back to `direct`. +- **Protected script**: Commit `scripts/evaluate.sh` with the executable bit (`0755`) and protect its entire parent directory under `scope.protected`. +- **Exec handler binding**: An `exec` role binds to a `pi.agent.v1` handler with `purpose: task`; `purpose: review` and mixed `exec` + `pi`/`delegated` plans fail `CONFIG_SCHEMA`. + +Compute the SHA-256 digest of `registry.yaml` before writing `controller.yaml`: + +```sh +REGISTRY_SHA=$(sha256sum /trust/registry.yaml | awk '{print $1}') +``` + +## Step 2: Author controller + +### ControllerConfig + +Embed the `TaskContract`, list `host_execution` in `acceptance.checks[].allowedEvidenceLevels`, protect `scripts/**`, and keep `timeoutMs + drainReserveMs <= wallTimeMs`: + +```yaml +apiVersion: loopwright.dev/v1alpha1 +kind: ControllerConfig +spec: + registry: + name: isolated-pod-registry + digest: + algorithm: sha256 + hex: + task: + apiVersion: loopwright.dev/v1alpha1 + kind: TaskContract + spec: + goal: Optimize kernels/rmsnorm.py and pass scripts/evaluate.sh. + taskpack: kernel-opt + target: + repository: acme/kernels + baseRevision: main + sourceRevision: HEAD + matrix: null + scope: + writable: + - "kernels/**" + protected: + - "scripts/**" + roles: + - id: author + adapter: exec + provider: openai + model: gpt-5 + thinking: medium + tools: + - read + - write + - edit + trustedContext: + revision: rev-2026-12 + discovery: disabled + resources: [] + budgets: + wallTimeMs: 900000 + totalTokens: 100000 + perCallOutputTokens: 4096 + maxModelCalls: 6 + maxConcurrency: 1 + maxFormatRepairs: 0 + maxImplementationRepairs: 2 + maxTransportRetries: 0 + enforcement: + wallTime: hard_admission + tokens: soft_accounting + modelCalls: hard_admission + concurrency: hard_admission + formatRepairs: hard_admission + implementationRepairs: hard_admission + transportRetries: hard_admission + steps: + - id: author-change + kind: agent + uses: author-step + roleId: author + dependsOn: [] + - id: run-eval + kind: check + uses: evaluate-kernel + roleId: null + dependsOn: + - author-change + onRework: # Optional rework loop back to author-change + rejectTo: author-change + maxReworks: 2 + acceptance: + required: + - evaluate-kernel + checks: + - id: evaluate-kernel + allowedEvidenceLevels: + - host_execution + profiles: + roles: + - roleId: author + profileRef: author-exec + steps: + - stepId: author-change + handlerRef: author-step + - stepId: run-eval + handlerRef: evaluate-kernel + credentials: + - ref: llm-token + template: "${LLM_TOKEN}" + controls: + drainReserveMs: 120000 + maxAttempts: 4 + repeatFailureLimit: 2 + submission: + mode: artifact_or_assistant + path: null + publication: + mode: disabled +``` + +## Step 3: Check and run + +Validate configuration statically with `loopwright check`, then run the full DAG unattended with `loopwright run`: + +```sh +export LLM_TOKEN="provider_token_value" + +loopwright check \ + --config /ops/controller.yaml \ + --registry /trust/registry.yaml \ + --registry-sha256 "$REGISTRY_SHA" \ + --json + +loopwright run \ + --config /ops/controller.yaml \ + --registry /trust/registry.yaml \ + --registry-sha256 "$REGISTRY_SHA" \ + --repo /workspace/repo \ + --run-root /state/runs \ + --run-id pod-run-01 \ + --json +``` + +- **Script contract**: `command.v1` runs with `cwd = $LOOPWRIGHT_BASE_DIR`, writes optional strict JSON `{ detail?, metrics?, findings? }` (`<= 64 KiB`) to `$LOOPWRIGHT_CHECK_OUT`, and never receives controller credentials. +- **Exec contract**: Loopwright spawns `[...command, ...args, promptFile, candidateDir]` with an allowlisted environment, sets `$LOOPWRIGHT_USAGE_OUT` for optional request usage JSON, maps exit `0` to `completed` and exit `3` to `blocked`, and scans `candidateDir` with delegated overlay checks. +- **Recovery**: Use `loopwright resume` with the exact same arguments after an interruption. Operations without a proof marker settle `blocked` (`EVIDENCE_UNAVAILABLE`) for `command.v1` or `RECOVERY_REQUIRED` for `exec`, kill the recorded process group, and never re-dispatch blindly. + +## Step 4: Inspect evidence + +Export the offline evidence bundle to a new output directory (`0700`): + +```sh +loopwright inspect \ + --run-root /state/runs \ + --run-id pod-run-01 \ + --output /state/inspect/pod-run-01 \ + --json +``` + +### Evidence artifacts + +| File | Contents | +| --- | --- | +| `result.json` | Terminal status (`completed`, `blocked`, `failed`), lock binding, and acceptance verdict | +| `verification.json` | Check outcomes bound to `candidateDigest` with `level: host_execution` | +| `verifier-receipts.json` | `direct_script` receipts recording script path, script directory digest, and registry digest | +| `usage.json` | Aggregated `exec` request records (`provenance: reported` or `unknown`, never fabricated zero) | +| `run-eval.json` | Run health summary classifying `exec` attempts separately from isolated Pi telemetry | + +## Direct execution limits + +Both `command.v1` under `direct` and `adapter: exec` execute child processes under the controller's own UID without OS containment: + +- **Shared UID access**: A child process can change file modes, inspect the local run store, read `/proc//environ`, and open any egress connection allowed by the Pod `NetworkPolicy`. +- **Process group escapes**: Loopwright runs each child in its own process group and kills the group on timeout, cancel, and recovery, but a child that calls `setsid` can escape the group; Pod exit is the final backstop. +- **Explicit evidence tier**: `command.v1` under `direct` emits only `host_execution` evidence so downstream consumers can require or refuse host-attested runs explicitly. +- **No unrelated host secrets**: Do not share the controller UID with publication tokens or unrelated credentials when an `exec` command invokes untrusted code. + +## Verification + +Repository unit and integration tests verify `command.v1` (`direct`), `adapter: exec`, credential vault scrubbing, overlay invariance, process-group timeout cleanup, crash recovery without re-dispatch, and `usage.json` / `verifier-receipts.json` exports locally and on CI (`ubuntu-24.04`, `ubuntu-24.04-arm`, and `macos-15`). + +Local and CI suites do not substitute for target container or restricted Pod qualification. Validate Pod security context, `NetworkPolicy` egress bounds, and physical accelerator behavior in your deployment environment before accepting `host_execution` evidence in production. + +--- + +**See also** — [Controller and Registry](../configuration/controller-and-registry.md) (handler digests, `command.v1`, and `exec` profiles) · [Task Contract](../configuration/task-contract.md) (scope, budgets, and `host_execution` evidence) · [CLI](../operations/cli.md) (`check`, `run`, `resume`, and `inspect` commands) + +**Next** → [Controller and Registry](../configuration/controller-and-registry.md) — review complete registry and controller configuration fields. diff --git a/packages/cli/src/closure.ts b/packages/cli/src/closure.ts index 70bfeffd..4456cae7 100644 --- a/packages/cli/src/closure.ts +++ b/packages/cli/src/closure.ts @@ -13,7 +13,8 @@ export type ClosureCapabilityId = | 'trusted-config-interpolation-and-mcp-token' | 'mcp-nested-deadline-and-limits-accounting' | 'retained-store-clock-drift-and-reopen-guard' | 'controller-recovery-cancellation-and-cli-surface' | 'external-build-and-accelerator-matrix' | 'remote-host-loss-and-durable-wake' | 'interactive-mcp-oauth-browser-flow' | 'deployed-github-app-and-webhook-ingress' | 'live-provider-billing-and-effort-attestation' - | 'reviewed-memory-and-cas-compaction' | 'system-one-decision-routing-and-benchmark'; + | 'reviewed-memory-and-cas-compaction' | 'system-one-decision-routing-and-benchmark' + | 'managed-controller-command-v1-direct' | 'managed-controller-exec-role-adapter' | 'in-process-benchmark-gate-hardware'; export type ClosureDisposition = 'closed_local' | 'deferred_owned' | 'blocked_external'; export type ClosureEvidenceLevel = 'unit_and_integration' | 'controlled_local_qualification' | 'frozen_offline_parity' | 'unprovisioned_external'; export type ClosureOwnerPackage = '@loopwright/core' | '@loopwright/state' | '@loopwright/agent-pi' | '@loopwright/controller' | '@loopwright/cli' @@ -122,7 +123,7 @@ const CLOSED = (id: ClosureCapabilityId, title: string, subsystem: ClosureSubsys ledgerEntry({ id, title, subsystem, ownerPackage, disposition: 'closed_local', verificationStatus: 'passed', evidenceLevel, closureCriterion: criterion, residualBoundary: residual, unlockPrerequisite: null, evidencePaths }); const EXTERNAL = (id: ClosureCapabilityId, title: string, subsystem: ClosureSubsystem, ownerPackage: ClosureOwnerPackage, disposition: ClosureDisposition, status: ClosureCapabilityEntry['verificationStatus'], criterion: string, residual: string, unlock: string, evidencePaths: readonly string[]): ClosureCapabilityEntry => ledgerEntry({ id, title, subsystem, ownerPackage, disposition, verificationStatus: status, evidenceLevel: 'unprovisioned_external', closureCriterion: criterion, residualBoundary: residual, unlockPrerequisite: unlock, evidencePaths }); -/** The frozen 23-row Capability Closure Ledger; every evidence path is a committed repository file. */ +/** The frozen 26-row Capability Closure Ledger; every evidence path is a committed repository file. */ export const CLOSURE_CAPABILITY_LEDGER: readonly ClosureCapabilityEntry[] = freezeEntries([ CLOSED('exclusive-owner-and-unknown-usage', 'Exclusive owner fencing and unknown-usage retention', 'controller-execution', '@loopwright/controller', 'controlled_local_qualification', 'A single active owner survives recovery and every unknown-outcome dispatch retains its reservation until reconciled.', @@ -205,6 +206,34 @@ export const CLOSURE_CAPABILITY_LEDGER: readonly ClosureCapabilityEntry[] = free CLOSED('system-one-decision-routing-and-benchmark', 'System-One decision routing and benchmark', 'decision-routing', '@loopwright/decisions', 'unit_and_integration', 'Decision authority boundaries refuse non-delegable intents and the controlled benchmark pins routing quality.', 'Live provider routing quality beyond the frozen benchmark corpus stays unmeasured.', ['packages/decisions/src/router.ts', 'packages/decisions/src/benchmark.ts', 'packages/decisions/test/benchmark.test.ts']), + CLOSED('managed-controller-command-v1-direct', 'Managed Controller command.v1 under direct', 'controller-local-checks', '@loopwright/controller', 'unit_and_integration', + 'Protected command.v1 scripts execute under registry-attested direct mode with host_execution evidence, process-group timeout cleanup, and fail-closed crash recovery.', + 'Scripts run under the controller UID without OS containment; host isolation is attested by the digest-pinned registry (host_execution evidence level).', + [ + 'packages/core/src/local-check-contract.ts', + 'packages/controller/src/local-check.ts', + 'packages/controller/test/local-check.test.ts', + 'packages/controller/test/local-check-integration.test.ts', + 'packages/controller/test/recovery-cycle.test.ts', + ]), + CLOSED('managed-controller-exec-role-adapter', 'Managed Controller exec role adapter', 'controller-exec-role', '@loopwright/controller', 'unit_and_integration', + 'Exec role profiles run local commands with allowlisted environment, consumer: exec credentials, delegated overlay checks, usage aggregation, and unknown-outcome recovery.', + 'Child processes share the controller UID and own provider calls; host isolation and external provider billing stay outside local tests.', + [ + 'packages/controller/src/exec-role.ts', + 'packages/controller/test/exec-role.test.ts', + 'packages/controller/test/exec-role-integration.test.ts', + 'packages/controller/test/exec-usage.test.ts', + 'packages/controller/test/recovery-owner.test.ts', + ]), + EXTERNAL('in-process-benchmark-gate-hardware', 'In-process benchmark-gate.v1 hardware gate', 'hardware-in-process-gate', '@loopwright/hardware-runner', 'blocked_external', 'blocked', + 'In-process benchmark-gate.v1 execution under native_os requires user-namespace support in the target Pod profile and physical CUDA host qualification.', + 'native_os bubblewrap namespaces are blocked (namespaces_blocked) under Pod Security Admission restricted (RuntimeDefault seccomp denies clone(CLONE_NEWUSER)); physical CUDA qualification stays unprovisioned.', + 'Qualify a target host or Pod profile permitting native_os isolation with physical CUDA hardware and attach a signed ExternalQualificationReceipt.', + [ + 'packages/hardware-runner/test/bwrap-namespace-probe.test.ts', + 'packages/hardware-runner/test/fixtures/bwrap-namespace-probe/evidence/restricted-probe-output.jsonl', + ]), ]); function receiptErrors(receipt: ExternalQualificationReceipt): string | null { if (typeof receipt.capabilityId !== 'string' || receipt.capabilityId.length === 0) return 'receipt names no capability'; diff --git a/packages/cli/src/main.ts b/packages/cli/src/main.ts index 058034c0..ba512340 100644 --- a/packages/cli/src/main.ts +++ b/packages/cli/src/main.ts @@ -61,7 +61,7 @@ export function closureExitCode(report: ClosureMatrixReport, verifyFailures: boo if (report.falsificationDetected || report.diagnostics.some(diagnostic => diagnostic.code === CLOSURE_FALSIFICATION_FORBIDDEN || diagnostic.code === 'CAPABILITY_UNSUPPORTED')) return 3; if (!report.integrity.ok) return 8; if (verifyFailures && (report.failureMatrix === null || !report.failureMatrix.allPassed)) return 4; - return report.summary.closedLocal === 18 && report.summary.unprovisionedExternal === 5 ? 0 : 3; + return report.summary.closedLocal === 20 && report.summary.unprovisionedExternal === 6 ? 0 : 3; } async function queryInspection(runRoot: string, runId: string): Promise { try { diff --git a/packages/cli/test/check-docs-rules.test.ts b/packages/cli/test/check-docs-rules.test.ts index d116e34f..49b41885 100644 --- a/packages/cli/test/check-docs-rules.test.ts +++ b/packages/cli/test/check-docs-rules.test.ts @@ -59,6 +59,7 @@ const PUBLIC_PAGES: readonly PageSpec[] = [ { relPath: 'operations/coding-agents.md', title: 'Coding Agents' }, { relPath: 'walkthroughs/declarative-taskpack.md', title: 'Declarative Taskpack' }, { relPath: 'walkthroughs/managed-controller.md', title: 'Managed Controller' }, + { relPath: 'walkthroughs/managed-controller-in-isolated-host.md', title: 'Managed Controller in Isolated Host' }, { relPath: 'walkthroughs/evolutionary-campaign.md', title: 'Evolutionary Campaign' }, { relPath: 'configuration/taskpack.md', title: 'Taskpack' }, { relPath: 'configuration/task-contract.md', title: 'Task Contract' }, @@ -90,6 +91,7 @@ const CONTRIBUTE_PAGES: readonly PageSpec[] = [ { relPath: 'contribute/closure-matrix.md', title: 'Capability Closure Matrix and Failure Semantics' }, { relPath: 'contribute/adr/0001-local-state-authority.md', title: 'ADR 0001: Local State Authority' }, { relPath: 'contribute/adr/0002-isolated-pi-sdk.md', title: 'ADR 0002: Isolated Pi SDK' }, + { relPath: 'contribute/adr/0003-linux-sqlite-profiles.md', title: 'ADR 0003: Linux SQLite Profiles' }, ]; const CANONICAL_PAGES: readonly PageSpec[] = [ @@ -319,6 +321,7 @@ function buildMinimalRepoFixture(): string { ' items:', ' - /docs/walkthroughs/declarative-taskpack/', ' - /docs/walkthroughs/managed-controller/', + ' - /docs/walkthroughs/managed-controller-in-isolated-host/', ' - /docs/walkthroughs/evolutionary-campaign/', ' - name: Configuration', ' items:', @@ -337,6 +340,7 @@ function buildMinimalRepoFixture(): string { ' /docs/operations/coding-agents/: Coding Agents', ' /docs/walkthroughs/declarative-taskpack/: Declarative Taskpack', ' /docs/walkthroughs/managed-controller/: Managed Controller', + ' /docs/walkthroughs/managed-controller-in-isolated-host/: Managed Controller in Isolated Host', ' /docs/walkthroughs/evolutionary-campaign/: Evolutionary Campaign', ' /docs/configuration/taskpack/: Taskpack', ' /docs/configuration/task-contract/: Task Contract', diff --git a/packages/cli/test/closure-and-failure-matrix.test.ts b/packages/cli/test/closure-and-failure-matrix.test.ts index 3089c1c1..6679ee49 100644 --- a/packages/cli/test/closure-and-failure-matrix.test.ts +++ b/packages/cli/test/closure-and-failure-matrix.test.ts @@ -15,9 +15,9 @@ function getFullClosureReport(): Promise { cachedFullClosureReport ??= evaluateClosureMatrix({ repoRoot: REPO_ROOT, verifyFailures: true }); return cachedFullClosureReport; } -test('closure: freezes the 23-row ledger with honest summary counts', () => { +test('closure: freezes the 26-row ledger with honest summary counts', () => { assert.equal(Object.isFrozen(CLOSURE_CAPABILITY_LEDGER), true); - assert.equal(CLOSURE_CAPABILITY_LEDGER.length, 23); + assert.equal(CLOSURE_CAPABILITY_LEDGER.length, 26); for (const entry of CLOSURE_CAPABILITY_LEDGER) { assert.equal(Object.isFrozen(entry), true); assert.equal(Object.isFrozen(entry.evidencePaths), true); @@ -27,9 +27,11 @@ test('closure: freezes the 23-row ledger with honest summary counts', () => { else assert.ok(entry.disposition !== 'closed_local' || entry.unlockPrerequisite !== null || entry.verificationStatus !== 'passed'); } const ids = new Set(CLOSURE_CAPABILITY_LEDGER.map(entry => entry.id)); - assert.equal(ids.size, 23); - assert.equal(CLOSURE_CAPABILITY_LEDGER.filter(entry => entry.disposition === 'closed_local').length, 18); - assert.equal(CLOSURE_CAPABILITY_LEDGER.filter(entry => entry.evidenceLevel === 'unprovisioned_external').length, 5); + assert.equal(ids.size, 26); + assert.equal(CLOSURE_CAPABILITY_LEDGER.filter(entry => entry.disposition === 'closed_local').length, 20); + assert.equal(CLOSURE_CAPABILITY_LEDGER.filter(entry => entry.disposition === 'blocked_external').length, 4); + assert.equal(CLOSURE_CAPABILITY_LEDGER.filter(entry => entry.disposition === 'deferred_owned').length, 2); + assert.equal(CLOSURE_CAPABILITY_LEDGER.filter(entry => entry.evidenceLevel === 'unprovisioned_external').length, 6); const hostProfileRow = CLOSURE_CAPABILITY_LEDGER.find(entry => entry.id === 'qualified-host-clock-and-storage-profile')!; assert.equal(hostProfileRow.ownerPackage, '@loopwright/taskpack'); assert.ok(hostProfileRow.evidencePaths.includes('packages/taskpack/src/qualification.ts')); @@ -50,18 +52,53 @@ test('closure: freezes the 23-row ledger with honest summary counts', () => { 'packages/hardware-runner/test/e2e-nat-loopback.test.ts', 'docs/configuration/sandbox-backends.md', ]); + const commandDirectRow = CLOSURE_CAPABILITY_LEDGER.find(entry => entry.id === 'managed-controller-command-v1-direct')!; + assert.equal(commandDirectRow.disposition, 'closed_local'); + assert.equal(commandDirectRow.verificationStatus, 'passed'); + assert.equal(commandDirectRow.evidenceLevel, 'unit_and_integration'); + assert.equal(commandDirectRow.ownerPackage, '@loopwright/controller'); + assert.deepEqual(commandDirectRow.evidencePaths, [ + 'packages/core/src/local-check-contract.ts', + 'packages/controller/src/local-check.ts', + 'packages/controller/test/local-check.test.ts', + 'packages/controller/test/local-check-integration.test.ts', + 'packages/controller/test/recovery-cycle.test.ts', + ]); + const execRoleRow = CLOSURE_CAPABILITY_LEDGER.find(entry => entry.id === 'managed-controller-exec-role-adapter')!; + assert.equal(execRoleRow.disposition, 'closed_local'); + assert.equal(execRoleRow.verificationStatus, 'passed'); + assert.equal(execRoleRow.evidenceLevel, 'unit_and_integration'); + assert.equal(execRoleRow.ownerPackage, '@loopwright/controller'); + assert.deepEqual(execRoleRow.evidencePaths, [ + 'packages/controller/src/exec-role.ts', + 'packages/controller/test/exec-role.test.ts', + 'packages/controller/test/exec-role-integration.test.ts', + 'packages/controller/test/exec-usage.test.ts', + 'packages/controller/test/recovery-owner.test.ts', + ]); + const inProcessGateRow = CLOSURE_CAPABILITY_LEDGER.find(entry => entry.id === 'in-process-benchmark-gate-hardware')!; + assert.equal(inProcessGateRow.disposition, 'blocked_external'); + assert.equal(inProcessGateRow.verificationStatus, 'blocked'); + assert.equal(inProcessGateRow.evidenceLevel, 'unprovisioned_external'); + assert.equal(inProcessGateRow.ownerPackage, '@loopwright/hardware-runner'); + assert.deepEqual(inProcessGateRow.evidencePaths, [ + 'packages/hardware-runner/test/bwrap-namespace-probe.test.ts', + 'packages/hardware-runner/test/fixtures/bwrap-namespace-probe/evidence/restricted-probe-output.jsonl', + ]); }); test('closure: evaluates the committed repository evidence with clean integrity', async () => { const report = await evaluateClosureMatrix({ repoRoot: REPO_ROOT }); assert.equal(report.version, 1); assert.equal(report.integrity.ok, true, JSON.stringify(report.integrity.failures)); - assert.ok(report.integrity.checkedFiles >= 23); + assert.ok(report.integrity.checkedFiles >= 26); assert.equal(report.falsificationDetected, false); assert.deepEqual(report.diagnostics, []); - assert.equal(report.summary.total, 23); - assert.equal(report.summary.closedLocal, 18); - assert.equal(report.summary.unprovisionedExternal, 5); - assert.equal(report.summary.passed, 18); + assert.equal(report.summary.total, 26); + assert.equal(report.summary.closedLocal, 20); + assert.equal(report.summary.blockedExternal, 4); + assert.equal(report.summary.deferredOwned, 2); + assert.equal(report.summary.unprovisionedExternal, 6); + assert.equal(report.summary.passed, 20); assert.equal(report.failureMatrix, null); assert.equal(closureExitCode(report, false), 0); assert.equal(closureExitCode(report, true), 4); @@ -196,7 +233,7 @@ test('closure: the full 14-scenario matrix passes against real public APIs', { t assert.ok(scenario13.assertions.some(claim => claim.includes('spec.vars'))); assert.equal(codes.get('decision_authority_escalation_refusal'), 'DECISION_AUTHORITY_VIOLATION'); for (const scenario of report.scenarios) { assert.ok(scenario.assertions.length > 0, scenario.scenarioId); assert.ok(scenario.elapsedMs >= 0); } - assert.equal(closureExitCode({ version: 1, integrity: { ok: true, checkedFiles: 23, failures: [] }, falsificationDetected: false, diagnostics: [], summary: { total: 23, closedLocal: 18, deferredOwned: 2, blockedExternal: 3, unprovisionedExternal: 5, passed: 18 }, failureMatrix: report } as ClosureMatrixReport, true), 0); + assert.equal(closureExitCode({ version: 1, integrity: { ok: true, checkedFiles: 26, failures: [] }, falsificationDetected: false, diagnostics: [], summary: { total: 26, closedLocal: 20, deferredOwned: 2, blockedExternal: 4, unprovisionedExternal: 6, passed: 20 }, failureMatrix: report } as ClosureMatrixReport, true), 0); }); test('closure: one injected scenario failure flips the report and maps to exit 4', { timeout: 60000 }, async () => { const scenarioOverrides: NonNullable[0]>['scenarioOverrides'] = {}; @@ -210,13 +247,13 @@ test('closure: one injected scenario failure flips the report and maps to exit 4 assert.equal(report.failed, 1); assert.equal(report.passed, 13); assert.equal(report.scenarios.find(scenario => !scenario.passed)?.diagnosticCode, 'INJECTED_FAULT'); - const withIntegrity: ClosureMatrixReport = { version: 1, integrity: { ok: true, checkedFiles: 23, failures: [] }, falsificationDetected: false, diagnostics: [], summary: { total: 23, closedLocal: 18, deferredOwned: 2, blockedExternal: 3, unprovisionedExternal: 5, passed: 18 }, failureMatrix: report }; + const withIntegrity: ClosureMatrixReport = { version: 1, integrity: { ok: true, checkedFiles: 26, failures: [] }, falsificationDetected: false, diagnostics: [], summary: { total: 26, closedLocal: 20, deferredOwned: 2, blockedExternal: 4, unprovisionedExternal: 6, passed: 20 }, failureMatrix: report }; assert.equal(closureExitCode(withIntegrity, true), 4); const falsified: ClosureMatrixReport = { ...withIntegrity, falsificationDetected: true }; assert.equal(closureExitCode(falsified, true), 3); const missingEvidence: ClosureMatrixReport = { ...withIntegrity, integrity: { ok: false, checkedFiles: 0, failures: [{ capabilityId: null, path: '.', code: CLOSURE_EVIDENCE_UNTRUSTED, detail: 'root missing' }] } }; assert.equal(closureExitCode(missingEvidence, true), 8); - const wrongCounts: ClosureMatrixReport = { ...withIntegrity, failureMatrix: { version: 1, total: 14, passed: 14, failed: 0, allPassed: true, scenarios: [] }, summary: { ...withIntegrity.summary, closedLocal: 17 } }; + const wrongCounts: ClosureMatrixReport = { ...withIntegrity, failureMatrix: { version: 1, total: 14, passed: 14, failed: 0, allPassed: true, scenarios: [] }, summary: { ...withIntegrity.summary, closedLocal: 19 } }; assert.equal(closureExitCode(wrongCounts, true), 3); const unsupported: ClosureMatrixReport = { ...withIntegrity, diagnostics: [{ code: 'CAPABILITY_UNSUPPORTED', capabilityId: null, path: '/entries/0', detail: 'shape' }] }; assert.equal(closureExitCode(unsupported, false), 3); @@ -228,8 +265,10 @@ test('closure: production subprocess audits the repository and refuses unusable assert.equal(envelope.kind, 'closure'); assert.equal(envelope.sequence, 1); assert.equal(envelope.runId, null); - assert.equal(envelope.data.summary.closedLocal, 18); - assert.equal(envelope.data.summary.unprovisionedExternal, 5); + assert.equal(envelope.data.summary.closedLocal, 20); + assert.equal(envelope.data.summary.unprovisionedExternal, 6); + assert.equal(envelope.data.summary.blockedExternal, 4); + assert.equal(envelope.data.summary.deferredOwned, 2); assert.equal(envelope.data.integrity.ok, true); const missingRoot = spawnSync(process.execPath, [MAIN, 'closure', '--repo', join(tmpdir(), 'lw-closure-missing-root'), '--json'], { encoding: 'utf8', timeout: 15000, env: { PATH: '/usr/bin:/bin' } }); assert.equal(missingRoot.status, 8, missingRoot.stdout + missingRoot.stderr); diff --git a/packages/cli/test/docs-and-site.test.ts b/packages/cli/test/docs-and-site.test.ts index 9c071454..c037149b 100644 --- a/packages/cli/test/docs-and-site.test.ts +++ b/packages/cli/test/docs-and-site.test.ts @@ -433,7 +433,7 @@ test('documentation verification: check-docs.mjs passes with zero errors', () => assert.match(run.stdout, /0 error\(s\)/, 'check-docs.mjs must report 0 error(s)'); }); -test('hugo site: site.mjs build builds 15-page site, exports three-zone llms.txt + 6 flat references, and verifies zero excluded-zone leaks in sitemap.xml and index.json', () => { +test('hugo site: site.mjs build builds 16-page site, exports three-zone llms.txt + 6 flat references, and verifies zero excluded-zone leaks in sitemap.xml and index.json', () => { const siteScript = join(REPO_ROOT, 'scripts', 'site.mjs'); assert.ok(existsSync(siteScript), 'scripts/site.mjs must exist'); @@ -462,7 +462,7 @@ test('hugo site: site.mjs build builds 15-page site, exports three-zone llms.txt }); assert.equal(build.status, 0, `site.mjs build failed:\nstdout: ${build.stdout}\nstderr: ${build.stderr}`); - assert.match(build.stdout, /Verified \d+ HTML pages and 15 Markdown exports; 0 broken link\(s\)/); + assert.match(build.stdout, /Verified \d+ HTML pages and 16 Markdown exports; 0 broken link\(s\)/); const publicDir = join(REPO_ROOT, 'site', 'public'); assert.ok(existsSync(join(publicDir, 'llms.txt')), 'llms.txt must exist'); @@ -470,10 +470,10 @@ test('hugo site: site.mjs build builds 15-page site, exports three-zone llms.txt assert.ok(existsSync(join(publicDir, 'index.json')), 'index.json must exist'); assert.ok(existsSync(join(publicDir, 'sitemap.xml')), 'sitemap.xml must exist'); - // Verify llms.txt content across all 3 zones (Public 15 + Reference 6 + Optional 13 [README + 12 Contribute]) + // Verify llms.txt content across all 3 zones (Public 16 + Reference 6 + Optional 14 [README + 13 Contribute]) const llms = readFileSync(join(publicDir, 'llms.txt'), 'utf8'); const llmsPublicMatches = llms.match(/^-\s+\[[^\]]+\]\((?:https?:\/\/[^/]+)?\/docs\/[^)]+\):/gm); - assert.equal(llmsPublicMatches?.length, 15, 'llms.txt must list exactly 15 public docs pages'); + assert.equal(llmsPublicMatches?.length, 16, 'llms.txt must list exactly 16 public docs pages'); assert.match(llms, /\/docs\/walkthroughs\/evolutionary-campaign\/index\.md\)/, 'llms.txt must link to singular evolutionary-campaign'); const expectedRefFiles = [ @@ -500,8 +500,8 @@ test('hugo site: site.mjs build builds 15-page site, exports three-zone llms.txt const optionalGithubMatches = llms.match(/^-\s+\[[^\]]+\]\(https:\/\/github\.com\/gpustack\/loopwright\/blob\/[^/]+\/docs\/[^)]+\):/gm); assert.equal( optionalGithubMatches?.length, - 13, - 'llms.txt ## Optional must list Repository navigation (docs/README.md) plus all 12 Contribute pages' + 14, + 'llms.txt ## Optional must list Repository navigation (docs/README.md) plus all 13 Contribute pages' ); for (const nonGithubLine of llms.split('\n').filter(l => l.startsWith('- ') && !l.includes('https://github.com/'))) { @@ -521,7 +521,7 @@ test('hugo site: site.mjs build builds 15-page site, exports three-zone llms.txt // Verify index.json content and 0 excluded-zone leaks const index = JSON.parse(readFileSync(join(publicDir, 'index.json'), 'utf8')) as Array<{ url?: string }>; - assert.ok(Array.isArray(index) && index.length >= 15, 'index.json must contain at least 15 pages'); + assert.ok(Array.isArray(index) && index.length >= 16, 'index.json must contain at least 16 pages'); for (const entry of index) { const u = String(entry.url ?? ''); assert.ok( @@ -540,7 +540,7 @@ test('hugo site: site.mjs build builds 15-page site, exports three-zone llms.txt ); } - // Verify 15 markdown and html exports exist under docs/// + // Verify 16 markdown and html exports exist under docs/// const canonicalPages = [ 'getting-started/architecture', 'getting-started/installation', @@ -550,6 +550,7 @@ test('hugo site: site.mjs build builds 15-page site, exports three-zone llms.txt 'operations/coding-agents', 'walkthroughs/declarative-taskpack', 'walkthroughs/managed-controller', + 'walkthroughs/managed-controller-in-isolated-host', 'walkthroughs/evolutionary-campaign', 'configuration/taskpack', 'configuration/task-contract', @@ -586,7 +587,7 @@ test('hugo site: site.mjs build builds 15-page site, exports three-zone llms.txt env: { ...process.env, SITE_BASE_URL: 'https://docs.gpustack.ai/loopwright/latest/' } }); assert.equal(subpathBuild.status, 0, `subpath site.mjs build failed:\nstdout: ${subpathBuild.stdout}\nstderr: ${subpathBuild.stderr}`); - assert.match(subpathBuild.stdout, /Verified \d+ HTML pages and 15 Markdown exports; 0 broken link\(s\)/); + assert.match(subpathBuild.stdout, /Verified \d+ HTML pages and 16 Markdown exports; 0 broken link\(s\)/); const subpathLlms = readFileSync(join(publicDir, 'llms.txt'), 'utf8'); assert.match( subpathLlms, diff --git a/scripts/check-docs.mjs b/scripts/check-docs.mjs index 7aaf8a8c..de828a31 100755 --- a/scripts/check-docs.mjs +++ b/scripts/check-docs.mjs @@ -90,6 +90,7 @@ export const PUBLIC_SITE_DOC_REL_PATHS = new Set([ "docs/operations/coding-agents.md", "docs/walkthroughs/declarative-taskpack.md", "docs/walkthroughs/managed-controller.md", + "docs/walkthroughs/managed-controller-in-isolated-host.md", "docs/walkthroughs/evolutionary-campaign.md", "docs/configuration/taskpack.md", "docs/configuration/task-contract.md", @@ -110,7 +111,8 @@ export const REPO_ONLY_DOC_REL_PATHS = new Set([ "docs/contribute/github-app-internals.md", "docs/contribute/closure-matrix.md", "docs/contribute/adr/0001-local-state-authority.md", - "docs/contribute/adr/0002-isolated-pi-sdk.md" + "docs/contribute/adr/0002-isolated-pi-sdk.md", + "docs/contribute/adr/0003-linux-sqlite-profiles.md" ]); const MAX_HEADING_DEPTH = 3; diff --git a/site/content/docs/_index.md b/site/content/docs/_index.md index 7b8d14bc..d51373ea 100644 --- a/site/content/docs/_index.md +++ b/site/content/docs/_index.md @@ -22,6 +22,7 @@ Loopwright supports two operating modes sharing one verification kernel: **Decla - [Declarative Taskpack](walkthroughs/declarative-taskpack/) walks through simple single-file repository automation and automatic synchronized workflow migration. - [Managed Controller](walkthroughs/managed-controller/) walks through fine-grained out-of-repo `TrustedRegistry`, `ControllerConfig`, and CLI execution. +- [Managed Controller in Isolated Host](walkthroughs/managed-controller-in-isolated-host/) runs `command.v1` checks under `direct` and `exec` roles unattended inside an isolated host. - [Evolutionary Campaign](walkthroughs/evolutionary-campaign/) coordinates multi-island evolutionary search, hardware benchmark relays, and reproducible bundle export. ## Configuration diff --git a/site/data/navigation.yaml b/site/data/navigation.yaml index d54db172..2a9cc3da 100644 --- a/site/data/navigation.yaml +++ b/site/data/navigation.yaml @@ -13,6 +13,7 @@ groups: items: - /docs/walkthroughs/declarative-taskpack/ - /docs/walkthroughs/managed-controller/ + - /docs/walkthroughs/managed-controller-in-isolated-host/ - /docs/walkthroughs/evolutionary-campaign/ - name: Configuration items: @@ -32,6 +33,7 @@ labels: /docs/operations/coding-agents/: Coding Agents /docs/walkthroughs/declarative-taskpack/: Declarative Taskpack /docs/walkthroughs/managed-controller/: Managed Controller + /docs/walkthroughs/managed-controller-in-isolated-host/: Managed Controller in Isolated Host /docs/walkthroughs/evolutionary-campaign/: Evolutionary Campaign /docs/configuration/taskpack/: Taskpack /docs/configuration/task-contract/: Task Contract diff --git a/site/layouts/index.html b/site/layouts/index.html index 0a454c92..10741277 100644 --- a/site/layouts/index.html +++ b/site/layouts/index.html @@ -59,6 +59,7 @@

Walkt diff --git a/specs/2026-11-30-managed-controller-in-process-execution.md b/specs/2026-11-30-managed-controller-in-process-execution.md index 01fe757d..91b8269d 100644 --- a/specs/2026-11-30-managed-controller-in-process-execution.md +++ b/specs/2026-11-30-managed-controller-in-process-execution.md @@ -596,7 +596,7 @@ and T11 have disjoint `Owns:` and start together; T5 follows T2. Owns: `packages/controller/src/budget-observations.ts`, `packages/controller/src/controller.ts`, `packages/controller/src/acceptance.ts`, `packages/controller/src/inspect.ts`, `packages/controller/src/run-eval.ts`, `packages/controller/src/exec-role.ts`, `packages/core/src/usage.ts`, `packages/core/test/usage.test.ts`, `packages/controller/test/exec-usage.test.ts` Acceptance: each `exec` dispatch charges one model call under `maxModelCalls` hard admission before the spawn; settled `exec-outcome` artifacts carry reported request records (namespaced per attempt as `:`, `provenance: 'reported'`) or `usageReported: false` (`provenance: 'unknown'`) without inserting `unknown` entries into frozen `LocalRunStore.requests`; `acceptance.ts` and `inspect.ts` aggregate them into `RunResult` and `usage.json`; `run-eval.ts` classifies `exec` honestly instead of counting it as `piAttempts` with `toolTelemetry: 'available'`. Verify: `node scripts/run-tests.mjs --pkg controller && node scripts/run-tests.mjs --pkg core` -- [ ] **T8 · Closure matrix, ADR, and documentation** +- [x] **T8 · Closure matrix, ADR, and documentation** Blocked by: T4, T6, T7 Owns: `packages/cli/src/closure.ts`, `packages/cli/src/failure-matrix.ts`, `packages/cli/test/closure-and-failure-matrix.test.ts`, `docs/contribute/closure-matrix.md`, `docs/configuration/controller-and-registry.md`, `docs/operations/cli.md`, `docs/operations/coding-agents.md`, `docs/configuration/task-contract.md`, `docs/walkthroughs/managed-controller-in-isolated-host.md`, `docs/contribute/adr/0003-linux-sqlite-profiles.md`, `docs/README.md`, `site/data/navigation.yaml`, `scripts/check-docs.mjs` Acceptance: the ledger has 26 rows (two `closed_local`, one `blocked_external`) with the tests named; `closure` reports the split and `--verify-failures` passes; ADR 0003 supersedes the profile sentence of ADR 0001 with the CI evidence and the Linux `fullfsync` semantics; the handler table, the registry fields, the role profiles, the credential consumers, the evidence level, the CLI pages, the ADR table, the new walkthrough, and this spec are linked from `docs/README.md`; the walkthrough is in the site navigation and the public site paths. From 1545830091659d8e836edc88f72318f4b64fc6ea Mon Sep 17 00:00:00 2001 From: thxCode Date: Tue, 1 Dec 2026 23:46:33 +0800 Subject: [PATCH 20/26] feat(cli): add campaign snapshot CLI commands, fix per-candidate lockHash verification, and add docs - Add evolve export --snapshot, evolve check --bundle, evolve import, --receipt-secret-env (optional when zero signed receipts, fail-closed otherwise), and --allow-host-attested in packages/cli/src/{arguments,main}.ts. - Drop expectedLockHash: campaign.lockHash in packages/evolution/src/snapshot.ts (matching bundle.ts) so real evolve campaigns with per-candidate child TaskContract lockHashes export and import cleanly while preserving HMAC signature, candidateDigest, targetCellId, and receipt field bindings. - Add packages/cli/test/evolve-snapshot.test.ts covering grammar, signed synthetic_fixture round-trip/tamper/secret-hygiene, direct-mode receipt: null without --receipt-secret-env, host_attested gating, and real evolve resume on a lower monotonic clock without EVOLUTION_CLOCK_DRIFT. - Add Campaign Snapshots public configuration page and sync docs/contribute/internals.md (snapshot_provenance), docs/operations/cli.md, docs/README.md, scripts/check-docs.mjs, site navigation/index/home, page-map.md, and docs/site CLI tests. - Check off T10 in the spec; all 37 docs pages, Hugo site exports, 56/57 evolution tests (1 skipped), and 105/105 CLI tests pass. Signed-off-by: thxCode --- .../loopwright-docs/references/page-map.md | 17 +- docs/README.md | 5 +- docs/configuration/campaign-snapshots.md | 82 + docs/contribute/internals.md | 4 +- docs/operations/cli.md | 7 +- packages/cli/src/arguments.ts | 34 +- packages/cli/src/main.ts | 128 +- packages/cli/test/check-docs-rules.test.ts | 3 + packages/cli/test/docs-and-site.test.ts | 17 +- packages/cli/test/evolve-snapshot.test.ts | 1364 +++++++++++++++++ packages/evolution/src/snapshot.ts | 2 - scripts/check-docs.mjs | 3 +- site/content/docs/_index.md | 1 + site/data/navigation.yaml | 2 + site/layouts/index.html | 1 + ...managed-controller-in-process-execution.md | 2 +- 16 files changed, 1635 insertions(+), 37 deletions(-) create mode 100644 docs/configuration/campaign-snapshots.md create mode 100644 packages/cli/test/evolve-snapshot.test.ts diff --git a/.agents/skills/loopwright-docs/references/page-map.md b/.agents/skills/loopwright-docs/references/page-map.md index ce086420..0255f767 100644 --- a/.agents/skills/loopwright-docs/references/page-map.md +++ b/.agents/skills/loopwright-docs/references/page-map.md @@ -2,16 +2,16 @@ One file owns each technical fact, schema dictionary, or operational workflow. When multiple pages touch a subject, the owning file states the normative contract and every other page links to it within allowed zone boundaries. -## Three-Zone Architecture (`36` Markdown Files Under `docs/`) +## Three-Zone Architecture (`37` Markdown Files Under `docs/`) -Loopwright maintains **`36` Markdown files** under `docs/`: **`1` shared index** (`docs/README.md`) plus **`35` zone pages** partitioned into three strict zones: +Loopwright maintains **`37` Markdown files** under `docs/`: **`1` shared index** (`docs/README.md`) plus **`36` zone pages** partitioned into three strict zones: -- **16 Public Human Site Pages (`Site Published: yes`)**: Built into the Hugo static site (`site/public/`) across `4` groups (`Getting Started`, `Operations`, `Walkthroughs`, `Configuration`), registered under `docs/README.md` `## All pages`, listed in `site/data/navigation.yaml`, `site/content/docs/_index.md`, and `site/layouts/index.html`, indexed in `index.json` and `sitemap.xml`, and exported to `site/public/llms.txt` topic sections. +- **17 Public Human Site Pages (`Site Published: yes`)**: Built into the Hugo static site (`site/public/`) across `4` groups (`Getting Started`, `Operations`, `Walkthroughs`, `Configuration`), registered under `docs/README.md` `## All pages`, listed in `site/data/navigation.yaml`, `site/content/docs/_index.md`, and `site/layouts/index.html`, indexed in `index.json` and `sitemap.xml`, and exported to `site/public/llms.txt` topic sections. - **6 Flat LLM Reference Pages (`Site Published: static /references/*.md`)**: Flat `docs/references/*.md` files (`README.md` hub + `5` topic references; `0` subdirectories) excluded from HTML navigation, `index.json`, and `sitemap.xml`, staged with rewritten links by `scripts/site.mjs` (`stageReferenceDocs()`) into `site/resources/references/` → `site/public/references/*.md`, and dynamically emitted under `## Reference` in `docs/README.md` and `site/public/llms.txt`. - **13 Repo-Only `Contribute` Pages (`Site Published: no (repo-only)`)**: `docs/development.md`, `docs/contribute/{internals,identity,evidence,state,pi-adapter,runner-taskpack,memory,github-app-internals,closure-matrix}.md`, and `docs/contribute/adr/{0001-local-state-authority,0002-isolated-pi-sdk,0003-linux-sqlite-profiles}.md` excluded from Hugo HTML, `index.json`, and `sitemap.xml`, registered under `docs/README.md` `## Contribute`, and emitted under `site/public/llms.txt` `## Optional` as GitHub `blob/` URLs. -- **One-Way Public Link Isolation**: None of the `16` public `docs/` pages or `site/content/**` files may link to `development.md`, `contribute/**`, or `references/**` (via relative, root-relative, or same-origin URLs). `docs/references/*.md` and `docs/contribute/**` may freely link inward to public pages. +- **One-Way Public Link Isolation**: None of the `17` public `docs/` pages or `site/content/**` files may link to `development.md`, `contribute/**`, or `references/**` (via relative, root-relative, or same-origin URLs). `docs/references/*.md` and `docs/contribute/**` may freely link inward to public pages. -## Zone 1: Public Human Site Inventory (`16` Pages Across `4` Groups) +## Zone 1: Public Human Site Inventory (`17` Pages Across `4` Groups) Every public page (`Site Published: yes`) obeys strict **1:1:1 alignment**: `docs//.md`, with `Exact # H1 Title === docs/README.md All pages Label === navigation.yaml Label`, `<= 8` content `##` H2 sections, and both `**See also**` and `**Next**` reading footer lines. @@ -33,6 +33,7 @@ Every public page (`Site Published: yes`) obeys strict **1:1:1 alignment**: `doc | `configuration/sandbox-backends.md` | Configuration | `yes` | `Sandbox Backends` | `Sandbox Backends` | `<= 400` | Platform & security engineers | `@loopwright/agent-pi`, `@loopwright/taskpack`; `specs/2026-11-11-native-os-sandbox-execution-backends.md` | | `configuration/decision-routing.md` | Configuration | `yes` | `Decision Routing` | `Decision Routing` | `<= 400` | Triage & policy operators | `@loopwright/decisions`; `specs/2026-11-11-jev-decision-routing-and-controlled-benchmark.md` | | `configuration/evolution-campaign.md` | Configuration | `yes` | `Evolution Campaign` | `Evolution Campaign` | `<= 400` | Kernel & optimization engineers | `@loopwright/evolution`; `specs/2026-11-23-evolutionary-campaigns-pareto-archive-and-bundle-export.md` | +| `configuration/campaign-snapshots.md` | Configuration | `yes` | `Campaign Snapshots` | `Campaign Snapshots` | `<= 400` | Kernel & optimization engineers | `@loopwright/evolution`, `@loopwright/cli`; `specs/2026-11-30-managed-controller-in-process-execution.md` | ## Zone 2: Flat LLM Reference Inventory (`6` Flat `docs/references/*.md` Files) @@ -71,12 +72,12 @@ Every contributor page (`Site Published: no (repo-only)`) is registered in `docs ### `docs/README.md` (Shared Three-Zone Index) - **Owns**: `## Reading paths`, `## Module map` (all `9` module IDs: `contracts`, `state`, `pi-adapter`, `controller`, `taskpacks`, `memory`, `github-app`, `decisions`, `development`), `## Specs`, and three top-level zone tables: - - `## All pages` (`16` public pages grouped under `### Getting Started`, `### Operations`, `### Walkthroughs`, and `### Configuration` — never nesting `### Contribute` or `### Reference`). + - `## All pages` (`17` public pages grouped under `### Getting Started`, `### Operations`, `### Walkthroughs`, and `### Configuration` — never nesting `### Contribute` or `### Reference`). - `## Reference` (all flat `docs/references/*.md` files dynamically verified against disk). - `## Contribute` (all `13` repo-only contributor pages). - **Must not absorb**: Narrative explanations or configuration snippets. -### Public `site/` Pages (`16` Pages Across `4` Groups, `<= 8` H2s) +### Public `site/` Pages (`17` Pages Across `4` Groups, `<= 8` H2s) - **`docs/getting-started/architecture.md` (`<= 200` lines)**: 4-stage execution lifecycle, operating modes, `architecture-flow.svg` + hidden Mermaid flowgraph comment, runtime baseline, and routing links to public guides. - **`docs/getting-started/installation.md` (`<= 400` lines)**: Choosing between GitHub Action, `@gpustack/loopwright` CLI (`npm`/`pnpm --ignore-scripts`), release tarballs, source checkouts, and `llms.txt` bootstrap prompts. - **`docs/operations/github-action.md` (`<= 400` lines)**: Reusable `action.yml` workflow setup, permissions, secret bindings, and common inputs (exhaustive 44-input catalog lives in `docs/references/cli-and-action-reference.md`). @@ -87,7 +88,7 @@ Every contributor page (`Site Published: no (repo-only)`) is registered in `docs - **`docs/walkthroughs/managed-controller.md` (`<= 400` lines)**: End-to-end walkthrough of out-of-repo `TrustedRegistry` + `ControllerConfig` (`managed-controller-relations.svg`) and CLI governance. - **`docs/walkthroughs/managed-controller-in-isolated-host.md` (`<= 400` lines)**: End-to-end walkthrough of unattended Managed Controller execution inside an isolated host using `command.v1` under `direct` and `adapter: exec`. - **`docs/walkthroughs/evolutionary-campaign.md` (`<= 400` lines)**: End-to-end walkthrough of evolutionary campaign mode (`EVOLVE-BLOCK`, `evolve-block-guard.v1`, `benchmark-gate.v1`, `runner relay|worker`, and `loopwright evolve`). -- **`docs/configuration/{taskpack,task-contract,controller-and-registry,sandbox-backends,decision-routing,evolution-campaign}.md` (`<= 400` lines each)**: Human-first mental models, strict block-style Pretty YAML Macro manifests (`Taskpack`, `TaskpackSuite`, `TaskContract`, `ControllerConfig`, `TrustedRegistry`, `DecisionPolicy`, `EvolutionCampaign`), and focused Micro constraints (exhaustive field/bound dictionaries live in `docs/references/{taskpack-and-contract-schema,controller-and-registry-schema}.md`). +- **`docs/configuration/{taskpack,task-contract,controller-and-registry,sandbox-backends,decision-routing,evolution-campaign,campaign-snapshots}.md` (`<= 400` lines each)**: Human-first mental models, strict block-style Pretty YAML Macro manifests (`Taskpack`, `TaskpackSuite`, `TaskContract`, `ControllerConfig`, `TrustedRegistry`, `DecisionPolicy`, `EvolutionCampaign`), portable `campaign-snapshot.v1` layout, and focused Micro constraints (exhaustive field/bound dictionaries live in `docs/references/{taskpack-and-contract-schema,controller-and-registry-schema}.md`). ### Flat LLM `docs/references/*.md` Pages (`6` Files, `<= 800` Lines) - **`docs/references/README.md`**: Task routing (pairing every reference lookup with its public owner), exact resource/CLI symbol aliases, and evidence labels (`contract`, `recorded capture`, `synthetic simulation`). diff --git a/docs/README.md b/docs/README.md index 23079cd3..1bd00d5a 100644 --- a/docs/README.md +++ b/docs/README.md @@ -5,7 +5,7 @@ - [Installation](getting-started/installation.md) and [Architecture](getting-started/architecture.md) - [Declarative Taskpack](walkthroughs/declarative-taskpack.md), [Taskpack](configuration/taskpack.md), and [GitHub Action](operations/github-action.md) - [Managed Controller](walkthroughs/managed-controller.md), [Managed Controller in Isolated Host](walkthroughs/managed-controller-in-isolated-host.md), [Task Contract](configuration/task-contract.md), and [Controller and Registry](configuration/controller-and-registry.md) -- [Evolutionary Campaign](walkthroughs/evolutionary-campaign.md) and [Evolution Campaign](configuration/evolution-campaign.md) +- [Evolutionary Campaign](walkthroughs/evolutionary-campaign.md), [Evolution Campaign](configuration/evolution-campaign.md), and [Campaign Snapshots](configuration/campaign-snapshots.md) - [GitHub App](operations/github-app.md), [CLI](operations/cli.md), and [Coding Agents](operations/coding-agents.md) - [Sandbox Backends](configuration/sandbox-backends.md) and [Decision Routing](configuration/decision-routing.md) - [Reference Hub](references/README.md) and [Bootstrap Interview Reference](references/bootstrap-interview.md) for machine-readable lookup and agent onboarding @@ -51,7 +51,7 @@ - ID: controller - Use for: compile trusted configuration and coordinate bounded runs - Aliases: controller -- Guides: [getting-started/installation.md](getting-started/installation.md), [walkthroughs/managed-controller.md](walkthroughs/managed-controller.md), [walkthroughs/managed-controller-in-isolated-host.md](walkthroughs/managed-controller-in-isolated-host.md), [walkthroughs/evolutionary-campaign.md](walkthroughs/evolutionary-campaign.md), [configuration/controller-and-registry.md](configuration/controller-and-registry.md), [configuration/evolution-campaign.md](configuration/evolution-campaign.md), [operations/cli.md](operations/cli.md), [operations/coding-agents.md](operations/coding-agents.md), [contribute/closure-matrix.md](contribute/closure-matrix.md) +- Guides: [getting-started/installation.md](getting-started/installation.md), [walkthroughs/managed-controller.md](walkthroughs/managed-controller.md), [walkthroughs/managed-controller-in-isolated-host.md](walkthroughs/managed-controller-in-isolated-host.md), [walkthroughs/evolutionary-campaign.md](walkthroughs/evolutionary-campaign.md), [configuration/controller-and-registry.md](configuration/controller-and-registry.md), [configuration/evolution-campaign.md](configuration/evolution-campaign.md), [configuration/campaign-snapshots.md](configuration/campaign-snapshots.md), [operations/cli.md](operations/cli.md), [operations/coding-agents.md](operations/coding-agents.md), [contribute/closure-matrix.md](contribute/closure-matrix.md) - Specs: [Specification](../specs/2026-11-06-bounded-controller-and-trusted-config.md), [Delegated Stepping](../specs/2026-11-14-delegated-role-stepping-and-multi-model-routing.md), [Multi-Domain Suites, Handoffs, and RunEval](../specs/2026-11-21-multi-domain-suite-handoff-and-run-eval.md), [Hardware Execution and Remote Runner](../specs/2026-11-21-hardware-execution-benchmark-gate-and-remote-runner.md), [Evolutionary Campaigns, Pareto Archive, and Bundle Export](../specs/2026-11-23-evolutionary-campaigns-pareto-archive-and-bundle-export.md), [Managed Controller In-Process Execution](../specs/2026-11-30-managed-controller-in-process-execution.md) - Code: [controller](../packages/controller/), [hardware-runner](../packages/hardware-runner/), [evolution](../packages/evolution/), [cli](../packages/cli/) - Related: [contracts](#contracts-and-evidence), [state](#persistent-state-store) @@ -178,6 +178,7 @@ | [Sandbox Backends](configuration/sandbox-backends.md) | Select OS or container sandboxes and required capabilities | | [Decision Routing](configuration/decision-routing.md) | Configure advisory routing policies, providers, and thresholds | | [Evolution Campaign](configuration/evolution-campaign.md) | Configure stages, islands, objectives, budgets, teamEvolution, and export | +| [Campaign Snapshots](configuration/campaign-snapshots.md) | Export, verify, and import portable campaign-snapshot.v1 archives | ## Reference diff --git a/docs/configuration/campaign-snapshots.md b/docs/configuration/campaign-snapshots.md new file mode 100644 index 00000000..f42bd655 --- /dev/null +++ b/docs/configuration/campaign-snapshots.md @@ -0,0 +1,82 @@ +# Campaign Snapshots + +Portable `campaign-snapshot.v1` directories capture an evolution campaign's archive, lineage, islands, bandit arms, team configs, scratchpads, CAS blobs, and approved verdict receipts without SQLite clock or lease state. Importing a snapshot initializes a fresh `campaign.sqlite` authority so search can resume on another host. + +For `EvolutionCampaign` manifest configuration and `evolution-bundle.v1` deployment bundles, see [Evolution Campaign](evolution-campaign.md). For full CLI command syntax, see [CLI](../operations/cli.md#evolution-campaigns). + +## Contents + +- [Snapshot layout](#snapshot-layout) +- [CLI workflow](#cli-workflow) +- [Receipt gates](#receipt-gates) +- [Fresh authority import](#fresh-authority-import) +- [Execution scope](#execution-scope) + +## Snapshot layout + +`loopwright evolve export --snapshot` stages every snapshot member under a sibling directory, hashes each file with SHA-256, scans textual files with `SecretScrubber`, and renames the directory atomically. + +| Member path | Format | Role | +| --- | --- | --- | +| `manifest.json` | Canonical JSON | `kind: CampaignSnapshot`, `version: 1`, generation range, `parentDigest`, member digests | +| `campaign.json` | Canonical JSON | Campaign metadata, manifest, lock hash, and counters without civil timestamps | +| `individuals.jsonl` | Canonical JSONL | Every evaluated candidate (passed, failed, preempted) with CAS and receipt digests | +| `lineage.jsonl` | Canonical JSONL | Parent-to-child lineage edges (`primary`, `crossover_donor`, `inspiration`, `portfolio_member`) | +| `islands.json` | Canonical JSON | Island generations, active team config IDs, stall counters, and hypervolume | +| `bandit.json` | Canonical JSON | Model bandit pull counts, cumulative rewards, and last pulled generations | +| `scratchpad.jsonl` | Canonical JSONL | Scratchpad index rows pointing to content-addressed Markdown payloads | +| `scratchpad/.md` | Markdown | Verified scratchpad content keyed by SHA-256 hex digest | +| `team_configs.jsonl` | Canonical JSONL | Topologically ordered baseline, trial, promoted, and rolled-back team configs | +| `blobs/sha256/` | Verified CAS blobs | Guarded code slices, team patches, and Stage A output artifacts | +| `receipts/.verdict.json` | Signed verdict JSON | Approved HMAC-signed hardware verdict receipts for passed individuals | + +- **Non-approved candidates**: Failed, preempted, and uncertified individuals travel with their full status, metrics, and `receipt: null`. +- **Unreferenced member ban**: Offline verification rejects any member in `manifest.json` that no campaign record references (`ARTIFACT_INVALID`, exit `4`). +- **Symlink refusal**: Export, check, and import refuse symlinked directories or files under `O_NOFOLLOW` (`EVOLUTION_SYMLINK_FORBIDDEN`, exit `3`). + +## CLI workflow + +Use `evolve export --snapshot`, `evolve check --bundle`, `evolve import`, and `evolve resume` to move a campaign cleanly between hosts: + +```sh +loopwright evolve export --campaign ../state-a --snapshot --out ../snap-1 --receipt-secret-env RECEIPT_HMAC --json +loopwright evolve check --bundle ../snap-1 --receipt-secret-env RECEIPT_HMAC --json +loopwright evolve import --bundle ../snap-1 --state ../state-b --receipt-secret-env RECEIPT_HMAC --json +loopwright evolve resume --campaign ../state-b --repo . --json +``` + +- **Mutually exclusive `check` inputs**: Pass either `--campaign FILE [--repo DIR]` or `--bundle DIR`; combining both or passing `--repo` with `--bundle` exits `2`. +- **Snapshot format**: `evolve export --snapshot` always writes `campaign-snapshot.v1` and refuses `--format` (`CLI_USAGE`, exit `2`). +- **Overwrite guard**: Re-exporting to an existing `--out` directory fails with `EVOLUTION_CONFLICT` (exit `7`) unless `--overwrite` is set. + +## Receipt gates + +Snapshot export, offline verification, and import enforce the same fail-closed receipt verification rules as `evolution-bundle.v1`: + +| Flag | Default | Effect | +| --- | --- | --- | +| `--receipt-secret-env NAME` | Optional when zero receipts | Resolves HMAC secret from `process.env[NAME]`; fails closed if unset or empty | +| `--allow-synthetic-probe` | Refused (`false`) | Permits `probeKind: synthetic_fixture` receipts during export, check, or import | +| `--allow-host-attested` | Refused (`false`) | Permits `isolation: host_attested` receipts during export, check, or import | + +- **Zero-receipt snapshots**: Direct-mode campaigns where every individual has `receipt: null` export, check, and import without `--receipt-secret-env`. +- **Signed snapshots**: If any individual carries a non-null `receipt`, omitting `--receipt-secret-env` or supplying a wrong secret fails closed (`EXPORT_UNVERIFIED_FORBIDDEN`, exit `3`). +- **Explicit env validation**: When `--receipt-secret-env NAME` is passed, `NAME` must match `[A-Za-z_][A-Za-z0-9_]{0,127}` and exist non-empty in the environment; the resolved value is scrubbed from all output. + +## Fresh authority import + +Copying raw `campaign.sqlite` files across hosts triggers `EVOLUTION_CLOCK_DRIFT` (exit `7`) whenever the destination monotonic clock is lower than the source host's persisted timestamp. `evolve import` avoids this by establishing a fresh local authority: + +- **Empty target required**: `--state DIR` must be absent or empty; existing files fail closed with `EVOLUTION_CONFLICT` (exit `7`) before writes occur. +- **New fence and clock basis**: Import writes a new `campaign_meta` row with a fresh lease epoch and the destination host's current monotonic clock. Source clock and fence columns never enter the snapshot. +- **Provenance chaining**: Import records the verified `manifestDigest` in `snapshot_provenance`. Later `evolve export --snapshot` runs populate `manifest.json` `parentDigest` from that row. + +## Execution scope + +`loopwright evolve` CLI commands (`run` and `resume`) currently drive `Taskpack` manifests with the Pi adapter. Consumers running Managed Controller `exec` roles and `command.v1` checks under `direct` compose `loopwright run` with `@loopwright/evolution` library APIs directly, while reusing `evolve export --snapshot`, `evolve check --bundle`, and `evolve import` for cross-host state transfer. + +--- + +**See also** — [Evolution Campaign](evolution-campaign.md) (`EvolutionCampaign` schema and `evolution-bundle.v1`) · [CLI](../operations/cli.md#evolution-campaigns) (`evolve` subcommands and exit codes) · [Managed Controller in Isolated Host](../walkthroughs/managed-controller-in-isolated-host.md) (unattended `command.v1` and `exec` host runs) + +**Next** → [Evolutionary Campaign](../walkthroughs/evolutionary-campaign.md) — run an evolutionary campaign end to end and export verified bundles. diff --git a/docs/contribute/internals.md b/docs/contribute/internals.md index 95fd493f..24aa0b42 100644 --- a/docs/contribute/internals.md +++ b/docs/contribute/internals.md @@ -18,7 +18,7 @@ Core owns contracts, canonical digests, and verified CAS descriptor acceptance; The runner owns offline parity, memory owns reviewed compaction, decisions provide bounded advice, `@loopwright/taskpack` owns declarative taskpacks and OS sandboxes, `@loopwright/github-app` owns GitHub intake and PR publication, `@loopwright/hardware-runner` owns the outbound pull-lease benchmark relay and two-stage evaluator, and CLI exposes local operations. Preserve unknown outcomes and do not promote fixture evidence into deployed acceptance. -`@loopwright/evolution` isolates campaign archives (`islands`, `team_configs`, `individuals`, `lineage_edges`, CAS `scratchpad_snapshots`) inside `/campaign.sqlite` (`journal_mode = DELETE`, `synchronous = FULL`, single-writer coordinator queue). It keeps `@loopwright/state` DDL (`format_version = 1`) and `controller/progress.ts` (`D <= 256`) unchanged. +`@loopwright/evolution` isolates campaign archives (`islands`, `team_configs`, `individuals`, `lineage_edges`, `model_bandit_arms`, CAS `scratchpad_snapshots`, `snapshot_provenance`) inside `/campaign.sqlite` (`journal_mode = DELETE`, `synchronous = FULL`, single-writer coordinator queue). It keeps `@loopwright/state` DDL (`format_version = 1`) and `controller/progress.ts` (`D <= 256`) unchanged. Each candidate executes inside an isolated child `LocalRunStore`. Plateau-triggered `team-patch.v1` synthesis stays bounded by host archetype envelopes (`tools <= archetype.tools`, `StepHandoffSelector` relays, `trialGenerations` rollback) and exports verified `evolution-bundle.v1` packages. @@ -32,7 +32,7 @@ This bypasses `.gitattributes` filters and preserves Git blob bytes. ## Architecture decisions -The public site contains 15 pages; [Development](../development.md) and this guide remain repository-only. Run `npm run lint:docs`, `node scripts/check-docs.mjs --report`, and `npm run site` after documentation changes. +The public site contains 17 pages; [Development](../development.md) and this guide remain repository-only. Run `npm run lint:docs`, `node scripts/check-docs.mjs --report`, and `npm run site` after documentation changes. YAML-first configuration uses `yaml` with the strict 1.2 core schema. Repository issue and PR templates live under `.github/`; the six `.agents/skills/loopwright-*` guides cover overview, docs, step driving, code review, issue and PR preparation, and releases. diff --git a/docs/operations/cli.md b/docs/operations/cli.md index 15b69184..0b0daa8e 100644 --- a/docs/operations/cli.md +++ b/docs/operations/cli.md @@ -133,9 +133,14 @@ loopwright evolve status --campaign ../campaign-state --json loopwright evolve inspect --campaign ../campaign-state --island 0 --json loopwright evolve resume --campaign ../campaign-state --repo . --json loopwright evolve export --campaign ../campaign-state --out ../bundle --format oci-layout --json +loopwright evolve export --campaign ../campaign-state --snapshot --out ../snapshot --receipt-secret-env RECEIPT_HMAC --json +loopwright evolve check --bundle ../snapshot --receipt-secret-env RECEIPT_HMAC --json +loopwright evolve import --bundle ../snapshot --state ../fresh-state --receipt-secret-env RECEIPT_HMAC --json ``` -Keep `--state` strictly outside `--repo` (`EVOLUTION_SCHEMA_INVALID`, exit `2` otherwise). `evolve export` verifies every HMAC verdict receipt fail-closed (`EXPORT_UNVERIFIED_FORBIDDEN`, exit `3`) and refuses `synthetic_fixture` receipts without `--allow-synthetic-probe`. +Keep `--state` strictly outside `--repo` (`EVOLUTION_SCHEMA_INVALID`, exit `2` otherwise). Bundle and snapshot commands verify signed HMAC receipts fail-closed (`EXPORT_UNVERIFIED_FORBIDDEN`, exit `3`), refusing `synthetic_fixture` without `--allow-synthetic-probe` and `host_attested` without `--allow-host-attested`. + +`evolve export --snapshot`, `evolve check --bundle`, and `evolve import` treat `--receipt-secret-env NAME` as optional when no individual carries a signed receipt and fail closed when any receipt exists or `NAME` is unset. See [Campaign Snapshots](../configuration/campaign-snapshots.md). | Environment variable | Purpose | | --- | --- | diff --git a/packages/cli/src/arguments.ts b/packages/cli/src/arguments.ts index 6035ab6d..f95b3966 100644 --- a/packages/cli/src/arguments.ts +++ b/packages/cli/src/arguments.ts @@ -5,7 +5,7 @@ export type StepAction = 'next' | 'submit' | 'cancel'; export type DigestAction = 'sync'; export type SuiteAction = 'check' | 'resolve'; export type RunnerAction = 'relay' | 'worker'; -export type EvolveAction = 'check' | 'run' | 'resume' | 'status' | 'inspect' | 'export'; +export type EvolveAction = 'check' | 'run' | 'resume' | 'status' | 'inspect' | 'export' | 'import'; export interface Arguments { readonly command: 'init' | 'check' | 'run' | 'resume' | 'reconcile' | 'status' | 'inspect' | 'closure' | 'app-serve' | 'step' | 'digest' | 'suite' | 'runner' | 'evolve'; readonly stepAction?: StepAction; @@ -67,9 +67,9 @@ const runnerRules: Record = { }; const evolveRules: Record = { check: { - required: ['campaign'], - values: ['campaign', 'repo'], - flags: ['json'], + required: [], + values: ['campaign', 'repo', 'bundle', 'receipt-secret-env'], + flags: ['allow-synthetic-probe', 'allow-host-attested', 'json'], }, run: { required: ['campaign'], @@ -93,8 +93,13 @@ const evolveRules: Record = { }, export: { required: ['out'], - values: ['campaign', 'campaign-dir', 'root', 'out', 'format'], - flags: ['allow-synthetic-probe', 'overwrite', 'json'], + values: ['campaign', 'campaign-dir', 'root', 'out', 'format', 'receipt-secret-env'], + flags: ['snapshot', 'allow-synthetic-probe', 'allow-host-attested', 'overwrite', 'json'], + }, + import: { + required: ['bundle', 'state'], + values: ['bundle', 'state', 'receipt-secret-env'], + flags: ['allow-synthetic-probe', 'allow-host-attested', 'json'], }, }; export const EVOLVE_ACTIONS: readonly EvolveAction[] = Object.freeze(Object.keys(evolveRules) as EvolveAction[]); @@ -321,17 +326,32 @@ export function parseArguments(argv: readonly string[]): Arguments { for (const val of values.values()) { if (val.trim().length === 0) throw new UsageError(); } - if (rawAction === 'run') { + if (rawAction === 'check') { + const hasCampaign = values.has('campaign'); + const hasBundle = values.has('bundle'); + if (hasCampaign === hasBundle) throw new UsageError(); + if (hasBundle && values.has('repo')) throw new UsageError(); + if ( + hasCampaign + && (values.has('receipt-secret-env') || flags.has('allow-synthetic-probe') || flags.has('allow-host-attested')) + ) { + throw new UsageError(); + } + } else if (rawAction === 'run') { const stateAliases = ['state', 'campaign-dir', 'root'].filter(k => values.has(k)); if (stateAliases.length !== 1) throw new UsageError(); } else if (rawAction === 'resume' || rawAction === 'status' || rawAction === 'inspect' || rawAction === 'export') { const dirAliases = ['campaign', 'campaign-dir', 'root'].filter(k => values.has(k)); if (dirAliases.length !== 1) throw new UsageError(); + if (rawAction === 'export' && flags.has('snapshot') && values.has('format')) throw new UsageError(); } if (values.has('format')) { const fmt = values.get('format')!; if (fmt !== 'dir' && fmt !== 'oci-layout') throw new UsageError(); } + if (values.has('receipt-secret-env')) { + if (!/^[A-Za-z_][A-Za-z0-9_]{0,127}$/.test(values.get('receipt-secret-env')!)) throw new UsageError(); + } if (values.has('island')) { if (!/^(?:0|[1-9][0-9]{0,5})$/.test(values.get('island')!)) throw new UsageError(); } diff --git a/packages/cli/src/main.ts b/packages/cli/src/main.ts index ba512340..b5aee8d2 100644 --- a/packages/cli/src/main.ts +++ b/packages/cli/src/main.ts @@ -22,9 +22,9 @@ function resolveCliVersion(): string { return '0.0.0'; } const CLI_VERSION = resolveCliVersion(); -const HELP = `loopwright ${CLI_VERSION}\ninit --directory DIR [--force] [--json]\ncheck --config FILE --registry FILE --registry-sha256 HEX [--role-model ROLE=PROVIDER/MODEL[:THINKING]] [--json] [--output FILE]\nrun --dry-run --config FILE --registry FILE --registry-sha256 HEX [--role-model ROLE=PROVIDER/MODEL[:THINKING]] [--json] [--output FILE]\nrun --config FILE --registry FILE --registry-sha256 HEX --repo DIR --run-root DIR --run-id ID [--role-model ROLE=PROVIDER/MODEL[:THINKING]] [--allow-privileged] [--allow-workflow-writes] [--json] [--output-format FORMATS] [--step-summary-file FILE]\nrun --dry-run --taskpack FILE --repo DIR [--mode candidate|no-change|auto] [--baseline-alignment off|fail-fast|extract-context] [--source-revision REV] [--role-model ROLE=PROVIDER/MODEL[:THINKING]] [--allow-privileged] [--allow-workflow-writes] [--allow-host-mounts PATHS] [--json] [--output FILE]\nrun --taskpack FILE --repo DIR --run-root DIR --run-id ID [--mode candidate|no-change|auto] [--baseline-alignment off|fail-fast|extract-context] [--source-revision REV] [--role-model ROLE=PROVIDER/MODEL[:THINKING]] [--allow-privileged] [--allow-workflow-writes] [--allow-host-mounts PATHS] [--json] [--output-format FORMATS] [--step-summary-file FILE]\nresume --run-root DIR --run-id ID --config FILE --registry FILE --registry-sha256 HEX --repo DIR [--role-model ROLE=PROVIDER/MODEL[:THINKING]] [--allow-privileged] [--allow-workflow-writes] [--json] [--output-format FORMATS] [--step-summary-file FILE]\nstep next --run-root DIR --run-id ID (--taskpack FILE --repo DIR | --config FILE --registry FILE --registry-sha256 HEX --repo DIR | [--repo DIR]) [--role-model ROLE=PROVIDER/MODEL[:THINKING]] [--mode candidate|no-change] [--baseline-alignment off|fail-fast|extract-context] [--source-revision REV] [--reissue-lease] [--allow-privileged] [--allow-workflow-writes] [--allow-host-mounts PATHS] [--json] [--output-format FORMATS] [--step-summary-file FILE]\nstep submit --run-root DIR --run-id ID --lease TOKEN [--submission-file FILE] [--status completed|no_change|failed|blocked] [--reason TEXT] [--allow-privileged] [--allow-workflow-writes] [--allow-host-mounts PATHS] [--json] [--output-format FORMATS] [--step-summary-file FILE]\nstep cancel --run-root DIR --run-id ID [--json] [--output-format FORMATS] [--step-summary-file FILE]\ndigest sync --taskpack FILE [--repo DIR] [--check] [--json]\nsuite check --suite FILE [--repo DIR] [--verify-digests] [--json]\nsuite resolve --suite FILE [--repo DIR] [--event NAME] [--schedule KEY] [--comment-body TEXT] [--pr-head-ref REF] [--pr-base-ref REF] [--domain ID] [--json]\nreconcile --config FILE --registry FILE --registry-sha256 HEX --repo DIR --run-root DIR --run-id ID --receipt FILE [--allow-workflow-writes] [--json] [--output FILE] [--output-format FORMATS] [--step-summary-file FILE]\nstatus --run-root DIR --run-id ID [--json]\ninspect --run-root DIR --run-id ID [--json] [--output DIR]\nclosure [--repo DIR] [--output FILE] [--json] [--verify-failures]\napp-serve --config FILE [--repo DIR] [--json]\nrunner relay --config FILE [--json]\nrunner worker --config FILE [--once] [--json]\nevolve check --campaign FILE [--repo DIR] [--json]\nevolve run --campaign FILE --state DIR [--repo DIR] [--out DIR] [--format dir|oci-layout] [--allow-synthetic-probe] [--json]\nevolve resume --campaign DIR [--repo DIR] [--out DIR] [--format dir|oci-layout] [--allow-synthetic-probe] [--json]\nevolve status --campaign DIR [--json]\nevolve inspect --campaign DIR [--island ID] [--individual ID] [--json]\nevolve export --campaign DIR --out DIR [--format dir|oci-layout] [--allow-synthetic-probe] [--overwrite] [--json]\nConfig and registry files accept YAML (.yaml, .yml) or JSON (.json); init writes controller.draft.yaml and registry.draft.yaml.\nStatic plans do not establish execution readiness. Strict proven_bound is the default.\nJSON verification requires both complete manifests and framing to fit the 16384-byte header; selected file <=1032184 bytes.\n`; +const HELP = `loopwright ${CLI_VERSION}\ninit --directory DIR [--force] [--json]\ncheck --config FILE --registry FILE --registry-sha256 HEX [--role-model ROLE=PROVIDER/MODEL[:THINKING]] [--json] [--output FILE]\nrun --dry-run --config FILE --registry FILE --registry-sha256 HEX [--role-model ROLE=PROVIDER/MODEL[:THINKING]] [--json] [--output FILE]\nrun --config FILE --registry FILE --registry-sha256 HEX --repo DIR --run-root DIR --run-id ID [--role-model ROLE=PROVIDER/MODEL[:THINKING]] [--allow-privileged] [--allow-workflow-writes] [--json] [--output-format FORMATS] [--step-summary-file FILE]\nrun --dry-run --taskpack FILE --repo DIR [--mode candidate|no-change|auto] [--baseline-alignment off|fail-fast|extract-context] [--source-revision REV] [--role-model ROLE=PROVIDER/MODEL[:THINKING]] [--allow-privileged] [--allow-workflow-writes] [--allow-host-mounts PATHS] [--json] [--output FILE]\nrun --taskpack FILE --repo DIR --run-root DIR --run-id ID [--mode candidate|no-change|auto] [--baseline-alignment off|fail-fast|extract-context] [--source-revision REV] [--role-model ROLE=PROVIDER/MODEL[:THINKING]] [--allow-privileged] [--allow-workflow-writes] [--allow-host-mounts PATHS] [--json] [--output-format FORMATS] [--step-summary-file FILE]\nresume --run-root DIR --run-id ID --config FILE --registry FILE --registry-sha256 HEX --repo DIR [--role-model ROLE=PROVIDER/MODEL[:THINKING]] [--allow-privileged] [--allow-workflow-writes] [--json] [--output-format FORMATS] [--step-summary-file FILE]\nstep next --run-root DIR --run-id ID (--taskpack FILE --repo DIR | --config FILE --registry FILE --registry-sha256 HEX --repo DIR | [--repo DIR]) [--role-model ROLE=PROVIDER/MODEL[:THINKING]] [--mode candidate|no-change] [--baseline-alignment off|fail-fast|extract-context] [--source-revision REV] [--reissue-lease] [--allow-privileged] [--allow-workflow-writes] [--allow-host-mounts PATHS] [--json] [--output-format FORMATS] [--step-summary-file FILE]\nstep submit --run-root DIR --run-id ID --lease TOKEN [--submission-file FILE] [--status completed|no_change|failed|blocked] [--reason TEXT] [--allow-privileged] [--allow-workflow-writes] [--allow-host-mounts PATHS] [--json] [--output-format FORMATS] [--step-summary-file FILE]\nstep cancel --run-root DIR --run-id ID [--json] [--output-format FORMATS] [--step-summary-file FILE]\ndigest sync --taskpack FILE [--repo DIR] [--check] [--json]\nsuite check --suite FILE [--repo DIR] [--verify-digests] [--json]\nsuite resolve --suite FILE [--repo DIR] [--event NAME] [--schedule KEY] [--comment-body TEXT] [--pr-head-ref REF] [--pr-base-ref REF] [--domain ID] [--json]\nreconcile --config FILE --registry FILE --registry-sha256 HEX --repo DIR --run-root DIR --run-id ID --receipt FILE [--allow-workflow-writes] [--json] [--output FILE] [--output-format FORMATS] [--step-summary-file FILE]\nstatus --run-root DIR --run-id ID [--json]\ninspect --run-root DIR --run-id ID [--json] [--output DIR]\nclosure [--repo DIR] [--output FILE] [--json] [--verify-failures]\napp-serve --config FILE [--repo DIR] [--json]\nrunner relay --config FILE [--json]\nrunner worker --config FILE [--once] [--json]\nevolve check --campaign FILE [--repo DIR] [--json]\nevolve check --bundle DIR [--receipt-secret-env NAME] [--allow-synthetic-probe] [--allow-host-attested] [--json]\nevolve run --campaign FILE --state DIR [--repo DIR] [--out DIR] [--format dir|oci-layout] [--allow-synthetic-probe] [--json]\nevolve resume --campaign DIR [--repo DIR] [--out DIR] [--format dir|oci-layout] [--allow-synthetic-probe] [--json]\nevolve status --campaign DIR [--json]\nevolve inspect --campaign DIR [--island ID] [--individual ID] [--json]\nevolve export --campaign DIR --out DIR [--format dir|oci-layout] [--receipt-secret-env NAME] [--allow-synthetic-probe] [--allow-host-attested] [--overwrite] [--json]\nevolve export --campaign DIR --snapshot --out DIR [--receipt-secret-env NAME] [--allow-synthetic-probe] [--allow-host-attested] [--overwrite] [--json]\nevolve import --bundle DIR --state DIR [--receipt-secret-env NAME] [--allow-synthetic-probe] [--allow-host-attested] [--json]\nConfig and registry files accept YAML (.yaml, .yml) or JSON (.json); init writes controller.draft.yaml and registry.draft.yaml.\nStatic plans do not establish execution readiness. Strict proven_bound is the default.\nJSON verification requires both complete manifests and framing to fit the 16384-byte header; selected file <=1032184 bytes.\n`; const RUNNER_HELP = `loopwright ${CLI_VERSION} runner\nrunner relay --config FILE [--json]\nrunner worker --config FILE [--once] [--json]\n`; -const EVOLVE_HELP = `loopwright ${CLI_VERSION} evolve\nevolve check --campaign FILE [--repo DIR] [--json]\nevolve run --campaign FILE --state DIR [--repo DIR] [--out DIR] [--format dir|oci-layout] [--allow-synthetic-probe] [--json]\nevolve resume --campaign DIR [--repo DIR] [--out DIR] [--format dir|oci-layout] [--allow-synthetic-probe] [--json]\nevolve status --campaign DIR [--json]\nevolve inspect --campaign DIR [--island ID] [--individual ID] [--json]\nevolve export --campaign DIR --out DIR [--format dir|oci-layout] [--allow-synthetic-probe] [--overwrite] [--json]\n`; +const EVOLVE_HELP = `loopwright ${CLI_VERSION} evolve\nevolve check --campaign FILE [--repo DIR] [--json]\nevolve check --bundle DIR [--receipt-secret-env NAME] [--allow-synthetic-probe] [--allow-host-attested] [--json]\nevolve run --campaign FILE --state DIR [--repo DIR] [--out DIR] [--format dir|oci-layout] [--allow-synthetic-probe] [--json]\nevolve resume --campaign DIR [--repo DIR] [--out DIR] [--format dir|oci-layout] [--allow-synthetic-probe] [--json]\nevolve status --campaign DIR [--json]\nevolve inspect --campaign DIR [--island ID] [--individual ID] [--json]\nevolve export --campaign DIR --out DIR [--format dir|oci-layout] [--receipt-secret-env NAME] [--allow-synthetic-probe] [--allow-host-attested] [--overwrite] [--json]\nevolve export --campaign DIR --snapshot --out DIR [--receipt-secret-env NAME] [--allow-synthetic-probe] [--allow-host-attested] [--overwrite] [--json]\nevolve import --bundle DIR --state DIR [--receipt-secret-env NAME] [--allow-synthetic-probe] [--allow-host-attested] [--json]\n`; export interface Envelope { readonly version: 1; readonly kind: 'plan' | 'event' | 'status' | 'inspection' | 'result' | 'diagnostic' | 'incident' | 'closure' | 'step' | 'digest' | 'suite'; readonly sequence: number; readonly runId: string | null; readonly data: unknown } export function encoded(value: unknown): string { return JSON.stringify(value).replace(/[\u007f-\u009f\u2028\u2029<>&]/g, char => '\\u' + char.charCodeAt(0).toString(16).padStart(4, '0')).replace(/::/g, '\\u003a\\u003a'); @@ -1863,18 +1863,27 @@ function scrubJsonPayload(value: unknown, scrubber: SecretScrubber, depth = 0): async function runEvolveCommand(args: Arguments, emit: EmitFn): Promise { const get = (key: string) => args.values.get(key)!; + const receiptSecretEnvName = args.values.get('receipt-secret-env'); const extraSecretKeys = [ 'LOOPWRIGHT_GATE_SIGNING_SECRET', 'BENCH_SIGNING_SECRET', 'LOOPWRIGHT_GATE_AUTH_TOKEN', 'LOCAL_OAI_KEY', + ...(receiptSecretEnvName !== undefined ? [receiptSecretEnvName] : []), ...Object.values(STANDARD_PI_PROVIDER_ENV), ]; const scrubber = createCliScrubber(extraSecretKeys); const coreScrubber = new CoreSecretScrubber(); for (const key of [...BASE_CLI_SECRET_ENV_KEYS, ...extraSecretKeys]) { - const value = process.env[key]; - if (typeof value === 'string' && value.length > 0) coreScrubber.register(value); + const value = Object.hasOwn(process.env, key) ? process.env[key] : undefined; + if (typeof value === 'string' && value.length > 0) { + coreScrubber.register(value); + const trimmed = value.trim(); + if (trimmed.length > 0 && trimmed !== value) { + scrubber.register(trimmed); + coreScrubber.register(trimmed); + } + } } const evolution = await import('@loopwright/evolution'); const resolveCampaignDir = (): string => resolve(args.values.get('campaign') ?? args.values.get('campaign-dir') ?? args.values.get('root')!); @@ -1890,10 +1899,68 @@ async function runEvolveCommand(args: Arguments, emit: EmitFn): Promise } return undefined; }; + const resolveExplicitReceiptSecret = (envName: string): string => { + const raw = Object.hasOwn(process.env, envName) ? process.env[envName] : undefined; + if (typeof raw === 'string' && raw.length > 0) { + scrubber.register(raw); + coreScrubber.register(raw); + } + const trimmed = typeof raw === 'string' ? raw.trim() : ''; + if (trimmed.length === 0) { + throw new evolution.EvolutionError( + 'EXPORT_UNVERIFIED_FORBIDDEN', + `environment variable "${envName}" specified by --receipt-secret-env is unset or empty`, + '/receiptSigningSecret', + ); + } + if (trimmed !== raw) { + scrubber.register(trimmed); + coreScrubber.register(trimmed); + } + return trimmed; + }; try { const action = args.evolveAction!; if (action === 'check') { + if (args.values.has('bundle')) { + const bundleDir = resolve(get('bundle')); + const allowSyntheticProbe = args.flags.has('allow-synthetic-probe'); + const allowHostAttested = args.flags.has('allow-host-attested'); + const receiptSigningSecret = receiptSecretEnvName !== undefined + ? resolveExplicitReceiptSecret(receiptSecretEnvName) + : undefined; + const verified = await evolution.verifyCampaignSnapshot({ + bundleDir, + allowSyntheticProbe, + allowHostAttested, + ...(receiptSigningSecret !== undefined ? { receiptSigningSecret } : {}), + scrubber: coreScrubber, + }); + const payload = { + version: 1, + action: 'check', + valid: true, + bundleDir: verified.bundleDir, + campaignId: verified.manifest.campaignId, + generations: verified.manifest.generations, + ...(verified.manifest.parentDigest !== undefined ? { parentDigest: verified.manifest.parentDigest } : {}), + manifestDigest: verified.manifestDigest, + individualCount: verified.individualCount, + receiptCount: verified.receiptCount, + blobCount: verified.blobCount, + manifest: verified.manifest, + }; + await emit( + 'plan', + scrubJsonPayload(payload, scrubber), + scrubber.scrub( + `evolve check --bundle: ok (${verified.manifest.campaignId}, individuals=${verified.individualCount}, receipts=${verified.receiptCount}, blobs=${verified.blobCount})`, + ), + ); + return 0; + } + const checked = await evolution.checkEvolutionCampaign({ manifestPath: resolve(get('campaign')), ...(args.values.has('repo') ? { repositoryRoot: resolve(get('repo')) } : {}), @@ -2005,10 +2072,14 @@ async function runEvolveCommand(args: Arguments, emit: EmitFn): Promise if (action === 'export') { const campaignRoot = resolveCampaignDir(); const outputDir = resolve(get('out')); + const snapshotMode = args.flags.has('snapshot'); const format = args.values.get('format') as 'dir' | 'oci-layout' | undefined; const allowSyntheticProbe = args.flags.has('allow-synthetic-probe'); + const allowHostAttested = args.flags.has('allow-host-attested'); const overwrite = args.flags.has('overwrite'); - const receiptSigningSecret = resolveSigningSecret(); + const receiptSigningSecret = receiptSecretEnvName !== undefined + ? resolveExplicitReceiptSecret(receiptSecretEnvName) + : (snapshotMode ? undefined : resolveSigningSecret()); const store = await evolution.EvolutionCampaignStore.open({ campaignRoot, @@ -2026,12 +2097,33 @@ async function runEvolveCommand(args: Arguments, emit: EmitFn): Promise if (target === undefined) { throw new evolution.EvolutionError('EVOLUTION_NOT_FOUND', 'no campaigns found in campaign.sqlite'); } + if (snapshotMode) { + const exported = await evolution.writeCampaignSnapshot({ + store, + campaignId: target.campaignId, + outDir: outputDir, + allowSyntheticProbe, + allowHostAttested, + overwrite, + ...(receiptSigningSecret !== undefined ? { receiptSigningSecret } : {}), + scrubber: coreScrubber, + }); + await emit( + 'result', + scrubJsonPayload(exported, scrubber), + scrubber.scrub( + `evolve export --snapshot: ok (${target.campaignId}, individuals=${exported.individualCount}, receipts=${exported.receiptCount}, blobs=${exported.blobCount})`, + ), + ); + return 0; + } const exported = await evolution.exportEvolutionBundle({ store, campaignId: target.campaignId, outputDir, ...(format !== undefined ? { format } : {}), allowSyntheticProbe, + allowHostAttested, overwrite, ...(receiptSigningSecret !== undefined ? { receiptSigningSecret } : {}), scrubber: coreScrubber, @@ -2047,6 +2139,32 @@ async function runEvolveCommand(args: Arguments, emit: EmitFn): Promise } } + if (action === 'import') { + const bundleDir = resolve(get('bundle')); + const stateDir = resolve(get('state')); + const allowSyntheticProbe = args.flags.has('allow-synthetic-probe'); + const allowHostAttested = args.flags.has('allow-host-attested'); + const receiptSigningSecret = receiptSecretEnvName !== undefined + ? resolveExplicitReceiptSecret(receiptSecretEnvName) + : undefined; + const imported = await evolution.importCampaignSnapshot({ + bundleDir, + stateDir, + allowSyntheticProbe, + allowHostAttested, + ...(receiptSigningSecret !== undefined ? { receiptSigningSecret } : {}), + scrubber: coreScrubber, + }); + await emit( + 'result', + scrubJsonPayload(imported, scrubber), + scrubber.scrub( + `evolve import: ok (${imported.campaignId}, individuals=${imported.individualCount}, receipts=${imported.receiptCount}, blobs=${imported.blobCount})`, + ), + ); + return 0; + } + const { createCliEvolutionEvaluator, createCliEvolutionSupervisorRunner } = await import('./evolve.js'); const repositoryRoot = resolve(args.values.has('repo') ? get('repo') : process.cwd()); const allowSyntheticProbe = args.flags.has('allow-synthetic-probe'); diff --git a/packages/cli/test/check-docs-rules.test.ts b/packages/cli/test/check-docs-rules.test.ts index 49b41885..b19064a4 100644 --- a/packages/cli/test/check-docs-rules.test.ts +++ b/packages/cli/test/check-docs-rules.test.ts @@ -67,6 +67,7 @@ const PUBLIC_PAGES: readonly PageSpec[] = [ { relPath: 'configuration/sandbox-backends.md', title: 'Sandbox Backends' }, { relPath: 'configuration/decision-routing.md', title: 'Decision Routing' }, { relPath: 'configuration/evolution-campaign.md', title: 'Evolution Campaign' }, + { relPath: 'configuration/campaign-snapshots.md', title: 'Campaign Snapshots' }, ]; const REFERENCE_PAGES: readonly PageSpec[] = [ @@ -331,6 +332,7 @@ function buildMinimalRepoFixture(): string { ' - /docs/configuration/sandbox-backends/', ' - /docs/configuration/decision-routing/', ' - /docs/configuration/evolution-campaign/', + ' - /docs/configuration/campaign-snapshots/', 'labels:', ' /docs/getting-started/architecture/: Architecture', ' /docs/getting-started/installation/: Installation', @@ -348,6 +350,7 @@ function buildMinimalRepoFixture(): string { ' /docs/configuration/sandbox-backends/: Sandbox Backends', ' /docs/configuration/decision-routing/: Decision Routing', ' /docs/configuration/evolution-campaign/: Evolution Campaign', + ' /docs/configuration/campaign-snapshots/: Campaign Snapshots', '', ].join('\n') ); diff --git a/packages/cli/test/docs-and-site.test.ts b/packages/cli/test/docs-and-site.test.ts index c037149b..20244dcc 100644 --- a/packages/cli/test/docs-and-site.test.ts +++ b/packages/cli/test/docs-and-site.test.ts @@ -433,7 +433,7 @@ test('documentation verification: check-docs.mjs passes with zero errors', () => assert.match(run.stdout, /0 error\(s\)/, 'check-docs.mjs must report 0 error(s)'); }); -test('hugo site: site.mjs build builds 16-page site, exports three-zone llms.txt + 6 flat references, and verifies zero excluded-zone leaks in sitemap.xml and index.json', () => { +test('hugo site: site.mjs build builds 17-page site, exports three-zone llms.txt + 6 flat references, and verifies zero excluded-zone leaks in sitemap.xml and index.json', () => { const siteScript = join(REPO_ROOT, 'scripts', 'site.mjs'); assert.ok(existsSync(siteScript), 'scripts/site.mjs must exist'); @@ -462,7 +462,7 @@ test('hugo site: site.mjs build builds 16-page site, exports three-zone llms.txt }); assert.equal(build.status, 0, `site.mjs build failed:\nstdout: ${build.stdout}\nstderr: ${build.stderr}`); - assert.match(build.stdout, /Verified \d+ HTML pages and 16 Markdown exports; 0 broken link\(s\)/); + assert.match(build.stdout, /Verified \d+ HTML pages and 17 Markdown exports; 0 broken link\(s\)/); const publicDir = join(REPO_ROOT, 'site', 'public'); assert.ok(existsSync(join(publicDir, 'llms.txt')), 'llms.txt must exist'); @@ -470,10 +470,10 @@ test('hugo site: site.mjs build builds 16-page site, exports three-zone llms.txt assert.ok(existsSync(join(publicDir, 'index.json')), 'index.json must exist'); assert.ok(existsSync(join(publicDir, 'sitemap.xml')), 'sitemap.xml must exist'); - // Verify llms.txt content across all 3 zones (Public 16 + Reference 6 + Optional 14 [README + 13 Contribute]) + // Verify llms.txt content across all 3 zones (Public 17 + Reference 6 + Optional 14 [README + 13 Contribute]) const llms = readFileSync(join(publicDir, 'llms.txt'), 'utf8'); const llmsPublicMatches = llms.match(/^-\s+\[[^\]]+\]\((?:https?:\/\/[^/]+)?\/docs\/[^)]+\):/gm); - assert.equal(llmsPublicMatches?.length, 16, 'llms.txt must list exactly 16 public docs pages'); + assert.equal(llmsPublicMatches?.length, 17, 'llms.txt must list exactly 17 public docs pages'); assert.match(llms, /\/docs\/walkthroughs\/evolutionary-campaign\/index\.md\)/, 'llms.txt must link to singular evolutionary-campaign'); const expectedRefFiles = [ @@ -521,7 +521,7 @@ test('hugo site: site.mjs build builds 16-page site, exports three-zone llms.txt // Verify index.json content and 0 excluded-zone leaks const index = JSON.parse(readFileSync(join(publicDir, 'index.json'), 'utf8')) as Array<{ url?: string }>; - assert.ok(Array.isArray(index) && index.length >= 16, 'index.json must contain at least 16 pages'); + assert.ok(Array.isArray(index) && index.length >= 17, 'index.json must contain at least 17 pages'); for (const entry of index) { const u = String(entry.url ?? ''); assert.ok( @@ -540,7 +540,7 @@ test('hugo site: site.mjs build builds 16-page site, exports three-zone llms.txt ); } - // Verify 16 markdown and html exports exist under docs/// + // Verify 17 markdown and html exports exist under docs/// const canonicalPages = [ 'getting-started/architecture', 'getting-started/installation', @@ -557,7 +557,8 @@ test('hugo site: site.mjs build builds 16-page site, exports three-zone llms.txt 'configuration/controller-and-registry', 'configuration/sandbox-backends', 'configuration/decision-routing', - 'configuration/evolution-campaign' + 'configuration/evolution-campaign', + 'configuration/campaign-snapshots' ]; for (const p of canonicalPages) { @@ -587,7 +588,7 @@ test('hugo site: site.mjs build builds 16-page site, exports three-zone llms.txt env: { ...process.env, SITE_BASE_URL: 'https://docs.gpustack.ai/loopwright/latest/' } }); assert.equal(subpathBuild.status, 0, `subpath site.mjs build failed:\nstdout: ${subpathBuild.stdout}\nstderr: ${subpathBuild.stderr}`); - assert.match(subpathBuild.stdout, /Verified \d+ HTML pages and 16 Markdown exports; 0 broken link\(s\)/); + assert.match(subpathBuild.stdout, /Verified \d+ HTML pages and 17 Markdown exports; 0 broken link\(s\)/); const subpathLlms = readFileSync(join(publicDir, 'llms.txt'), 'utf8'); assert.match( subpathLlms, diff --git a/packages/cli/test/evolve-snapshot.test.ts b/packages/cli/test/evolve-snapshot.test.ts new file mode 100644 index 00000000..8dc3b14d --- /dev/null +++ b/packages/cli/test/evolve-snapshot.test.ts @@ -0,0 +1,1364 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { execFileSync, spawnSync } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { createServer } from 'node:http'; +import { chmod, cp, mkdir, mkdtemp, readdir, readFile, realpath, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { DatabaseSync } from 'node:sqlite'; +import { fileURLToPath } from 'node:url'; +import { + SecretScrubber, + type Digest, + type HardwareDiagnostics, + type HardwareProvenance, +} from '@loopwright/core'; +import { + CAMPAIGN_SQLITE_FILENAME, + DEFAULT_CAMPAIGN_CLOCK, + EvolutionCampaignStore, + parseEvolutionCampaignDocument, + runEvolutionCampaign, + writeCampaignSnapshot, + type CampaignClockSource, +} from '@loopwright/evolution'; +import { + runHardwareWorker, + signBenchmarkVerdict, + startRelayServer, + type BenchmarkOutputArtifact, + type BenchmarkVerdict, + type SignedBenchmarkVerdictReceipt, + type WorkerConfig, +} from '@loopwright/hardware-runner'; +import { SecretScrubber as TaskpackSecretScrubber } from '@loopwright/taskpack'; +import { parseArguments, UsageError } from '../src/arguments.js'; +import { createCliEvolutionEvaluator } from '../src/evolve.js'; +import { main as cliMain } from '../src/main.js'; + +const MAIN = fileURLToPath(new URL('../src/main.js', import.meta.url)); +const TEST_RECEIPT_SECRET = 'snapshot-cli-receipt-hmac-secret-9f8e7d6c5b4a3210'; +const WRONG_RECEIPT_SECRET = 'wrong-snapshot-cli-hmac-secret-0000000000000000'; +const WORKER_BEARER_TOKEN = 'snapshot-cli-worker-token-0123456789abcdef'; +const LOCAL_OAI_KEY = 'sk-snapshot-cli-test-key-0123456789abcdef'; + +function sha256Hex(data: Uint8Array | string): string { + return createHash('sha256').update(data).digest('hex'); +} + +function makeDigest(seed: string): Digest { + return { algorithm: 'sha256', hex: sha256Hex(seed) }; +} + +function makeSteppingClock(monoMs: number, wallMs: number): CampaignClockSource { + let mono = monoMs; + let wall = wallMs; + return { + nowMonotonicMs: (): number => ++mono, + nowWallMs: (): number => ++wall, + }; +} + +function buildElf64Cubin(symbols: readonly string[]): Buffer { + const parts: Buffer[] = [Buffer.from([0])]; + const offsets: number[] = []; + let cursor = 1; + for (const sym of symbols) { + offsets.push(cursor); + const b = Buffer.from(`${sym}\0`, 'utf8'); + parts.push(b); + cursor += b.byteLength; + } + const strTab = Buffer.concat(parts); + const symTab = Buffer.alloc((1 + offsets.length) * 24, 0); + for (let i = 0; i < offsets.length; i += 1) { + const off = (i + 1) * 24; + symTab.writeUInt32LE(offsets[i]!, off); + symTab.writeUInt8(0x12, off + 4); + symTab.writeUInt16LE(0, off + 6); + } + const shStrParts = [Buffer.from([0]), Buffer.from('.strtab\0'), Buffer.from('.symtab\0'), Buffer.from('.shstrtab\0')]; + const shStrOffsets = [1, 9, 17]; + const shStrTab = Buffer.concat(shStrParts); + + const sections = [ + { shType: 3, shLink: 0, shEntSize: 0, data: strTab }, + { shType: 2, shLink: 1, shEntSize: 24, data: symTab }, + { shType: 3, shLink: 0, shEntSize: 0, data: shStrTab }, + ]; + + const ehdr = Buffer.alloc(64, 0); + ehdr[0] = 0x7f; + ehdr[1] = 0x45; + ehdr[2] = 0x4c; + ehdr[3] = 0x46; + ehdr[4] = 2; + ehdr[5] = 1; + ehdr[6] = 1; + ehdr.writeUInt16LE(2, 16); + ehdr.writeUInt16LE(190, 18); + ehdr.writeUInt32LE(1, 20); + ehdr.writeUInt16LE(64, 52); + ehdr.writeUInt16LE(64, 58); + ehdr.writeUInt16LE(1 + sections.length, 60); + ehdr.writeUInt16LE(3, 62); + + const chunks: Buffer[] = [ehdr]; + const secOffsets: number[] = []; + let offset = 64; + for (const sec of sections) { + const pad = (8 - (offset % 8)) % 8; + if (pad > 0) { + chunks.push(Buffer.alloc(pad, 0)); + offset += pad; + } + secOffsets.push(offset); + chunks.push(sec.data); + offset += sec.data.byteLength; + } + const shPad = (8 - (offset % 8)) % 8; + if (shPad > 0) { + chunks.push(Buffer.alloc(shPad, 0)); + offset += shPad; + } + ehdr.writeBigUInt64LE(BigInt(offset), 40); + chunks.push(Buffer.alloc(64, 0)); + for (let i = 0; i < sections.length; i += 1) { + const sec = sections[i]!; + const shdr = Buffer.alloc(64, 0); + shdr.writeUInt32LE(shStrOffsets[i]!, 0); + shdr.writeUInt32LE(sec.shType, 4); + shdr.writeBigUInt64LE(BigInt(secOffsets[i]!), 24); + shdr.writeBigUInt64LE(BigInt(sec.data.byteLength), 32); + shdr.writeUInt32LE(sec.shLink, 40); + shdr.writeBigUInt64LE(1n, 48); + shdr.writeBigUInt64LE(BigInt(sec.shEntSize), 56); + chunks.push(shdr); + } + return Buffer.concat(chunks); +} + +async function initGitRepo( + repoDir: string, + files: Readonly>, +): Promise { + await mkdir(repoDir, { recursive: true, mode: 0o700 }); + for (const [relPath, entry] of Object.entries(files)) { + const absPath = join(repoDir, relPath); + await mkdir(join(absPath, '..'), { recursive: true, mode: 0o700 }); + await writeFile(absPath, entry.content, { mode: entry.executable ? 0o755 : 0o644 }); + if (entry.executable) await chmod(absPath, 0o755); + } + const gitEnv = { + PATH: '/usr/bin:/bin', + LANG: 'C', + LC_ALL: 'C', + HOME: '/nonexistent', + GIT_CONFIG_NOSYSTEM: '1', + GIT_CONFIG_GLOBAL: '/dev/null', + GIT_TERMINAL_PROMPT: '0', + GIT_AUTHOR_NAME: 'Loopwright Test', + GIT_AUTHOR_EMAIL: 'test@loopwright.dev', + GIT_COMMITTER_NAME: 'Loopwright Test', + GIT_COMMITTER_EMAIL: 'test@loopwright.dev', + }; + execFileSync('/usr/bin/git', ['-c', 'core.hooksPath=/dev/null', 'init', '-b', 'main'], { cwd: repoDir, env: gitEnv, stdio: 'ignore' }); + execFileSync('/usr/bin/git', ['-c', 'core.hooksPath=/dev/null', 'add', '.'], { cwd: repoDir, env: gitEnv, stdio: 'ignore' }); + execFileSync('/usr/bin/git', ['-c', 'core.hooksPath=/dev/null', 'commit', '-m', 'Initial baseline'], { cwd: repoDir, env: gitEnv, stdio: 'ignore' }); + return execFileSync('/usr/bin/git', ['-c', 'core.hooksPath=/dev/null', 'rev-parse', 'HEAD'], { cwd: repoDir, env: gitEnv, encoding: 'utf8' }).trim(); +} + +async function runCliInProcess( + argv: readonly string[], + envOverrides: Readonly> = {}, +): Promise<{ readonly status: number; readonly stdout: string; readonly stderr: string }> { + const prevEnv: Record = {}; + for (const [k, v] of Object.entries(envOverrides)) { + prevEnv[k] = process.env[k]; + if (v === undefined) delete process.env[k]; + else process.env[k] = v; + } + + let stdout = ''; + let stderr = ''; + const origStdoutWrite = process.stdout.write.bind(process.stdout); + const origStderrWrite = process.stderr.write.bind(process.stderr); + process.stdout.write = (( + chunk: string | Uint8Array, + encodingOrCb?: BufferEncoding | ((err?: Error | null) => void), + cb?: (err?: Error | null) => void, + ) => { + stdout += typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString('utf8'); + const callback = typeof encodingOrCb === 'function' ? encodingOrCb : cb; + if (callback) callback(null); + return true; + }) as typeof process.stdout.write; + process.stderr.write = (( + chunk: string | Uint8Array, + encodingOrCb?: BufferEncoding | ((err?: Error | null) => void), + cb?: (err?: Error | null) => void, + ) => { + stderr += typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString('utf8'); + const callback = typeof encodingOrCb === 'function' ? encodingOrCb : cb; + if (callback) callback(null); + return true; + }) as typeof process.stderr.write; + + try { + const status = await cliMain(argv); + return { status, stdout, stderr }; + } finally { + process.stdout.write = origStdoutWrite; + process.stderr.write = origStderrWrite; + for (const [k, v] of Object.entries(prevEnv)) { + if (v === undefined) delete process.env[k]; + else process.env[k] = v; + } + } +} + +async function collectFilesRecursive(rootDir: string): Promise { + const entries = await readdir(rootDir, { withFileTypes: true }); + const files: string[] = []; + for (const entry of entries) { + const abs = join(rootDir, entry.name); + if (entry.isDirectory()) { + files.push(...await collectFilesRecursive(abs)); + } else { + files.push(abs); + } + } + return files; +} + +const SINGLE_TARGET_CAMPAIGN_YAML = `apiVersion: loopwright.dev/v1alpha1 +kind: EvolutionCampaign +metadata: + name: snap-cli-campaign +spec: + taskpack: .loopwright/taskpack.yaml + targetCellId: cuda-h100-whole + stages: + mode: single-target + heldOutWorkloadId: decode-h100-holdout + population: + islands: 2 + migrationIntervalGenerations: 4 + maxMigrationElites: 1 + nicheAxes: + - id: bound_pipeline + kind: enum + values: [hbm, l2, smem_lds_ub, tensor_cube] + sampling: + noveltyDecayLambda: 1.0 + mutationWeights: + diff_tune: 0.5 + full_rewrite: 0.3 + crossover: 0.2 + maxCrossoversPerPrompt: 2 + objectives: + - metric: latency_us_p50 + direction: minimize + - metric: goodput_rps + direction: maximize + budgets: + maxGenerations: 10 + maxEvaluations: 40 + maxConcurrentEvaluations: 2 + scratchpadIntervalGenerations: 5 +`; + +const BASELINE_KERNEL_SOURCE = [ + '#include ', + 'static constexpr int LOCKED_ABI_VERSION = 1;', + '// EVOLVE-BLOCK-START: flash_decode', + 'int flash_decode_mode() {', + ' return 0; // baseline', + '}', + '// EVOLVE-BLOCK-END: flash_decode', + '', +].join('\n'); + +const KERNEL_CUBIN_BYTES = buildElf64Cubin(['flash_decode_snap_sm90a']); + +function makeSignedReceipt(opts: { + readonly lockHash: Digest; + readonly operationId: string; + readonly probeKind: 'physical' | 'synthetic_fixture'; + readonly isolation?: 'docker' | 'host_attested'; + readonly outputArtifacts: readonly BenchmarkOutputArtifact[]; + readonly metrics: Readonly>; + readonly secret?: string; +}): { readonly rawBytes: Buffer; readonly provenance: HardwareProvenance } { + const provenance: HardwareProvenance = { + targetCellId: 'cuda-h100-whole', + probeKind: opts.probeKind, + ...(opts.isolation !== undefined ? { isolation: opts.isolation } : {}), + vendor: 'nvidia', + deviceModel: 'NVIDIA H100 80GB HBM3', + accelerator: 'sm_90a', + isolationMode: 'whole_device', + deviceCount: 1, + driverVersion: '560.35.03', + runtimeVersion: 'cuda-12.6', + topology: 'single_gpu', + workloadDigest: makeDigest('workload-snap-cli'), + clockLockMode: 'locked', + }; + const verdictBase: Record = { + version: 1, + kind: 'benchmark_verdict', + storeId: 'store-snap-cli', + runId: 'run-snap-cli', + lockHash: opts.lockHash, + operationId: opts.operationId, + dispatchId: `disp-${opts.operationId}`, + dispatchGeneration: 1, + gateId: 'benchmark-gate', + checkId: 'hw-bench', + candidateDigest: sha256Hex(`cand-${opts.operationId}`), + status: 'approved', + reason: null, + expiresAtMs: '1900000000000', + preemptionCount: 0, + metrics: opts.metrics, + hardwareProvenance: provenance, + outputArtifacts: opts.outputArtifacts, + }; + const signature = signBenchmarkVerdict(opts.secret ?? TEST_RECEIPT_SECRET, verdictBase as unknown as BenchmarkVerdict); + const receipt = { ...verdictBase, signature } as unknown as SignedBenchmarkVerdictReceipt; + return { rawBytes: Buffer.from(`${JSON.stringify(receipt, null, 2)}\n`, 'utf8'), provenance }; +} + +async function seedCampaignStore( + campaignRoot: string, + options: { + readonly mode: 'signed_synthetic' | 'direct_null_receipt' | 'host_attested'; + readonly clock?: CampaignClockSource; + }, +): Promise<{ readonly campaignId: string }> { + const store = await EvolutionCampaignStore.open({ + campaignRoot, + ...(options.clock !== undefined ? { clock: options.clock } : {}), + }); + try { + const lease = await store.acquireLease('seed-owner'); + const manifest = parseEvolutionCampaignDocument(SINGLE_TARGET_CAMPAIGN_YAML); + const lockHash = makeDigest('lock-snap-cli'); + const campaignId = 'camp-snap-cli'; + await store.createCampaign(lease, { + campaignId, + manifest, + manifestDigest: makeDigest(SINGLE_TARGET_CAMPAIGN_YAML), + baseRevision: 'a'.repeat(40), + lockHash, + modelIds: ['model-a', 'model-b'], + }); + const islands = await store.listIslands(campaignId); + const teamOf = (islandId: number): string => islands.find(i => i.islandId === islandId)!.activeTeamConfigId; + + const cubinCas = await store.writeCasBlob(KERNEL_CUBIN_BYTES); + const code1 = await store.writeCasBlob('// ind-win-1 baseline\n'); + const code2 = await store.writeCasBlob('// ind-win-2 diff_tune\n'); + const codeFail = await store.writeCasBlob('// ind-fail-1 rewrite\n'); + const codePreempt = await store.writeCasBlob('// ind-pre-1 diff_tune\n'); + + const benchArtifacts: readonly BenchmarkOutputArtifact[] = [{ + name: 'flash_decode_snap.cubin', + digest: cubinCas.digest, + byteLength: cubinCas.byteLength, + mediaType: 'application/x-nvidia-cubin', + }]; + const diagnostics: HardwareDiagnostics = { + boundPipeline: 'tensor_cube', + rooflineHeadroom: 1.12, + achievedSolPct: 84.5, + occupancyPct: 75, + localSpillBytes: 0, + }; + + const recordPassed = async ( + individualId: 'ind-win-1' | 'ind-win-2', + generation: number, + metrics: Readonly>, + codeDigest: Digest, + parentId?: string, + ): Promise => { + if (options.mode === 'direct_null_receipt') { + await store.recordIndividual(lease, { + individualId, + campaignId, + islandId: 0, + generation, + bucketId: null, + teamConfigId: teamOf(0), + modelId: generation === 0 ? 'model-a' : 'model-b', + trackId: 'cute', + mutationKind: generation === 0 ? 'baseline' : 'diff_tune', + status: 'passed', + failureReason: null, + nicheKey: generation === 0 ? 'bound_pipeline=tensor_cube' : 'bound_pipeline=hbm', + paretoRank: 1, + crowdingDistance: generation === 0 ? Number.POSITIVE_INFINITY : 0.75, + scalarFitness: generation === 0 ? 0.9 : 0.85, + codeSliceCasDigest: codeDigest, + evidenceDigest: makeDigest(`direct-ev-${individualId}`), + verdictReceiptCasDigest: null, + outputArtifacts: [], + metrics, + ...(parentId !== undefined + ? { + lineageEdges: [{ + campaignId, + childIndividualId: individualId, + parentIndividualId: parentId, + role: 'primary' as const, + sourceIslandId: 0, + createdGeneration: generation, + }], + } + : {}), + }); + return; + } + + const receipt = makeSignedReceipt({ + lockHash, + operationId: `op-${individualId}`, + probeKind: options.mode === 'host_attested' ? 'physical' : 'synthetic_fixture', + ...(options.mode === 'host_attested' ? { isolation: 'host_attested' as const } : {}), + outputArtifacts: benchArtifacts, + metrics, + }); + const receiptCas = await store.writeCasBlob(receipt.rawBytes); + await store.recordIndividual(lease, { + individualId, + campaignId, + islandId: 0, + generation, + bucketId: null, + teamConfigId: teamOf(0), + modelId: generation === 0 ? 'model-a' : 'model-b', + trackId: 'cute', + mutationKind: generation === 0 ? 'baseline' : 'diff_tune', + status: 'passed', + failureReason: null, + nicheKey: generation === 0 ? 'bound_pipeline=tensor_cube' : 'bound_pipeline=hbm', + paretoRank: 1, + crowdingDistance: generation === 0 ? Number.POSITIVE_INFINITY : 0.75, + scalarFitness: generation === 0 ? 0.9 : 0.85, + codeSliceCasDigest: codeDigest, + evidenceDigest: makeDigest(`ev-${individualId}`), + verdictReceiptCasDigest: receiptCas.digest, + outputArtifacts: benchArtifacts.map(a => ({ + name: `.loopwright-verifier/check.hw-bench/${a.name}`, + digest: a.digest, + byteLength: a.byteLength, + uri: `cas://sha256/${a.digest.hex}`, + mediaType: a.mediaType ?? null, + })), + metrics, + hardwareDiagnostics: diagnostics, + hardwareProvenance: receipt.provenance, + ...(parentId !== undefined + ? { + lineageEdges: [{ + campaignId, + childIndividualId: individualId, + parentIndividualId: parentId, + role: 'primary' as const, + sourceIslandId: 0, + createdGeneration: generation, + }], + } + : {}), + }); + }; + + await recordPassed('ind-win-1', 0, { latency_us_p50: 50, goodput_rps: 2000 }, code1.digest); + await recordPassed('ind-win-2', 1, { latency_us_p50: 42.5, goodput_rps: 2400 }, code2.digest, 'ind-win-1'); + + await store.recordIndividual(lease, { + individualId: 'ind-fail-1', + campaignId, + islandId: 1, + generation: 1, + bucketId: null, + teamConfigId: teamOf(1), + modelId: 'model-a', + trackId: 'cute', + mutationKind: 'full_rewrite', + status: 'failed', + failureReason: 'COMPILE_ERROR', + nicheKey: null, + paretoRank: null, + crowdingDistance: null, + scalarFitness: null, + codeSliceCasDigest: codeFail.digest, + evidenceDigest: null, + verdictReceiptCasDigest: null, + outputArtifacts: [], + metrics: {}, + }); + await store.recordIndividual(lease, { + individualId: 'ind-pre-1', + campaignId, + islandId: 1, + generation: 1, + bucketId: null, + teamConfigId: teamOf(1), + modelId: 'model-b', + trackId: 'cute', + mutationKind: 'diff_tune', + status: 'preempted', + failureReason: 'BENCHMARK_PREEMPTED', + nicheKey: null, + paretoRank: null, + crowdingDistance: null, + scalarFitness: null, + codeSliceCasDigest: codePreempt.digest, + evidenceDigest: null, + verdictReceiptCasDigest: null, + outputArtifacts: [], + metrics: {}, + }); + + await store.recordModelBanditReward(lease, { campaignId, modelId: 'model-a', reward: 0.7, generation: 0 }); + await store.recordModelBanditReward(lease, { campaignId, modelId: 'model-b', reward: 0.9, generation: 1 }); + await store.updateCampaignProgress(lease, { + campaignId, + status: 'paused', + currentGeneration: 1, + }); + await store.releaseLease(lease); + return { campaignId }; + } finally { + await store.close(); + } +} + +test('evolve-snapshot: CLI argument grammar and help output cover snapshot export, check --bundle, and import', () => { + const checkBundle = parseArguments([ + 'evolve', 'check', '--bundle', '/snap', '--receipt-secret-env', 'MY_SECRET_1', '--allow-synthetic-probe', '--allow-host-attested', '--json', + ]); + assert.equal(checkBundle.evolveAction, 'check'); + assert.equal(checkBundle.values.get('bundle'), '/snap'); + assert.equal(checkBundle.values.get('receipt-secret-env'), 'MY_SECRET_1'); + assert.equal(checkBundle.flags.has('allow-synthetic-probe'), true); + assert.equal(checkBundle.flags.has('allow-host-attested'), true); + + const exportSnap = parseArguments([ + 'evolve', 'export', '--campaign', '/state', '--snapshot', '--out', '/snap', '--receipt-secret-env', 'MY_SECRET', '--allow-host-attested', '--overwrite', '--json', + ]); + assert.equal(exportSnap.evolveAction, 'export'); + assert.equal(exportSnap.flags.has('snapshot'), true); + assert.equal(exportSnap.flags.has('allow-host-attested'), true); + + const importSnap = parseArguments([ + 'evolve', 'import', '--bundle', '/snap', '--state', '/fresh', '--receipt-secret-env', 'MY_SECRET', '--allow-synthetic-probe', '--allow-host-attested', '--json', + ]); + assert.equal(importSnap.evolveAction, 'import'); + assert.equal(importSnap.values.get('bundle'), '/snap'); + assert.equal(importSnap.values.get('state'), '/fresh'); + + for (const bad of [ + ['evolve', 'check', '--campaign', 'c.yaml', '--bundle', '/snap'], + ['evolve', 'check', '--bundle', '/snap', '--repo', '/repo'], + ['evolve', 'check', '--campaign', 'c.yaml', '--receipt-secret-env', 'MY_SECRET'], + ['evolve', 'check', '--campaign', 'c.yaml', '--allow-synthetic-probe'], + ['evolve', 'check', '--campaign', 'c.yaml', '--allow-host-attested'], + ['evolve', 'export', '--campaign', '/state', '--snapshot', '--out', '/snap', '--format', 'dir'], + ['evolve', 'export', '--campaign', '/state', '--snapshot', '--out', '/snap', '--receipt-secret-env', '123INVALID'], + ['evolve', 'check', '--bundle', '/snap', '--receipt-secret-env', 'BAD-NAME'], + ['evolve', 'import', '--bundle', '/snap'], + ['evolve', 'import', '--state', '/fresh'], + ['evolve', 'import', '--bundle', '/snap', '--state', '/fresh', '--receipt-secret-env', 'bad name'], + ]) { + assert.throws(() => parseArguments(bad), UsageError, `expected UsageError for ${JSON.stringify(bad)}`); + } + + for (const helpArgv of [['--help'], ['evolve', '--help'], ['evolve', 'import', '--help']]) { + const res = spawnSync(process.execPath, [MAIN, ...helpArgv], { + encoding: 'utf8', + timeout: 15_000, + env: { PATH: '/usr/bin:/bin' }, + }); + assert.equal(res.status, 0, res.stderr); + assert.match(res.stdout, /evolve check --bundle DIR/); + assert.match(res.stdout, /evolve export --campaign DIR --snapshot --out DIR/); + assert.match(res.stdout, /evolve import --bundle DIR --state DIR/); + assert.match(res.stdout, /--receipt-secret-env NAME/); + assert.match(res.stdout, /--allow-host-attested/); + } +}); + +test('evolve-snapshot: signed synthetic_fixture export -> check -> import round-trip, refusals, tamper detection, and secret hygiene', async () => { + const root = await mkdtemp(join(await realpath(tmpdir()), 'lw-evo-snap-signed-')); + try { + const srcState = join(root, 'src-state'); + const snapDir = join(root, 'snapshot'); + const importedState = join(root, 'imported-state'); + await seedCampaignStore(srcState, { mode: 'signed_synthetic' }); + + const secretEnv = { + TEST_RECEIPT_SECRET, + LOOPWRIGHT_GATE_SIGNING_SECRET: TEST_RECEIPT_SECRET, + BENCH_SIGNING_SECRET: undefined, + }; + + // Export refuses without --allow-synthetic-probe + const noSynthExport = await runCliInProcess([ + 'evolve', 'export', '--campaign', srcState, '--snapshot', '--out', snapDir, + '--receipt-secret-env', 'TEST_RECEIPT_SECRET', '--json', + ], secretEnv); + assert.equal(noSynthExport.status, 3, noSynthExport.stdout + noSynthExport.stderr); + assert.equal(JSON.parse(noSynthExport.stdout.trim()).data.code, 'EXPORT_UNVERIFIED_FORBIDDEN'); + assert.equal(noSynthExport.stdout.includes(TEST_RECEIPT_SECRET), false); + assert.equal(noSynthExport.stderr.includes(TEST_RECEIPT_SECRET), false); + + // Export refuses without --receipt-secret-env even when LOOPWRIGHT_GATE_SIGNING_SECRET is present + const noSecretFlagExport = await runCliInProcess([ + 'evolve', 'export', '--campaign', srcState, '--snapshot', '--out', snapDir, + '--allow-synthetic-probe', '--json', + ], secretEnv); + assert.equal(noSecretFlagExport.status, 3, noSecretFlagExport.stdout + noSecretFlagExport.stderr); + assert.equal(JSON.parse(noSecretFlagExport.stdout.trim()).data.code, 'EXPORT_UNVERIFIED_FORBIDDEN'); + + // Export refuses unset explicit --receipt-secret-env + const unsetSecretExport = await runCliInProcess([ + 'evolve', 'export', '--campaign', srcState, '--snapshot', '--out', snapDir, + '--allow-synthetic-probe', '--receipt-secret-env', 'UNSET_RECEIPT_VAR', '--json', + ], { ...secretEnv, UNSET_RECEIPT_VAR: undefined }); + assert.equal(unsetSecretExport.status, 3, unsetSecretExport.stdout + unsetSecretExport.stderr); + assert.equal(JSON.parse(unsetSecretExport.stdout.trim()).data.code, 'EXPORT_UNVERIFIED_FORBIDDEN'); + + // Export refuses wrong secret + const wrongSecretExport = await runCliInProcess([ + 'evolve', 'export', '--campaign', srcState, '--snapshot', '--out', snapDir, + '--allow-synthetic-probe', '--receipt-secret-env', 'WRONG_SECRET_VAR', '--json', + ], { ...secretEnv, WRONG_SECRET_VAR: WRONG_RECEIPT_SECRET }); + assert.equal(wrongSecretExport.status, 3, wrongSecretExport.stdout + wrongSecretExport.stderr); + assert.equal(JSON.parse(wrongSecretExport.stdout.trim()).data.code, 'EXPORT_UNVERIFIED_FORBIDDEN'); + assert.equal(wrongSecretExport.stdout.includes(WRONG_RECEIPT_SECRET), false); + + // Export succeeds with explicit --receipt-secret-env and --allow-synthetic-probe + const okExport = await runCliInProcess([ + 'evolve', 'export', '--campaign', srcState, '--snapshot', '--out', snapDir, + '--allow-synthetic-probe', '--receipt-secret-env', 'TEST_RECEIPT_SECRET', '--json', + ], secretEnv); + assert.equal(okExport.status, 0, okExport.stdout + okExport.stderr); + assert.equal(okExport.stdout.includes(TEST_RECEIPT_SECRET), false); + assert.equal(okExport.stderr.includes(TEST_RECEIPT_SECRET), false); + const exportEnv = JSON.parse(okExport.stdout.trim()) as { + kind: string; + data: { manifestDigest: Digest; individualCount: number; receiptCount: number; blobCount: number }; + }; + assert.equal(exportEnv.kind, 'result'); + assert.equal(exportEnv.data.individualCount, 4); + assert.equal(exportEnv.data.receiptCount, 2); + assert.ok(exportEnv.data.blobCount >= 5); + + // Secret hygiene: secret must not appear anywhere in exported snapshot files + for (const filePath of await collectFilesRecursive(snapDir)) { + const bytes = await readFile(filePath); + assert.equal(bytes.includes(TEST_RECEIPT_SECRET), false, `secret leaked into ${filePath}`); + } + + // Check refuses without --allow-synthetic-probe, without --receipt-secret-env, with unset var, or wrong secret + const noSynthCheck = await runCliInProcess([ + 'evolve', 'check', '--bundle', snapDir, '--receipt-secret-env', 'TEST_RECEIPT_SECRET', '--json', + ], secretEnv); + assert.equal(noSynthCheck.status, 3); + assert.equal(JSON.parse(noSynthCheck.stdout.trim()).data.code, 'EXPORT_UNVERIFIED_FORBIDDEN'); + + const noSecretCheck = await runCliInProcess([ + 'evolve', 'check', '--bundle', snapDir, '--allow-synthetic-probe', '--json', + ], secretEnv); + assert.equal(noSecretCheck.status, 3); + assert.equal(JSON.parse(noSecretCheck.stdout.trim()).data.code, 'EXPORT_UNVERIFIED_FORBIDDEN'); + + const unsetSecretCheck = await runCliInProcess([ + 'evolve', 'check', '--bundle', snapDir, '--allow-synthetic-probe', '--receipt-secret-env', 'UNSET_RECEIPT_VAR', '--json', + ], { ...secretEnv, UNSET_RECEIPT_VAR: undefined }); + assert.equal(unsetSecretCheck.status, 3); + assert.equal(JSON.parse(unsetSecretCheck.stdout.trim()).data.code, 'EXPORT_UNVERIFIED_FORBIDDEN'); + + const wrongSecretCheck = await runCliInProcess([ + 'evolve', 'check', '--bundle', snapDir, '--allow-synthetic-probe', '--receipt-secret-env', 'WRONG_SECRET_VAR', '--json', + ], { ...secretEnv, WRONG_SECRET_VAR: WRONG_RECEIPT_SECRET }); + assert.equal(wrongSecretCheck.status, 3); + assert.equal(JSON.parse(wrongSecretCheck.stdout.trim()).data.code, 'EXPORT_UNVERIFIED_FORBIDDEN'); + + // Check succeeds + const okCheck = await runCliInProcess([ + 'evolve', 'check', '--bundle', snapDir, '--allow-synthetic-probe', '--receipt-secret-env', 'TEST_RECEIPT_SECRET', '--json', + ], secretEnv); + assert.equal(okCheck.status, 0, okCheck.stdout + okCheck.stderr); + assert.equal(okCheck.stdout.includes(TEST_RECEIPT_SECRET), false); + const checkEnv = JSON.parse(okCheck.stdout.trim()) as { + kind: string; + data: { valid: boolean; campaignId: string; manifestDigest: Digest; individualCount: number; receiptCount: number }; + }; + assert.equal(checkEnv.kind, 'plan'); + assert.equal(checkEnv.data.valid, true); + assert.equal(checkEnv.data.campaignId, 'camp-snap-cli'); + assert.equal(checkEnv.data.manifestDigest.hex, exportEnv.data.manifestDigest.hex); + assert.equal(checkEnv.data.individualCount, 4); + assert.equal(checkEnv.data.receiptCount, 2); + + // Import refuses without --allow-synthetic-probe or without --receipt-secret-env + const noSynthImport = await runCliInProcess([ + 'evolve', 'import', '--bundle', snapDir, '--state', importedState, '--receipt-secret-env', 'TEST_RECEIPT_SECRET', '--json', + ], secretEnv); + assert.equal(noSynthImport.status, 3); + assert.equal(JSON.parse(noSynthImport.stdout.trim()).data.code, 'EXPORT_UNVERIFIED_FORBIDDEN'); + + const noSecretImport = await runCliInProcess([ + 'evolve', 'import', '--bundle', snapDir, '--state', importedState, '--allow-synthetic-probe', '--json', + ], secretEnv); + assert.equal(noSecretImport.status, 3); + assert.equal(JSON.parse(noSecretImport.stdout.trim()).data.code, 'EXPORT_UNVERIFIED_FORBIDDEN'); + + // Import into fresh state dir succeeds + const okImport = await runCliInProcess([ + 'evolve', 'import', '--bundle', snapDir, '--state', importedState, + '--allow-synthetic-probe', '--receipt-secret-env', 'TEST_RECEIPT_SECRET', '--json', + ], secretEnv); + assert.equal(okImport.status, 0, okImport.stdout + okImport.stderr); + assert.equal(okImport.stdout.includes(TEST_RECEIPT_SECRET), false); + const importEnv = JSON.parse(okImport.stdout.trim()) as { + kind: string; + data: { campaignId: string; snapshotDigest: Digest; individualCount: number; receiptCount: number }; + }; + assert.equal(importEnv.kind, 'result'); + assert.equal(importEnv.data.campaignId, 'camp-snap-cli'); + assert.equal(importEnv.data.snapshotDigest.hex, exportEnv.data.manifestDigest.hex); + assert.equal(importEnv.data.individualCount, 4); + assert.equal(importEnv.data.receiptCount, 2); + + // Re-importing into non-empty --state fails closed with EVOLUTION_CONFLICT (exit 7) + const nonEmptyImport = await runCliInProcess([ + 'evolve', 'import', '--bundle', snapDir, '--state', importedState, + '--allow-synthetic-probe', '--receipt-secret-env', 'TEST_RECEIPT_SECRET', '--json', + ], secretEnv); + assert.equal(nonEmptyImport.status, 7, nonEmptyImport.stdout + nonEmptyImport.stderr); + assert.equal(JSON.parse(nonEmptyImport.stdout.trim()).data.code, 'EVOLUTION_CONFLICT'); + + // Tampered individuals.jsonl metric fails both check and import + const tamperedIndDir = join(root, 'snap-tampered-ind'); + await cp(snapDir, tamperedIndDir, { recursive: true }); + const indPath = join(tamperedIndDir, 'individuals.jsonl'); + const rawInd = await readFile(indPath, 'utf8'); + await writeFile(indPath, rawInd.replace('42.5', '12.5')); + + const tamperedIndCheck = await runCliInProcess([ + 'evolve', 'check', '--bundle', tamperedIndDir, '--allow-synthetic-probe', '--receipt-secret-env', 'TEST_RECEIPT_SECRET', '--json', + ], secretEnv); + assert.equal(tamperedIndCheck.status, 4); + assert.equal(JSON.parse(tamperedIndCheck.stdout.trim()).data.code, 'ARTIFACT_INVALID'); + + const tamperedIndImport = await runCliInProcess([ + 'evolve', 'import', '--bundle', tamperedIndDir, '--state', join(root, 'tampered-ind-state'), + '--allow-synthetic-probe', '--receipt-secret-env', 'TEST_RECEIPT_SECRET', '--json', + ], secretEnv); + assert.equal(tamperedIndImport.status, 4); + assert.equal(JSON.parse(tamperedIndImport.stdout.trim()).data.code, 'ARTIFACT_INVALID'); + + // Tampered manifest.json fails check + const tamperedManifestDir = join(root, 'snap-tampered-manifest'); + await cp(snapDir, tamperedManifestDir, { recursive: true }); + await writeFile(join(tamperedManifestDir, 'manifest.json'), '{"kind":"CampaignSnapshot","version":99}\n'); + const tamperedManifestCheck = await runCliInProcess([ + 'evolve', 'check', '--bundle', tamperedManifestDir, '--allow-synthetic-probe', '--receipt-secret-env', 'TEST_RECEIPT_SECRET', '--json', + ], secretEnv); + assert.equal(tamperedManifestCheck.status, 4); + assert.equal(JSON.parse(tamperedManifestCheck.stdout.trim()).data.code, 'ARTIFACT_INVALID'); + + // Tampered receipt bytes fail check (ARTIFACT_INVALID on digest mismatch) + const tamperedReceiptDir = join(root, 'snap-tampered-receipt'); + await cp(snapDir, tamperedReceiptDir, { recursive: true }); + const recPath = join(tamperedReceiptDir, 'receipts', 'ind-win-1.verdict.json'); + const recRaw = await readFile(recPath, 'utf8'); + await writeFile(recPath, recRaw.replace('"goodput_rps": 2000', '"goodput_rps": 9999')); + const tamperedReceiptCheck = await runCliInProcess([ + 'evolve', 'check', '--bundle', tamperedReceiptDir, '--allow-synthetic-probe', '--receipt-secret-env', 'TEST_RECEIPT_SECRET', '--json', + ], secretEnv); + assert.equal(tamperedReceiptCheck.status, 4); + assert.equal(JSON.parse(tamperedReceiptCheck.stdout.trim()).data.code, 'ARTIFACT_INVALID'); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test('evolve-snapshot: direct-mode (receipt: null) snapshot exports, checks, and imports without --receipt-secret-env', async () => { + const root = await mkdtemp(join(await realpath(tmpdir()), 'lw-evo-snap-direct-')); + try { + const srcState = join(root, 'src-state'); + const snapDir = join(root, 'snapshot'); + const importedState = join(root, 'imported-state'); + await seedCampaignStore(srcState, { mode: 'direct_null_receipt' }); + + const cleanEnv = { + LOOPWRIGHT_GATE_SIGNING_SECRET: undefined, + BENCH_SIGNING_SECRET: undefined, + }; + + const exported = await runCliInProcess([ + 'evolve', 'export', '--campaign', srcState, '--snapshot', '--out', snapDir, '--json', + ], cleanEnv); + assert.equal(exported.status, 0, exported.stdout + exported.stderr); + const expData = JSON.parse(exported.stdout.trim()).data as { + individualCount: number; + receiptCount: number; + manifestDigest: Digest; + }; + assert.equal(expData.individualCount, 4); + assert.equal(expData.receiptCount, 0); + + const checked = await runCliInProcess([ + 'evolve', 'check', '--bundle', snapDir, '--json', + ], cleanEnv); + assert.equal(checked.status, 0, checked.stdout + checked.stderr); + const chkData = JSON.parse(checked.stdout.trim()).data as { + valid: boolean; + individualCount: number; + receiptCount: number; + }; + assert.equal(chkData.valid, true); + assert.equal(chkData.individualCount, 4); + assert.equal(chkData.receiptCount, 0); + + // Explicit --receipt-secret-env pointing to an unset var still fails closed even on zero-receipt snapshots + const explicitMissing = await runCliInProcess([ + 'evolve', 'check', '--bundle', snapDir, '--receipt-secret-env', 'EXPLICIT_MISSING_SECRET', '--json', + ], { ...cleanEnv, EXPLICIT_MISSING_SECRET: undefined }); + assert.equal(explicitMissing.status, 3); + assert.equal(JSON.parse(explicitMissing.stdout.trim()).data.code, 'EXPORT_UNVERIFIED_FORBIDDEN'); + + const imported = await runCliInProcess([ + 'evolve', 'import', '--bundle', snapDir, '--state', importedState, '--json', + ], cleanEnv); + assert.equal(imported.status, 0, imported.stdout + imported.stderr); + const impData = JSON.parse(imported.stdout.trim()).data as { + individualCount: number; + receiptCount: number; + snapshotDigest: Digest; + }; + assert.equal(impData.individualCount, 4); + assert.equal(impData.receiptCount, 0); + assert.equal(impData.snapshotDigest.hex, expData.manifestDigest.hex); + + const inspected = await runCliInProcess(['evolve', 'inspect', '--campaign', importedState, '--json'], cleanEnv); + assert.equal(inspected.status, 0, inspected.stdout + inspected.stderr); + const insData = JSON.parse(inspected.stdout.trim()).data as { + individuals: readonly { individualId: string; status: string; verdictReceiptCasDigest: Digest | null }[]; + }; + assert.equal(insData.individuals.length, 4); + assert.equal(insData.individuals.every(i => i.verdictReceiptCasDigest === null), true); + assert.equal(insData.individuals.filter(i => i.status === 'passed').length, 2); + assert.equal(insData.individuals.filter(i => i.status === 'failed').length, 1); + assert.equal(insData.individuals.filter(i => i.status === 'preempted').length, 1); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test('evolve-snapshot: host_attested receipts are refused without --allow-host-attested and accepted with it', async () => { + const root = await mkdtemp(join(await realpath(tmpdir()), 'lw-evo-snap-host-')); + try { + const srcState = join(root, 'src-state'); + const bundleDir = join(root, 'bundle-dir'); + const snapDir = join(root, 'snapshot'); + const importedState = join(root, 'imported-state'); + await seedCampaignStore(srcState, { mode: 'host_attested' }); + + const env = { TEST_RECEIPT_SECRET }; + + // Non-snapshot evolve export refuses without --allow-host-attested and accepts with it + const refusedBundle = await runCliInProcess([ + 'evolve', 'export', '--campaign', srcState, '--out', bundleDir, '--format', 'dir', + '--receipt-secret-env', 'TEST_RECEIPT_SECRET', '--json', + ], env); + assert.equal(refusedBundle.status, 3, refusedBundle.stdout + refusedBundle.stderr); + assert.equal(JSON.parse(refusedBundle.stdout.trim()).data.code, 'EXPORT_UNVERIFIED_FORBIDDEN'); + + const okBundle = await runCliInProcess([ + 'evolve', 'export', '--campaign', srcState, '--out', bundleDir, '--format', 'dir', + '--receipt-secret-env', 'TEST_RECEIPT_SECRET', '--allow-host-attested', '--json', + ], env); + assert.equal(okBundle.status, 0, okBundle.stdout + okBundle.stderr); + + // Snapshot export refuses without --allow-host-attested and accepts with it + const refusedSnapExport = await runCliInProcess([ + 'evolve', 'export', '--campaign', srcState, '--snapshot', '--out', snapDir, + '--receipt-secret-env', 'TEST_RECEIPT_SECRET', '--json', + ], env); + assert.equal(refusedSnapExport.status, 3); + assert.equal(JSON.parse(refusedSnapExport.stdout.trim()).data.code, 'EXPORT_UNVERIFIED_FORBIDDEN'); + + const okSnapExport = await runCliInProcess([ + 'evolve', 'export', '--campaign', srcState, '--snapshot', '--out', snapDir, + '--receipt-secret-env', 'TEST_RECEIPT_SECRET', '--allow-host-attested', '--json', + ], env); + assert.equal(okSnapExport.status, 0, okSnapExport.stdout + okSnapExport.stderr); + + // Snapshot check refuses without --allow-host-attested and accepts with it + const refusedCheck = await runCliInProcess([ + 'evolve', 'check', '--bundle', snapDir, '--receipt-secret-env', 'TEST_RECEIPT_SECRET', '--json', + ], env); + assert.equal(refusedCheck.status, 3); + assert.equal(JSON.parse(refusedCheck.stdout.trim()).data.code, 'EXPORT_UNVERIFIED_FORBIDDEN'); + + const okCheck = await runCliInProcess([ + 'evolve', 'check', '--bundle', snapDir, '--receipt-secret-env', 'TEST_RECEIPT_SECRET', '--allow-host-attested', '--json', + ], env); + assert.equal(okCheck.status, 0, okCheck.stdout + okCheck.stderr); + + // Snapshot import refuses without --allow-host-attested and accepts with it + const refusedImport = await runCliInProcess([ + 'evolve', 'import', '--bundle', snapDir, '--state', importedState, '--receipt-secret-env', 'TEST_RECEIPT_SECRET', '--json', + ], env); + assert.equal(refusedImport.status, 3); + assert.equal(JSON.parse(refusedImport.stdout.trim()).data.code, 'EXPORT_UNVERIFIED_FORBIDDEN'); + + const okImport = await runCliInProcess([ + 'evolve', 'import', '--bundle', snapDir, '--state', importedState, + '--receipt-secret-env', 'TEST_RECEIPT_SECRET', '--allow-host-attested', '--json', + ], env); + assert.equal(okImport.status, 0, okImport.stdout + okImport.stderr); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test('evolve-snapshot: real evolve resume continues on a host with a lower monotonic clock without EVOLUTION_CLOCK_DRIFT', { timeout: 120000 }, async () => { + const root = await mkdtemp(join(await realpath(tmpdir()), 'lw-evo-snap-resume-')); + const relayCasDir = join(root, 'relay-cas'); + const workerWorkDir = join(root, 'worker-work'); + const workloadsDir = join(root, 'workloads'); + await mkdir(workerWorkDir, { recursive: true, mode: 0o700 }); + await mkdir(join(workloadsDir, 'decode-h100-holdout'), { recursive: true, mode: 0o700 }); + + const evalScript = [ + `#!${process.execPath}`, + 'const fs = require("node:fs");', + 'const path = require("node:path");', + 'const stageADir = process.env.LOOPWRIGHT_STAGE_A_OUT;', + 'const files = fs.readdirSync(stageADir);', + 'const lat = files.some(f => f.includes("gen2")) ? 32.0 : 48.0;', + 'const rps = files.some(f => f.includes("gen2")) ? 2900 : 2100;', + 'const payload = {', + ' status: "approved",', + ' metrics: { latency_us_p50: lat, goodput_rps: rps, max_ulp: 1 },', + ' bucketMetrics: [{ bucketId: "decode-h100-holdout", dimensions: { bs: 1 }, metrics: { latency_us_p50: lat, goodput_rps: rps, max_ulp: 1 } }],', + ' hardwareDiagnostics: { boundPipeline: "tensor_cube", occupancyPct: 80, rooflineHeadroom: 1.15 }', + '};', + 'process.stdout.write("LOOPWRIGHT_STAGE_B_RESULT:" + JSON.stringify(payload) + "\\n");', + '', + ].join('\n'); + const evalPath = join(workloadsDir, 'decode-h100-holdout', 'evaluate.sh'); + await writeFile(evalPath, evalScript, { mode: 0o755 }); + await chmod(evalPath, 0o755); + + const cubinHex = KERNEL_CUBIN_BYTES.toString('hex'); + const buildScript = [ + `#!${process.execPath}`, + 'const fs = require("node:fs");', + 'const path = require("node:path");', + 'const src = fs.readFileSync(path.join(process.cwd(), "src/kernels/flash_decode.cu"), "utf8");', + 'const tag = src.includes("GEN2_VARIANT") ? "gen2" : "gen1";', + `fs.writeFileSync(path.join(process.env.LOOPWRIGHT_STAGE_A_OUT, "flash_decode_" + tag + ".cubin"), Buffer.from(${JSON.stringify(cubinHex)}, "hex"));`, + '', + ].join('\n'); + + const relay = await startRelayServer({ + port: 0, + casDir: relayCasDir, + controllerSigningSecret: TEST_RECEIPT_SECRET, + workerTokens: [WORKER_BEARER_TOKEN], + leaseTtlMs: 30_000, + sweepIntervalMs: 150, + }); + + const workerAbort = new AbortController(); + let workerFatalError: unknown = null; + const workerPromise = runHardwareWorker({ + config: { + workerId: 'snap-resume-worker', + relayUrl: relay.url, + workerToken: WORKER_BEARER_TOKEN, + workDir: workerWorkDir, + heldOutWorkloadsDir: workloadsDir, + sandboxBackend: 'native_os', + capabilities: { + accelerator: 'sm_90a', + isolationModes: ['whole_device'], + deviceCount: 1, + driverVersion: '550.90.07', + workloadIds: ['decode-h100-holdout'], + }, + pollWaitMs: 40, + heartbeatIntervalMs: 50, + requestTimeoutMs: 15_000, + stageATimeoutMs: 45_000, + stageBTimeoutMs: 45_000, + toolchainPaths: [join(process.execPath, '..')], + probeMode: 'synthetic_fixture', + } satisfies WorkerConfig, + once: false, + signal: workerAbort.signal, + registerProcessSignalHandlers: false, + }).catch((err: unknown) => { + if (!workerAbort.signal.aborted) workerFatalError = err; + }); + + const hostAAbort = new AbortController(); + let pauseOnSecondVariant = true; + let sseTurn = 0; + const sseServer = createServer((req, res) => { + const chunks: Buffer[] = []; + req.on('data', (c: Buffer) => chunks.push(c)); + req.on('end', () => { + const parsedBody = JSON.parse(Buffer.concat(chunks).toString('utf8')) as { + readonly messages?: readonly { readonly role?: string }[]; + }; + const isSecondMessage = parsedBody.messages?.some(m => m.role === 'tool') ?? false; + res.writeHead(200, { 'content-type': 'text/event-stream' }); + if (!isSecondMessage) { + sseTurn += 1; + if (pauseOnSecondVariant && sseTurn === 2) { + pauseOnSecondVariant = false; + setTimeout(() => hostAAbort.abort(), 20); + } + const marker = sseTurn === 1 ? 'GEN1_VARIANT' : `GEN2_VARIANT_${sseTurn}`; + const nextKernel = BASELINE_KERNEL_SOURCE.replace('return 0; // baseline', `return ${sseTurn}; // ${marker}`); + const toolChunk = { + id: `chatcmpl-snap-tool-${sseTurn}`, + object: 'chat.completion.chunk', + choices: [{ + index: 0, + delta: { + role: 'assistant', + tool_calls: [{ + index: 0, + id: `call_snap_write_${sseTurn}`, + type: 'function', + function: { + name: 'write', + arguments: JSON.stringify({ path: 'src/kernels/flash_decode.cu', content: nextKernel }), + }, + }], + }, + finish_reason: 'tool_calls', + }], + usage: { prompt_tokens: 20, completion_tokens: 15, total_tokens: 35 }, + }; + res.end(`data: ${JSON.stringify(toolChunk)}\n\ndata: [DONE]\n\n`); + return; + } + + const doneChunk = { + id: `chatcmpl-snap-done-${sseTurn}`, + object: 'chat.completion.chunk', + choices: [{ + index: 0, + delta: { + role: 'assistant', + content: '{"version":1,"status":"completed","checks":[],"reason":"updated flash_decode.cu"}', + }, + finish_reason: 'stop', + }], + usage: { prompt_tokens: 20, completion_tokens: 10, total_tokens: 30 }, + }; + res.end(`data: ${JSON.stringify(doneChunk)}\n\ndata: [DONE]\n\n`); + }); + }); + await new Promise(resolveListen => sseServer.listen(0, '127.0.0.1', () => resolveListen())); + const ssePort = (sseServer.address() as { port: number }).port; + + const savedEnv: Record = {}; + const setEnv = (overrides: Readonly>): void => { + for (const [k, v] of Object.entries(overrides)) { + if (!Object.hasOwn(savedEnv, k)) savedEnv[k] = process.env[k]; + if (v === undefined) delete process.env[k]; + else process.env[k] = v; + } + }; + + try { + const modelsJsonPath = join(root, 'models.json'); + await writeFile( + modelsJsonPath, + JSON.stringify({ + providers: { + 'local-oai': { + baseUrl: `http://127.0.0.1:${ssePort}/v1`, + api: 'openai-completions', + apiKey: 'LOCAL_OAI_KEY', + models: [{ id: 'mock-model', contextWindow: 128_000, maxTokens: 4_096 }], + }, + }, + }), + { mode: 0o600 }, + ); + + const repoDir = join(root, 'repo'); + await initGitRepo(repoDir, { + '.loopwright/taskpack.yaml': { + content: [ + 'apiVersion: loopwright.dev/v1alpha1', + 'kind: Taskpack', + 'metadata:', + ' name: snap-resume-tp', + 'spec:', + ' goal:', + ' candidate: Evolve flash decode kernel inside EVOLVE-BLOCK markers.', + ' noChange: No kernel change needed.', + ' target:', + ' matrix:', + ' - id: cuda-sm90', + ' platform: linux/amd64', + ' variant: cuda12', + ' hardware:', + ' accelerator: sm_90a', + ' isolationMode: whole_device', + ' deviceCount: 1', + ' driverConstraint: ">=550.0"', + ' scope:', + ' writable: [src/kernels/**]', + ' protected: [scripts/**]', + ' models:', + ' - provider: local-oai', + ' id: mock-model', + ' apiKeyEnv: LOCAL_OAI_KEY', + ' roles:', + ' - id: mutator', + ' provider: local-oai', + ' model: mock-model', + ' purpose: task', + ' tools: [read, write, edit]', + ' prompt: Mutate src/kernels/flash_decode.cu inside EVOLVE-BLOCK markers.', + ' verification:', + ' localChecks:', + ' - id: evolve-guard', + ' implementation: evolve-block-guard.v1', + ' parameters:', + ' files: [src/kernels/flash_decode.cu]', + ' externalGates:', + ' - id: gpu-bench', + ' implementation: benchmark-gate.v1', + ' endpointId: hw-relay', + ' gateId: flash-decode-bench', + ' required: true', + ' targetCellId: cuda-sm90', + ' heldOutWorkloadId: decode-h100-holdout', + ' allowSyntheticHardwareProbe: true', + ' metricThresholds:', + ' - kind: bounds', + ' metric: max_ulp', + ' max: 2', + ' bucketScope: all_buckets', + ' publication:', + ' mode: disabled', + ].join('\n'), + }, + '.loopwright/campaign.yaml': { + content: [ + 'apiVersion: loopwright.dev/v1alpha1', + 'kind: EvolutionCampaign', + 'metadata:', + ' name: snap-resume-camp', + 'spec:', + ' taskpack: .loopwright/taskpack.yaml', + ' targetCellId: cuda-sm90', + ' stages:', + ' mode: single-target', + ' heldOutWorkloadId: decode-h100-holdout', + ' population:', + ' islands: 1', + ' migrationIntervalGenerations: 4', + ' maxMigrationElites: 1', + ' nicheAxes:', + ' - id: bound_pipeline', + ' kind: enum', + ' values: [hbm, tensor_cube]', + ' sampling:', + ' noveltyDecayLambda: 1.0', + ' mutationWeights:', + ' diff_tune: 0.5', + ' full_rewrite: 0.5', + ' crossover: 0.0', + ' modelBandit: ucb1', + ' maxCrossoversPerPrompt: 1', + ' objectives:', + ' - metric: latency_us_p50', + ' direction: minimize', + ' - metric: goodput_rps', + ' direction: maximize', + ' budgets:', + ' maxGenerations: 2', + ' maxEvaluations: 2', + ' maxConcurrentEvaluations: 1', + ' scratchpadIntervalGenerations: 5', + ].join('\n'), + }, + 'src/kernels/flash_decode.cu': { content: BASELINE_KERNEL_SOURCE }, + 'scripts/build.sh': { content: buildScript, executable: true }, + }); + + const hostAState = join(root, 'host-a-state'); + const snapDir1 = join(root, 'snapshot-1'); + const hostBState = join(root, 'host-b-state'); + const snapDir2 = join(root, 'snapshot-2'); + + const cliEnv = { + PATH: '/usr/bin:/bin', + LOOPWRIGHT_MODELS_JSON: modelsJsonPath, + LOOPWRIGHT_ALLOW_MANIFEST_CUSTOM_BASE_URL: 'true', + LOOPWRIGHT_BENCHMARK_GATE_URL: `${relay.url}/v1/benchmark/jobs`, + LOOPWRIGHT_GATE_SIGNING_SECRET: TEST_RECEIPT_SECRET, + SNAP_RECEIPT_SECRET: TEST_RECEIPT_SECRET, + LOCAL_OAI_KEY, + }; + setEnv(cliEnv); + + // 1. Run generation 1 on Host A with a monotonic clock strictly higher than this host's current clock + const hostBMonoBaseline = DEFAULT_CAMPAIGN_CLOCK.nowMonotonicMs(); + const highMonoStart = hostBMonoBaseline + 10_000_000_000; + const hostAClock = makeSteppingClock(highMonoStart, Date.now() - 60_000); + const coreScrubber = new SecretScrubber(); + const taskpackScrubber = new TaskpackSecretScrubber(); + coreScrubber.register(TEST_RECEIPT_SECRET); + coreScrubber.register(LOCAL_OAI_KEY); + taskpackScrubber.register(TEST_RECEIPT_SECRET); + taskpackScrubber.register(LOCAL_OAI_KEY); + + const hostARun = await runEvolutionCampaign({ + campaignRoot: hostAState, + manifestPath: join(repoDir, '.loopwright', 'campaign.yaml'), + repositoryRoot: repoDir, + clock: hostAClock, + evaluator: createCliEvolutionEvaluator({ repositoryRoot: repoDir, coreScrubber, taskpackScrubber }), + signal: hostAAbort.signal, + autoExport: false, + allowSyntheticProbe: true, + receiptSigningSecret: TEST_RECEIPT_SECRET, + scrubber: coreScrubber, + }); + assert.equal(hostARun.campaign.status, 'paused'); + assert.equal(hostARun.campaign.evaluationsUsed, 1); + + const hostAExport = await writeCampaignSnapshot({ + store: hostARun.store, + campaignId: hostARun.campaign.campaignId, + outDir: snapDir1, + allowSyntheticProbe: true, + receiptSigningSecret: TEST_RECEIPT_SECRET, + scrubber: coreScrubber, + }); + await hostARun.store.close(); + + // Verify Host A's persisted monotonic clock is strictly higher than Host B's current monotonic clock + const readMetaMono = (dir: string): number => { + const db = new DatabaseSync(join(dir, CAMPAIGN_SQLITE_FILENAME), { readOnly: true }); + try { + const row = db.prepare('SELECT last_monotonic_ms FROM campaign_meta WHERE singleton = 1;').get() as { + readonly last_monotonic_ms: number; + }; + return Number(row.last_monotonic_ms); + } finally { + db.close(); + } + }; + const hostAMono = readMetaMono(hostAState); + assert.ok(hostAMono > DEFAULT_CAMPAIGN_CLOCK.nowMonotonicMs(), 'Host A monotonic clock must exceed Host B clock'); + + // Opening Host A's raw SQLite directly on Host B fails closed with EVOLUTION_CLOCK_DRIFT (exit 7) + const directOpenOnHostB = await runCliInProcess(['evolve', 'status', '--campaign', hostAState, '--json'], cliEnv); + assert.equal(directOpenOnHostB.status, 7, directOpenOnHostB.stdout + directOpenOnHostB.stderr); + assert.equal(JSON.parse(directOpenOnHostB.stdout.trim()).data.code, 'EVOLUTION_CLOCK_DRIFT'); + + // 2. Host B verifies and imports the snapshot via real CLI (creating fresh authority with Host B's lower monotonic clock) + const checkRes = await runCliInProcess([ + 'evolve', 'check', '--bundle', snapDir1, '--allow-synthetic-probe', '--receipt-secret-env', 'SNAP_RECEIPT_SECRET', '--json', + ], cliEnv); + assert.equal(checkRes.status, 0, checkRes.stdout + checkRes.stderr); + + const importRes = await runCliInProcess([ + 'evolve', 'import', '--bundle', snapDir1, '--state', hostBState, + '--allow-synthetic-probe', '--receipt-secret-env', 'SNAP_RECEIPT_SECRET', '--json', + ], cliEnv); + assert.equal(importRes.status, 0, importRes.stdout + importRes.stderr); + const hostBMonoAfterImport = readMetaMono(hostBState); + assert.ok(hostBMonoAfterImport < hostAMono, 'imported store must use Host B lower monotonic clock basis'); + + // 3. Real CLI `evolve resume` continues the imported campaign cleanly on Host B (zero EVOLUTION_CLOCK_DRIFT!) + const resumeRes = await runCliInProcess([ + 'evolve', 'resume', '--campaign', hostBState, '--repo', repoDir, '--allow-synthetic-probe', '--json', + ], cliEnv); + assert.equal(resumeRes.status, 0, resumeRes.stdout + resumeRes.stderr); + assert.equal(resumeRes.stdout.includes(TEST_RECEIPT_SECRET), false); + assert.equal(resumeRes.stdout.includes(LOCAL_OAI_KEY), false); + + const resumedEnv = JSON.parse(resumeRes.stdout.trim()) as { + kind: string; + data: { + campaign: { campaignId: string; status: string; currentGeneration: number; evaluationsUsed: number }; + paretoFrontier: readonly { individualId: string }[]; + }; + }; + assert.equal(resumedEnv.kind, 'result'); + assert.equal(resumedEnv.data.campaign.status, 'completed'); + assert.equal(resumedEnv.data.campaign.evaluationsUsed, 2); + assert.ok(resumedEnv.data.campaign.currentGeneration >= 2); + assert.ok(resumedEnv.data.paretoFrontier.length >= 1); + + // Inspect Host B state: Pareto archive, lineage, islands, bandit state, and snapshot_provenance remain intact + const inspectRes = await runCliInProcess(['evolve', 'inspect', '--campaign', hostBState, '--json'], cliEnv); + assert.equal(inspectRes.status, 0, inspectRes.stdout + inspectRes.stderr); + const inspectData = JSON.parse(inspectRes.stdout.trim()).data as { + islands: readonly { islandId: number; currentGeneration: number }[]; + individuals: readonly { individualId: string; status: string; generation: number }[]; + lineageEdges: readonly { childIndividualId: string; parentIndividualId: string }[]; + modelBanditArms: readonly { modelId: string; pullCount: number }[]; + }; + assert.equal(inspectData.islands.length, 1); + assert.equal(inspectData.individuals.filter(i => i.status === 'passed').length, 2); + assert.ok(inspectData.lineageEdges.length >= 1, 'resumed generation must record lineage from imported parent'); + assert.ok(inspectData.modelBanditArms.some(arm => arm.pullCount >= 2), 'bandit arm pull counts must continue'); + + const hostBStore = await EvolutionCampaignStore.open({ campaignRoot: hostBState, createIfMissing: false }); + try { + const prov = await hostBStore.getSnapshotProvenance(resumedEnv.data.campaign.campaignId); + assert.ok(prov !== null, 'snapshot_provenance row must persist across resume'); + assert.equal(prov.snapshotDigest.hex, hostAExport.manifestDigest.hex); + } finally { + await hostBStore.close(); + } + + // 4. Re-exporting a snapshot from Host B via CLI chains parentDigest from snapshot_provenance + const export2Res = await runCliInProcess([ + 'evolve', 'export', '--campaign', hostBState, '--snapshot', '--out', snapDir2, + '--allow-synthetic-probe', '--receipt-secret-env', 'SNAP_RECEIPT_SECRET', '--json', + ], cliEnv); + assert.equal(export2Res.status, 0, export2Res.stdout + export2Res.stderr); + const export2Data = JSON.parse(export2Res.stdout.trim()).data as { + parentDigest?: Digest; + receiptCount: number; + }; + assert.equal(export2Data.parentDigest?.hex, hostAExport.manifestDigest.hex); + assert.equal(export2Data.receiptCount, 2); + } finally { + workerAbort.abort(); + await workerPromise; + await relay.close(); + await new Promise(resolveClose => sseServer.close(() => resolveClose())); + for (const [k, v] of Object.entries(savedEnv)) { + if (v === undefined) delete process.env[k]; + else process.env[k] = v; + } + await rm(root, { recursive: true, force: true }); + } + assert.equal(workerFatalError, null); +}); diff --git a/packages/evolution/src/snapshot.ts b/packages/evolution/src/snapshot.ts index 1fa974f6..b7aa5718 100644 --- a/packages/evolution/src/snapshot.ts +++ b/packages/evolution/src/snapshot.ts @@ -979,7 +979,6 @@ export async function writeCampaignSnapshot(options: WriteCampaignSnapshotOption ); } const parsed = await verifyIndividualReceiptBytes(rawBytes, ind, { - expectedLockHash: campaign.lockHash, expectedTargetCellId: campaign.manifest.spec.targetCellId, allowSyntheticProbe: resolved.allowSyntheticProbe, allowHostAttested: resolved.allowHostAttested, @@ -1422,7 +1421,6 @@ async function loadAndVerifySnapshot(options: VerifyCampaignSnapshotOptions): Pr ); } const parsed = await verifyIndividualReceiptBytes(bytes, ind, { - expectedLockHash: campaign.lockHash, expectedTargetCellId: campaign.manifest.spec.targetCellId, allowSyntheticProbe: resolved.allowSyntheticProbe, allowHostAttested: resolved.allowHostAttested, diff --git a/scripts/check-docs.mjs b/scripts/check-docs.mjs index de828a31..fea5af2c 100755 --- a/scripts/check-docs.mjs +++ b/scripts/check-docs.mjs @@ -97,7 +97,8 @@ export const PUBLIC_SITE_DOC_REL_PATHS = new Set([ "docs/configuration/controller-and-registry.md", "docs/configuration/sandbox-backends.md", "docs/configuration/decision-routing.md", - "docs/configuration/evolution-campaign.md" + "docs/configuration/evolution-campaign.md", + "docs/configuration/campaign-snapshots.md" ]); export const REPO_ONLY_DOC_REL_PATHS = new Set([ "docs/development.md", diff --git a/site/content/docs/_index.md b/site/content/docs/_index.md index d51373ea..e6aaf2b9 100644 --- a/site/content/docs/_index.md +++ b/site/content/docs/_index.md @@ -33,3 +33,4 @@ Loopwright supports two operating modes sharing one verification kernel: **Decla - [Sandbox Backends](configuration/sandbox-backends/) covers native OS and container sandbox policies and capabilities. - [Decision Routing](configuration/decision-routing/) details System-One advisory confidence zones, providers, and disclosure policies. - [Evolution Campaign](configuration/evolution-campaign/) configures islands, specialist-to-portfolio stages, team evolution, and bundle export in `campaign.yaml` (`EvolutionCampaign`). +- [Campaign Snapshots](configuration/campaign-snapshots/) defines the portable `campaign-snapshot.v1` layout, fail-closed receipt gates, and fresh-authority import across hosts. diff --git a/site/data/navigation.yaml b/site/data/navigation.yaml index 2a9cc3da..c583026b 100644 --- a/site/data/navigation.yaml +++ b/site/data/navigation.yaml @@ -23,6 +23,7 @@ groups: - /docs/configuration/sandbox-backends/ - /docs/configuration/decision-routing/ - /docs/configuration/evolution-campaign/ + - /docs/configuration/campaign-snapshots/ labels: /docs/getting-started/architecture/: Architecture @@ -41,3 +42,4 @@ labels: /docs/configuration/sandbox-backends/: Sandbox Backends /docs/configuration/decision-routing/: Decision Routing /docs/configuration/evolution-campaign/: Evolution Campaign + /docs/configuration/campaign-snapshots/: Campaign Snapshots diff --git a/site/layouts/index.html b/site/layouts/index.html index 10741277..c1cb2080 100644 --- a/site/layouts/index.html +++ b/site/layouts/index.html @@ -73,6 +73,7 @@

ConfigurationSandbox Backends
  • Decision Routing
  • Evolution Campaign
  • +
  • Campaign Snapshots
  • diff --git a/specs/2026-11-30-managed-controller-in-process-execution.md b/specs/2026-11-30-managed-controller-in-process-execution.md index 91b8269d..15d678dd 100644 --- a/specs/2026-11-30-managed-controller-in-process-execution.md +++ b/specs/2026-11-30-managed-controller-in-process-execution.md @@ -607,7 +607,7 @@ and T11 have disjoint `Owns:` and start together; T5 follows T2. Gate: review Acceptance: `writeCampaignSnapshot(store, outDir, { parentDigest })` writes the F4 members, includes every individual with its status and `receipt: null` when no approved receipt exists, verifies receipts fail-closed, and refuses `synthetic_fixture` without the flag; `verifyCampaignSnapshot(bundleDir, { receiptSecret })` validates offline; `importCampaignSnapshot(bundleDir, stateDir, { receiptSecret })` refuses a non-empty state directory, creates a fresh `campaign_meta` and a `snapshot_provenance` row, copies the search tables verbatim, and never copies clock or fence columns. `HardwareProvenance` gains the optional `isolation` field in core and in the evolution parser; `exportEvolutionBundle` refuses `host_attested` receipts without the flag and accepts them with it. Land that field edit first: T11 produces it. Verify: `node scripts/run-tests.mjs --pkg evolution --concurrency 1` -- [ ] **T10 · Snapshot CLI and documentation (phase 2)** +- [x] **T10 · Snapshot CLI and documentation (phase 2)** Blocked by: T8, T9 Owns: `packages/cli/src/evolve.ts`, `packages/cli/src/main.ts`, `packages/cli/src/arguments.ts`, `packages/cli/test/evolve-snapshot.test.ts`, `docs/configuration/campaign-snapshots.md`, `docs/contribute/internals.md`, `docs/operations/cli.md`, `docs/README.md`, `site/data/navigation.yaml` Acceptance: `evolve export --snapshot`, `evolve check --bundle`, and `evolve import` exist with `--receipt-secret-env` (optional when the snapshot contains no signed receipts, required fail-closed when any individual has a non-null receipt), `--allow-synthetic-probe`, and `--allow-host-attested`, and exit codes consistent with the other `evolve` commands; `evolve-snapshot.test.ts` asserts the real `evolve resume` continuation on a host with a lower monotonic clock; `docs/contribute/internals.md` lists the `snapshot_provenance` table; `docs/README.md` and the site navigation index the new page; `lint:docs` and `site` pass. From 1c8f599680659b74ac188b2781b4abfdf5840067 Mon Sep 17 00:00:00 2001 From: thxCode Date: Tue, 1 Dec 2026 23:50:17 +0800 Subject: [PATCH 21/26] docs(hardware-runner): document namespaces_blocked probe verdict and hardwareProvenance.isolation - Document in docs/operations/cli.md that loopwright runner inline and deviceOwnership: host are not implemented in this version due to the recorded namespaces_blocked probe under PSA restricted, pointing isolated-Pod users to command.v1 (direct) and adapter: exec. - Document optional hardwareProvenance.isolation (docker | host_attested) fail-closed semantics in docs/configuration/task-contract.md. - Expand the in-process-benchmark-gate-hardware blocked_external explanation in docs/contribute/closure-matrix.md and update docs/README.md index entries. - Check off T12 in the spec; lint:docs (37 pages, 0 errors), Hugo site (20 HTML / 17 Markdown, 0 broken links), and docs/closure tests pass. Signed-off-by: thxCode --- docs/README.md | 4 ++-- docs/configuration/task-contract.md | 2 ++ docs/contribute/closure-matrix.md | 6 +++++- docs/operations/cli.md | 4 ++++ specs/2026-11-30-managed-controller-in-process-execution.md | 2 +- 5 files changed, 14 insertions(+), 4 deletions(-) diff --git a/docs/README.md b/docs/README.md index 1bd00d5a..8904fb6e 100644 --- a/docs/README.md +++ b/docs/README.md @@ -49,7 +49,7 @@ ### Bounded Controller and CLI - ID: controller -- Use for: compile trusted configuration and coordinate bounded runs +- Use for: compile trusted configuration, coordinate bounded or isolated-host runs, export campaign snapshots, and audit hardware gate closure - Aliases: controller - Guides: [getting-started/installation.md](getting-started/installation.md), [walkthroughs/managed-controller.md](walkthroughs/managed-controller.md), [walkthroughs/managed-controller-in-isolated-host.md](walkthroughs/managed-controller-in-isolated-host.md), [walkthroughs/evolutionary-campaign.md](walkthroughs/evolutionary-campaign.md), [configuration/controller-and-registry.md](configuration/controller-and-registry.md), [configuration/evolution-campaign.md](configuration/evolution-campaign.md), [configuration/campaign-snapshots.md](configuration/campaign-snapshots.md), [operations/cli.md](operations/cli.md), [operations/coding-agents.md](operations/coding-agents.md), [contribute/closure-matrix.md](contribute/closure-matrix.md) - Specs: [Specification](../specs/2026-11-06-bounded-controller-and-trusted-config.md), [Delegated Stepping](../specs/2026-11-14-delegated-role-stepping-and-multi-model-routing.md), [Multi-Domain Suites, Handoffs, and RunEval](../specs/2026-11-21-multi-domain-suite-handoff-and-run-eval.md), [Hardware Execution and Remote Runner](../specs/2026-11-21-hardware-execution-benchmark-gate-and-remote-runner.md), [Evolutionary Campaigns, Pareto Archive, and Bundle Export](../specs/2026-11-23-evolutionary-campaigns-pareto-archive-and-bundle-export.md), [Managed Controller In-Process Execution](../specs/2026-11-30-managed-controller-in-process-execution.md) @@ -139,7 +139,7 @@ | [2026-11-21-hardware-execution-benchmark-gate-and-remote-runner.md](../specs/2026-11-21-hardware-execution-benchmark-gate-and-remote-runner.md) | Hardware execution, benchmark-gate.v1, and outbound remote runner | | [2026-11-21-multi-domain-suite-handoff-and-run-eval.md](../specs/2026-11-21-multi-domain-suite-handoff-and-run-eval.md) | Multi-domain `TaskpackSuite`, compact handoffs, conditional rules, `RunEval`, and baseline alignment | | [2026-11-23-evolutionary-campaigns-pareto-archive-and-bundle-export.md](../specs/2026-11-23-evolutionary-campaigns-pareto-archive-and-bundle-export.md) | Evolutionary campaigns (`@loopwright/evolution`), `evolve-block-guard.v1`, plateau `teamEvolution`, `hardwareScope`, and `evolution-bundle.v1` | -| [2026-11-30-managed-controller-in-process-execution.md](../specs/2026-11-30-managed-controller-in-process-execution.md) | Managed Controller `command.v1` under `direct`, `exec` role adapter, and portable campaign state | +| [2026-11-30-managed-controller-in-process-execution.md](../specs/2026-11-30-managed-controller-in-process-execution.md) | Isolated-host `command.v1` (`direct`), `exec` adapter, portable campaign snapshots, and blocked in-process hardware gate probe | ## All pages diff --git a/docs/configuration/task-contract.md b/docs/configuration/task-contract.md index f7353b6a..981243e5 100644 --- a/docs/configuration/task-contract.md +++ b/docs/configuration/task-contract.md @@ -174,6 +174,8 @@ Each `spec.target.matrix[]` cell accepts an optional `hardware` block (`accelera - **Metric thresholds**: `metricThresholds[]` (`0..32`) enforces `bounds` or `comparative` (`min_ratio`/`max_ratio`/`max_delta`) rules across optional `bucketScope`. - **Physical provenance**: `hardware_execution` requires `hardwareProvenance` with `probeKind: 'physical'` unless `allowSyntheticHardwareProbe: true`, failing closed on mismatch (`hardware_provenance_mismatch`, `metric_threshold_failed`). +- **Provenance isolation**: Optional `hardwareProvenance.isolation` (`docker` | `host_attested`) marks receipt isolation; absent marks pre-field Docker receipts. `benchmark-gate.v1` accepts `docker` and refuses `host_attested` fail-closed. +- **Host-attested gate**: Evolution export, check, and import refuse `host_attested` without `--allow-host-attested`. No worker emits `host_attested` in this version because `deviceOwnership: host` and `runner inline` remain unimplemented after `namespaces_blocked`. --- diff --git a/docs/contribute/closure-matrix.md b/docs/contribute/closure-matrix.md index 1adaf6b9..a79b5f4a 100644 --- a/docs/contribute/closure-matrix.md +++ b/docs/contribute/closure-matrix.md @@ -40,7 +40,11 @@ resolves to a committed regular file in the repository. Non-passed rows must car `external-build-and-accelerator-matrix` lists `@loopwright/hardware-runner` evidence paths (`relay-server.ts`, `worker.ts`, `evaluator.ts`, `e2e-nat-loopback.test.ts`, and `docs/configuration/sandbox-backends.md`). -`in-process-benchmark-gate-hardware` records the `namespaces_blocked` probe (`packages/hardware-runner/test/bwrap-namespace-probe.test.ts` and `packages/hardware-runner/test/fixtures/bwrap-namespace-probe/evidence/restricted-probe-output.jsonl`). Both stay `blocked_external` (`20` `closedLocal`, `6` `unprovisionedExternal`) until signed `ExternalQualificationReceipt` records are attached (`CLOSURE_FALSIFICATION_FORBIDDEN`). +`in-process-benchmark-gate-hardware` records the `namespaces_blocked` feasibility probe in `packages/hardware-runner/test/bwrap-namespace-probe.test.ts` and its tracked JSONL evidence under `packages/hardware-runner/test/fixtures/bwrap-namespace-probe/evidence/`. Under Pod Security Admission `restricted`, `RuntimeDefault` seccomp denies `clone(CLONE_NEWUSER)`, and Ubuntu `kernel.apparmor_restrict_unprivileged_userns=1` still blocks user-namespace setup under relaxed seccomp. + +Consequently, `loopwright runner inline` and `deviceOwnership: host` are intentionally not implemented in this version. The optional `hardwareProvenance.isolation` field (`docker` | `host_attested`) exists in the schema, and `benchmark-gate.v1` plus evolution snapshot/bundle commands refuse `host_attested` fail-closed without opt-in. + +Both `blocked_external` rows stay blocked (`20` `closedLocal`, `6` `unprovisionedExternal`) until signed `ExternalQualificationReceipt` records are attached (`CLOSURE_FALSIFICATION_FORBIDDEN`). ## Non-falsification invariant diff --git a/docs/operations/cli.md b/docs/operations/cli.md index 0b0daa8e..a0f41eb9 100644 --- a/docs/operations/cli.md +++ b/docs/operations/cli.md @@ -124,6 +124,10 @@ loopwright runner worker --config worker.yaml --once --json `runner relay` isolates controller HMAC secrets from worker tokens, enforces `leaseEpoch` fencing, and streams `1 MiB` CAS artifacts so private GPU workers open zero inbound ports. Workers compile Stage A without `held_out_workloads` and execute Stage B read-only with `networkMode: none`. +`loopwright runner inline` and `deviceOwnership: host` are not implemented in this version. The Pod Security Admission `restricted` feasibility probe recorded `namespaces_blocked` because `RuntimeDefault` seccomp denies `clone(CLONE_NEWUSER)`. + +Single-host isolated Pod runs use Managed Controller `command.v1` (`direct`) and `adapter: exec` instead; see [Managed Controller in Isolated Host](../walkthroughs/managed-controller-in-isolated-host.md). + ### Evolution campaigns ```sh diff --git a/specs/2026-11-30-managed-controller-in-process-execution.md b/specs/2026-11-30-managed-controller-in-process-execution.md index 15d678dd..3cf6ec4a 100644 --- a/specs/2026-11-30-managed-controller-in-process-execution.md +++ b/specs/2026-11-30-managed-controller-in-process-execution.md @@ -619,7 +619,7 @@ and T11 have disjoint `Owns:` and start together; T5 follows T2. Status: blocked_external (2026-12-01). The probe ran under PSA `restricted` on kind v0.33 (Kubernetes 1.37, containerd 2.3.4, kernel 6.17) and settled `namespaces_blocked`: RuntimeDefault seccomp denies namespace creation (`clone(CLONE_NEWUSER)` -> `EPERM`), and even with seccomp relaxed (which PSA `restricted` forbids) the host's Ubuntu `kernel.apparmor_restrict_unprivileged_userns=1` transition kept `unconfined` processes from setting up userns uid mapping/loopback; Landlock ABI was not probed via syscall. Stage 1 is delivered (`packages/hardware-runner/test/bwrap-namespace-probe.test.ts` holds `RECORDED_PROBE_OUTCOME`); no feature code was written and the stage-2 `Owns:` widenings are void. Acceptance: first, a recorded probe decides whether `native_os` can create its namespaces under the target Pod profile (RuntimeDefault seccomp, all capabilities dropped); if it cannot, the task reports that and stops before any feature code. Then `deviceOwnership: host` permits `sandboxBackend: native_os` with `probeMode: physical`, `hardwareProvenance.isolation` (the optional T9 field) records `docker` or `host_attested`, and `loopwright runner inline --config worker.yaml` serves relay and worker in one process on loopback; a loopback end-to-end test runs `benchmark-gate.v1` through the inline runner on `synthetic_fixture`; the physical evidence row stays `blocked_external`. Verify: `node scripts/run-tests.mjs --pkg hardware-runner && node scripts/run-tests.mjs --pkg cli` -- [ ] **T12 · In-process gate documentation (phase 2)** +- [x] **T12 · In-process gate documentation (phase 2)** Blocked by: T8, T10, T11 Owns: `docs/operations/cli.md`, `docs/configuration/task-contract.md`, `docs/contribute/closure-matrix.md`, `docs/README.md` Acceptance: the feasibility probe, its recorded `namespaces_blocked` verdict, the `isolation` field, and the `blocked_external` row are documented and indexed; `runner inline` and `deviceOwnership` are documented as not implemented in this version because the probe blocked them. From c027f83242445ce47195a23d8d6c4b6b9a78e365 Mon Sep 17 00:00:00 2001 From: thxCode Date: Wed, 2 Dec 2026 00:14:38 +0800 Subject: [PATCH 22/26] docs(references): sync Zone 2 reference tables and mark spec shipped - Add command.v1, host.localChecks, exec role profiles, and consumer: exec to controller-and-registry-schema.md. - Update cli-and-action-reference.md for the 26-row closure matrix, evolve import, --snapshot, and --bundle. - Add exec adapter, host_execution, and hardwareProvenance.isolation to taskpack-and-contract-schema.md and README.md. - Advance specs/2026-11-30-managed-controller-in-process-execution.md Status to Shipped. Signed-off-by: thxCode --- docs/references/README.md | 4 ++-- docs/references/cli-and-action-reference.md | 9 +++++---- docs/references/controller-and-registry-schema.md | 12 +++++++----- docs/references/taskpack-and-contract-schema.md | 6 +++--- ...-11-30-managed-controller-in-process-execution.md | 2 +- 5 files changed, 18 insertions(+), 15 deletions(-) diff --git a/docs/references/README.md b/docs/references/README.md index dd3f7106..84417f8d 100644 --- a/docs/references/README.md +++ b/docs/references/README.md @@ -30,7 +30,7 @@ Flat machine-readable reference hub for Loopwright schemas, CLI flags, Action in | `AttemptReceipt` | Resource kind | [Taskpack and Contract Reference](taskpack-and-contract-schema.md#receipts-and-evidence) | | `ArtifactManifest` | Contract schema | [Taskpack and Contract Reference](taskpack-and-contract-schema.md#receipts-and-evidence) | | `EvolutionCampaign` | Resource kind | [Taskpack and Contract Reference](taskpack-and-contract-schema.md#evolutioncampaign-bounds) | -| `evolution-bundle.v1` | Export format | [Taskpack and Contract Reference](taskpack-and-contract-schema.md#evolutioncampaign-bounds) | +| `evolution-bundle.v1` / `campaign-snapshot.v1` | Export formats | [Taskpack and Contract Reference](taskpack-and-contract-schema.md#evolutioncampaign-bounds) · [Campaign Snapshots](../configuration/campaign-snapshots.md) | | `TrustedRegistry` | Resource kind | [Controller and Registry Reference](controller-and-registry-schema.md#registry-and-handlers) | | `ControllerConfig` | Resource kind | [Controller and Registry Reference](controller-and-registry-schema.md#controllerconfig-bounds) | | `DecisionPolicy` | Resource kind | [Controller and Registry Reference](controller-and-registry-schema.md#decisionpolicy-schema) | @@ -42,7 +42,7 @@ Flat machine-readable reference hub for Loopwright schemas, CLI flags, Action in | `loopwright step next\|submit\|cancel` | CLI coroutine | [Coding Agent Protocol Reference](coding-agent-protocol.md#stepyield-schema) | | `StepYield` | JSON envelope | [Coding Agent Protocol Reference](coding-agent-protocol.md#stepyield-schema) | | `candidate.files.json` | Inspect bundle | [Coding Agent Protocol Reference](coding-agent-protocol.md#overlay-apply-script) | -| `command.v1` / `benchmark-gate.v1` | Check handlers | [Taskpack and Contract Reference](taskpack-and-contract-schema.md#verifiers-and-mounts) | +| `command.v1` / `benchmark-gate.v1` | Check handlers | [Taskpack Ref](taskpack-and-contract-schema.md#verifiers-and-mounts) · [Controller Ref](controller-and-registry-schema.md#registry-and-handlers) | | `environmentBindings` | Env allowlist | [Controller and Registry Reference](controller-and-registry-schema.md#credentials-and-interpolation) | | `DECISION_FORBIDDEN_AUTHORITY_INTENTS` | Guard list | [Controller and Registry Reference](controller-and-registry-schema.md#advisory-port-hooks) | diff --git a/docs/references/cli-and-action-reference.md b/docs/references/cli-and-action-reference.md index 213198d1..48246c5a 100644 --- a/docs/references/cli-and-action-reference.md +++ b/docs/references/cli-and-action-reference.md @@ -90,18 +90,19 @@ CLI limits total `argv` to `64` entries and repeatable `--role-model ROLE=PROVID | `resume` | `--config`, `--registry`, `--registry-sha256`, `--repo`, `--run-root`, `--run-id` | `--role-model`, `--allow-privileged`, `--allow-workflow-writes`, `--json`, `--output-format`, `--step-summary-file` | Resume an existing run under identical trusted bindings | | `step` | `--run-root`, `--run-id`, action (`next\|submit\|cancel`) | `--action`, `--taskpack` or config flags, `--repo`, `--mode`, `--role-model`, `--reissue-lease`, `--lease`, `--status`, `--submission-file`, `--reason`, privilege flags, `--json` | Pull, submit, or cancel delegated work | | `status` | `--run-root`, `--run-id` | `--json` | Read current run stage, lease state, and checkpoint summary | -| `inspect` | `--run-root`, `--run-id` | `--output`, `--json` | Export redacted receipts, `candidate.files.json`, `run-eval.json`, and diagnostics | +| `inspect` | `--run-root`, `--run-id` | `--output`, `--json` | Export redacted receipts, `verifier-receipts.json`, `usage.json`, `candidate.files.json`, and `run-eval.json` | | `reconcile` | `--config`, `--registry`, `--registry-sha256`, `--repo`, `--run-root`, `--run-id`, `--receipt` | `--allow-workflow-writes`, `--output`, `--json`, `--output-format`, `--step-summary-file` | Settle an unknown external outcome with an authenticated receipt | -| `closure` | None | `--repo`, `--output`, `--verify-failures`, `--json` | Audit the 23-capability closure matrix and 14-case failure suite | +| `closure` | None | `--repo`, `--output`, `--verify-failures`, `--json` | Audit the 26-capability closure matrix and 14-case failure suite | | `app-serve` | `--config` | `--repo`, `--json` | Start the opt-in GitHub App HTTP webhook and token listener | | `runner relay` | `--config` | `--json` | Start the outbound-pull benchmark relay and CAS server | | `runner worker` | `--config` | `--once`, `--json` | Poll relay leases and execute two-stage hardware benchmarks | -| `evolve check` | `--campaign` | `--repo`, `--json` | Validate an `EvolutionCampaign`, taskpack, and target cell | +| `evolve check` | `--campaign` or `--bundle` | `--repo` (with `--campaign`), `--receipt-secret-env`, `--allow-synthetic-probe`, `--allow-host-attested`, `--json` | Validate an `EvolutionCampaign` manifest or offline `campaign-snapshot.v1` directory | | `evolve run` | `--campaign`, `--state` | `--repo`, `--out`, `--format`, `--allow-synthetic-probe`, `--json` | Run an evolutionary campaign over isolated child runs | | `evolve resume` | `--campaign` (or `--root`) | `--repo`, `--out`, `--format`, `--allow-synthetic-probe`, `--json` | Resume a paused or preempted campaign from `campaign.sqlite` | | `evolve status` | `--campaign` (or `--root`) | `--json` | Read campaign stage, generation, evaluations, and island state | | `evolve inspect` | `--campaign` (or `--root`) | `--island`, `--individual`, `--json` | Inspect Pareto frontier, niches, teams, and lineage edges | -| `evolve export` | `--campaign` (or `--root`), `--out` | `--format`, `--allow-synthetic-probe`, `--overwrite`, `--json` | Export a verified `evolution-bundle.v1` package | +| `evolve export` | `--campaign` (or `--root`), `--out` | `--snapshot`, `--format`, `--receipt-secret-env`, `--allow-synthetic-probe`, `--allow-host-attested`, `--overwrite`, `--json` | Export a verified `evolution-bundle.v1` package or `campaign-snapshot.v1` directory | +| `evolve import` | `--bundle`, `--state` | `--receipt-secret-env`, `--allow-synthetic-probe`, `--allow-host-attested`, `--json` | Verify a `campaign-snapshot.v1` directory and initialize a fresh `campaign.sqlite` authority | ### Runner and evolve environment diff --git a/docs/references/controller-and-registry-schema.md b/docs/references/controller-and-registry-schema.md index a3233f8b..02c321a2 100644 --- a/docs/references/controller-and-registry-schema.md +++ b/docs/references/controller-and-registry-schema.md @@ -16,17 +16,18 @@ Machine-readable field, bound, enum, interpolation, and hook dictionary for `Tru ## Registry and handlers -Store `TrustedRegistry` (`registry.yaml`, `metadata.name` `1..64` chars) outside `cwd`, outside `dirname(controller.yaml)`, and outside `--repo` (`REGISTRY_UNTRUSTED` otherwise). Top-level `spec` requires `version: 1`, `resourceVersion`, `handlers`, `roleProfiles`, `resources`, `runtimeProfiles`, `credentialBindings`, and `environmentBindings`; `gateEndpoints` and `publicationEndpoints` are optional (`0..16` items). +Store `TrustedRegistry` (`registry.yaml`, `metadata.name` `1..64` chars) outside `cwd`, outside `dirname(controller.yaml)`, and outside `--repo` (`REGISTRY_UNTRUSTED` otherwise). Top-level `spec` requires `version: 1`, `resourceVersion`, `handlers`, `roleProfiles`, `resources`, `runtimeProfiles`, `credentialBindings`, and `environmentBindings`; `host` (`localChecks: { backend: 'direct' }`), `gateEndpoints`, and `publicationEndpoints` (`0..16`) are optional. | Implementation | `kind` | Required `capabilities` | Required `parameters` keys | | --- | --- | --- | --- | | `pi.agent.v1` | `agent` | `['pi']` | `prompt` (string), `purpose` (`'task'` or `'review'`) | -| `pi.compact.v1` | `agent` | `['pi', 'compaction']` | `{}` (empty mapping; cannot target delegated roles) | +| `pi.compact.v1` | `agent` | `['pi', 'compaction']` | `{}` (empty mapping; cannot target delegated or `exec` roles) | | `scope.v1` | `check` | `['inert_bytes', 'read_only']` | `checkId` (identifier or `null` for implicit guard) | | `json-artifact.v1` | `check` | `['inert_bytes', 'read_only']` | `checkId`, `path`, `required` (key list), `equals` (scalar map) | | `json-keys-guard.v1` | `check` | `['inert_bytes', 'read_only']` | `checkId`, `path`, `allowedPointers` (JSON pointer list) | | `line-section-guard.v1` | `check` | `['inert_bytes', 'read_only']` | `checkId`, `path`, `startMarker`, `endMarker` | | `no-change.v1` | `check` | `['inert_bytes', 'read_only']` | `checkId` (identifier or `null` for implicit comparison) | +| `command.v1` | `check` | `['host_execution']` | `checkId`, `script`, `args`, `env`, `toolchainPaths`, `timeoutMs` (`1000..3600000`; requires `host.localChecks.backend: direct`) | | `gate.v1` | `check` | `['external_service', 'read_only']` | `checkId`, `endpointRef` (`gateEndpoints[].id`), `gateId` | | `benchmark-gate.v1` | `check` | `['hardware_execution', 'read_only']` | `checkId`, `endpointRef`, `gateId`, `heldOutWorkloadId`, optional `maxPreemptions` (`0..16`) | @@ -34,15 +35,16 @@ Store `TrustedRegistry` (`registry.yaml`, `metadata.name` `1..64` chars) outside ### Role and runtime fields -`roleProfiles[]` accepts `adapter: 'pi'` or `'delegated'`. Secret-free delegated profiles set `runtimeRef: null`, `providerCredentialRef: null`, and `mcp: null`, defaulting `context` to `DEFAULT_DELEGATED_CONTEXT`. Unattended `run`/`resume` refuse active or parked delegated roles (`CAPABILITY_UNSUPPORTED`). `ControllerConfig.spec.profiles.roles[]` accepts optional `selection` (`provider`, `model`, `thinking`); CLI `--role-model` takes precedence and persists in `run.json`. +`roleProfiles[]` accepts `adapter: 'pi'`, `'delegated'`, or `'exec'`. Delegated and `exec` profiles set `runtimeRef: null`, `providerCredentialRef: null`, and `mcp: null`. Unattended `run`/`resume` admit all-`exec` plans (refusing mixed plans with `CONFIG_SCHEMA`) and refuse delegated roles; `step` refuses `exec` plans (`CAPABILITY_UNSUPPORTED`). `ControllerConfig.spec.profiles.roles[]` accepts optional `selection`; `--role-model` takes precedence. | Field path | Required | Values and bounds | Meaning | | --- | --- | --- | --- | | `roleProfiles[].id` | Yes | Identifier (`1..64` chars) | Unique role profile ID referenced by `ControllerConfig` | | `roleProfiles[].selection` | Yes | `{ provider, model, thinking, api, customProvider? }` | `thinking`: `off..max`; `api`: `anthropic-messages`, `openai-completions`, `openai-responses` | | `roleProfiles[].tools` | Yes | Subset of `read`, `write`, `edit`, `bash`, `codemode`, `mcp__workspace__read_file` | Host-approved tool ceiling for bound task roles | -| `roleProfiles[].runtimeRef` | Yes | `runtimeProfiles[].id` or `null` for delegated | Binds a Pi role to a verified runtime identity | +| `roleProfiles[].runtimeRef` | Yes | `runtimeProfiles[].id`, or `null` for `delegated`/`exec` | Binds a Pi role to a verified runtime identity | | `roleProfiles[].providerCredentialRef` | Yes | `credentialBindings[].id` or `null` | Selects the `provider` credential injected into the broker | +| `roleProfiles[].exec` | Conditional | `command` (`1..64`, abs `[0]`), `args?`, `env?`, `credentialRefs?`, `timeoutMs` (`1..3600000`), `captureBytes?` | Required when `adapter: 'exec'`; `captureBytes`: `1024..1048576` (default `65536`) | | `roleProfiles[].limits` | No | Positive integer map | Optional `promptBytes`, `responseBytes`, `toolArgsBytes`, `toolResultBytes`, `sessionBytes`, `fileBytes`, `candidateEntries`, `toolWallMs` | | `runtimeProfiles[].id` | Yes | Identifier (`1..64` chars) | Unique runtime profile ID | | `runtimeProfiles[].dockerExecutable` / `dockerSocket` | Yes | Absolute host paths | Verified container binary and UNIX socket paths | @@ -71,7 +73,7 @@ Secrets resolve in memory into a `CredentialVault` (`vault.assertClean` aborts i | Field path | Required | Values and bounds | Meaning | | --- | --- | --- | --- | | `credentialBindings[].id` | Yes | Identifier (`1..64` chars) | Unique credential ID referenced by profiles or endpoints | -| `credentialBindings[].consumer` | Yes | `'provider'` \| `'mcp'` \| `'gate'` \| `'publisher'` | Subsystem restriction for resolved secret | +| `credentialBindings[].consumer` | Yes | `'provider'` \| `'mcp'` \| `'gate'` \| `'publisher'` \| `'exec'` | Subsystem restriction for resolved secret | | `credentialBindings[].destinationRef` | Yes | Identifier (`1..64` chars) | Target service identifier bound to the credential | | `credentialBindings[].environmentNames` | Yes | Env var list (`[A-Za-z_][A-Za-z0-9_]*`) | Host environment variables permitted inside `template` | | `credentialBindings[].template` | Yes | Template string (`${ENV_VAR}`) | Secret assembly pattern matched identically in `ControllerConfig.spec.credentials` | diff --git a/docs/references/taskpack-and-contract-schema.md b/docs/references/taskpack-and-contract-schema.md index ef4d3b55..62a612b0 100644 --- a/docs/references/taskpack-and-contract-schema.md +++ b/docs/references/taskpack-and-contract-schema.md @@ -111,11 +111,11 @@ Strict `contractSchema` validation (`<= 1 MiB` input) requires `apiVersion`, `ki | `spec.scope.writable` / `protected` | Yes | `1..128` / `0..128` globs | Relative path globs; protected overrides writable | | `trustedContext.revision` / `discovery` | Yes | `1..128` chars / `'disabled'` | Pinned context revision with runtime prompt discovery disabled | | `trustedContext.resources[]` | Yes | `0..128` items (`<= 1 MiB` total) | `{ id, kind: 'instruction'\|'skill'\|'document', path, digest: { algorithm: 'sha256', hex }, when? }` | -| `spec.roles[]` | Yes | `1..64` roles | `{ id, adapter: 'pi'\|'delegated', provider, model, thinking, tools (0..128), resourceIds? (0..128) }` | +| `spec.roles[]` | Yes | `1..64` roles | `{ id, adapter: 'pi'\|'delegated'\|'exec', provider, model, thinking, tools (0..128), resourceIds? (0..128) }` | | `spec.steps[]` | Yes | `1..256` nodes (`<= 2048` edges, `<= 256` checkpoints) | `{ id, kind: 'agent'\|'check', uses, roleId, dependsOn, onRework?, handoffs? }` | | `spec.budgets.*` | Yes | Positive ints (`<= parent`) | `wallTimeMs`, `totalTokens`, `perCallOutputTokens` (`<= 262144`), `maxModelCalls`, `maxConcurrency`, repair/retry caps, `enforcement.*` (7 keys) | | `spec.budgets.overlay` | No | `maxFiles: 1..16384`, `maxBytes: 1024..16 GiB` | Optional candidate overlay limits (default `128` files / `4 MiB`) | -| `spec.acceptance.required` / `checks` | Yes | `1..256` IDs / `1..256` check objects | `{ id, allowedEvidenceLevels (1..5), targetCellId?, allowSyntheticHardwareProbe?, metricThresholds? (0..32) }` | +| `spec.acceptance.required` / `checks` | Yes | `1..256` IDs / `1..256` check objects | `{ id, allowedEvidenceLevels (1..6, incl. host_execution), targetCellId?, allowSyntheticHardwareProbe?, metricThresholds? (0..32) }` | ### Activation and handoff selectors @@ -141,7 +141,7 @@ Strict `contractSchema` validation (`<= 1 MiB` input) requires `apiVersion`, `ki | `hardware.maxRegisterCount` / `maxLocalSpillBytes` | No | Safe integer (`>= 0`) | Stage A register and local spill ceilings (`STAGE_A_STATIC_AUDIT_FAILED`) | | `metricThresholds[]` | No | `0..32` `bounds` or `comparative` | `bounds`: `{ metric, min?, max? }`; `comparative`: `min_ratio\|max_ratio\|max_delta`; optional `bucketScope` | -- **`hardwareProvenance` fields**: Passing `hardware_execution` `Evidence` requires `targetCellId`, `probeKind: 'physical' | 'synthetic_fixture'`, `vendor`, `deviceModel`, `accelerator`, `isolationMode`, `deviceCount`, `driverVersion`, `runtimeVersion`, `topology?`, `workloadDigest`, and `clockLockMode: 'locked' | 'unlocked' | 'unknown'`. `evaluateAcceptance` requires `probeKind: 'physical'` unless `allowSyntheticHardwareProbe: true` (`hardware_provenance_mismatch`, `metric_threshold_failed`). +- **`hardwareProvenance` fields**: Passing `hardware_execution` `Evidence` requires `targetCellId`, `probeKind: 'physical' | 'synthetic_fixture'`, `vendor`, `deviceModel`, `accelerator`, `isolationMode`, `deviceCount`, `driverVersion`, `runtimeVersion`, `topology?`, `isolation?: 'docker' | 'host_attested'`, `workloadDigest`, and `clockLockMode: 'locked' | 'unlocked' | 'unknown'`. `benchmark-gate.v1` refuses `host_attested` fail-closed; evolution export/check/import requires `--allow-host-attested`. ## EvolutionCampaign bounds diff --git a/specs/2026-11-30-managed-controller-in-process-execution.md b/specs/2026-11-30-managed-controller-in-process-execution.md index 3cf6ec4a..55be69e4 100644 --- a/specs/2026-11-30-managed-controller-in-process-execution.md +++ b/specs/2026-11-30-managed-controller-in-process-execution.md @@ -1,6 +1,6 @@ # Spec: Managed Controller in-process execution: `command.v1` checks, exec roles, and portable campaign state -Status: Building +Status: Shipped Type: Feature ## Summary From 348777764092bd3a511801b7d88d59a161a1c80f Mon Sep 17 00:00:00 2001 From: thxCode Date: Wed, 2 Dec 2026 00:43:48 +0800 Subject: [PATCH 23/26] fixup! fix(controller): harden LocalCheck, exec-role, scrubber, and isolation parity Signed-off-by: thxCode --- packages/controller/src/local-check.ts | 50 +++++++++++++------- packages/controller/src/parser.ts | 11 +++-- packages/controller/src/registry.ts | 2 +- packages/controller/test/local-check.test.ts | 4 +- packages/core/src/scrubber.ts | 24 ++++++++-- packages/core/test/scrubber.test.ts | 16 +++++++ 6 files changed, 79 insertions(+), 28 deletions(-) diff --git a/packages/controller/src/local-check.ts b/packages/controller/src/local-check.ts index b47b74e9..c06a1850 100644 --- a/packages/controller/src/local-check.ts +++ b/packages/controller/src/local-check.ts @@ -402,6 +402,7 @@ export class LocalCheck { // The script's own exit decides the verdict; whatever it left behind in the group is killed before the capture. const exit = await exited; clearTimeout(timer); + signal.removeEventListener('abort', stop); await confirmProcessGroupGone(pgid, 'verification'); onGroupCleaned(); await drainStream(child.stderr); @@ -507,6 +508,36 @@ export class LocalCheck { } } + async #settleFailClosed( + job: PreparedLocalCheck, + data: Preparation, + binding: Binding | null, + view: RunView, + intentDigest: Digest, + dispatchReceipt: DispatchReceipt, + phase: ControllerDiagnostic['phase'], + reconciling: boolean, + ): Promise<{ + readonly disposition: Disposition; + readonly output: ArtifactRef; + readonly receiptRef: ArtifactRef; + readonly evidence: Evidence; + readonly receipt: OperationReceipt; + readonly record: LocalCheckReceipt; + }> { + const disposition: Disposition = { status: 'blocked', reason: 'EVIDENCE_UNAVAILABLE', method: LOCAL_CHECK_METHOD }; + const observation: Observation = { transport: 'interrupted', exitCode: null, exitSignal: null, timedOut: false, elapsedMs: 0, output: null, outputError: null, stderrTail: '', stderrTruncated: false }; + const output = await this.artifacts.json('local-check-output', { version: 1, binding, observation, disposition }, LOCAL_CHECK_OUTPUT_BYTES); + const evidence = this.#evidence(job, data, disposition, observation, output, phase); + const { receipt, record } = this.#receipt(job, data, disposition, view, intentDigest, dispatchReceipt, output, binding?.scriptDigest ?? null); + const receiptRef = await this.artifacts.json('local-check-receipt', record, 65536); + await this.#marker(job.operationId, job.producerNonce, 'proof', { version: 1, output, receipt: receiptRef, evidence }); + stateValue(reconciling + ? this.store.reconcileOperation(this.authority, job.operationId, receipt) + : this.store.recordOperationReceipt(this.authority, job.operationId, receipt)); + return { disposition, output, receiptRef, evidence, receipt, record }; + } + async #settleAbortedDispatch(job: PreparedLocalCheck, data: Preparation, binding: Binding, intentDigest: Digest): Promise { const inspected = this.store.inspect(); if ( @@ -522,14 +553,7 @@ export class LocalCheck { if (!same(this.currentSubject(), data.subject)) refuse('AUTHORITY_REFUSED', '', 'verification'); stateValue(this.store.renew(this.authority)); const view = stateValue(this.store.inspect()); - const disposition: Disposition = { status: 'blocked', reason: 'EVIDENCE_UNAVAILABLE', method: LOCAL_CHECK_METHOD }; - const observation: Observation = { transport: 'interrupted', exitCode: null, exitSignal: null, timedOut: false, elapsedMs: 0, output: null, outputError: null, stderrTail: '', stderrTruncated: false }; - const output = await this.artifacts.json('local-check-output', { version: 1, binding, observation, disposition }, LOCAL_CHECK_OUTPUT_BYTES); - const evidence = this.#evidence(job, data, disposition, observation, output, 'verification'); - const { receipt, record } = this.#receipt(job, data, disposition, view, intentDigest, binding.dispatchReceipt, output, binding.scriptDigest); - const receiptRef = await this.artifacts.json('local-check-receipt', record, 65536); - await this.#marker(job.operationId, job.producerNonce, 'proof', { version: 1, output, receipt: receiptRef, evidence }); - stateValue(this.store.recordOperationReceipt(this.authority, job.operationId, receipt)); + await this.#settleFailClosed(job, data, binding, view, intentDigest, binding.dispatchReceipt, 'verification', false); } /** Intent, permit, binding marker with the process group, execution, capture. Refusals here leave no proof; recovery settles them. */ @@ -693,14 +717,8 @@ export class LocalCheck { await this.artifacts.owner.assertCurrent(); if (!same(this.currentSubject(), data.subject)) refuse('RECOVERY_REQUIRED', '', 'recovery'); stateValue(this.store.renew(this.authority)); if (binding?.pgid !== null && binding?.pgid !== undefined) await confirmProcessGroupGone(binding.pgid, 'recovery'); await removeTree(binding?.workspaceDir ?? this.#attemptDir(job), 'recovery'); - const disposition: Disposition = { status: 'blocked', reason: 'EVIDENCE_UNAVAILABLE', method: LOCAL_CHECK_METHOD }; - const observation: Observation = { transport: 'interrupted', exitCode: null, exitSignal: null, timedOut: false, elapsedMs: 0, output: null, outputError: null, stderrTail: '', stderrTruncated: false }; - const output = await this.artifacts.json('local-check-output', { version: 1, binding, observation, disposition }, LOCAL_CHECK_OUTPUT_BYTES); - const evidence = this.#evidence(job, data, disposition, observation, output, 'recovery'); - const { receipt, record } = this.#receipt(job, data, disposition, view, intentDigest, binding?.dispatchReceipt ?? { generation: dispatch.generation, dispatchId: dispatch.dispatchId, revision: dispatch.revision, clockEpoch: view.clock.basis.clockEpoch }, output, binding?.scriptDigest ?? null); - const receiptRef = await this.artifacts.json('local-check-receipt', record, 65536); - await this.#marker(job.operationId, job.producerNonce, 'proof', { version: 1, output, receipt: receiptRef, evidence }); - stateValue(this.store.reconcileOperation(this.authority, job.operationId, receipt)); + const dispatchReceipt: DispatchReceipt = binding?.dispatchReceipt ?? { generation: dispatch.generation, dispatchId: dispatch.dispatchId, revision: dispatch.revision, clockEpoch: view.clock.basis.clockEpoch }; + const { disposition, output, receiptRef, evidence, receipt, record } = await this.#settleFailClosed(job, data, binding, view, intentDigest, dispatchReceipt, 'recovery', true); return await this.#attest(job, data, disposition, output, receiptRef, evidence, receipt, record, binding?.pgid ?? null); } } diff --git a/packages/controller/src/parser.ts b/packages/controller/src/parser.ts index 39812e1e..7bc10f62 100644 --- a/packages/controller/src/parser.ts +++ b/packages/controller/src/parser.ts @@ -64,7 +64,7 @@ function json(source: string, collectionLimit = 128, nodeLimit = 8192, stringLim return allowPrivateFloats ? normalizeZero(parsed) : parsed; } catch { refuse('CONFIG_SYNTAX'); } } -function yaml(source: string): Json { +function yaml(source: string, collectionLimit = 128): Json { let flow = 0, tokens = 0, scalar = false, inlineSequence = 0; for (const token of new Lexer().lex(source)) { if (scalar) { scalar = false; continue; } @@ -78,15 +78,16 @@ function yaml(source: string): Json { } const document = parseDocument(source, { version: '1.2', schema: 'core', uniqueKeys: true, merge: false, strict: true, customTags: [] }); if (document.errors.length) refuse(document.errors.some(error => error.code === 'DUPLICATE_KEY') ? 'CONFIG_DUPLICATE_KEY' : 'CONFIG_SYNTAX'); + const nodeLimit = Math.max(8192, collectionLimit * 16); let nodes = 0; function visit(node: unknown, depth: number): void { - if (++nodes > 8192 || depth > 32) refuse('CONFIG_LIMIT'); + if (++nodes > nodeLimit || depth > 32) refuse('CONFIG_LIMIT'); if (node === null) return; if (isAlias(node) || !node || typeof node !== 'object' || 'tag' in node && node.tag !== undefined || 'anchor' in node && node.anchor !== undefined) refuse('CONFIG_SYNTAX'); if (isMap(node)) { - if (node.items.length > 128) refuse('CONFIG_LIMIT'); + if (node.items.length > collectionLimit) refuse('CONFIG_LIMIT'); for (const pair of node.items) { if (!isScalar(pair.key) || typeof pair.key.value !== 'string' || pair.key.value === '<<' || pair.key.value.length > 16384) refuse('CONFIG_SYNTAX'); visit(pair.key, depth + 1); visit(pair.value, depth + 1); } - } else if (isSeq(node)) { if (node.items.length > 128) refuse('CONFIG_LIMIT'); for (const child of node.items) visit(child, depth + 1); } + } else if (isSeq(node)) { if (node.items.length > collectionLimit) refuse('CONFIG_LIMIT'); for (const child of node.items) visit(child, depth + 1); } else { if (!isScalar(node) || node.value !== null && !['string', 'boolean', 'number'].includes(typeof node.value)) refuse('CONFIG_SYNTAX'); if (typeof node.value === 'string' && node.value.length > 16384 || typeof node.value === 'number' && (!Number.isFinite(node.value) || Math.abs(node.value) > Number.MAX_SAFE_INTEGER || Object.is(node.value, -0))) refuse('CONFIG_LIMIT'); @@ -97,7 +98,7 @@ function yaml(source: string): Json { export function parseDocumentBytes(bytes: Uint8Array, format: 'json' | 'yaml', collectionLimit = 128): Json { if (bytes.byteLength > DOCUMENT_BYTES || !Number.isSafeInteger(collectionLimit) || collectionLimit < 1 || collectionLimit > 65_536) refuse('CONFIG_LIMIT'); let source: string; try { source = new TextDecoder('utf-8', { fatal: true }).decode(bytes); } catch { refuse('CONFIG_SYNTAX'); } - return format === 'json' ? json(source, collectionLimit, Math.max(8192, collectionLimit * 16)) : yaml(source); + return format === 'json' ? json(source, collectionLimit, Math.max(8192, collectionLimit * 16)) : yaml(source, collectionLimit); } /** Private immutable records have their own explicit collection bound; authoring config keeps the default 128. */ export function parsePrivateJson(bytes: Uint8Array, maximum: number, collectionLimit = 256): Json { diff --git a/packages/controller/src/registry.ts b/packages/controller/src/registry.ts index 0891ca28..c24de939 100644 --- a/packages/controller/src/registry.ts +++ b/packages/controller/src/registry.ts @@ -254,7 +254,7 @@ function execCommand(raw: unknown, path: string): ExecProfileCommand { if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) || name.length > 64 || EXEC_RESERVED_ENV_NAMES.includes(name) || name.startsWith('LOOPWRIGHT_')) { refuse('CONFIG_SCHEMA', `${path}/env/${name}`); } - const checkedVal = text(rawValue, `${path}/env/${name}`); + const checkedVal = text(rawValue, `${path}/env/${name}`, 16384); if (checkedVal.includes('\0')) refuse('CONFIG_SCHEMA', `${path}/env/${name}`); checkedEnv[name] = checkedVal; } diff --git a/packages/controller/test/local-check.test.ts b/packages/controller/test/local-check.test.ts index 8eeae276..a6163554 100644 --- a/packages/controller/test/local-check.test.ts +++ b/packages/controller/test/local-check.test.ts @@ -225,8 +225,8 @@ test('the child environment is exactly the F1 contract plus the configured env, assert.equal(verified.status, 'passed'); const lines = (authenticatedLocalCheck(verified).evidence.spec.detail ?? '').split('\n').filter(line => line.length > 0); const env = new Map(lines.map(line => { const index = line.indexOf('='); return [line.slice(0, index), line.slice(index + 1)] as const; })); - const shellAdded = ['PWD', 'SHLVL', '_']; - assert.deepEqual([...env.keys()].sort(), [...LOCAL_CHECK_ENV_NAMES, 'FORGEVO_KERNEL_ID', ...shellAdded].sort()); + const shellAdded = new Set(['PWD', 'SHLVL', '_']); + assert.deepEqual([...env.keys()].filter(name => !shellAdded.has(name)).sort(), [...LOCAL_CHECK_ENV_NAMES, 'FORGEVO_KERNEL_ID'].sort()); for (const [name, value] of Object.entries(LOCAL_CHECK_ENV_FIXED)) assert.equal(env.get(name), value, name); const baseDir = env.get('LOOPWRIGHT_BASE_DIR')!, candidateDir = env.get('LOOPWRIGHT_CANDIDATE_DIR')!, scratch = env.get('HOME')!; assert.equal(env.get('PATH'), [baseDir, 'scripts'].join('/') + ':' + [baseDir, 'tools/bin'].join('/') + ':' + LOCAL_CHECK_PATH_BASE); diff --git a/packages/core/src/scrubber.ts b/packages/core/src/scrubber.ts index 9e006f5a..98a46404 100644 --- a/packages/core/src/scrubber.ts +++ b/packages/core/src/scrubber.ts @@ -1,10 +1,6 @@ const GENERIC_SECRET_PATTERNS: readonly RegExp[] = Object.freeze([ - /ghs_[A-Za-z0-9]{20,}/g, - /ghu_[A-Za-z0-9]{20,}/g, - /ghp_[A-Za-z0-9]{20,}/g, /gh[pousr]_[A-Za-z0-9]{20,}/g, /github_pat_[A-Za-z0-9_]{20,}/g, - /-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/g, /-----BEGIN (?:RSA |EC |DSA |OPENSSH |ENCRYPTED )?PRIVATE KEY-----/g, /sk-(?:ant-|proj-)[A-Za-z0-9_-]{20,}/g, /(?= 8`, strictly shorter than + * the full form) of any registered credential form cut mid-token at a truncation boundary. + */ + scrubTruncated(value: string): string { + const output = this.scrub(value); + if (this.#forms.size === 0 || output.length < MIN_FORM_LENGTH) return output; + let longestPrefix = 0; + for (const form of this.#forms) { + const maxLen = Math.min(form.length - 1, output.length); + for (let len = maxLen; len >= MIN_FORM_LENGTH && len > longestPrefix; len--) { + if (output.endsWith(form.slice(0, len))) { + longestPrefix = len; + break; + } + } + } + return longestPrefix > 0 ? output.slice(0, output.length - longestPrefix) + '[scrubbed]' : output; + } + /** Return true when any tracked credential form or generic token pattern appears in the value. */ containsSecret(value: string): boolean { for (const form of this.#forms) { diff --git a/packages/core/test/scrubber.test.ts b/packages/core/test/scrubber.test.ts index 09ba856a..b17de894 100644 --- a/packages/core/test/scrubber.test.ts +++ b/packages/core/test/scrubber.test.ts @@ -61,4 +61,20 @@ describe('SecretScrubber', () => { assert.equal(scrubber.scrub(text), 'a [scrubbed] b [scrubbed] c'); assert.equal(scrubber.scrub('clean text'), 'clean text'); }); + + it('scrubTruncated strips trailing >= 8-char prefixes of registered secrets at truncation boundaries', () => { + const scrubber = new SecretScrubber(); + assert.equal(scrubber.scrubTruncated('plain output without secrets'), 'plain output without secrets'); + scrubber.register('sk-exec-canary-Zx91Yy82Ww73Qq64'); + assert.equal(scrubber.scrubTruncated('prefix sk-exec-canary-Z'), 'prefix [scrubbed]'); + assert.equal(scrubber.scrubTruncated('prefix sk-exec-'), 'prefix [scrubbed]'); + assert.equal(scrubber.scrubTruncated('prefix sk-exec'), 'prefix sk-exec'); + assert.equal( + scrubber.scrubTruncated('a sk-exec-canary-Zx91Yy82Ww73Qq64 b sk-exec-canary-'), + 'a [scrubbed] b [scrubbed]', + ); + scrubber.register('12345678'); + assert.equal(scrubber.scrubTruncated('x 12345678'), 'x [scrubbed]'); + assert.equal(scrubber.scrubTruncated('x 1234567'), 'x 1234567'); + }); }); From 543fce44a23e0173861b6175663a30ff0ee7b691 Mon Sep 17 00:00:00 2001 From: thxCode Date: Wed, 2 Dec 2026 00:43:49 +0800 Subject: [PATCH 24/26] fixup! feat(controller): integrate exec role adapter across compile, dispatch, capture, and recovery Signed-off-by: thxCode --- packages/controller/src/controller.ts | 3 +- packages/controller/src/exec-role.ts | 21 ++- packages/controller/src/recovery.ts | 12 +- packages/controller/test/exec-role.test.ts | 31 ++++- .../controller/test/recovery-owner.test.ts | 124 ++++++++++++++++++ 5 files changed, 178 insertions(+), 13 deletions(-) diff --git a/packages/controller/src/controller.ts b/packages/controller/src/controller.ts index 6afe2d8a..0a5d0044 100644 --- a/packages/controller/src/controller.ts +++ b/packages/controller/src/controller.ts @@ -14,7 +14,6 @@ export { EXEC_ROLE_METHOD, EXEC_ROLE_PRODUCER_ID }; import { readBoundedFile, removeTree } from './files.js'; import { privateDirectory, ArtifactStore, checkedRef, stateValue, streamVerifiedCasBlob } from './storage.js'; import { ControllerOwner, bootIdentity } from './ownership.js'; -import { confirmProcessGroupGone } from './process-group.js'; import { effectiveRunHostPolicy, hostProtectionFromPolicy, resolveStoreLeaseMs, validatePortPolicyFields } from './retained.js'; export { resolveStoreLeaseMs }; import { compareUtf16, freezeSource, gitObjectOid, materializeBaseline, overlayManifestBounds, verifySource, type FrozenSource, type HostPathProtectionOptions } from './source.js'; @@ -2170,7 +2169,7 @@ let cleanupKnown = false, reader: Promise | null = null, nativeOutcome: Ar throw this.#mapDeadlineError(runError); } - await confirmProcessGroupGone(outcome.pgid, 'execution'); + // `runExecRole` already confirmed the process group gone before returning. groupClean = true; if (!this.#hasActiveStoreAuthority()) refuse('AUTHORITY_REFUSED', '', 'execution'); diff --git a/packages/controller/src/exec-role.ts b/packages/controller/src/exec-role.ts index aac84874..2fe01591 100644 --- a/packages/controller/src/exec-role.ts +++ b/packages/controller/src/exec-role.ts @@ -83,16 +83,17 @@ function parseExecOutcomeUsage( const rawItems = list(raw['usage'], '', LIMITS.requests); const seen = new Set(); const requests: RequestUsage[] = []; - for (const item of rawItems) { + for (let index = 0; index < rawItems.length; index++) { + const item = rawItems[index]; const entry = record(item, ['requestId', 'inputTokens', 'outputTokens', 'costMicrousd']); const rawRequestId = id(entry['requestId']); if (seen.has(rawRequestId)) refuse('ARTIFACT_INVALID', '', 'verification'); seen.add(rawRequestId); requests.push({ requestId: execUsageRequestId(attemptId, rawRequestId), - inputTokens: { provenance: 'reported', value: integer(entry['inputTokens'], 0, Number.MAX_SAFE_INTEGER) }, - outputTokens: { provenance: 'reported', value: integer(entry['outputTokens'], 0, Number.MAX_SAFE_INTEGER) }, - costMicrousd: { provenance: 'reported', value: integer(entry['costMicrousd'], 0, Number.MAX_SAFE_INTEGER) }, + inputTokens: { provenance: 'reported', value: integer(entry['inputTokens'], 0, Number.MAX_SAFE_INTEGER, `/usage/${index}/inputTokens`) }, + outputTokens: { provenance: 'reported', value: integer(entry['outputTokens'], 0, Number.MAX_SAFE_INTEGER, `/usage/${index}/outputTokens`) }, + costMicrousd: { provenance: 'reported', value: integer(entry['costMicrousd'], 0, Number.MAX_SAFE_INTEGER, `/usage/${index}/costMicrousd`) }, }); } return { usageReported: true, requests }; @@ -256,6 +257,8 @@ function environment(spec: ExecRoleSpec, context: ExecRoleContext, scrubber: Sec if (binding.consumer !== 'exec') refuse('CONFIG_REFERENCE', '/exec/credentialRefs', 'execution'); for (const name of binding.environmentNames) claim(name, '/exec/credentialRefs'); } + if (context.scopeWritable.some(entry => entry.includes(':'))) refuse('CONFIG_SCHEMA', '/scopeWritable', 'execution'); + if (context.contextFiles.some(entry => entry.includes(':'))) refuse('CONFIG_SCHEMA', '/contextFiles', 'execution'); for (const binding of spec.credentials) { const value = context.secrets.resolveExecCredential(binding.id); scrubber.register(value); @@ -388,12 +391,16 @@ export async function runExecRole(spec: ExecRoleSpec, context: ExecRoleContext): if (context.onSpawned) await context.onSpawned(pgid); const exit = await exited; clearTimeout(timer); + context.signal.removeEventListener('abort', stop); await confirmProcessGroupGone(pgid, 'execution'); await Promise.all([drainStream(child.stdout), drainStream(child.stderr)]); if (context.signal.aborted) refuse('CANCELLED', '', 'execution'); - const clean = (captured: string): string => { const scrubbed = scrubber.scrub(captured); context.secrets.assertClean(scrubbed); return scrubbed; }; - // shortcut: truncation may cut a secret longer than `captureBytes`; scrubber and assertion see only the captured bytes, as `artifacts.put` would. - const out = clean(stdout.text()), err = clean(stderr.text()); + const clean = (captured: string, truncated: boolean): string => { + const scrubbed = truncated ? scrubber.scrubTruncated(captured) : scrubber.scrub(captured); + context.secrets.assertClean(scrubbed); + return scrubbed; + }; + const out = clean(stdout.text(), stdout.truncated), err = clean(stderr.text(), stderr.truncated); const { usage, usageReported } = timedOut ? { usage: [] as readonly ExecUsageRequest[], usageReported: false } : await readUsage(usageOut, context.secrets); const status = timedOut ? 'failed' : exit.code === 0 ? 'completed' : exit.code === 3 ? 'blocked' : 'failed'; const reason = timedOut ? 'exec_timeout' diff --git a/packages/controller/src/recovery.ts b/packages/controller/src/recovery.ts index b6f31653..4aaf58bd 100644 --- a/packages/controller/src/recovery.ts +++ b/packages/controller/src/recovery.ts @@ -23,7 +23,7 @@ import { ControllerEvents } from './events.js'; import { Finalizer, type ControllerIncident } from './finalize.js'; import { parsePrivateJson } from './parser.js'; import { boundFindingsForObservations, hydrateStepVerdicts, normalizeSubmission, type RetainedSubmission } from './submission.js'; -import { digestValue, freeze, hash, id, isRecord, record, same } from './schema.js'; +import { digestValue, freeze, hash, id, record, same } from './schema.js'; import { Verifier, prepareVerification, verifierProofPaths, type ByteInventory } from './verification.js'; import { Gate, GATE_OUTPUT_BYTES, prepareGate, validateGateUrlOverrides } from './gate.js'; import { LOCAL_CHECK_OUTPUT_BYTES, LocalCheck, prepareLocalCheck } from './local-check.js'; @@ -229,6 +229,7 @@ async function settleInterruptedExec(context: CycleContext, operation: Operation }, ); if (hasProof) { + let proofPgid: number | null; try { const proofBytes = await readBoundedFile(proofPath, EXEC_MARKER_BYTES, true); const parsedProof = record(parsePrivateJson(proofBytes, EXEC_MARKER_BYTES), [ @@ -240,20 +241,27 @@ async function settleInterruptedExec(context: CycleContext, operation: Operation 'capture', 'settled', ]); + const validPgid = parsedProof.pgid === null + || (typeof parsedProof.pgid === 'number' && Number.isSafeInteger(parsedProof.pgid) && parsedProof.pgid > 0); if ( parsedProof.version !== 1 || parsedProof.operationId !== operation.intent.operationId || parsedProof.attemptId !== attemptId - || !isRecord(parsedProof) + || !validPgid + || (pgid !== null && parsedProof.pgid !== pgid) ) { refuse('RECOVERY_REQUIRED', '', 'recovery'); } + proofPgid = parsedProof.pgid as number | null; } catch (error) { if (error instanceof ControllerFailure && ['RECOVERY_REQUIRED', 'REGISTRY_UNTRUSTED', 'CONFIG_LIMIT', 'CONFIG_SCHEMA', 'ARTIFACT_INVALID'].includes(error.diagnostic.code)) { refuse('RECOVERY_REQUIRED', '', 'recovery'); } throw error; } + if (pgid === null && proofPgid !== null) { + await confirmProcessGroupGone(proofPgid, 'recovery'); + } } else { await writeExecMarker( artifacts, diff --git a/packages/controller/test/exec-role.test.ts b/packages/controller/test/exec-role.test.ts index 7dbf2d91..8417acc4 100644 --- a/packages/controller/test/exec-role.test.ts +++ b/packages/controller/test/exec-role.test.ts @@ -18,7 +18,14 @@ const BINDING: CredentialBinding = { id: 'llm-token', consumer: 'exec', destinat interface Attempt { readonly root: string; readonly candidateDir: string; readonly scratchDir: string; readonly promptFile: string; readonly usageOut: string } interface SpecOptions { readonly mode?: string; readonly command?: readonly string[]; readonly env?: Readonly>; readonly captureBytes?: number; readonly timeoutMs?: number; readonly credentials?: readonly CredentialBinding[] } -interface ContextOptions { readonly signal?: AbortSignal; readonly secrets?: SecretResolver; readonly usageOut?: string; readonly onSpawned?: (pgid: number) => Promise } +interface ContextOptions { + readonly signal?: AbortSignal; + readonly secrets?: SecretResolver; + readonly usageOut?: string; + readonly onSpawned?: (pgid: number) => Promise; + readonly scopeWritable?: readonly string[]; + readonly contextFiles?: readonly string[]; +} async function attempt(): Promise { const root = await realpath(await mkdtemp(join(await realpath(tmpdir()), 'lw-exec-role-'))); @@ -52,7 +59,7 @@ const forbiddenVault: SecretResolver = { function context(attempt: Attempt, options: ContextOptions = {}): ExecRoleContext { return { runId: 'run-1', stepId: 'build', roleId: 'author', attemptId: 'attempt-1', - scopeWritable: ['src/**', 'tests/**'], contextFiles: [join(attempt.root, 'context', 'a.md')], + scopeWritable: options.scopeWritable ?? ['src/**', 'tests/**'], contextFiles: options.contextFiles ?? [join(attempt.root, 'context', 'a.md')], scratchDir: attempt.scratchDir, promptFile: attempt.promptFile, candidateDir: attempt.candidateDir, usageOut: options.usageOut ?? attempt.usageOut, secrets: options.secrets ?? fakeVault().secrets, signal: options.signal ?? new AbortController().signal, ...(options.onSpawned !== undefined ? { onSpawned: options.onSpawned } : {}), @@ -185,6 +192,24 @@ test('exec role captures each stream up to captureBytes and reports truncation', assert.equal(full.stdout, FLOOD); assert.equal(full.stderr, FLOOD); assert.equal(full.stdoutTruncated, false); assert.equal(full.stderrTruncated, false); })); +test('exec role scrubs a registered secret cut mid-token at the captureBytes truncation boundary', () => withAttempt(async current => { + const pad = EXEC_LIMITS.captureBytesMin - 16; + const script = `const s = 'a'.repeat(${pad}) + process.env.LLM_TOKEN; process.stdout.write(s); process.stderr.write(s);`; + const { secrets, asserted } = fakeVault(); + const outcome = await runExecRole( + spec({ command: [process.execPath, '-e', script], captureBytes: EXEC_LIMITS.captureBytesMin, credentials: [BINDING] }), + context(current, { secrets }), + ); + assert.equal(outcome.status, 'completed'); + assert.equal(outcome.stdoutTruncated, true); + assert.equal(outcome.stderrTruncated, true); + assert.equal(outcome.stdout.includes(SECRET.slice(0, 8)), false); + assert.equal(outcome.stderr.includes(SECRET.slice(0, 8)), false); + assert.equal(outcome.stdout, 'a'.repeat(pad) + '[scrubbed]'); + assert.equal(outcome.stderr, 'a'.repeat(pad) + '[scrubbed]'); + assert.ok(asserted.includes(outcome.stdout) && asserted.includes(outcome.stderr)); +})); + test('exec role reads the usage file after exit into request records (including >128 items and empty arrays) and distinguishes usageReported from absent usageOut', () => withAttempt(async current => { const written = await runExecRole(spec({ mode: 'write-usage' }), context(current)); assert.deepEqual(written.usage, [{ requestId: 'req_1', inputTokens: 120, outputTokens: 45, costMicrousd: 1500 }]); @@ -244,6 +269,8 @@ test('exec role refuses an invalid command[0], colliding env names, non-exec bin await assert.rejects(runExecRole(spec(), context(current, { secrets: forbiddenVault, usageOut: join(current.root, 'usage.json') })), refusal('CONFIG_SCHEMA')); await assert.rejects(runExecRole(spec(), context(current, { secrets: forbiddenVault, usageOut: `${current.scratchDir}/../usage.json` })), refusal('CONFIG_SCHEMA')); await assert.rejects(runExecRole(spec(), context(current, { secrets: forbiddenVault, usageOut: current.scratchDir })), refusal('CONFIG_SCHEMA')); + await assert.rejects(runExecRole(spec({ credentials: [BINDING] }), context(current, { secrets: forbiddenVault, scopeWritable: ['src:bad/**'] })), refusal('CONFIG_SCHEMA')); + await assert.rejects(runExecRole(spec({ credentials: [BINDING] }), context(current, { secrets: forbiddenVault, contextFiles: [join(current.root, 'a:b.md')] })), refusal('CONFIG_SCHEMA')); const aborted = new AbortController(); aborted.abort(); await assert.rejects(runExecRole(spec(), context(current, { secrets: forbiddenVault, signal: aborted.signal })), refusal('CANCELLED')); })); diff --git a/packages/controller/test/recovery-owner.test.ts b/packages/controller/test/recovery-owner.test.ts index f7b5cc33..35233a86 100644 --- a/packages/controller/test/recovery-owner.test.ts +++ b/packages/controller/test/recovery-owner.test.ts @@ -456,5 +456,129 @@ test('mid-exec controller crash settles exec_unknown on recovery, kills the reco await f.cleanup(); } } + + // Part 4: Proof marker pgid validation — mismatched or non-integer pgid refuses RECOVERY_REQUIRED without reconciling; + // absent binding with a valid proof pgid confirms the group gone and reconciles. + { + const f = await makeExecCrashFixture('print-env'); + const input = { configuration: f.loaded, repository: f.repository, runRoot: f.runRoot, runId: 'exec-crash-proof-pgid' }; + const context = await createCycle(input, {}); + try { + const deadChild = spawn(process.execPath, ['-e', ''], { detached: true, stdio: 'ignore' }); + const deadPgid = deadChild.pid!; + await new Promise(resolveExit => deadChild.once('exit', () => resolveExit())); + + const cycle = new Cycle(context); + await cycle.bootstrap(); + const attemptId = 'attempt.' + hash('loopwright.dev/controller/attempt/v1\0' + canonical({ runId: input.runId, nodeId: 'implement', purpose: 'task', repair: 'none', ordinal: 1 })).hex.slice(0, 40); + const operationId = 'exec.' + hash('loopwright.dev/controller/exec/v1\0' + canonical({ runId: input.runId, attemptId })).hex.slice(0, 40); + const expectedAttemptDir = join(f.runRoot, 'workspaces', input.runId, attemptId); + const cmdRef = await context.artifacts.put('command', Buffer.from('prompt', 'utf8'), 65_536); + await cycle.publish( + { + ...cycle.draft, + stage: { ...cycle.draft.stage, kind: 'role_pre' }, + attempts: [{ + ordinal: 1, + id: attemptId, + nodeId: 'implement', + nativeStepId: 'implement', + sessionId: 'session.' + 'b'.repeat(40), + purpose: 'task', + repair: 'none', + command: cmdRef, + before: { requests: 0, operations: 0 }, + finished: null, + }], + nodes: [{ id: 'implement', state: 'running' }], + }, + 'role.1.pre', + ); + stateValue(context.store.putIntent(context.authority, { + operationId, + nodeId: 'implement', + attemptId, + effect: 'local_write', + requestDigest: hash('req-proof'), + targetIdentity: 'exec:implement:1:' + cycle.draft.candidate.digest.hex, + })); + const dispatched = stateValue(context.store.authorizeOperationDispatch(context.authority, operationId)); + assert.equal(dispatched.kind, 'new_dispatch'); + if (dispatched.kind !== 'new_dispatch') throw new Error('expected new_dispatch'); + const opRecord = stateValue(context.store.getOperation(operationId)); + const view = stateValue(context.store.inspect()); + + const bindingPath = join(context.artifacts.directory, 'exec-role-producer-' + hash(operationId).hex + '.binding.json'); + const proofPath = join(context.artifacts.directory, 'exec-role-producer-' + hash(operationId).hex + '.proof.json'); + await writeFile( + bindingPath, + canonical({ + version: 1, + planDigest: context.plan.planDigest, + operationId, + attemptId, + nodeId: 'implement', + roleId: 'author', + promptDigest: cmdRef.digest, + intentDigest: opRecord.intentDigest, + dispatchReceipt: { + generation: dispatched.permit.generation, + dispatchId: dispatched.permit.dispatchId, + revision: dispatched.permit.authorizedRevision, + clockEpoch: view.clock.basis.clockEpoch, + }, + pgid: deadPgid, + workspaceDir: expectedAttemptDir, + }), + { mode: 0o600 }, + ); + await writeFile( + proofPath, + canonical({ version: 1, operationId, attemptId, pgid: deadPgid + 1, outcome: null, capture: null, settled: 'unknown' }), + { mode: 0o600 }, + ); + + await cycle.deadline.dispose(); + await cycle.events.close(); + stateValue(context.store.release(context.authority)); + stateValue(context.store.close()); + await context.owner.release(); + + const checkOpState = () => { + const reopened = stateValue(reopenLocalRun(context.descriptor.identity)); + try { return stateValue(reopened.getOperation(operationId)).state; } + finally { stateValue(reopened.close()); } + }; + + const mismatchResume = await resumeCycle(input); + assert.equal(mismatchResume.ok, false); + if (!mismatchResume.ok) assert.equal(mismatchResume.error.code, 'RECOVERY_REQUIRED'); + assert.equal(checkOpState(), 'dispatch_uncertain', 'mismatched proof pgid refuses before reconciliation'); + + await writeFile( + proofPath, + canonical({ version: 1, operationId, attemptId, pgid: 'bad', outcome: null, capture: null, settled: 'unknown' }), + { mode: 0o600 }, + ); + const invalidPgidResume = await resumeCycle(input); + assert.equal(invalidPgidResume.ok, false); + if (!invalidPgidResume.ok) assert.equal(invalidPgidResume.error.code, 'RECOVERY_REQUIRED'); + assert.equal(checkOpState(), 'dispatch_uncertain', 'non-integer proof pgid refuses before reconciliation'); + + const { unlink } = await import('node:fs/promises'); + await unlink(bindingPath); + await writeFile( + proofPath, + canonical({ version: 1, operationId, attemptId, pgid: deadPgid, outcome: null, capture: null, settled: 'unknown' }), + { mode: 0o600 }, + ); + const adoptedResume = await resumeCycle(input); + assert.equal(adoptedResume.ok, false); + if (!adoptedResume.ok) assert.equal(adoptedResume.error.code, 'RECOVERY_REQUIRED'); + assert.equal(checkOpState(), 'confirmed', 'valid proof pgid with absent binding adopts pgid and reconciles'); + } finally { + await f.cleanup(); + } + } }); From 4bf83cf8f7fbad2f3b526cd05423e557def9892e Mon Sep 17 00:00:00 2001 From: thxCode Date: Wed, 2 Dec 2026 00:43:49 +0800 Subject: [PATCH 25/26] fixup! fix(evolution): harden campaign snapshot secrets, bounds, receipt binding, and import atomicity Signed-off-by: thxCode --- packages/evolution/src/snapshot.ts | 55 ++++-- packages/evolution/src/store.ts | 12 +- packages/evolution/test/snapshot.test.ts | 222 +++++++++++++++++++++++ 3 files changed, 271 insertions(+), 18 deletions(-) diff --git a/packages/evolution/src/snapshot.ts b/packages/evolution/src/snapshot.ts index b7aa5718..d7eacea2 100644 --- a/packages/evolution/src/snapshot.ts +++ b/packages/evolution/src/snapshot.ts @@ -43,6 +43,7 @@ import { verifyIndividualReceiptBytes, verifyNonSymlinkDirectoryFd, writeNewFileNoFollow, + type ReceiptSignatureVerifier, } from './bundle-fs.js'; import { canonicalizeJson, @@ -209,6 +210,7 @@ export interface CampaignSnapshotCommonOptions { readonly allowSyntheticProbe?: boolean; readonly allowHostAttested?: boolean; readonly receiptSigningSecret?: string; + readonly verifyReceiptSignature?: ReceiptSignatureVerifier; readonly scrubber?: SecretScrubber; readonly maxBlobBytes?: number; } @@ -264,6 +266,7 @@ interface ResolvedSnapshotOptions { readonly allowHostAttested: boolean; readonly maxBlobBytes: number; readonly receiptSigningSecret: string | undefined; + readonly verifyReceiptSignature: ReceiptSignatureVerifier | undefined; } interface VerifiedCampaignSnapshot { @@ -434,13 +437,19 @@ function parseManifest(obj: Record, path: string): Campai } if (seenPaths.has(relPath)) invalid(`duplicate member path "${relPath}"`, `${mPath}/path`); seenPaths.add(relPath); + let mediaType: string | undefined; + if (mObj['mediaType'] !== undefined) { + const mt = expectString(mObj['mediaType'], 1, 128, `${mPath}/mediaType`); + if (!PRINTABLE_ASCII_RE.test(mt)) { + invalid('mediaType must be printable ASCII', `${mPath}/mediaType`); + } + mediaType = mt; + } members.push({ path: relPath, digest: expectDigest(mObj['digest'], `${mPath}/digest`), byteLength: expectInteger(mObj['byteLength'], 0, Number.MAX_SAFE_INTEGER, `${mPath}/byteLength`), - ...(mObj['mediaType'] === undefined - ? {} - : { mediaType: expectString(mObj['mediaType'], 1, 128, `${mPath}/mediaType`) }), + ...(mediaType === undefined ? {} : { mediaType }), }); } for (const required of REQUIRED_MEMBERS) { @@ -820,14 +829,16 @@ function toScratchpadV1(snap: ScratchpadSnapshotRecord): SnapshotScratchpadRecor } /** Read only the `status` field of a stored receipt so a signed non-approved verdict can be skipped. */ -function peekReceiptStatus(rawBytes: Uint8Array, individualId: string): string { +function peekReceiptStatus(rawBytes: Uint8Array, individualId: string, scrubber: SecretScrubber): string { const diagPath = `/receipts/${individualId}`; if (rawBytes.byteLength === 0 || rawBytes.byteLength > MAX_RECEIPT_FILE_BYTES) { throw new EvolutionError('ARTIFACT_INVALID', `receipt exceeds bounds for ${individualId}`, diagPath); } + const text = decodeUtf8Strict(rawBytes, diagPath); + assertCleanSecretText(text, scrubber, diagPath); let parsed: NullProtoJson; try { - parsed = parseNullProtoJson(decodeUtf8Strict(rawBytes, diagPath), MAX_RECEIPT_FILE_BYTES, diagPath); + parsed = parseNullProtoJson(text, MAX_RECEIPT_FILE_BYTES, diagPath); } catch (err: unknown) { throw new EvolutionError('ARTIFACT_INVALID', `malformed verdict receipt JSON: ${err instanceof Error ? err.message : String(err)}`, diagPath); } @@ -848,6 +859,9 @@ function resolveOptions(options: CampaignSnapshotCommonOptions): ResolvedSnapsho if (!Number.isSafeInteger(maxBlobBytes) || maxBlobBytes < 1) { throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'maxBlobBytes must be a positive integer', '/maxBlobBytes'); } + if (options.verifyReceiptSignature !== undefined && typeof options.verifyReceiptSignature !== 'function') { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'verifyReceiptSignature must be a function', '/verifyReceiptSignature'); + } return { scrubber: options.scrubber ?? DEFAULT_SECRET_SCRUBBER, allowSyntheticProbe: options.allowSyntheticProbe === true, @@ -856,6 +870,7 @@ function resolveOptions(options: CampaignSnapshotCommonOptions): ResolvedSnapsho receiptSigningSecret: typeof options.receiptSigningSecret === 'string' && options.receiptSigningSecret.length > 0 ? options.receiptSigningSecret : undefined, + verifyReceiptSignature: options.verifyReceiptSignature, }; } @@ -970,11 +985,11 @@ export async function writeCampaignSnapshot(options: WriteCampaignSnapshotOption const rawBytes = await readVerifiedCasBlob(campaignRoot, verdictReceiptCasDigest.hex, { maxBytes: MAX_RECEIPT_FILE_BYTES, }); - if (peekReceiptStatus(rawBytes, ind.individualId) === 'approved') { - if (resolved.receiptSigningSecret === undefined) { + if (peekReceiptStatus(rawBytes, ind.individualId, resolved.scrubber) === 'approved') { + if (resolved.receiptSigningSecret === undefined && resolved.verifyReceiptSignature === undefined) { throw new EvolutionError( 'EXPORT_UNVERIFIED_FORBIDDEN', - `receiptSigningSecret is required to verify the approved verdict receipt of ${ind.individualId}`, + `receiptSigningSecret or verifyReceiptSignature is required to verify the approved verdict receipt of ${ind.individualId}`, '/receiptSigningSecret', ); } @@ -982,7 +997,8 @@ export async function writeCampaignSnapshot(options: WriteCampaignSnapshotOption expectedTargetCellId: campaign.manifest.spec.targetCellId, allowSyntheticProbe: resolved.allowSyntheticProbe, allowHostAttested: resolved.allowHostAttested, - receiptSigningSecret: resolved.receiptSigningSecret, + ...(resolved.receiptSigningSecret !== undefined ? { receiptSigningSecret: resolved.receiptSigningSecret } : {}), + ...(resolved.verifyReceiptSignature !== undefined ? { verifyReceiptSignature: resolved.verifyReceiptSignature } : {}), scrubber: resolved.scrubber, maxBlobBytes: resolved.maxBlobBytes, bindReceiptFields: true, @@ -1028,7 +1044,15 @@ export async function writeCampaignSnapshot(options: WriteCampaignSnapshotOption const stagedFiles: { readonly relPath: string; readonly bytes: Buffer; readonly mediaType: string }[] = []; const pushText = (relPath: string, text: string, mediaType: string): void => { assertCleanSecretText(text, resolved.scrubber, `/${relPath}`); - stagedFiles.push({ relPath, bytes: Buffer.from(text, 'utf8'), mediaType }); + const bytes = Buffer.from(text, 'utf8'); + if (bytes.byteLength > MAX_SNAPSHOT_MEMBER_BYTES) { + throw new EvolutionError( + 'ARTIFACT_INVALID', + `snapshot member ${relPath} exceeds ${MAX_SNAPSHOT_MEMBER_BYTES} bytes`, + `/${relPath}`, + ); + } + stagedFiles.push({ relPath, bytes, mediaType }); }; pushText(CAMPAIGN_MEMBER, canonicalizeJson(toCampaignV1(campaign)), CAMPAIGN_SNAPSHOT_JSON_MEDIA_TYPE); pushText(INDIVIDUALS_MEMBER, serializeJsonl(individualDocs), CAMPAIGN_SNAPSHOT_NDJSON_MEDIA_TYPE); @@ -1413,10 +1437,10 @@ async function loadAndVerifySnapshot(options: VerifyCampaignSnapshotOptions): Pr if (listed.digest.hex !== ind.receipt.hex) { invalid(`receipt member "${relPath}" digest does not match individual "${ind.individualId}"`, `/${relPath}`); } - if (resolved.receiptSigningSecret === undefined) { + if (resolved.receiptSigningSecret === undefined && resolved.verifyReceiptSignature === undefined) { throw new EvolutionError( 'EXPORT_UNVERIFIED_FORBIDDEN', - `receiptSigningSecret is required to verify the approved verdict receipt of ${ind.individualId}`, + `receiptSigningSecret or verifyReceiptSignature is required to verify the approved verdict receipt of ${ind.individualId}`, '/receiptSigningSecret', ); } @@ -1424,7 +1448,8 @@ async function loadAndVerifySnapshot(options: VerifyCampaignSnapshotOptions): Pr expectedTargetCellId: campaign.manifest.spec.targetCellId, allowSyntheticProbe: resolved.allowSyntheticProbe, allowHostAttested: resolved.allowHostAttested, - receiptSigningSecret: resolved.receiptSigningSecret, + ...(resolved.receiptSigningSecret !== undefined ? { receiptSigningSecret: resolved.receiptSigningSecret } : {}), + ...(resolved.verifyReceiptSignature !== undefined ? { verifyReceiptSignature: resolved.verifyReceiptSignature } : {}), scrubber: resolved.scrubber, maxBlobBytes: resolved.maxBlobBytes, bindReceiptFields: true, @@ -1659,9 +1684,7 @@ export async function importCampaignSnapshot(options: ImportCampaignSnapshotOpti try { await populateImportedStore(stateDir, verified, resolved, clock); } catch (err: unknown) { - if (!(err instanceof EvolutionError && err.code === 'EVOLUTION_CONFLICT')) { - await removeImportedFilesInExistingDir(stateDir); - } + await removeImportedFilesInExistingDir(stateDir); throw err; } } diff --git a/packages/evolution/src/store.ts b/packages/evolution/src/store.ts index 1ece13b4..6d1edcac 100644 --- a/packages/evolution/src/store.ts +++ b/packages/evolution/src/store.ts @@ -29,6 +29,7 @@ import { CAMPAIGN_APPLICATION_ID, CAMPAIGN_CLOCK_MAX_DRIFT_MS, CAMPAIGN_FORMAT_VERSION, + SCRATCHPAD_MAX_BYTES, EvolutionError, type CampaignClockSource, type CampaignLease, @@ -2173,6 +2174,9 @@ export class EvolutionCampaignStore { assertDigest(input.snapshotDigest, 'snapshotDigest'); assertDriverConstraint(campaign.driverConstraint, '/driverConstraint'); const manifest = parseEvolutionCampaignDocument(campaign.manifest); + if (campaign.name !== manifest.metadata.name) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'campaign.name must match manifest.metadata.name', '/name'); + } for (const tc of input.teamConfigs) { assertSafeId(tc.teamConfigId, 'teamConfigId'); @@ -2220,8 +2224,12 @@ export class EvolutionCampaignStore { for (const snap of input.scratchpadSnapshots) { assertSafeId(snap.snapshotId, 'snapshotId'); assertDigest(snap.casDigest, 'casDigest'); - if (!Number.isSafeInteger(snap.byteLength) || snap.byteLength < 0 || snap.byteLength > 16_384) { - throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'byteLength must be within 0..16384', '/byteLength'); + if (!Number.isSafeInteger(snap.byteLength) || snap.byteLength < 0 || snap.byteLength > SCRATCHPAD_MAX_BYTES) { + throw new EvolutionError( + 'EVOLUTION_SCHEMA_INVALID', + `byteLength must be within 0..${SCRATCHPAD_MAX_BYTES}`, + '/byteLength', + ); } } diff --git a/packages/evolution/test/snapshot.test.ts b/packages/evolution/test/snapshot.test.ts index 54116684..ea324891 100644 --- a/packages/evolution/test/snapshot.test.ts +++ b/packages/evolution/test/snapshot.test.ts @@ -16,6 +16,7 @@ import { } from '@loopwright/core'; import { signBenchmarkVerdict, + verifyBenchmarkVerdictSignature, type BenchmarkOutputArtifact, type BenchmarkVerdict, type SignedBenchmarkVerdictReceipt, @@ -1783,3 +1784,224 @@ test('snapshot: prototype-pollution keys and forbidden modelId labels are reject rmSync(tempDir, { recursive: true, force: true }); } }); + +test('snapshot: verifyReceiptSignature callback parity across export, verify, and import without receiptSigningSecret', async () => { + const tempDir = mkdtempSync(join(tmpdir(), 'evo-snapshot-verifier-cb-')); + try { + const campaignRoot = join(tempDir, 'campaign'); + const seeded = await seedSnapshotCampaign(campaignRoot, { clock: makeSteppingClock(HIGH_MONO_MS) }); + const outDir = join(tempDir, 'snapshot'); + const verifiedOnWrite: string[] = []; + const verifyHmac = (receipt: SignedBenchmarkVerdictReceipt): boolean => verifyBenchmarkVerdictSignature( + TEST_HMAC_SECRET, + receipt as unknown as Readonly>, + receipt.signature, + ); + const verifier = ( + receipt: SignedBenchmarkVerdictReceipt, + _rawBytes: Uint8Array, + individualId: string, + ): boolean => { + verifiedOnWrite.push(individualId); + return verifyHmac(receipt); + }; + try { + await assertEvolutionErrorAsync( + () => writeCampaignSnapshot({ + store: seeded.store, + campaignId: seeded.campaignId, + outDir: join(tempDir, 'snapshot-bad-cb'), + verifyReceiptSignature: 'not-a-function' as unknown as NonNullable, + }), + 'EVOLUTION_SCHEMA_INVALID', + ); + + const written = await writeCampaignSnapshot({ + store: seeded.store, + campaignId: seeded.campaignId, + outDir, + verifyReceiptSignature: verifier, + }); + assert.equal(written.receiptCount, 2); + assert.deepEqual(verifiedOnWrite.sort(), ['ind-win-1', 'ind-win-2']); + } finally { + await seeded.store.close(); + } + + const verifiedOnRead: string[] = []; + const verified = await verifyCampaignSnapshot({ + bundleDir: outDir, + verifyReceiptSignature: (receipt, _rawBytes, individualId) => { + verifiedOnRead.push(individualId); + return verifyHmac(receipt); + }, + }); + assert.equal(verified.receiptCount, 2); + assert.deepEqual(verifiedOnRead.sort(), ['ind-win-1', 'ind-win-2']); + + await assertEvolutionErrorAsync( + () => verifyCampaignSnapshot({ + bundleDir: outDir, + verifyReceiptSignature: () => false, + }), + 'EXPORT_UNVERIFIED_FORBIDDEN', + ); + + const stateDir = join(tempDir, 'state'); + const imported = await importCampaignSnapshot({ + bundleDir: outDir, + stateDir, + verifyReceiptSignature: (receipt) => verifyHmac(receipt), + clock: makeSteppingClock(LOW_MONO_MS), + }); + assert.equal(imported.receiptCount, 2); + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } +}); + +test('snapshot: rejects non-printable/non-ASCII mediaType, secrets in non-approved receipts, mismatched campaign.name, and cleans up empty stateDir on failure', async () => { + const tempDir = mkdtempSync(join(tmpdir(), 'evo-snapshot-r1-hardening-')); + try { + const campaignRoot = join(tempDir, 'campaign'); + const seeded = await seedSnapshotCampaign(campaignRoot, { clock: makeSteppingClock(HIGH_MONO_MS) }); + const cleanBundle = join(tempDir, 'snapshot-clean'); + try { + await writeCampaignSnapshot({ + store: seeded.store, + campaignId: seeded.campaignId, + outDir: cleanBundle, + receiptSigningSecret: TEST_HMAC_SECRET, + }); + } finally { + await seeded.store.close(); + } + + // 1. Manifest member mediaType with control or non-ASCII chars is rejected + for (const [label, badMediaType] of [['control', 'application/json\n'], ['non-ascii', 'application/json\u00e9']] as const) { + const badMediaDir = join(tempDir, `bad-media-${label}`); + cpSync(cleanBundle, badMediaDir, { recursive: true }); + const manifestPath = join(badMediaDir, 'manifest.json'); + const manifestObj = JSON.parse(readFileSync(manifestPath, 'utf8')) as { + members: Array<{ path: string; digest: Digest; byteLength: number; mediaType?: string }>; + }; + manifestObj.members[0]!.mediaType = badMediaType; + writeFileSync(manifestPath, JSON.stringify(manifestObj)); + await assertEvolutionErrorAsync( + () => verifyCampaignSnapshot({ bundleDir: badMediaDir, receiptSigningSecret: TEST_HMAC_SECRET }), + 'ARTIFACT_INVALID', + ); + } + + // 2. Secret inside a non-approved (denied) receipt is rejected by peekReceiptStatus on export + const deniedSecretRoot = join(tempDir, 'camp-denied-secret'); + const seededDenied = await seedSnapshotCampaign(deniedSecretRoot, { clock: makeSteppingClock(HIGH_MONO_MS) }); + try { + const lease = await seededDenied.store.acquireLease('denied-secret-owner'); + const leakReceipt = makeSignedReceiptBytes({ + lockHash: seededDenied.lockHash, + operationId: 'op-ind-denied-leak', + status: 'denied', + reason: 'DENIED_WITH_TOKEN_ghp_1234567890abcdefghijklmnopqrstuvwxyz', + }); + const leakReceiptCas = await seededDenied.store.writeCasBlob(leakReceipt.rawBytes); + await seededDenied.store.recordIndividual(lease, { + individualId: 'ind-denied-leak', + campaignId: seededDenied.campaignId, + islandId: 0, + generation: 2, + bucketId: null, + teamConfigId: seededDenied.source.islands[0]!.activeTeamConfigId, + modelId: 'model-a', + trackId: 'cute', + mutationKind: 'diff_tune', + status: 'passed', + failureReason: null, + nicheKey: null, + paretoRank: null, + crowdingDistance: null, + scalarFitness: null, + codeSliceCasDigest: null, + evidenceDigest: null, + verdictReceiptCasDigest: leakReceiptCas.digest, + outputArtifacts: [], + metrics: {}, + }); + await seededDenied.store.releaseLease(lease); + + const outLeak = join(tempDir, 'out-denied-secret'); + await assertEvolutionErrorAsync( + () => writeCampaignSnapshot({ + store: seededDenied.store, + campaignId: seededDenied.campaignId, + outDir: outLeak, + receiptSigningSecret: TEST_HMAC_SECRET, + }), + 'SECRET_LEAK_DETECTED', + ); + assert.equal(existsSync(outLeak), false); + } finally { + await seededDenied.store.close(); + } + + // 3. importCampaignState rejects mismatched campaign.name !== manifest.metadata.name + const mismatchRoot = join(tempDir, 'direct-name-mismatch'); + const mismatchStore = await EvolutionCampaignStore.open({ campaignRoot: mismatchRoot, clock: makeSteppingClock(LOW_MONO_MS) }); + try { + const lease = await mismatchStore.acquireLease('mismatch-owner'); + const manifest = parseEvolutionCampaignDocument(SINGLE_TARGET_CAMPAIGN_YAML); + await assertEvolutionErrorAsync( + () => mismatchStore.importCampaignState(lease, { + campaign: { + campaignId: 'camp-mismatch', + name: 'renamed-campaign-mismatch', + status: 'paused', + stagePhase: 'single-target', + activeBucketId: null, + manifest, + manifestDigest: makeDigest(SINGLE_TARGET_CAMPAIGN_YAML), + baseRevision: 'a'.repeat(40), + lockHash: makeDigest('lock-mismatch'), + driverConstraint: null, + currentGeneration: 0, + evaluationsUsed: 0, + preemptionsCount: 0, + }, + islands: [], + teamConfigs: [], + individuals: [], + lineageEdges: [], + modelBanditArms: [], + scratchpadSnapshots: [], + snapshotDigest: makeDigest('snap-mismatch'), + }), + 'EVOLUTION_SCHEMA_INVALID', + ); + await mismatchStore.releaseLease(lease); + } finally { + await mismatchStore.close(); + } + + // 4. Existing empty stateDir cleans up campaign.sqlite & cas/ even on EVOLUTION_CONFLICT inside populateImportedStore + const emptyStateDir = join(tempDir, 'empty-state-conflict'); + mkdirSync(emptyStateDir); + const conflictClock: CampaignClockSource = { + nowMonotonicMs: (): number => LOW_MONO_MS + 1, + nowWallMs: (): number => { + throw new EvolutionError('EVOLUTION_CONFLICT', 'simulated conflict after O_EXCL claim'); + }, + }; + await assertEvolutionErrorAsync( + () => importCampaignSnapshot({ + bundleDir: cleanBundle, + stateDir: emptyStateDir, + receiptSigningSecret: TEST_HMAC_SECRET, + clock: conflictClock, + }), + 'EVOLUTION_CONFLICT', + ); + assert.deepEqual(readdirSync(emptyStateDir), []); + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } +}); From 0aaf5a5d630a40a6cea34e1c082811e25e95df54 Mon Sep 17 00:00:00 2001 From: thxCode Date: Wed, 2 Dec 2026 00:55:34 +0800 Subject: [PATCH 26/26] fixup! fix(controller): harden LocalCheck, exec-role, scrubber, and isolation parity Signed-off-by: thxCode --- packages/core/src/scrubber.ts | 30 ++++++++++++++++++----------- packages/core/test/scrubber.test.ts | 12 ++++++++++++ 2 files changed, 31 insertions(+), 11 deletions(-) diff --git a/packages/core/src/scrubber.ts b/packages/core/src/scrubber.ts index 98a46404..c9e2523b 100644 --- a/packages/core/src/scrubber.ts +++ b/packages/core/src/scrubber.ts @@ -16,6 +16,9 @@ const GENERIC_SECRET_PATTERNS: readonly RegExp[] = Object.freeze([ /AWS_SECRET_ACCESS_KEY/g, ]); const MIN_FORM_LENGTH = 8; +/** Trailing-boundary matcher for generic token formats cut mid-token at a capture limit. */ +const TRAILING_GENERIC_SECRET_PATTERN = + /(?:gh[pousr]_[A-Za-z0-9]*|github_pat_[A-Za-z0-9_]*|sk-(?:ant-|proj-)[A-Za-z0-9_-]*|(?= 8`, strictly shorter than - * the full form) of any registered credential form cut mid-token at a truncation boundary. + * the full form) of any registered credential form and any trailing partial generic token format + * cut mid-token at a truncation boundary. */ scrubTruncated(value: string): string { - const output = this.scrub(value); - if (this.#forms.size === 0 || output.length < MIN_FORM_LENGTH) return output; - let longestPrefix = 0; - for (const form of this.#forms) { - const maxLen = Math.min(form.length - 1, output.length); - for (let len = maxLen; len >= MIN_FORM_LENGTH && len > longestPrefix; len--) { - if (output.endsWith(form.slice(0, len))) { - longestPrefix = len; - break; + let output = this.scrub(value); + if (this.#forms.size > 0 && output.length >= MIN_FORM_LENGTH) { + let longestPrefix = 0; + for (const form of this.#forms) { + const maxLen = Math.min(form.length - 1, output.length); + for (let len = maxLen; len >= MIN_FORM_LENGTH && len > longestPrefix; len--) { + if (output.endsWith(form.slice(0, len))) { + longestPrefix = len; + break; + } } } + if (longestPrefix > 0) { + output = output.slice(0, output.length - longestPrefix) + '[scrubbed]'; + } } - return longestPrefix > 0 ? output.slice(0, output.length - longestPrefix) + '[scrubbed]' : output; + return output.replace(TRAILING_GENERIC_SECRET_PATTERN, '[scrubbed]'); } /** Return true when any tracked credential form or generic token pattern appears in the value. */ diff --git a/packages/core/test/scrubber.test.ts b/packages/core/test/scrubber.test.ts index b17de894..03605d1d 100644 --- a/packages/core/test/scrubber.test.ts +++ b/packages/core/test/scrubber.test.ts @@ -77,4 +77,16 @@ describe('SecretScrubber', () => { assert.equal(scrubber.scrubTruncated('x 12345678'), 'x [scrubbed]'); assert.equal(scrubber.scrubTruncated('x 1234567'), 'x 1234567'); }); + + it('scrubTruncated redacts trailing partial generic token formats without registration', () => { + const scrubber = new SecretScrubber(); + assert.equal(scrubber.scrubTruncated('token ghp_Ab3dEf6Hi'), 'token [scrubbed]'); + assert.equal(scrubber.scrubTruncated('token ghp_Ab'), 'token [scrubbed]'); + assert.equal(scrubber.scrubTruncated('token github_pat_12'), 'token [scrubbed]'); + assert.equal(scrubber.scrubTruncated('token sk-ant-api03-Ab'), 'token [scrubbed]'); + assert.equal(scrubber.scrubTruncated('token sk-proj-Ab12'), 'token [scrubbed]'); + assert.equal(scrubber.scrubTruncated('aws=AKIA0123'), 'aws=[scrubbed]'); + assert.equal(scrubber.scrubTruncated('XAKIA0123'), 'XAKIA0123'); + assert.equal(scrubber.scrubTruncated('-----BEGIN RSA PRIVATE KEY---'), '[scrubbed]'); + }); });