diff --git a/.agents/skills/loopwright-overview/SKILL.md b/.agents/skills/loopwright-overview/SKILL.md index dcd0de6..b26953b 100644 --- a/.agents/skills/loopwright-overview/SKILL.md +++ b/.agents/skills/loopwright-overview/SKILL.md @@ -33,7 +33,8 @@ Read [Architecture](../../../docs/getting-started/architecture.md) for the four- | `@loopwright/taskpack` | [packages/taskpack](../../../packages/taskpack/) | Generic declarative `Taskpack` and `TaskpackSuite` parser/router, compiler, isolated 3-way `baselineAlignment`, OS sandbox backends, preflight/upstream staging, local `command.v1` gate, and turnkey execution (`local` and `github` policy profiles) | | `@loopwright/github-app` | [packages/github-app](../../../packages/github-app/) | GitHub webhook intake, suite PR ownership lookup, multi-domain fan-out routing, collaborator permission checks, `InstallationTokenBroker`, `TenantAdmissionQueue`, streamed 3-way CAS PR publisher, `github-app.yaml` loader, and Action entrypoint | | `@loopwright/hardware-runner` | [packages/hardware-runner](../../../packages/hardware-runner/) | Outbound pull-lease benchmark relay, two-stage blind GPU/NPU evaluator (`native_os`/`docker`), `1 MiB` CAS streaming, and trusted hardware provenance probes | -| `@loopwright/cli` | [packages/cli](../../../packages/cli/) | Local operator CLI (`init`, `check`, `digest sync`, `suite check|resolve`, `run --taskpack`, `run`, `resume`, `step`, `status`, `inspect`, `reconcile`, `closure`, `app-serve`, `runner relay\|worker`), `--baseline-alignment`, `--role-model` routing, and YAML draft generator | +| `@loopwright/evolution` | [packages/evolution](../../../packages/evolution/) | Isolated `campaign.sqlite` island/MAP-Elites archive, NSGA-II Pareto ranking, UCB1 model bandit, plateau `team-patch.v1` supervisor, CAS scratchpads, and deterministic `evolution-bundle.v1` export | +| `@loopwright/cli` | [packages/cli](../../../packages/cli/) | Local operator CLI (`init`, `check`, `digest sync`, `suite check|resolve`, `run --taskpack`, `run`, `resume`, `step`, `status`, `inspect`, `reconcile`, `closure`, `app-serve`, `runner relay\|worker`, `evolve check\|run\|resume\|status\|inspect\|export`), `--baseline-alignment`, `--role-model` routing, and YAML draft generator | ## YAML-First Configuration Surfaces @@ -47,6 +48,7 @@ Loopwright uses deterministic two-space Pretty YAML (YAML 1.2 core schema, rejec | `.loopwright/suite.yaml` | `kind: TaskpackSuite` (`metadata.name` + `spec.domains[]`, `spec.stages[]` readiness probes) | `@loopwright/taskpack`, `@loopwright/github-app`, `@loopwright/cli` — [Taskpack](../../../docs/configuration/taskpack.md#taskpacksuite), [GitHub Action](../../../docs/operations/github-action.md), [CLI](../../../docs/operations/cli.md#suite-commands) | | `github-app.yaml` | `kind: GitHubAppConfig` (`apiVersion`, `kind`, `spec`; `loadGitHubAppConfig`) | `@loopwright/github-app` — [GitHub App](../../../docs/operations/github-app.md) | | `decisions.yaml` | `kind: DecisionPolicy` (`apiVersion`, `kind`, `spec`; `loadDecisionPolicyFile`) | `@loopwright/decisions` — [Decision Routing](../../../docs/configuration/decision-routing.md) | +| `campaign.yaml` | `kind: EvolutionCampaign` (`metadata.name` + `spec.taskpack`, `spec.targetCellId`, `spec.stages`, `spec.population`, `spec.sampling`, `spec.teamEvolution?`, `spec.objectives`, `spec.budgets`, `spec.export?`) | `@loopwright/evolution`, `@loopwright/cli` — [Task Contract](../../../docs/configuration/task-contract.md#evolutioncampaign), [CLI](../../../docs/operations/cli.md#evolution-campaigns) | | `examples/task.yaml` | `kind: TaskContract` (`apiVersion`, `kind`, `spec`; `loopwright check` / `loopwright run`) | `@loopwright/core`, `@loopwright/cli` — [Task Contract](../../../docs/configuration/task-contract.md) | ## Module Map & Skill Routing diff --git a/.auto-sync/checks/verify.sh b/.auto-sync/checks/verify.sh index 95bd089..943fb2e 100755 --- a/.auto-sync/checks/verify.sh +++ b/.auto-sync/checks/verify.sh @@ -272,6 +272,7 @@ UNMANAGED_WORKSPACES = [ "packages/memory", "packages/taskpack-runner", "packages/hardware-runner", + "packages/evolution", ] ALL_WORKSPACES = sorted(["packages/agent-pi", *YAML_WORKSPACES, *UNMANAGED_WORKSPACES]) ALLOWED_WORKSPACE_LINKS = { @@ -307,6 +308,7 @@ PROTECTED_TREE_PREFIXES = [ "packages/memory", "packages/taskpack-runner", "packages/hardware-runner", + "packages/evolution", "packages/agent-pi/qualification", "packages/controller/qualification", "docs/contribute", diff --git a/.auto-sync/digests.lock.json b/.auto-sync/digests.lock.json index 47e74d8..55bdbdc 100644 --- a/.auto-sync/digests.lock.json +++ b/.auto-sync/digests.lock.json @@ -5,7 +5,7 @@ { "path": ".auto-sync/checks", "kind": "directory", - "sha256": "b24e311a2845a0a9e40b5ed673f928a3f569656ed72ebee047296877bfd98aff" + "sha256": "bc0085a2f3df69d371aa0b3b819d0b854be6d9e7c0d69ea0b9ef655cacbd59c0" }, { "path": ".auto-sync/instructions.md", @@ -15,7 +15,7 @@ { "path": "scripts/prepare-self-upgrade.mjs", "kind": "file", - "sha256": "743fa0372866f9288161b2789b6ad037126475275afa36b638c069048c0d51e2" + "sha256": "879ba4c35f1b7765a999a66fd2f730e6229bdce0b24102b1151153e38c494688" } ] } diff --git a/.opencodereview/rule.json b/.opencodereview/rule.json index 5f225d2..05dd07c 100644 --- a/.opencodereview/rule.json +++ b/.opencodereview/rule.json @@ -64,6 +64,11 @@ "merge_system_rule": true, "rule": "Flag violations of lease fencing, stage-A/stage-B isolation, CAS bounds and secret containment; cite concrete scenarios and preserve package boundaries." }, + { + "path": "packages/evolution/**/*.ts", + "merge_system_rule": true, + "rule": "Flag violations of campaign.sqlite isolation, archetype capability envelopes, CAS bounds and secret containment; cite concrete scenarios and preserve package boundaries." + }, { "path": "packages/cli/**/*.ts", "merge_system_rule": true, diff --git a/AGENTS.md b/AGENTS.md index 96dccf6..1b53eb4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -7,7 +7,7 @@ Loopwright is a TypeScript harness and GitHub Action/App control plane for bound - `packages/core`: contracts, identity, evidence; `packages/state`: fenced SQLite state. - `packages/agent-pi`: isolated runtime; `packages/controller`: orchestration and verification. - `packages/taskpack-runner`: runner parity; `packages/memory`: reviewed memory. -- `packages/decisions`: advisory routing; `packages/taskpack`: declarative taskpacks; `packages/github-app`: intake and App; `packages/hardware-runner`: outbound benchmark relay and worker; `packages/cli`: local operations. +- `packages/decisions`: advisory routing; `packages/taskpack`: declarative taskpacks; `packages/github-app`: intake and App; `packages/hardware-runner`: outbound benchmark relay and worker; `packages/evolution`: evolutionary campaigns, Pareto archive, and bundle export; `packages/cli`: local operations. - `action.yml`: reusable Action; `docs/`: usage contracts; `site/`: generated documentation site; `specs/`: rationale; `scripts/`: automation. ## Architecture @@ -24,7 +24,7 @@ Run `npm run build`, `npm run typecheck`, `npm run lint`, `npm run lint:docs`, a - `core`, `decisions`, `memory`, `controller`, `hardware-runner`, `cli`: `node scripts/run-tests.mjs --pkg ` - `github-app`, `taskpack`, `taskpack-runner`: target `.test-build/packages//test/.test.js` with `--test-name-pattern` during iteration, then `node scripts/run-tests.mjs --pkg ` -- `state`, `agent-pi`: `node scripts/run-tests.mjs --pkg ` (use `--concurrency 1` for sandbox, child-kill, or SQLite lock contention) +- `state`, `agent-pi`, `evolution`: `node scripts/run-tests.mjs --pkg ` (use `--concurrency 1` for sandbox, child-kill, or SQLite lock contention) Use `loopwright-overview` for architecture routing, `loopwright-docs` for documentation changes, `loopwright-code-review` for reviews, `loopwright-issue-pr` for issue or PR preparation, and `loopwright-release` for releases. diff --git a/README.md b/README.md index 3198969..90a6411 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,7 @@ Read the [architecture overview](./docs/getting-started/architecture.md) and [do - **Declarative taskpacks & suites**: Define repository scope, triggers, compact step handoffs, conditional rules, baseline alignment (`baselineAlignment`), and multi-domain `TaskpackSuite` manifests (`.loopwright/suite.yaml`) in YAML. See [Declarative Taskpack](./docs/walkthroughs/declarative-taskpack.md) and [Taskpack](./docs/configuration/taskpack.md). - **Run diagnostics (`RunEval`)**: Export deterministic tool-repeat, ping-pong, repair-convergence, and per-role/per-step breakdowns via `loopwright inspect` and `Run Health` step summaries. See [CLI](./docs/operations/cli.md). - **Hardware benchmark gates**: Bind hardware `target.matrix` cells to host-owned `benchmark-gate.v1` slots and run outbound-only `@loopwright/hardware-runner` workers (`loopwright runner relay|worker`). See [Task Contract](./docs/configuration/task-contract.md) and [CLI](./docs/operations/cli.md). +- **Evolutionary campaigns**: Run bounded island and MAP-Elites optimization (`@loopwright/evolution`, `loopwright evolve`) with `evolve-block-guard.v1`, plateau `teamEvolution`, and signed `evolution-bundle.v1` exports. See [Task Contract](./docs/configuration/task-contract.md#evolutioncampaign) and [CLI](./docs/operations/cli.md#evolution-campaigns). - **Reviewed memory**: Content-addressed proposals apply separately after review. See [memory](./docs/contribute/memory.md). - **Capability closure**: Inspect local evidence and external prerequisites with the [closure matrix](./docs/contribute/closure-matrix.md). diff --git a/docs/README.md b/docs/README.md index d2c0324..5d5daba 100644 --- a/docs/README.md +++ b/docs/README.md @@ -51,8 +51,8 @@ - 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), [configuration/controller-and-registry.md](configuration/controller-and-registry.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) -- Code: [controller](../packages/controller/), [hardware-runner](../packages/hardware-runner/), [cli](../packages/cli/) +- 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) +- 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) @@ -137,6 +137,7 @@ | [2026-11-20-decouple-taskpack-and-cas-blob-pointers.md](../specs/2026-11-20-decouple-taskpack-and-cas-blob-pointers.md) | Decoupled `@loopwright/taskpack` package, policy profiles, and CAS blob pointers | | [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` | ## All pages diff --git a/docs/assets/diagrams/hardware-relay-flow.svg b/docs/assets/diagrams/hardware-relay-flow.svg new file mode 100644 index 0000000..c35a335 --- /dev/null +++ b/docs/assets/diagrams/hardware-relay-flow.svg @@ -0,0 +1,75 @@ + +Hardware Relay and Network Boundaries +Three isolated network zones: Control Plane outbound HTTPS submit, Relay DMZ hub, and Private GPU Cluster behind a zero-inbound-ports firewall with offline zero-network Docker sandboxes. + + + + + + + + + +LOOPWRIGHT / HARDWARE RUNNER +Hardware Relay and Network Boundaries +Three isolated network zones separate control plane credentials, relay DMZ routing, and private GPU clusters + + + +ZONE 1 · CONTROL PLANE ZONE · OUTBOUND HTTPS ONLY + +SIGNED BENCHMARK SUBMISSION · LOCAL CLI OR GITHUB ACTIONS +CAMPAIGN CLIENTS · Job ProducersLOCAL CLIEvolution campaignsDispatches candidate jobsCI WORKFLOWGitHub ActionsRuns with read scopeSIGNED PAYLOAD · Controller SecretBENCHMARK JOBTarget pool routingMatches GPU capabilitiesHMAC SECRETController signing keyAuthenticates verdict receipts + + + + +OUTBOUND HTTPS ONLY · HMAC JOB SUBMIT · NO WORKER TOKENS + + +ZONE 2 · RELAY DMZ BOUNDARY · HTTPS & CREDENTIAL ISOLATION + + +HARDWARE RELAY & CAS HUB · RELAY DMZ +HTTPS Endpoint · HMAC Auth · Monotonic Lease Fence · 1 MB CAS Store +Separates controller signing secrets from worker bearer tokens across distinct endpoints + + + + +CLUSTER FIREWALL · ZERO INBOUND PORTS · WORKER PULLS OVER HTTPS + + +ZONE 3 · PRIVATE GPU CLUSTER ZONE · OUTBOUND PULL & OFFLINE SANDBOX + + +OFFLINE DOCKER SANDBOX · ZERO NETWORK +01 · Worker PullZero inbound GPU portsPolls leases outbound02 · Build AuditOffline zero-network compileChecks forbidden symbols03 · GPU BenchZero-network Docker sandboxMounts holdout read-only04 · Verdict ReceiptReturns signed HMACBacks archive export + +GPU hosts open zero inbound ports and hold no signing secrets; controllers never read held-out suites. +Zone 1 to DMZ: outbound HTTPS job submitCluster firewall: zero inbound GPU portsStage A and B: offline zero-network Docker + diff --git a/docs/configuration/decision-routing.md b/docs/configuration/decision-routing.md index 1127e8f..958054c 100644 --- a/docs/configuration/decision-routing.md +++ b/docs/configuration/decision-routing.md @@ -134,9 +134,13 @@ Programmatic `@loopwright/decisions` callers compose structured requests from fo | `evaluateCycleAlignment` | Before repair or `rejectTo` rework | Advisory route (`continue`, `revise`, `needs_review`, `blocked`) | | `adviseSoftCompaction` | Prior to `pi.compact.v1` steps | Cannot veto active hard-compaction triggers | | `triageCandidateDiff` | Post-capture pre-publication | Skips cleanly when `triageRules` is empty; sets `verificationCertified: false` | +| `advise_mutation_novelty` | Pre-compile evolution mutation | Rejects `Jaccard === 1.0` clones offline (`0` network calls); queries Jev `noul` in soft band | +| `route_evolution_strategy` | Pre-mutation evolution track choice | Routes `(trackId, mutationKind)` from declared tracks with deterministic Roofline fallback | +| `advise_cascade_escalation` | Post-smoke benchmark triage | Returns `prune`, `confirm`, or `escalate`; never bypasses full multi-bucket verification | -- **Deterministic fallback**: Missing provider credentials, timeouts, or unreachable endpoints fall back deterministically (`source: 'deterministic_fallback'`) without blocking or certifying runs. -- **Non-delegable authority**: All six `DECISION_FORBIDDEN_AUTHORITY_INTENTS` (such as certifying verification receipts, bypassing required gates, overriding pinned models, expanding `writable` scope, or granting execution authority) are permanently refused and never sent to a decision model. Recorded entries appear in run observations (`advisoryDecisions`) with `verificationCertified: false`. +- **Advisory stamps**: Every decision result stamps `advisoryOnly: true` and `verificationCertified: false`. +- **Deterministic fallback**: Missing provider credentials, timeouts, or unreachable endpoints fall back deterministically (`source: 'deterministic_fallback'` or `'deterministic_heuristic'`) without blocking or certifying runs. +- **Non-delegable authority**: All six `DECISION_FORBIDDEN_AUTHORITY_INTENTS` (`grant_execution_authority`, `certify_verification_evidence`, `skip_adversarial_review`, `approve_external_gate`, `override_pinned_model`, `veto_hard_compaction`) throw `DecisionError('DECISION_AUTHORITY_VIOLATION')` with `authorityViolation: true`. Recorded entries appear in run observations (`advisoryDecisions`) with `verificationCertified: false`. --- diff --git a/docs/configuration/task-contract.md b/docs/configuration/task-contract.md index 44892e1..0d72b4c 100644 --- a/docs/configuration/task-contract.md +++ b/docs/configuration/task-contract.md @@ -10,6 +10,7 @@ - [Roles and steps](#roles-and-steps) - [Budgets and enforcement](#budgets-and-enforcement) - [Acceptance and evidence](#acceptance-and-evidence) +- [EvolutionCampaign](#evolutioncampaign) ## TaskContract @@ -244,7 +245,7 @@ Otherwise, admission selects `tree_overlay` with `{ baseTree, entries, deleted } Verifier-namespaced descriptors (`.loopwright-verifier//*`) use a dedicated verifier output budget (`64` files per slot, `256` total files, and `16 GiB` total bytes) separate from candidate `budgets.overlay.maxBytes`. -`ArtifactRef` accepts optional `uri` (`<= 2048` chars) and `mediaType` (`<= 128` chars), omitted from canonical serialization when unset. `Evidence` and `EvaluatedCheck` accept optional `metrics` (finite numbers, strings, or booleans), `findings`, and `detail` even on `passed` (`Evidence.spec.reason` stays `null`). +`ArtifactRef` accepts optional `uri` (`<= 2048` chars) and `mediaType` (`<= 128` chars), omitted from canonical serialization when unset. `Evidence.spec` accepts optional `metrics`, `findings`, `detail`, `bucketMetrics` (`1..64` buckets, `<= 16` numeric metrics and `<= 8` dimensions per bucket), and closed-enum `hardwareDiagnostics` (`boundPipeline`: `hbm | l2 | smem_lds_ub | tensor_cube | vector_valu | host_launch | comm | unknown`, optional counters/percentages/stalls). ### Acceptance fields @@ -279,13 +280,96 @@ Each `spec.target.matrix[]` cell accepts an optional `hardware` block alongside | `hardware.deviceCount` | No | Safe integer (`1..64`) | Expected device count verified against observed `hardwareProvenance` | | `hardware.driverConstraint` | No | Printable string (`1..128`) | Exact driver match or `>=` minimum version constraint | | `hardware.topology` | No | Printable string (`1..128`) | Optional interconnect or device topology constraint | +| `hardware.forbiddenSymbolPatterns` | No | `0..64` ASCII substrings (`<= 128`) | Glob-free Stage A symbol denylist (`cublas`, `rocblas`, `aclnn`) | +| `hardware.maxRegisterCount` | No | Safe integer (`>= 0`) | Stage A per-thread register ceiling before Stage B | +| `hardware.maxLocalSpillBytes` | No | Safe integer (`>= 0`) | Stage A local memory spill ceiling (`STAGE_A_STATIC_AUDIT_FAILED`) | ### Thresholds and provenance -- **Bounds rules**: `{ kind: 'bounds', metric, min?, max? }` requires at least one finite endpoint (`min <= max`; `-0` normalizes to `0`). -- **Comparative rules**: `{ kind: 'comparative', metric, baselineMetric, operator, threshold }` supports `min_ratio`, `max_ratio`, and `max_delta` (`baseline > 0` for ratios). +- **Bounds and comparative rules**: `bounds` requires `{ metric, min?, max? }`; `comparative` requires `{ metric, baselineMetric, operator, threshold }` (`min_ratio`, `max_ratio`, `max_delta`). Both accept optional `bucketScope` (`'aggregate' | 'all_buckets' | { bucketId }`). - **Hardware provenance**: Passing `hardware_execution` `Evidence` requires `hardwareProvenance` (`targetCellId`, `probeKind: 'physical' | 'synthetic_fixture'`, `vendor`, `deviceModel`, `accelerator`, `isolationMode`, `deviceCount`, `driverVersion`, `runtimeVersion`, `topology?`, `workloadDigest`, `clockLockMode: 'locked' | 'unlocked' | 'unknown'`). -- **Independent core check**: `evaluateAcceptance` requires `probeKind: 'physical'` unless `allowSyntheticHardwareProbe` is `true`, and blocks mismatches (`hardware_provenance_mismatch`, `metric_threshold_failed`). +- **Independent core check**: `evaluateAcceptance` enforces `bucketScope` across `bucketMetrics`, requires `probeKind: 'physical'` unless `allowSyntheticHardwareProbe` is `true`, and blocks mismatches (`hardware_provenance_mismatch`, `metric_threshold_failed`). + +## EvolutionCampaign + +`EvolutionCampaign` (`<= 64 KiB`) coordinates bounded multi-generation search over an isolated `campaign.sqlite` archive and child `LocalRunStore` runs. + +```yaml +apiVersion: loopwright.dev/v1alpha1 +kind: EvolutionCampaign +metadata: + name: flash-decode-sm90a +spec: + taskpack: .loopwright/taskpack.yaml + targetCellId: cuda-h100-whole + tracks: [triton, cute, cuda_raw] # Optional 1..32 track IDs + stages: # Optional (defaults to single-target) + mode: specialist-then-portfolio # Optional single-target or specialist-then-portfolio + specialistBuckets: + - id: bs1-isl4k + heldOutWorkloadId: decode-bs1-4k + - id: bs16-isl8k + heldOutWorkloadId: decode-bs16-8k + portfolioHeldOutWorkloadId: decode-portfolio-holdout + population: + islands: 4 + migrationIntervalGenerations: 8 + maxMigrationElites: 1 + nicheAxes: + - id: bound_pipeline + kind: enum + values: [hbm, l2, smem_lds_ub, tensor_cube, vector_valu] + - id: occupancy_band + kind: numeric_bins + edges: [0, 25, 50, 75, 100] + sampling: + noveltyDecayLambda: 1.0 + mutationWeights: + diff_tune: 0.5 + full_rewrite: 0.3 + crossover: 0.2 + modelBandit: ucb1 # Optional deterministic-round-robin or ucb1 + maxCrossoversPerPrompt: 2 + teamEvolution: # Optional plateau-triggered bounded role synthesis + enabled: true + supervisorRoleId: supervisor + allowedArchetypeRoles: [probe-readonly, mutator-sandboxed, reviewer] + stallGenerations: 4 # Optional (1..32) + minHypervolumeDelta: 0.001 # Optional (>= 0) + triggerOnRunEvalPathology: true # Optional (defaults to true) + trialGenerations: 2 # Optional (1..8) + maxTeamSize: 3 # Optional (1..4) + maxTeamSteps: 4 # Optional (1..6) + objectives: + - metric: latency_us_p50 + direction: minimize + - metric: goodput_rps + direction: maximize + budgets: + maxGenerations: 40 + maxEvaluations: 160 + maxConcurrentEvaluations: 4 + targetRooflineHeadroom: 1.08 # Optional early-stop ratio >= 1.0 + scratchpadIntervalGenerations: 5 # Optional (1..32) + export: # Optional auto-export on completion + format: oci-layout # Optional dir or oci-layout + outputDir: .loopwright-out/bundles/flash-decode-sm90a +``` + +| Field path | Required | Bounds and defaults | Behavior | +| --- | --- | --- | --- | +| `spec.heldOutWorkloadId` | No | Identifier (`1..64` chars) | Single-target holdout workload ID override | +| `spec.tracks` | No | `1..32` unique IDs | Candidate implementation tracks (`cuda_raw`, `cute`, `triton`) | +| `spec.stages` | No | `single-target` (default) or `specialist-then-portfolio` | `specialistBuckets` (`1..64`) + `portfolioHeldOutWorkloadId` | +| `spec.population` | Yes | `islands` `1..16`, `migrationIntervalGenerations` `1..1024`, `maxMigrationElites` `0..16` | Ring-topology island archive and migration cadence | +| `population.nicheAxes[]` | Yes | `1..4` axes (`enum` `1..32` values or `numeric_bins` `2..32` edges) | Optional `field` maps metric/diagnostic key into MAP-Elites cell | +| `spec.sampling` | Yes | `noveltyDecayLambda` `(0, 100]`, `modelBandit` `deterministic-round-robin` (default) \| `ucb1`, `maxCrossoversPerPrompt` `0..4` | Parent selection, novelty decay, and model bandit routing | +| `sampling.mutationWeights` | Yes | `diff_tune`, `full_rewrite`, `crossover` in `[0, 1000]` (sum `> 0`) | Deterministic per-slot mutation operator weights | +| `spec.teamEvolution` | No | `enabled`, `supervisorRoleId`, `allowedArchetypeRoles` (`1..16`), `maxTeamSize` `1..4` (`4`), `maxTeamSteps` `1..6` (`6`) | Read-only plateau supervisor bounded by archetype envelopes | +| `teamEvolution` triggers | No | `stallGenerations` `1..32` (`4`), `minHypervolumeDelta` `>= 0` (`0.001`), `triggerOnRunEvalPathology` (`true`), `trialGenerations` `1..8` (`2`) | Plateau/pathology trigger thresholds and trial rollback window | +| `spec.objectives[]` | Yes | `1..8` unique metrics (`minimize` \| `maximize`) | Multi-objective NSGA-II Pareto frontier and scalar fitness | +| `spec.budgets` | Yes | `maxGenerations` `1..10000`, `maxEvaluations` `1..100000`, `maxConcurrentEvaluations` `1..64`, `scratchpadIntervalGenerations` `1..32` (`5`) | Hard caps (`maxConcurrent <= maxEvaluations`) and `targetRooflineHeadroom` `>= 1.0` | +| `spec.export` | No | `format` `dir` (default) \| `oci-layout`, relative `outputDir` | Auto-exports signed `evolution-bundle.v1` upon completion | --- diff --git a/docs/configuration/taskpack.md b/docs/configuration/taskpack.md index 94089d3..dd5da38 100644 --- a/docs/configuration/taskpack.md +++ b/docs/configuration/taskpack.md @@ -1,8 +1,6 @@ # Taskpack -`Taskpack` powers Loopwright's automated mode. Declare repository intent in a bounded YAML document (`<= 64 KiB`), such as `.loopwright/taskpack.yaml` or `.auto-sync/taskpack.yaml`. The host compiles runtime contracts, handler SHA-256 digests, and credential bindings. - -For out-of-repo `TrustedRegistry` governance or CLI controller files, see [Task Contract](task-contract.md) and [Controller and Registry](controller-and-registry.md). +`Taskpack` powers Loopwright's automated mode in a bounded YAML document (`<= 64 KiB`, `.loopwright/taskpack.yaml`). For out-of-repo `TrustedRegistry` governance or CLI controller files, see [Task Contract](task-contract.md) and [Controller and Registry](controller-and-registry.md). ## Contents @@ -264,7 +262,7 @@ spec: | `spec.goal.candidate` / `noChange` | Yes | Strings (`1..1024` chars) | Role objectives for candidate and `no_change` runs | | `spec.scope.writable` / `protected` | No | String lists (`1..128` / `0..128`) | Explicit `/**` directories, exact files, or single-segment `*`/`?` globs | | `spec.instructions` / `skills` | No | Entry or list (`1..16` entries) | Protected UTF-8 files as paths or `{ path, when }` rules (`<= 256 KiB` total) | -| `spec.target.matrix` | No | `null` or `1..64` cells | `{ id, platform, variant, hardware? }`; `hardware` adds `accelerator`, `isolationMode`, `deviceCount?`, `driverConstraint?`, `topology?` | +| `spec.target.matrix` | No | `null` or `1..64` cells | `{ id, platform, variant, hardware? }`; `hardware` adds `accelerator`, `isolationMode`, `forbiddenSymbolPatterns?`, `maxRegisterCount?`, `maxLocalSpillBytes?` | | `spec.proposal` | No | `{ path, requiredFields, schemaVersion }` | Optional writable `.yaml`/`.yml`/`.json` proposal ledger | | `spec.submission` | No | `{ path, required? }` | Optional writable `.json` agent deliverable path | @@ -331,6 +329,7 @@ spec: | `json-artifact.v1` | Scalar expectations (binds `spec.proposal`) | Validates JSON/YAML keys and scalar equality | | `json-keys-guard.v1` | `path`, `allowedPointers` (`/json/pointer`) | Fails if any JSON key outside `allowedPointers` changed vs baseline | | `line-section-guard.v1` | `path`, `startMarker`, `endMarker` | Fails if any line outside delimited marker sections changed vs baseline | +| `evolve-block-guard.v1` | `files`, `allowedBlockIds?`, `maxBlockBytes?` | Verifies bytes outside `EVOLVE-BLOCK-START/END` markers match baseline SHA-256 | | `scope.v1` / `no-change.v1` | `checkId` (plus implicit guards) | Verifies writable/protected scope or untouched tree parity | | `command.v1` | `script`, `args`, `env`, `toolchainPaths`, `mountReadOnlyGit`, `preserveRepoDirName`, `mounts` | Mounts the script's parent directory read-only (whole-tree SHA-256 digest so `./lib.sh` works) | @@ -340,7 +339,7 @@ spec: - **Explicit host mounts (`parameters.mounts[]`)**: Declare `0..16` Docker-style bind entries `{ source, target?, mode?: 'ro' | 'rw' }` (`target` defaults to `source`; `mode` defaults to `'ro'`) for host files, directories, or Unix domain sockets (for example `{ source: /var/run/docker.sock, mode: rw }`). Every `source` requires dual-key `allow-privileged-execution: 'true'` (`--allow-privileged`) plus an explicit entry in `allow-host-mounts` (`--allow-host-mounts`). Broad roots, `/etc`, `/proc`, `/sys`, `/dev`, `/var/lib`, control-plane directories, and `$HOME` secrets are always refused; under `/run` and `/var/run`, only Unix domain sockets are permitted. Missing sources, or socket, `rw`, and remapped mounts without Linux `bwrap`, fail closed (`SANDBOX_CAPABILITY_INSUFFICIENT`). - **Structured check output**: Writing bounded JSON (`{ metrics?, findings?, detail? }`, `<= 64 KiB`; unknown keys such as `passed` or `summary` fail closed) to `$LOOPWRIGHT_CHECK_OUT` propagates through HMAC-signed `gate.v1` verdicts (`metrics`, `findings`, `detail`, `retryablePreemption`) even on exit `0`. - **Inner sandboxes and repair early-stop**: Checks running inner OS sandboxes should set `allowCheckNetwork: true` under `--allow-privileged`. Repair prompts instruct agents to submit `status: 'blocked'` immediately when failures originate in protected check scripts or missing host tools instead of looping until `repairNoProgress`. `gate.v1` entries in `externalGates[]` support per-gate `signingCredentialRef`, `authCredentialRef`, and `url`. -- **External benchmark gates (`benchmark-gate.v1`)**: Requires `targetCellId` (matching a `spec.target.matrix` cell with `hardware`), `heldOutWorkloadId`, and optional `maxPreemptions` (`0..16`), `allowSyntheticHardwareProbe`, and `metricThresholds` (`bounds`/`comparative`). Manifest-level `url`, `signingCredentialRef`, and `authCredentialRef` overrides are forbidden; host `gateEndpoints` bindings enforce strict credential isolation across endpoints, local command gates, `GH_TOKEN`/`GITHUB_TOKEN`, and publication. +- **External benchmark gates (`benchmark-gate.v1`)**: Requires `targetCellId` (matching a `spec.target.matrix` cell with `hardware`), `heldOutWorkloadId`, and optional `maxPreemptions` (`0..16`), `allowSyntheticHardwareProbe`, and `metricThresholds` (`bounds`/`comparative` with optional `bucketScope`: `aggregate | all_buckets | { bucketId }`). Manifest-level `url`, `signingCredentialRef`, and `authCredentialRef` overrides are forbidden; host `gateEndpoints` bindings isolate credentials across endpoints, local gates, `GH_TOKEN`, and publication. ## Publication and triggers diff --git a/docs/contribute/closure-matrix.md b/docs/contribute/closure-matrix.md index a58f4c1..2166d2d 100644 --- a/docs/contribute/closure-matrix.md +++ b/docs/contribute/closure-matrix.md @@ -21,7 +21,7 @@ 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 11 workspace packages (`@loopwright/hardware-runner` is 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 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`). 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: diff --git a/docs/contribute/evidence.md b/docs/contribute/evidence.md index 747b0fb..d8f68b6 100644 --- a/docs/contribute/evidence.md +++ b/docs/contribute/evidence.md @@ -7,6 +7,8 @@ A valid schema, producer name, hash, or serialized type brand cannot make eviden ## Contents - [Boundary](#boundary) +- [Block guards](#block-guards) +- [Hardware bundles](#hardware-bundles) ## Boundary @@ -66,6 +68,17 @@ All-unknown observations have unknown provenance; an empty trusted inventory is The host must include every admitted request and normalize overlapping provider token categories. The library cannot discover omitted calls or certify provider billing. It does not settle a budget ledger. +## Block guards + +- **`evolve-block-guard.v1`**: Parses `1..32` `EVOLVE-BLOCK-START: ` / `EVOLVE-BLOCK-END: ` pairs per file (`//`, `#`, or `/* */`) and rejects nested, duplicate, reordered, or unclosed markers. Every byte outside mutable blocks must match `baseRevision` SHA-256 while optional `allowedBlockIds` and `maxBlockBytes` constrain mutable regions. +- **Stage A static audits**: `evaluator.ts` inspects sealed Stage A `.so`, `.o`, `.cubin`, `.ptx`, and `.sass` binaries (`O_NOFOLLOW`, `1 MiB` symbol cap) against `forbiddenSymbolPatterns` (`0..64` literal substrings) and `maxRegisterCount`/`maxLocalSpillBytes` before Stage B starts, denying breaches with `STAGE_A_STATIC_AUDIT_FAILED`. + +## Hardware bundles + +- **Bucketed Stage B diagnostics**: Stage B envelopes (`<= 49,152` bytes stdout, zero exported files) carry optional `bucketMetrics` (`1..64` buckets, `<= 16` numeric metrics, `<= 8` dimensions) and closed-enum `hardwareDiagnostics`. `evaluateAcceptance` enforces `bucketScope` (`aggregate`, `all_buckets`, or `{ bucketId }`) across buckets. +- **Post-crash quarantine**: After any Stage B timeout or crash, `worker.ts` runs host accelerator probes via `provenance.ts` (`Xid`, uncorrectable ECC, hang) and transitions wedged workers to `WORKER_DEVICE_QUARANTINED` (exit `3`) before polling `/v1/runner/leases:acquire`. +- **Bundle export (`evolution-bundle.v1`)**: `exportEvolutionBundle` verifies CAS blobs (`O_NOFOLLOW`, `nlink === 1`, SHA-256, `SecretScrubber`), emits `manifest.json`, `dispatch-manifest.json` (`fallback: 'baseline'`), unmodified HMAC-signed `receipts/*.verdict.json`, and `blobs/sha256/` (`dir` or `oci-layout`), and refuses unverified or `synthetic_fixture` receipts with `EXPORT_UNVERIFIED_FORBIDDEN` unless `--allow-synthetic-probe` is set. + --- diff --git a/docs/contribute/internals.md b/docs/contribute/internals.md index 888f427..027df8d 100644 --- a/docs/contribute/internals.md +++ b/docs/contribute/internals.md @@ -10,7 +10,7 @@ The workspace separates contracts, authority, execution, verification and public ## Build order -The root build compiles `core`, `state`, `agent-pi`, `controller`, `taskpack-runner`, `memory`, `decisions`, `taskpack`, `github-app`, `hardware-runner`, then `cli`. Run `npm run build`, `npm run typecheck`, and `npm run lint` from the root. +The root build compiles `core`, `state`, `agent-pi`, `controller`, `taskpack-runner`, `memory`, `decisions`, `taskpack`, `github-app`, `hardware-runner`, `evolution`, then `cli`. Run `npm run build`, `npm run typecheck`, and `npm run lint` from the root. ## Authority boundaries @@ -18,6 +18,10 @@ 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. + +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. + Controller admits `version: 2` `tree_overlay` sources with `git ls-tree -r -l -z --full-tree`. Admission permits up to 65,536 regular files, an 8 MiB `source-tree` NDJSON artifact, and overlays up to 16,384 files / 16 GiB via `1 MiB` streaming CAS blobs and single-descriptor read-only projections. It skips protected Git symlinks (`120000`) and gitlinks (`160000`); unprotected ones fail admission. diff --git a/docs/contribute/memory.md b/docs/contribute/memory.md index c1124f4..d734a61 100644 --- a/docs/contribute/memory.md +++ b/docs/contribute/memory.md @@ -10,7 +10,7 @@ The package never mutates a primary `RunResult`, never spends exhausted model bu - [Three-tier separation](#three-tier-separation) - [Entries](#entries) - [Settled-outcome finalization](#settled-outcome-finalization) -- [Five-gate verification](#five-gate-verification) +- [Six-gate verification](#six-gate-verification) - [Compare-and-swap application](#compare-and-swap-application) - [Two-layer compaction](#two-layer-compaction) - [Commands](#commands) @@ -53,7 +53,9 @@ Each `entries/.md` carries the canonical JSON entry between `---` fences plu `checkCodeFingerprint` and `checkUpstreamVersions` default to `false`; when `currentCodeFingerprint` or `currentUpstreamVersions` is `null` or `undefined`, `selectActiveMemory` skips those exclusions. When non-null values are supplied, `selectActiveMemory` enforces `fingerprint_mismatch` and `upstream_version_changed`. -`selectActiveMemory` filters `ownExclusion` (including `targetMatrix`), `expired`, and `superseded` before applying `maxPromptEntries` (default `32`) and internal byte caps (`16_384` resource / `4_096` inline prompt). It keeps entries in priority order (`invariant` -> `failure_observation` -> `fact`, newest `verifiedAtMs` first) and sanitizes single-line claims. +`selectActiveMemory` filters `ownExclusion` (including `targetMatrix` and optional `hardwareScope`), `expired`, and `superseded` before applying `maxPromptEntries` (default `32`) and internal byte caps (`16_384` resource / `4_096` inline prompt). It keeps entries in priority order (`invariant` -> `failure_observation` -> `fact`, newest `verifiedAtMs` first) and sanitizes single-line claims. + +`MemoryEntry.scope.hardwareScope` optionally binds `{ accelerator, driverConstraint?, operatorFamily?, boundPipeline? }` (omitted when unset so v1 `storeDigest` and `proposalDigest` stay byte-identical). When present, `selectActiveMemory` excludes entries whose `accelerator` or `driverConstraint` mismatches the active `target.matrix` cell. Supersession requires a *valid* successor: an expired or drifted successor does not retire its predecessor. The snapshot digest covers store content only, not evaluation time, so drift detection compares meaningfully across calls. @@ -65,7 +67,7 @@ Supersession requires a *valid* successor: an expired or drifted successor does Passing checks on `completed` runs become `fact` entries bound to authenticated evidence. Deterministic `no_change` runs skip routine `fact` synthesis so healthy scheduled sweeps emit `operations: []` with zero PR churn. Failing, blocked, or absent checks become `failure_observation` entries, normalizing `/tmp/loopwright-gate-...` paths to ``. -Default retention uses a `15`-day TTL (`DEFAULT_MEMORY_TTL_DAYS = 15`) and `128` active entries (`DEFAULT_MEMORY_MAX_ENTRIES = 128`). `targetMatrix` passes through from config into `MemoryEntry.scope.targetMatrix`. +Default retention uses a `15`-day TTL (`DEFAULT_MEMORY_TTL_DAYS = 15`) and `128` active entries (`DEFAULT_MEMORY_MAX_ENTRIES = 128`). `targetMatrix` and optional `hardwareScope` pass through from matched hardware config cells into `MemoryEntry.scope`. Before capacity eviction, `finalizeRunMemory` eagerly emits `retire` operations for expired entries, drifted `upstreamVersions` (when `checkUpstreamVersions` is `true`), and healed `failure_observation` entries. Excess entries past `maxEntries` evict deterministically (`failure_observation` -> `fact` -> `invariant`, oldest `verifiedAtMs` first). @@ -76,7 +78,7 @@ The curator port runs only when budget remains and the port is configured. With With `onNoModelBudget: 'skip'`, finalization returns `pending` (`no_model_budget_skipped`) and emits no proposal. Emitted proposals carry the base store digest, revision, `memory.json`, and a unified `memory.patch` over `//`. -## Five-gate verification +## Six-gate verification `verifyMemoryProposal` re-checks every proposal before any store update: @@ -90,6 +92,7 @@ Emitted proposals carry the base store digest, revision, `memory.json`, and a un characters never reach proposal text. 5. `memory-review` — superseded ids exist and are active, supersession cycles and duplicate targets are rejected, and an unresolved claim-key overlap is a `MEMORY_CONFLICT_UNRESOLVED`. +6. `hardware-evidence` — any `upsert` of `kind: 'fact'` or `'invariant'` carrying `hardwareScope` must cite at least one `evidenceRef` with `level: 'hardware_execution'` and `observedStatus: 'passed'` (`MEMORY_HARDWARE_EVIDENCE_REQUIRED`); `failure_observation` entries admit without a passing hardware receipt. ## Compare-and-swap application @@ -97,13 +100,13 @@ Emitted proposals carry the base store digest, revision, `memory.json`, and a un Both `cas.ts` and `finalizer.ts` read bounded on-disk `index.json` preimage bytes, and `unifiedFileDiff` tracks EOF-newline state to emit `\ No newline at end of file` when migrating no-LF files. Rollback restores unlinked `.md` files (`0o600`) after backing up prior bytes. -Retiring or superseding an entry removes it from `index.entries`, leaves `index.retired: []`, and compacts any legacy `retired` rows. A matching `baseStoreDigest` and revision applies directly; a drifted store rebases only when disjoint and all five gates pass, otherwise failing with `MEMORY_CAS_CONFLICT`. +Retiring or superseding an entry removes it from `index.entries`, leaves `index.retired: []`, and compacts any legacy `retired` rows. A matching `baseStoreDigest` and revision applies directly; a drifted store rebases only when disjoint and all six gates pass, otherwise failing with `MEMORY_CAS_CONFLICT`. The result carries a `SeparateMemoryPullRequestSpec` with unified deletion diffs (`+++ /dev/null`) and `excludesCodeCandidatePaths: true`. `apply: separate-pull-request` opens cleanup PRs even when `no_change` runs only retire stale entries, while `local-only` and `disabled` skip remote memory PRs. In `@loopwright/github-app`, `separate-pull-request` skips non-passing (`failed`, `blocked`, `exhausted`, `expired`, `cancelled`) or incident runs by default (`publishOnFailure: false`) while `@loopwright/memory` and `local-only` still record `failure_observation` entries. Separate memory commits insert `[skip ci]` before the `Signed-off-by:` trailer (`skipCi: true`) while keeping subjects and PR titles clean. -`inline-with-candidate` skips runs without a published candidate PR. When a candidate PR is published, the host runs the same five-gate CAS check and appends a memory-only commit onto that PR branch with `--force-with-lease` and `skipCi: false` by default. +`inline-with-candidate` skips runs without a published candidate PR. When a candidate PR is published, the host runs the same six-gate CAS check and appends a memory-only commit onto that PR branch with `--force-with-lease` and `skipCi: false` by default. ## Two-layer compaction diff --git a/docs/development.md b/docs/development.md index 1ff9cf5..7e3b239 100644 --- a/docs/development.md +++ b/docs/development.md @@ -15,7 +15,7 @@ uses pinned Pi 1.6.0 packages. The root minimatch override applies to the resolv After installation, checks need no credentials, model, deployed service, Docker, or accelerator. The package is private and is not published. -Build emits `dist` across all 11 workspace packages (`core`, `state`, `agent-pi`, `controller`, `taskpack-runner`, `memory`, `decisions`, `taskpack`, `github-app`, `hardware-runner`, and `cli`); test compilation emits `.test-build`. Both are ignored, as are dependencies and root `.claude` scratch. Git permits `.claude/skills` and `.claude/settings.json`; reports, handoffs, and worktrees remain ignored. Tests use Node's test runner and public package boundaries. +Build emits `dist` across all 12 workspace packages (`core`, `state`, `agent-pi`, `controller`, `taskpack-runner`, `memory`, `decisions`, `taskpack`, `github-app`, `hardware-runner`, `evolution`, and `cli`); test compilation emits `.test-build`. Both are ignored, as are dependencies and root `.claude` scratch. Git permits `.claude/skills` and `.claude/settings.json`; reports, handoffs, and worktrees remain ignored. Tests use Node's test runner and public package boundaries. Private constructor seams isolate clock/transaction faults over actual SQLite; they are absent from the public state factories. Test files run serially to bound owned children. The integration fixture runs authoring, admission, candidate identity, evidence evaluation, and honest run construction. Example outputs are checked against this flow. @@ -109,6 +109,10 @@ LOOPWRIGHT_ROCM_SSH_HOST=user@gpu-host.example \ node --test .test-build/packages/hardware-runner/test/live-ssh-smoke.test.js ``` +### Evolution campaigns + +Run `node scripts/run-tests.mjs --pkg evolution --concurrency 1` to run `campaign.sqlite` store, Pareto, sampler, `team-patch.v1` supervisor, `evolution-bundle.v1`, and e2e tests offline (`allowSyntheticHardwareProbe: true`) under single-concurrency SQLite serialization. + ## Self-upgrade validation Loopwright dogfoods `.auto-sync/taskpack.yaml` to upgrade `@earendil-works/pi-*` in lockstep and `yaml` across workspace packages. Run the offline preflight check and contained verification suite locally: diff --git a/docs/getting-started/architecture.md b/docs/getting-started/architecture.md index fe62edc..a7eb0e0 100644 --- a/docs/getting-started/architecture.md +++ b/docs/getting-started/architecture.md @@ -25,7 +25,7 @@ Loopwright runs bounded repository work inside isolated sandboxes and verifies e ## Operating modes -Loopwright supports two distinct configuration and execution modes sharing one verification kernel: +Loopwright supports two single-run modes sharing one verification kernel, plus bounded multi-generation evolution (`@loopwright/evolution`) over isolated child `LocalRunStore` runs: | Dimension | Declarative taskpack | Managed controller | | --- | --- | --- | @@ -49,6 +49,7 @@ Every Loopwright document uses `apiVersion: loopwright.dev/v1alpha1` across decl | Managed mode | `TaskContract` | `apiVersion`, `kind`, `spec` | [Task Contract](../configuration/task-contract.md) | | Shared policy | `spec.sandbox` | Nested under `Taskpack.spec` | [Sandbox Backends](../configuration/sandbox-backends.md) | | Shared policy | `DecisionPolicy` | `apiVersion`, `kind`, `spec` | [Decision Routing](../configuration/decision-routing.md) | +| Evolution mode | `EvolutionCampaign` | `apiVersion`, `kind`, `metadata.name`, `spec` | [Task Contract](../configuration/task-contract.md#evolutioncampaign) | | Entry points | Action or `GitHubAppConfig` | Workflow or `apiVersion`, `kind`, `spec` | [GitHub Action](../operations/github-action.md) · [GitHub App](../operations/github-app.md) | ## Runtime baseline diff --git a/docs/operations/cli.md b/docs/operations/cli.md index 921f9d0..6b4239b 100644 --- a/docs/operations/cli.md +++ b/docs/operations/cli.md @@ -164,6 +164,12 @@ JSON output is NDJSON. An envelope with `kind: 'step'` contains `data.status: 'a | `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 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 | ### Suite commands @@ -183,34 +189,62 @@ Set `spec.listen.enabled: true` first. The command exits `2` for disabled or inv ### Hardware runner +![Hardware relay and outbound worker topology](../assets/diagrams/hardware-relay-flow.svg) + + + ```sh loopwright runner --help loopwright runner relay --config relay.yaml --json loopwright runner worker --config worker.yaml --once --json ``` -`runner relay` listens for controller submissions (`/v1/benchmark/jobs/*`) and worker pull-lease polls (`/v1/runner/leases*`) with monotonic `leaseEpoch` fencing and `1 MiB` CAS streaming. +`runner relay` decouples controllers from GPU clusters so worker hosts open zero inbound ports. Controllers submit signed jobs to `/v1/benchmark/jobs/*`, while workers poll `/v1/runner/leases*` outbound across heterogeneous pools (`sm_89`, `gfx1101`, `ascend_910b`). -`runner worker` opens zero inbound ports, pulls leases outbound over HTTPS or loopback HTTP, compiles Stage A artifacts without `held_out_workloads`, executes Stage B benchmarks read-only under `networkMode: none`, and returns signed verdicts. +The relay isolates credentials (`controllerSigningSecret` vs `workerToken`), enforces monotonic `leaseEpoch` preemption fencing, and streams `1 MiB` CAS artifacts. Workers compile Stage A without `held_out_workloads`, run Stage B read-only under `networkMode: none`, and return signed verdicts. - **Graceful shutdown (`SIGINT`)**: Exits `130` (`runner worker` returns `8` if an `unknown` settlement takes precedence). - **Preemption (`SIGTERM`)**: Reports lease preemption to the relay and exits `143`, unless superseded by `unknown` (`8`) or a `fenced` preemption acknowledgment (`7`). - **Fenced lease (`7`)**: Exits `7` when the relay rejects a stale `leaseEpoch` or `relayBootId` (`QUEUE_LEASE_FENCED`). - **Unknown or teardown (`8`)**: Exits `8` on `unknown` acknowledgment, `RUNNER_TEARDOWN_FAILED`, or `RUNNER_TRANSPORT_ERROR`. +### Evolution campaigns + +```sh +loopwright evolve check --campaign campaign.yaml --repo . --json +loopwright evolve run --campaign campaign.yaml --state ../campaign-state --repo . --allow-synthetic-probe --json +loopwright evolve resume --campaign ../campaign-state --repo . --json +loopwright evolve status --campaign ../campaign-state --json +loopwright evolve inspect --campaign ../campaign-state --island 0 --json +loopwright evolve export --campaign ../campaign-state --out ../bundle --format oci-layout --json +``` + +`evolve` lazily loads `@loopwright/evolution`, persists archive state in `/campaign.sqlite`, and dispatches each candidate into an isolated child `LocalRunStore`. Keep `--state` (`--campaign-dir` / `--root`) outside `--repo` or runs fail closed with `EVOLUTION_SCHEMA_INVALID` (`2`). + +`evolve export` verifies every HMAC verdict receipt fail-closed (`EXPORT_UNVERIFIED_FORBIDDEN`, exit `3` when no signing secret is set) and rejects `synthetic_fixture` receipts unless `--allow-synthetic-probe` is passed. GitHub Actions workflows can run `loopwright evolve` against an HTTPS `runner relay` (or self-hosted loopback relay) using `permissions: { contents: read }` and state under `${RUNNER_TEMP}`. + +| Environment variable | Purpose | +| --- | --- | +| `LOOPWRIGHT_BENCHMARK_GATE_URL` | Fallback HTTPS or loopback `benchmark-gate.v1` submission URL for `runner relay` | +| `LOOPWRIGHT_GATE_SIGNING_SECRET` | Required HMAC secret for benchmark submission and fail-closed `evolve export` (`BENCH_SIGNING_SECRET` fallback) | +| `LOOPWRIGHT_GATE_AUTH_TOKEN` | Optional bearer token bound to `authCredentialRef` on remote `runner relay` endpoints | +| `LOOPWRIGHT_MODELS_JSON` | Optional Pi `models.json` path for custom providers and local model endpoints | + ## Exit codes | Code | Meaning | | --- | --- | | 0 | Completed, no change, successful static command, or `suite` `eligible`/`deferred`/`ignored` | -| 2 | Usage, configuration, unknown `--domain`, or `TaskpackSuite` manifest rejected | -| 3 | Unsupported capability or runtime `blocked` (`baseline_merge_conflict`, stage probe, branch mismatch) | -| 4 | Execution or acceptance failed | -| 5 | Allowance exhausted | +| 2 | Usage, configuration, unknown `--domain`, or `TaskpackSuite`/`EvolutionCampaign` manifest rejected | +| 3 | Unsupported capability, blocked work, `TEAM_ENVELOPE_VIOLATION`, `EXPORT_UNVERIFIED_FORBIDDEN`, or `WORKER_DEVICE_QUARANTINED` | +| 4 | Execution, acceptance, or artifact validation failed | +| 5 | Allowance or campaign budget exhausted | | 6 | Deadline expired | -| 7 | Reconciliation, ownership needed, or fenced runner lease | -| 8 | Authoritative result unavailable, incident, or runner teardown failure | -| 130 | Step cancellation or accounted SIGINT, subject to uncertainty precedence | +| 7 | Reconciliation, `EVOLUTION_CONFLICT`, `EVOLUTION_LEASE_FENCED`, `EVOLUTION_CLOCK_DRIFT`, or fenced runner lease | +| 8 | Authoritative result unavailable, incident, store corruption, or runner teardown failure | +| 130 | Step cancellation, paused evolution campaign, or accounted SIGINT, subject to uncertainty precedence | | 143 | Accounted SIGTERM, subject to uncertainty precedence | --- diff --git a/package-lock.json b/package-lock.json index ff83f5c..3748823 100644 --- a/package-lock.json +++ b/package-lock.json @@ -18,7 +18,8 @@ "packages/github-app", "packages/memory", "packages/decisions", - "packages/hardware-runner" + "packages/hardware-runner", + "packages/evolution" ], "devDependencies": { "@eslint/js": "10.0.1", @@ -873,6 +874,10 @@ "resolved": "packages/decisions", "link": true }, + "node_modules/@loopwright/evolution": { + "resolved": "packages/evolution", + "link": true + }, "node_modules/@loopwright/github-app": { "resolved": "packages/github-app", "link": true @@ -2820,6 +2825,7 @@ "@loopwright/controller": "0.0.0", "@loopwright/core": "0.0.0", "@loopwright/decisions": "0.0.0", + "@loopwright/evolution": "0.0.0", "@loopwright/github-app": "0.0.0", "@loopwright/hardware-runner": "0.0.0", "@loopwright/memory": "0.0.0", @@ -2913,6 +2919,20 @@ "url": "https://github.com/sponsors/eemeli" } }, + "packages/evolution": { + "name": "@loopwright/evolution", + "version": "0.0.0", + "dependencies": { + "@loopwright/controller": "0.0.0", + "@loopwright/core": "0.0.0", + "@loopwright/decisions": "0.0.0", + "@loopwright/hardware-runner": "0.0.0", + "@loopwright/taskpack": "0.0.0" + }, + "engines": { + "node": "26.x" + } + }, "packages/github-app": { "name": "@loopwright/github-app", "version": "0.0.0", diff --git a/package.json b/package.json index c4b5458..0e5c7f3 100644 --- a/package.json +++ b/package.json @@ -19,7 +19,8 @@ "packages/github-app", "packages/memory", "packages/decisions", - "packages/hardware-runner" + "packages/hardware-runner", + "packages/evolution" ], "scripts": { "build": "node scripts/build.mjs", diff --git a/packages/cli/package.json b/packages/cli/package.json index 1eae4e2..456f899 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -11,6 +11,7 @@ "@loopwright/controller": "0.0.0", "@loopwright/core": "0.0.0", "@loopwright/decisions": "0.0.0", + "@loopwright/evolution": "0.0.0", "@loopwright/github-app": "0.0.0", "@loopwright/hardware-runner": "0.0.0", "@loopwright/memory": "0.0.0", diff --git a/packages/cli/src/arguments.ts b/packages/cli/src/arguments.ts index 4020a20..6035ab6 100644 --- a/packages/cli/src/arguments.ts +++ b/packages/cli/src/arguments.ts @@ -5,12 +5,14 @@ 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 interface Arguments { - readonly command: 'init' | 'check' | 'run' | 'resume' | 'reconcile' | 'status' | 'inspect' | 'closure' | 'app-serve' | 'step' | 'digest' | 'suite' | 'runner'; + readonly command: 'init' | 'check' | 'run' | 'resume' | 'reconcile' | 'status' | 'inspect' | 'closure' | 'app-serve' | 'step' | 'digest' | 'suite' | 'runner' | 'evolve'; readonly stepAction?: StepAction; readonly digestAction?: DigestAction; readonly suiteAction?: SuiteAction; readonly runnerAction?: RunnerAction; + readonly evolveAction?: EvolveAction; readonly roleModelOverrides?: readonly RoleModelOverride[]; readonly values: ReadonlyMap; readonly flags: ReadonlySet; @@ -21,7 +23,7 @@ interface CommandRule { readonly flags: readonly string[]; readonly allowRoleModel?: boolean; } -const commands: Record, CommandRule> = { +const commands: Record, CommandRule> = { init: { required: ['directory'], values: ['directory'], flags: ['force', 'json'] }, check: { required: ['config', 'registry', 'registry-sha256'], values: ['config', 'registry', 'registry-sha256', 'output'], flags: ['json'], allowRoleModel: true }, run: { required: [], values: ['config', 'registry', 'registry-sha256', 'taskpack', 'mode', 'baseline-alignment', 'source-revision', 'repo', 'run-root', 'run-id', 'output', 'output-format', 'step-summary-file', 'allow-host-mounts'], flags: ['json', 'dry-run', 'allow-privileged', 'allow-workflow-writes'], allowRoleModel: true }, @@ -63,6 +65,39 @@ const runnerRules: Record = { flags: ['once', 'json'], }, }; +const evolveRules: Record = { + check: { + required: ['campaign'], + values: ['campaign', 'repo'], + flags: ['json'], + }, + run: { + required: ['campaign'], + values: ['campaign', 'state', 'campaign-dir', 'root', 'repo', 'out', 'format'], + flags: ['allow-synthetic-probe', 'json'], + }, + resume: { + required: [], + values: ['campaign', 'campaign-dir', 'root', 'repo', 'out', 'format'], + flags: ['allow-synthetic-probe', 'json'], + }, + status: { + required: [], + values: ['campaign', 'campaign-dir', 'root'], + flags: ['json'], + }, + inspect: { + required: [], + values: ['campaign', 'campaign-dir', 'root', 'island', 'individual'], + flags: ['json'], + }, + export: { + required: ['out'], + values: ['campaign', 'campaign-dir', 'root', 'out', 'format'], + flags: ['allow-synthetic-probe', 'overwrite', 'json'], + }, +}; +export const EVOLVE_ACTIONS: readonly EvolveAction[] = Object.freeze(Object.keys(evolveRules) as EvolveAction[]); const stepRules: Record = { next: { required: ['run-root', 'run-id'], @@ -274,7 +309,44 @@ export function parseArguments(argv: readonly string[]): Arguments { }; } - const command = rawCommand as Exclude; + if (rawCommand === 'evolve') { + const rawAction = argv[1]; + if (typeof rawAction !== 'string' || !Object.hasOwn(evolveRules, rawAction)) { + throw new UsageError(); + } + const action = rawAction as keyof typeof evolveRules; + const rule = evolveRules[action]; + parseOptions(2, key => rule.flags.includes(key), key => rule.values.includes(key), false); + if (rule.required.some(key => !values.has(key))) throw new UsageError(); + for (const val of values.values()) { + if (val.trim().length === 0) throw new UsageError(); + } + 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 (values.has('format')) { + const fmt = values.get('format')!; + if (fmt !== 'dir' && fmt !== 'oci-layout') throw new UsageError(); + } + if (values.has('island')) { + if (!/^(?:0|[1-9][0-9]{0,5})$/.test(values.get('island')!)) throw new UsageError(); + } + if (values.has('individual')) { + if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(values.get('individual')!)) throw new UsageError(); + } + return { + command: 'evolve', + evolveAction: action, + values, + flags, + }; + } + + const command = rawCommand as Exclude; if (!Object.hasOwn(commands, command)) throw new UsageError(); const rule = commands[command]; parseOptions(1, key => rule.flags.includes(key), key => rule.values.includes(key), rule.allowRoleModel === true); diff --git a/packages/cli/src/closure.ts b/packages/cli/src/closure.ts index c58a240..70bfeff 100644 --- a/packages/cli/src/closure.ts +++ b/packages/cli/src/closure.ts @@ -18,7 +18,7 @@ export type ClosureDisposition = 'closed_local' | 'deferred_owned' | 'blocked_ex 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' | '@loopwright/taskpack-runner' | '@loopwright/memory' | '@loopwright/taskpack' | '@loopwright/github-app' | '@loopwright/decisions' - | '@loopwright/hardware-runner'; + | '@loopwright/hardware-runner' | '@loopwright/evolution'; export type ClosureSubsystem = string; export interface ClosureCapabilityEntry { readonly id: ClosureCapabilityId; @@ -86,7 +86,7 @@ export interface ClosureMatrixReport { const DISPOSITIONS: readonly ClosureDisposition[] = ['closed_local', 'deferred_owned', 'blocked_external']; const EVIDENCE_LEVELS: readonly ClosureEvidenceLevel[] = ['unit_and_integration', 'controlled_local_qualification', 'frozen_offline_parity', 'unprovisioned_external']; const STATUSES: readonly ClosureCapabilityEntry['verificationStatus'][] = ['passed', 'failed', 'blocked', 'not_run']; -const OWNER_PACKAGES: readonly ClosureOwnerPackage[] = ['@loopwright/core', '@loopwright/state', '@loopwright/agent-pi', '@loopwright/controller', '@loopwright/cli', '@loopwright/taskpack-runner', '@loopwright/memory', '@loopwright/taskpack', '@loopwright/github-app', '@loopwright/decisions', '@loopwright/hardware-runner']; +const OWNER_PACKAGES: readonly ClosureOwnerPackage[] = ['@loopwright/core', '@loopwright/state', '@loopwright/agent-pi', '@loopwright/controller', '@loopwright/cli', '@loopwright/taskpack-runner', '@loopwright/memory', '@loopwright/taskpack', '@loopwright/github-app', '@loopwright/decisions', '@loopwright/hardware-runner', '@loopwright/evolution']; function text(value: unknown): string { return typeof value === 'string' ? value : ''; } function entryShapeErrors(entry: ClosureCapabilityEntry, path: string): ClosureDiagnostic[] { const errors: ClosureDiagnostic[] = []; diff --git a/packages/cli/src/evolve.ts b/packages/cli/src/evolve.ts new file mode 100644 index 0000000..f1927ca --- /dev/null +++ b/packages/cli/src/evolve.ts @@ -0,0 +1,1397 @@ +import { execFile } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { chmod, mkdir, mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { dirname, join, resolve } from 'node:path'; +import { promisify } from 'node:util'; + +const execFileAsync = promisify(execFile); +import { + SecretScrubber as CoreSecretScrubber, + type Digest, +} from '@loopwright/core'; +import { + inspectRun, + loadTrustedConfiguration, + resolveCanonicalCasBlobPath, + runCycleWithPorts, + type ControllerPorts, + type RunEvalReport, +} from '@loopwright/controller'; +import { + buildDefaultAuthorPrompt, + collectManifestSecretEnvNames, + compileDeclarativeTaskpack, + createTaskpackDecisionPort, + DEFAULT_HOST_BUDGETS, + DEFAULT_LOCAL_COMMAND_GATE_ENV, + loadPiModelsJson, + LOOPWRIGHT_ACTIVE_PROVIDER_TOKEN_ENV, + makeAttemptRunId, + parseTaskpackManifest, + resolveDefaultProviderTokenEnv, + resolveTaskpackModelCandidates, + SecretScrubber as TaskpackSecretScrubber, + serializePrettyYaml, + stageCompiledInstructionResources, + startLocalCommandGateServer, + type CompiledTaskpack, + type ExecutionHostPolicy, + type HostGateEndpointPlan, + type LocalCommandGateServer, + type ParsedPiModelsJson, + type ResolvedModelCandidate, + type TaskpackManifest, + type WrittenCompiledTaskpack, +} from '@loopwright/taskpack'; +import type { + CandidateEvaluationProposal, + CandidateEvaluationResult, + CandidateEvaluator, + IndividualStatus, + ReadOnlySupervisorTurnContext, + SupervisorRunnerPort, +} from '@loopwright/evolution'; +import type { DecisionMutationNoveltyResult } from '@loopwright/decisions'; + +type OpenPiHostSessionAdapterV2Fn = typeof import('@loopwright/agent-pi/host-session')['openPiHostSessionAdapterV2']; +type EvolutionModule = typeof import('@loopwright/evolution'); + +function createLazyHostSessionLoader(): () => Promise { + let promise: Promise | null = null; + return () => { + promise ??= import('@loopwright/agent-pi/host-session').then(mod => mod.openPiHostSessionAdapterV2); + return promise; + }; +} + +async function writeCompiledEvolutionDir( + trustedDirectory: string, + compiled: CompiledTaskpack, + proposal: CandidateEvaluationProposal, + scrubber: TaskpackSecretScrubber, + evolution: EvolutionModule, +): Promise { + const registryDirectory = join(trustedDirectory, 'registry'); + const configDirectory = join(trustedDirectory, 'config'); + await mkdir(registryDirectory, { recursive: true, mode: 0o700 }); + await mkdir(configDirectory, { recursive: true, mode: 0o700 }); + await chmod(trustedDirectory, 0o700); + await chmod(registryDirectory, 0o700); + await chmod(configDirectory, 0o700); + + const extraResources: Array<{ + readonly id: string; + readonly kind: 'document'; + readonly path: string; + readonly digest: Digest; + }> = []; + + // Read and secret-check all staged parent and scratchpad bytes before writing anything to + // registryDirectory so a SECRET_LEAK_DETECTED refusal never leaves partial files on disk. + const stagedParentsToWrite: Array<{ readonly relPath: string; readonly bytes: Buffer; readonly digest: Digest }> = []; + for (let i = 0; i < proposal.stagedParentFiles.length; i += 1) { + const pf = proposal.stagedParentFiles[i]!; + const relPath = `.loopwright-evo/parents/parent-${i}.json`; + const bytes = await readFile(pf.filePath); + if (scrubber.containsSecret(bytes.toString('utf8'))) { + throw new evolution.EvolutionError( + 'SECRET_LEAK_DETECTED', + `staged evolution parent context "${relPath}" contained a registered secret and was refused`, + ); + } + const verifiedDigest = evolution.sha256Digest(bytes); + if (verifiedDigest.hex !== pf.digest.hex) { + throw new evolution.EvolutionError( + 'ARTIFACT_INVALID', + `staged evolution parent context "${relPath}" digest mismatch against staged digest`, + ); + } + stagedParentsToWrite.push({ relPath, bytes, digest: verifiedDigest }); + } + + let stagedScratchpadToWrite: { readonly relPath: string; readonly bytes: Buffer; readonly digest: Digest } | null = null; + if (proposal.stagedScratchpadPath !== undefined) { + const scBytes = await readFile(proposal.stagedScratchpadPath); + if (scrubber.containsSecret(scBytes.toString('utf8'))) { + throw new evolution.EvolutionError( + 'SECRET_LEAK_DETECTED', + 'staged evolution scratchpad contained a registered secret and was refused', + ); + } + stagedScratchpadToWrite = { + relPath: '.loopwright-evo/scratchpad/latest.md', + bytes: scBytes, + digest: evolution.sha256Digest(scBytes), + }; + } + + if (stagedParentsToWrite.length > 0) { + const parentResDir = join(registryDirectory, '.loopwright-evo', 'parents'); + await mkdir(parentResDir, { recursive: true, mode: 0o700 }); + for (let i = 0; i < stagedParentsToWrite.length; i += 1) { + const item = stagedParentsToWrite[i]!; + const dstPath = join(registryDirectory, item.relPath); + await writeFile(dstPath, item.bytes, { mode: 0o400 }); + await chmod(dstPath, 0o400); + extraResources.push({ + id: `evo-parent-${i}`, + kind: 'document', + path: item.relPath, + digest: item.digest, + }); + } + } + + if (stagedScratchpadToWrite !== null) { + const scDir = join(registryDirectory, '.loopwright-evo', 'scratchpad'); + await mkdir(scDir, { recursive: true, mode: 0o700 }); + const dstPath = join(registryDirectory, stagedScratchpadToWrite.relPath); + await writeFile(dstPath, stagedScratchpadToWrite.bytes, { mode: 0o400 }); + await chmod(dstPath, 0o400); + extraResources.push({ + id: 'evo-scratchpad', + kind: 'document', + path: stagedScratchpadToWrite.relPath, + digest: stagedScratchpadToWrite.digest, + }); + } + + const patchRoleById = new Map( + (proposal.teamPatch?.roles ?? []).map(r => [r.id, r] as const), + ); + const updatedRoleProfiles = compiled.registry.spec.roleProfiles.map(prof => { + for (const [rId, pr] of patchRoleById.entries()) { + if ((prof.id === rId || prof.id === `taskpack.profile.${rId}`) && pr.timeoutSeconds !== undefined) { + const requestedWallMs = pr.timeoutSeconds * 1000; + const currentWallMs = prof.limits?.toolWallMs; + const narrowedWallMs = currentWallMs !== undefined ? Math.min(currentWallMs, requestedWallMs) : requestedWallMs; + return { + ...prof, + limits: { + ...prof.limits, + toolWallMs: narrowedWallMs, + }, + }; + } + } + return prof; + }); + + const finalRegistry = { + ...compiled.registry, + spec: { + ...compiled.registry.spec, + resources: extraResources.length > 0 + ? [...compiled.registry.spec.resources, ...extraResources] + : compiled.registry.spec.resources, + roleProfiles: updatedRoleProfiles, + }, + }; + const registryBytes = Buffer.from(`${JSON.stringify(finalRegistry, null, 2)}\n`, 'utf8'); + const registrySha256 = createHash('sha256').update(registryBytes).digest('hex'); + + const extraResourceIds = extraResources.map(r => r.id); + const updatedTaskRoles = compiled.config.spec.task.spec.roles.map(role => { + const pr = patchRoleById.get(role.id); + const baseResIds = pr?.resourceIds !== undefined ? [...pr.resourceIds] : role.resourceIds; + if (baseResIds === undefined) { + return role; + } + const mergedResIds = extraResourceIds.length > 0 + ? Array.from(new Set([...baseResIds, ...extraResourceIds])) + : Array.from(new Set(baseResIds)); + return { + ...role, + resourceIds: mergedResIds, + }; + }); + + const finalTask = { + ...compiled.config.spec.task, + spec: { + ...compiled.config.spec.task.spec, + roles: updatedTaskRoles, + trustedContext: extraResources.length > 0 + ? { + ...compiled.config.spec.task.spec.trustedContext, + resources: [...compiled.config.spec.task.spec.trustedContext.resources, ...extraResources], + } + : compiled.config.spec.task.spec.trustedContext, + }, + }; + + const finalConfig = { + ...compiled.config, + spec: { + ...compiled.config.spec, + registry: { + name: finalRegistry.metadata.name, + digest: { algorithm: 'sha256' as const, hex: registrySha256 }, + }, + task: finalTask, + }, + }; + + const configBytes = Buffer.from(serializePrettyYaml(finalConfig), 'utf8'); + const scrubCheck = (bytes: Buffer, label: string): void => { + const text = bytes.toString('utf8'); + if (scrubber.containsSecret(text)) { + throw new Error(`secret pattern detected in compiled ${label}`); + } + }; + scrubCheck(registryBytes, 'registry'); + scrubCheck(configBytes, 'config'); + + const registryPath = join(registryDirectory, 'registry.yaml'); + const configPath = join(configDirectory, 'config.yaml'); + await writeFile(registryPath, registryBytes, { mode: 0o600 }); + await writeFile(configPath, configBytes, { mode: 0o600 }); + await chmod(registryPath, 0o600); + await chmod(configPath, 0o600); + if (compiled.instructionResources !== undefined && compiled.instructionResources.length > 0) { + await stageCompiledInstructionResources(registryDirectory, compiled.instructionResources); + } + + return { + ...compiled, + registry: finalRegistry, + registryBytes, + registrySha256, + config: finalConfig, + configBytes, + trustedDirectory, + registryPath, + configPath, + }; +} + +async function extractSliceFromWorkspaceDir( + workspaceDir: string, + fallbackRepoDir: string, + guardedFiles: readonly string[], + fallbackId: string, + evolution: EvolutionModule, +): Promise { + if (guardedFiles.length === 0) { + return `// individual:${fallbackId}\n`; + } + const slices: string[] = []; + for (const rel of guardedFiles) { + const content = await readFile(join(workspaceDir, rel), 'utf8') + .catch(() => readFile(join(fallbackRepoDir, rel), 'utf8').catch(() => '')); + if (content.length > 0) { + slices.push(evolution.extractEvolveBlocksFromSource(content)); + } + } + return slices.length > 0 ? slices.join('\n') : `// individual:${fallbackId}\n`; +} + +async function extractCandidateGuardedCodeSlice( + controllerRunRoot: string, + attemptRunId: string, + childRepoDir: string, + guardedFiles: readonly string[], + fallbackId: string, + evolution: EvolutionModule, +): Promise { + if (guardedFiles.length === 0) { + return `// individual:${fallbackId}\n`; + } + const artifactsDir = join(controllerRunRoot, attemptRunId, 'artifacts'); + const tmpHolder = await mkdtemp(join(await realpath(tmpdir()), 'lw-evo-cand-inspect-')); + const fileDigestMap = new Map(); + const fileContentMap = new Map(); + try { + const inspected = await inspectRun({ + runRoot: controllerRunRoot, + runId: attemptRunId, + output: join(tmpHolder, 'bundle'), + }).catch(() => null); + if (inspected !== null && inspected.ok) { + const rawCandidate = await readFile(join(tmpHolder, 'bundle', 'candidate.files.json'), 'utf8').catch(() => null); + if (rawCandidate !== null) { + let parsed: { + readonly files?: readonly { + readonly name?: unknown; + readonly sha256?: unknown; + readonly encoding?: unknown; + readonly body?: unknown; + }[]; + }; + try { + parsed = JSON.parse(rawCandidate) as typeof parsed; + } catch { + parsed = {}; + } + if (Array.isArray(parsed.files)) { + for (const entry of parsed.files) { + if (typeof entry.name !== 'string') continue; + if (typeof entry.sha256 === 'string') { + fileDigestMap.set(entry.name, entry.sha256); + } else if (entry.encoding === 'base64' && typeof entry.body === 'string') { + fileContentMap.set(entry.name, Buffer.from(entry.body, 'base64').toString('utf8')); + } + } + } + } + } + } finally { + await rm(tmpHolder, { recursive: true, force: true }).catch(() => undefined); + } + + const slices: string[] = []; + for (const rel of guardedFiles) { + let content = fileContentMap.get(rel) ?? ''; + if (content.length === 0) { + const hex = fileDigestMap.get(rel); + if (hex !== undefined) { + const casPath = await resolveCanonicalCasBlobPath(artifactsDir, hex).catch(() => null); + if (casPath !== null) { + content = await readFile(casPath, 'utf8').catch(() => ''); + } + } + } + if (content.length === 0) { + content = await readFile(join(childRepoDir, rel), 'utf8').catch(() => ''); + } + if (content.length > 0) { + slices.push(evolution.extractEvolveBlocksFromSource(content)); + } + } + return slices.length > 0 ? slices.join('\n') : `// individual:${fallbackId}\n`; +} + +function buildEffectiveEnv( + runtimeEnv: NodeJS.ProcessEnv, + ephemeralEnv: Readonly>, + scrubber: TaskpackSecretScrubber, +): Record { + const effectiveEnv: Record = Object.create(null) as Record; + for (const [key, value] of Object.entries(runtimeEnv)) { + if (value !== undefined) { + effectiveEnv[key] = value; + } + } + for (const [key, value] of Object.entries(ephemeralEnv)) { + effectiveEnv[key] = value; + if (value.length > 0) scrubber.register(value); + } + const activeToken = effectiveEnv[LOOPWRIGHT_ACTIVE_PROVIDER_TOKEN_ENV]; + if (typeof activeToken === 'string' && activeToken.length > 0) { + scrubber.register(activeToken); + } + return effectiveEnv; +} + +function createEvolutionOpenAdapter(options: { + readonly writtenTaskpack: WrittenCompiledTaskpack; + readonly effectiveEnv: Readonly>; + readonly scrubber: TaskpackSecretScrubber; + readonly openPiHostSessionAdapterV2: OpenPiHostSessionAdapterV2Fn; + readonly onAfterExecute?: ((candidateDir: string, stepId: string, roleId: string) => Promise | void) | undefined; + readonly onAfterCapture?: ((artifactsDirectory: string, sessionArtifactName: string) => Promise | void) | undefined; +}): NonNullable { + const { writtenTaskpack, effectiveEnv, scrubber, openPiHostSessionAdapterV2, onAfterExecute, onAfterCapture } = options; + + return async (host, adapterInput) => { + const wrappedHost = { + ...host, + resolveCredential: async (binding: Parameters[0]) => { + let originalError: unknown; + try { + const bound = await host.resolveCredential(binding); + if (bound.bearerToken.length > 0) return bound; + } catch (err: unknown) { + // Fall through to active candidate token only for taskpack provider bindings. + originalError = err; + } + const bindingMeta = binding as { readonly env?: unknown; readonly ref?: unknown }; + const hasExplicitMeta = bindingMeta.env !== undefined || bindingMeta.ref !== undefined; + const boundRoleMapping = writtenTaskpack.config.spec.profiles.roles.find( + item => item.roleId === adapterInput.roleId, + ); + const roleProfile = boundRoleMapping === undefined + ? undefined + : writtenTaskpack.registry.spec.roleProfiles.find( + item => item.id === boundRoleMapping.profileRef, + ); + const explicitEntry = hasExplicitMeta + ? writtenTaskpack.registry.spec.credentialBindings.find(entry => + entry.consumer === 'provider' + && ( + (typeof bindingMeta.ref === 'string' && entry.id === bindingMeta.ref) + || (typeof bindingMeta.env === 'string' && entry.environmentNames.includes(bindingMeta.env)) + )) + : undefined; + const matchesExplicitMeta = + bindingMeta.env === LOOPWRIGHT_ACTIVE_PROVIDER_TOKEN_ENV + || bindingMeta.ref === 'taskpack-provider-token' + || (explicitEntry?.environmentNames.includes(LOOPWRIGHT_ACTIVE_PROVIDER_TOKEN_ENV) ?? false); + const matchesRegistryProviderBinding = writtenTaskpack.registry.spec.credentialBindings.some(entry => + entry.consumer === 'provider' + && entry.destinationRef === binding.provider + && (roleProfile?.providerCredentialRef === undefined || entry.id === roleProfile.providerCredentialRef) + && (entry.id === 'taskpack-provider-token' || entry.environmentNames.includes(LOOPWRIGHT_ACTIVE_PROVIDER_TOKEN_ENV)), + ); + if ((hasExplicitMeta && matchesExplicitMeta) || (!hasExplicitMeta && matchesRegistryProviderBinding)) { + const active = effectiveEnv[LOOPWRIGHT_ACTIVE_PROVIDER_TOKEN_ENV]; + if (typeof active === 'string' && active.length > 0) { + return { bearerToken: active }; + } + } + throw new Error( + 'missing provider credential for active candidate', + originalError !== undefined ? { cause: originalError } : undefined, + ); + }, + }; + + const opened = await openPiHostSessionAdapterV2(wrappedHost, adapterInput, { + scrub: text => scrubber.scrub(text), + }); + if (!opened.ok) { + return opened; + } + + const inner = opened.value; + const sessionCandidateDir = join(host.directory, `sdk-${adapterInput.sessionId}`, 'candidate'); + return { + ok: true, + value: { + capabilities: () => inner.capabilities(), + events: () => inner.events(), + close: () => inner.close(), + cancel: input => inner.cancel(input), + compact: input => inner.compact(input), + execute: async input => { + const res = await inner.execute(input); + if (res.ok && res.value.status === 'execution_settled' && onAfterExecute !== undefined) { + await onAfterExecute(sessionCandidateDir, adapterInput.stepId, adapterInput.roleId); + } + return res; + }, + capture: async input => { + const res = await inner.capture(input); + if (res.ok && onAfterCapture !== undefined) { + await onAfterCapture(host.artifactsDirectory, res.value.session.name); + } + return res; + }, + }, + }; + }; +} + +function extractLastAssistantTextFromSessionJsonl(sessionText: string): string | null { + const lines = sessionText.split('\n'); + let lastAssistantText: string | null = null; + for (let i = 1; i < lines.length; i += 1) { + const line = lines[i]?.trim(); + if (!line) continue; + let entry: unknown; + try { + entry = JSON.parse(line); + } catch { + continue; + } + if (entry === null || typeof entry !== 'object') continue; + const rec = entry as { readonly type?: unknown; readonly message?: unknown }; + if (rec.type !== 'message' || rec.message === null || typeof rec.message !== 'object') continue; + const msg = rec.message as { readonly role?: unknown; readonly content?: unknown }; + if (msg.role !== 'assistant') continue; + if (typeof msg.content === 'string') { + lastAssistantText = msg.content; + } else if (Array.isArray(msg.content)) { + let combined = ''; + for (const block of msg.content) { + if (block !== null && typeof block === 'object') { + const b = block as { readonly type?: unknown; readonly text?: unknown }; + if (b.type === 'text' && typeof b.text === 'string') { + combined += b.text; + } + } + } + if (combined.length > 0) { + lastAssistantText = combined; + } + } + } + return lastAssistantText; +} + +function unwrapOptionalJsonCodeFence(rawText: string): string { + const trimmed = rawText.trim(); + const fenced = /^```(?:json)?\s*\n([\s\S]*?)\n```\s*$/i.exec(trimmed); + return fenced !== null ? fenced[1]!.trim() : trimmed; +} + +/** + * Create a lazy-loaded Pi-backed `CandidateEvaluator` for CLI `evolve run` and `evolve resume`. + */ +export function createCliEvolutionEvaluator(options: { + readonly repositoryRoot: string; + readonly coreScrubber: CoreSecretScrubber; + readonly taskpackScrubber: TaskpackSecretScrubber; +}): CandidateEvaluator { + const openPiHostSessionPromise = createLazyHostSessionLoader(); + + const resolvedBaseRepo = resolve(options.repositoryRoot); + const coreScrubber = options.coreScrubber; + const taskpackScrubber = options.taskpackScrubber; + const registerSecret = (val: string): void => { + if (val.length > 0) { + coreScrubber.register(val); + taskpackScrubber.register(val); + } + }; + + return async (proposal: CandidateEvaluationProposal): Promise => { + const evolution = await import('@loopwright/evolution'); + const openPiHostSessionAdapterV2 = await openPiHostSessionPromise(); + + await mkdir(proposal.childRunDir, { recursive: true, mode: 0o700 }); + const childRunDir = await realpath(proposal.childRunDir); + const realBaseRepo = await realpath(resolvedBaseRepo); + const childRepoDir = join(childRunDir, 'repo'); + const controllerRunRoot = join(childRunDir, 'controller'); + const runId = evolution.sanitizeRunId(proposal.individualId); + const attemptRunId = makeAttemptRunId(runId, 0); + + await evolution.materializeGitCheckoutNoFollow(realBaseRepo, childRepoDir); + + const scopedTaskpack = evolution.buildStageScopedTaskpack({ + taskpack: proposal.taskpack, + heldOutWorkloadId: proposal.heldOutWorkloadId, + targetCellId: proposal.manifest.spec.targetCellId, + ...(proposal.teamPatch !== undefined ? { teamPatch: proposal.teamPatch } : {}), + }); + + for (const envName of collectManifestSecretEnvNames(scopedTaskpack)) { + const val = process.env[envName]; + if (typeof val === 'string' && val.length > 0) registerSecret(val); + } + + const modelsJsonPath = process.env['LOOPWRIGHT_MODELS_JSON']?.trim() || undefined; + const modelsConfig: ParsedPiModelsJson | undefined = modelsJsonPath !== undefined + ? await loadPiModelsJson(modelsJsonPath) + : undefined; + const allowManifestCustomBaseUrl = process.env['LOOPWRIGHT_ALLOW_MANIFEST_CUSTOM_BASE_URL'] === 'true'; + + const gateEndpoints: HostGateEndpointPlan[] = []; + const byCredentialRef: Record = {}; + const benchmarkGateEnvUrl = process.env['LOOPWRIGHT_BENCHMARK_GATE_URL']?.trim(); + let defaultBenchSecretEnv = 'LOOPWRIGHT_GATE_SIGNING_SECRET'; + if (!process.env['LOOPWRIGHT_GATE_SIGNING_SECRET']?.trim() && process.env['BENCH_SIGNING_SECRET']?.trim()) { + defaultBenchSecretEnv = 'BENCH_SIGNING_SECRET'; + } + + for (const extGate of scopedTaskpack.spec.verification.externalGates) { + if (extGate.implementation !== 'benchmark-gate.v1') continue; + const url = extGate.url ?? benchmarkGateEnvUrl; + if (url === undefined || url.length === 0) { + throw new evolution.EvolutionError( + 'EVOLUTION_SCHEMA_INVALID', + `declared benchmark-gate.v1 "${extGate.id}" requires either gate.url or LOOPWRIGHT_BENCHMARK_GATE_URL`, + `/spec/verification/externalGates/${extGate.id}`, + ); + } + const signingRef = extGate.signingCredentialRef ?? 'bench-sign'; + byCredentialRef[signingRef] = defaultBenchSecretEnv; + if (extGate.authCredentialRef !== undefined) { + byCredentialRef[extGate.authCredentialRef] = 'LOOPWRIGHT_GATE_AUTH_TOKEN'; + } + gateEndpoints.push({ + id: extGate.endpointId, + url: new URL(url).href, + signingCredentialRef: signingRef, + ...(extGate.authCredentialRef !== undefined ? { authCredentialRef: extGate.authCredentialRef } : {}), + implementation: 'benchmark-gate.v1', + timeoutMs: 30_000, + maxPollMs: 120_000, + pollInitialMs: 100, + pollMaxMs: 500, + jitter: 25, + }); + } + + const hostPolicy: ExecutionHostPolicy = { + policyProfile: 'local', + allowWorkflowWrites: false, + }; + + const acceptanceCheckIds = [ + ...scopedTaskpack.spec.verification.localChecks.map(c => c.id), + ...scopedTaskpack.spec.verification.externalGates.map(g => g.id), + ]; + + const declaredModels = scopedTaskpack.spec.models ?? []; + const declaredRoles = scopedTaskpack.spec.roles ?? []; + const hasDeclaredRoles = declaredRoles.length > 0; + const matchingModelIdx = declaredModels.findIndex(m => m.id === proposal.modelId); + const selectedModelDecl = matchingModelIdx >= 0 ? declaredModels[matchingModelIdx] : declaredModels[0]; + + const stagePromptSuffix = proposal.stagePhase === 'portfolio' + ? `\n\nEvolution stage: portfolio synthesis (track: ${proposal.trackId}, specialists: ${proposal.portfolioSpecialists?.length ?? 0}).` + : `\n\nEvolution stage: specialist${proposal.bucketId !== null ? ` (bucket: ${proposal.bucketId})` : ''} (track: ${proposal.trackId}, mutation: ${proposal.mutationKind}).`; + const baseAuthorPrompt = buildDefaultAuthorPrompt({ + mode: 'candidate', + repositoryFullName: 'local/evolution', + acceptanceCheckIds, + runtimeEnv: process.env, + scrubber: taskpackScrubber, + }) + stagePromptSuffix; + + const buildBindings = ( + activeCandidate?: ResolvedModelCandidate, + activeGateEndpoints: readonly HostGateEndpointPlan[] = gateEndpoints, + ) => { + const providerForEnv = activeCandidate?.selection.provider ?? selectedModelDecl?.provider; + const providerEnvName = activeCandidate?.providerEnvName + ?? (providerForEnv !== undefined + ? resolveDefaultProviderTokenEnv(providerForEnv, { + modelsJsonApiKeyEnv: modelsConfig?.providers.get(providerForEnv)?.apiKeyEnv, + manifestApiKeyEnv: selectedModelDecl?.apiKeyEnv, + env: process.env, + }) + : undefined); + const byProvider: Record = Object.create(null) as Record; + for (const role of declaredRoles) { + const roleProvider = role.provider; + if (roleProvider === undefined || Object.hasOwn(byProvider, roleProvider)) continue; + if ( + activeCandidate !== undefined + && activeCandidate.selection.provider === roleProvider + && activeCandidate.usesActiveTokenEnv + ) { + byProvider[roleProvider] = activeCandidate.providerEnvName; + continue; + } + const roleModelDecl = declaredModels.find(m => m.provider === roleProvider && m.id === role.model) + ?? declaredModels.find(m => m.provider === roleProvider); + const roleEnv = resolveDefaultProviderTokenEnv(roleProvider, { + modelsJsonApiKeyEnv: modelsConfig?.providers.get(roleProvider)?.apiKeyEnv, + manifestApiKeyEnv: roleModelDecl?.apiKeyEnv, + env: process.env, + }); + if (roleEnv !== undefined) { + byProvider[roleProvider] = roleEnv; + } + } + const includeDefaultProviderEnv = + providerEnvName !== undefined + && (!hasDeclaredRoles || declaredRoles.every(r => r.provider === undefined || r.provider === providerForEnv)); + return { + mode: 'candidate' as const, + hostPolicy, + repository: 'local/evolution', + repositoryRoot: childRepoDir, + taskpackPath: proposal.manifest.spec.taskpack, + baseRevision: proposal.baseRevision, + sourceRevision: proposal.baseRevision, + targetMatrix: scopedTaskpack.spec.target?.matrix ?? null, + ...(matchingModelIdx >= 0 ? { candidateIndex: matchingModelIdx } : {}), + allowManifestCustomBaseUrl, + ...(modelsJsonPath !== undefined ? { modelsJsonPath } : {}), + budgets: { + ...DEFAULT_HOST_BUDGETS, + overlay: { + maxFiles: Math.max(256, scopedTaskpack.spec.limits?.overlay?.maxFiles ?? 0), + maxBytes: Math.max(16_777_216, scopedTaskpack.spec.limits?.overlay?.maxBytes ?? 0), + }, + }, + gateEndpoints: activeGateEndpoints, + publicationEndpoint: null, + credentialEnvMap: { + ...(includeDefaultProviderEnv ? { provider: providerEnvName } : {}), + ...(Object.keys(byProvider).length > 0 ? { byProvider } : {}), + gate: defaultBenchSecretEnv, + localCommandGate: DEFAULT_LOCAL_COMMAND_GATE_ENV, + ...(Object.keys(byCredentialRef).length > 0 ? { byCredentialRef } : {}), + }, + authorPrompt: baseAuthorPrompt, + scrubber: taskpackScrubber, + }; + }; + + const candidates = resolveTaskpackModelCandidates(scopedTaskpack, buildBindings(), { + modelsConfig, + env: process.env, + scrubber: taskpackScrubber, + }); + const singleDeclaredRole = declaredRoles.length === 1 ? declaredRoles[0] : undefined; + const activeCandidate = (singleDeclaredRole?.provider !== undefined + ? (candidates.find(c => c.selection.provider === singleDeclaredRole.provider && c.selection.model === singleDeclaredRole.model) + ?? candidates.find(c => c.selection.provider === singleDeclaredRole.provider)) + : undefined) + ?? (matchingModelIdx >= 0 + ? candidates.find(c => c.manifestIndex === matchingModelIdx) + : undefined) + ?? candidates[0]; + + const ephemeralEnv: Record = {}; + if (activeCandidate !== undefined && activeCandidate.usesActiveTokenEnv && activeCandidate.token !== undefined) { + ephemeralEnv[LOOPWRIGHT_ACTIVE_PROVIDER_TOKEN_ENV] = activeCandidate.token; + registerSecret(activeCandidate.token); + } + + let localGateServer: LocalCommandGateServer | undefined; + try { + let compiled = await compileDeclarativeTaskpack(scopedTaskpack, buildBindings(activeCandidate)); + const localCommandGates = compiled.localCommandGates ?? []; + if (localCommandGates.length > 0) { + localGateServer = await startLocalCommandGateServer({ + runRoot: controllerRunRoot, + repositoryRoot: childRepoDir, + gates: localCommandGates, + hostPolicy, + runtimeEnv: process.env, + scrubber: taskpackScrubber, + }); + ephemeralEnv[DEFAULT_LOCAL_COMMAND_GATE_ENV] = localGateServer.signingSecret; + compiled = await compileDeclarativeTaskpack( + scopedTaskpack, + buildBindings(activeCandidate, [...gateEndpoints, localGateServer.endpointPlan]), + ); + } + + const trustedDir = join(controllerRunRoot, `trusted-${runId}`); + const writtenTaskpack = await writeCompiledEvolutionDir(trustedDir, compiled, proposal, taskpackScrubber, evolution); + const decisionPort = createTaskpackDecisionPort(scopedTaskpack, { + runtimeEnv: process.env, + scrubber: taskpackScrubber, + hasPinnedRoles: (scopedTaskpack.spec.roles?.length ?? 0) > 0, + }); + + const evolveGuardDecl = scopedTaskpack.spec.verification.localChecks.find( + c => c.implementation === 'evolve-block-guard.v1', + ); + let guardedFiles: readonly string[] = []; + if (evolveGuardDecl !== undefined) { + const rawGuardedFiles = evolveGuardDecl.parameters?.['files']; + if ( + !Array.isArray(rawGuardedFiles) + || rawGuardedFiles.length === 0 + || !rawGuardedFiles.every(f => typeof f === 'string' && f.length > 0) + ) { + throw new evolution.EvolutionError( + 'EVOLUTION_SCHEMA_INVALID', + 'evolve-block-guard.v1 parameters.files must be a non-empty array of non-empty strings', + '/spec/verification/localChecks', + ); + } + guardedFiles = rawGuardedFiles as readonly string[]; + } + const allAgentStepIds = writtenTaskpack.config.spec.task.spec.steps + .filter(s => s.kind === 'agent') + .map(s => s.id); + + const effectiveEnv = buildEffectiveEnv(process.env, ephemeralEnv, taskpackScrubber); + const runRoot = dirname(writtenTaskpack.trustedDirectory); + await mkdir(runRoot, { recursive: true, mode: 0o700 }); + await chmod(runRoot, 0o700).catch(() => undefined); + + const loaded = await loadTrustedConfiguration({ + configPath: writtenTaskpack.configPath, + registryPath: writtenTaskpack.registryPath, + registrySha256: writtenTaskpack.registrySha256, + untrustedRoots: [childRepoDir], + environment: name => (Object.hasOwn(effectiveEnv, name) ? effectiveEnv[name] : undefined), + }); + if (!loaded.ok) { + throw new evolution.EvolutionError( + 'EVOLUTION_STORE_ERROR', + `child loadTrustedConfiguration failed: ${loaded.error.code} (${loaded.error.path})`, + ); + } + + const cycleAbort = new AbortController(); + const onExternalAbort = (): void => { + cycleAbort.abort(); + }; + if (proposal.signal !== undefined) { + if (proposal.signal.aborted) { + cycleAbort.abort(); + } else { + proposal.signal.addEventListener('abort', onExternalAbort, { once: true }); + } + } + + let latestCandidateSlice: string | undefined; + let noveltyDecisionOut: DecisionMutationNoveltyResult | undefined; + let noveltyRejectedOutcome: { + readonly slice: string; + readonly decision: DecisionMutationNoveltyResult; + } | null = null; + let noveltyScreened = false; + + const ports: ControllerPorts = { + policyProfile: 'local', + allowWorkflowWrites: false, + ...(writtenTaskpack.roleMcpServers !== undefined ? { roleMcpServers: writtenTaskpack.roleMcpServers } : {}), + ...(writtenTaskpack.watchedPaths !== undefined && writtenTaskpack.watchedPaths.length > 0 + ? { watchedPaths: writtenTaskpack.watchedPaths } + : {}), + ...(decisionPort !== undefined ? { decisions: decisionPort } : {}), + openAdapter: createEvolutionOpenAdapter({ + writtenTaskpack, + effectiveEnv, + scrubber: taskpackScrubber, + openPiHostSessionAdapterV2, + onAfterExecute: async candidateDir => { + latestCandidateSlice = await extractSliceFromWorkspaceDir( + candidateDir, + childRepoDir, + guardedFiles, + proposal.individualId, + evolution, + ); + }, + }), + afterCheckpoint: async (phase, head) => { + if ( + noveltyScreened + || !phase.startsWith('role.') + || !phase.endsWith('.post') + || proposal.stagePhase === 'portfolio' + || proposal.proposedCodeSlice !== undefined + || (proposal.noveltyGate === undefined && (proposal.islandHistorySlices?.length ?? 0) === 0) + ) { + return; + } + const allAgentsCompleted = allAgentStepIds.length > 0 + && allAgentStepIds.every(stepId => head.progress.nodes.some(n => n.id === stepId && n.state === 'completed')); + if (!allAgentsCompleted) { + return; + } + noveltyScreened = true; + const candidateSlice = latestCandidateSlice + ?? await extractCandidateGuardedCodeSlice( + runRoot, + attemptRunId, + childRepoDir, + guardedFiles, + proposal.individualId, + evolution, + ); + latestCandidateSlice = candidateSlice; + const noveltyOutcome = proposal.noveltyGate !== undefined + ? await proposal.noveltyGate(candidateSlice) + : await evolution.screenCandidateNoveltyBeforeDispatch({ + candidateId: proposal.individualId, + candidateSlice, + historySlices: proposal.islandHistorySlices ?? [], + scrubber: coreScrubber, + }); + noveltyDecisionOut = noveltyOutcome.decision; + if (noveltyOutcome.rejected) { + noveltyRejectedOutcome = { + slice: candidateSlice, + decision: noveltyOutcome.decision, + }; + cycleAbort.abort(); + } + }, + }; + + const childRunRelPath = `runs/${proposal.individualId}/controller/${attemptRunId}`; + let cycleResult: Awaited>; + try { + cycleResult = await runCycleWithPorts( + { + configuration: loaded.value, + repository: childRepoDir, + runRoot, + runId: attemptRunId, + signal: cycleAbort.signal, + }, + ports, + ); + } finally { + proposal.signal?.removeEventListener('abort', onExternalAbort); + } + + if (noveltyRejectedOutcome !== null) { + const rejected: { readonly slice: string; readonly decision: DecisionMutationNoveltyResult } = noveltyRejectedOutcome; + return Object.freeze({ + status: 'failed' as const, + failureReason: 'NOVELTY_CLONE_REJECTED', + codeSlice: rejected.slice, + metrics: Object.freeze({}), + outputArtifacts: Object.freeze([]), + evidenceDigest: null, + childRunRelPath, + noveltyDecision: rejected.decision, + }); + } + + const extractedCodeSlice = latestCandidateSlice ?? await extractCandidateGuardedCodeSlice( + runRoot, + attemptRunId, + childRepoDir, + guardedFiles, + proposal.individualId, + evolution, + ); + + let runEvalReport: RunEvalReport | undefined; + const inspectedRes = await inspectRun({ + runRoot, + runId: attemptRunId, + }).catch(() => null); + if (inspectedRes !== null && inspectedRes.ok && inspectedRes.value.runEval !== null) { + runEvalReport = inspectedRes.value.runEval; + } + + let cycleStatus: string = 'failed'; + let cycleReasonCode: string | null = null; + if (!cycleResult.ok) { + cycleStatus = cycleResult.error.code === 'CANCELLED' ? 'cancelled' : 'failed'; + cycleReasonCode = cycleResult.error.code; + } else if (cycleResult.value.kind === 'incident') { + cycleStatus = 'failed'; + cycleReasonCode = cycleResult.value.incident.code; + } else { + cycleStatus = cycleResult.value.result.spec.status; + cycleReasonCode = cycleResult.value.result.spec.verification.spec.diagnostics[0]?.code ?? null; + } + + const runSucceeded = cycleStatus === 'completed'; + const artifactsDir = join(runRoot, attemptRunId, 'artifacts'); + const collected = await evolution.collectChildBenchmarkArtifacts(artifactsDir, runSucceeded, coreScrubber); + + let finalStatus: IndividualStatus; + let failureReason: string | null = null; + if (cycleStatus === 'cancelled' || proposal.signal?.aborted) { + finalStatus = 'preempted'; + failureReason = 'CANCELLED'; + } else if (collected.retryablePreemption) { + finalStatus = 'preempted'; + failureReason = 'BENCHMARK_PREEMPTED'; + } else if (runSucceeded) { + finalStatus = 'passed'; + failureReason = null; + } else { + finalStatus = 'failed'; + failureReason = collected.dispositionReason ?? cycleReasonCode ?? 'LOCAL_VERIFICATION_FAILED'; + } + + let evidenceDigest: Digest | null = null; + if (finalStatus === 'passed') { + if (collected.rawVerdictReceiptBytes !== undefined) { + evidenceDigest = evolution.sha256Digest(collected.rawVerdictReceiptBytes); + } else { + const candidateDigest = cycleResult.ok && cycleResult.value.kind === 'result' + ? cycleResult.value.result.spec.subject.candidateDigest.hex + : null; + evidenceDigest = evolution.sha256Digest( + JSON.stringify({ + candidateDigest, + metrics: collected.metrics, + bucketMetrics: collected.bucketMetrics ?? null, + outputArtifacts: collected.outputArtifacts.map(a => ({ name: a.name, digest: a.digest.hex, byteLength: a.byteLength })), + }), + ); + } + } + + return Object.freeze({ + status: finalStatus, + failureReason, + codeSlice: extractedCodeSlice, + metrics: collected.metrics, + ...(collected.bucketMetrics !== undefined ? { bucketMetrics: collected.bucketMetrics } : {}), + ...(collected.hardwareDiagnostics !== undefined ? { hardwareDiagnostics: collected.hardwareDiagnostics } : {}), + ...(collected.hardwareProvenance !== undefined ? { hardwareProvenance: collected.hardwareProvenance } : {}), + ...(collected.findings !== undefined ? { findings: collected.findings } : {}), + outputArtifacts: collected.outputArtifacts, + ...(collected.stageABlobs.length > 0 ? { stageABlobs: collected.stageABlobs } : {}), + ...(collected.rawVerdictReceiptBytes !== undefined ? { rawVerdictReceiptBytes: collected.rawVerdictReceiptBytes } : {}), + evidenceDigest, + childRunRelPath, + ...(runEvalReport !== undefined ? { runEvalReport } : {}), + ...(noveltyDecisionOut !== undefined ? { noveltyDecision: noveltyDecisionOut } : {}), + }); + } finally { + if (localGateServer !== undefined) { + await localGateServer.close().catch(() => undefined); + } + } + }; +} + +/** + * Create a lazy-loaded, strictly read-only `LocalRunStore` Pi-backed plateau supervisor runner + * for CLI `evolve run` and `evolve resume` (`tools: ['read']`, `scope.protected: ['**']`, + * zero `held_out_workloads` mounts). + */ +export function createCliEvolutionSupervisorRunner(options: { + readonly coreScrubber: CoreSecretScrubber; + readonly taskpackScrubber: TaskpackSecretScrubber; + readonly signal?: AbortSignal | undefined; +}): SupervisorRunnerPort { + const openPiHostSessionPromise = createLazyHostSessionLoader(); + const coreScrubber = options.coreScrubber; + const taskpackScrubber = options.taskpackScrubber; + const registerSecret = (val: string): void => { + if (val.length > 0) { + coreScrubber.register(val); + taskpackScrubber.register(val); + } + }; + + return async context => { + const evolution = await import('@loopwright/evolution'); + const runner = evolution.createLocalRunStoreSupervisorRunner({ + policyProfile: 'local', + ...(options.signal !== undefined ? { signal: options.signal } : {}), + scrubber: coreScrubber, + executeReadOnlySupervisorTurn: async (turn: ReadOnlySupervisorTurnContext) => { + const openPiHostSessionAdapterV2 = await openPiHostSessionPromise(); + const supRole = turn.supervisorContract.spec.roles[0]; + if (supRole === undefined) { + throw new evolution.EvolutionError('TEAM_ENVELOPE_VIOLATION', 'supervisor TaskContract missing role declaration'); + } + + const modelsJsonPath = process.env['LOOPWRIGHT_MODELS_JSON']?.trim() || undefined; + const modelsConfig: ParsedPiModelsJson | undefined = modelsJsonPath !== undefined + ? await loadPiModelsJson(modelsJsonPath) + : undefined; + const allowManifestCustomBaseUrl = process.env['LOOPWRIGHT_ALLOW_MANIFEST_CUSTOM_BASE_URL'] === 'true'; + + const providerEnvName = resolveDefaultProviderTokenEnv(supRole.provider, { + modelsJsonApiKeyEnv: modelsConfig?.providers.get(supRole.provider)?.apiKeyEnv, + env: process.env, + }); + + const workspaceDir = join(turn.stagingDir, 'workspace'); + let workspaceHeadRev: string; + try { + const { stdout: revOut } = await execFileAsync('git', ['rev-parse', 'HEAD'], { + cwd: workspaceDir, + encoding: 'utf8', + maxBuffer: 1024 * 64, + }); + workspaceHeadRev = revOut.trim().toLowerCase(); + } catch (gitErr: unknown) { + throw new evolution.EvolutionError( + 'EVOLUTION_STORE_ERROR', + `failed to resolve supervisor workspace HEAD revision: ${gitErr instanceof Error ? gitErr.message : String(gitErr)}`, + ); + } + + const supervisorTaskpack: TaskpackManifest = parseTaskpackManifest( + JSON.stringify({ + apiVersion: 'loopwright.dev/v1alpha1', + kind: 'Taskpack', + metadata: { + name: 'evo-supervisor', + }, + spec: { + goal: { + candidate: turn.prompt, + noChange: turn.prompt, + }, + scope: { + writable: ['__supervisor_readonly__/**'], + protected: [], + }, + models: [ + { + provider: supRole.provider, + id: supRole.model, + thinking: supRole.thinking, + ...(providerEnvName !== undefined ? { apiKeyEnv: providerEnvName } : {}), + }, + ], + roles: [ + { + id: turn.roleId, + provider: supRole.provider, + model: supRole.model, + thinking: supRole.thinking, + purpose: 'task', + tools: ['read'], + prompt: turn.prompt, + }, + ], + verification: { + localChecks: [ + { + id: 'supervisor-no-change', + implementation: 'no-change.v1', + }, + ], + externalGates: [], + }, + publication: { + mode: 'disabled', + }, + }, + }), + { hostPolicy: { policyProfile: 'local', allowWorkflowWrites: false } }, + ); + + const hostPolicy: ExecutionHostPolicy = { + policyProfile: 'local', + allowWorkflowWrites: false, + }; + const baseBindings = { + mode: 'no-change' as const, + hostPolicy, + repository: 'local/evolution', + repositoryRoot: workspaceDir, + baseRevision: workspaceHeadRev, + sourceRevision: workspaceHeadRev, + targetMatrix: null, + allowManifestCustomBaseUrl, + ...(modelsJsonPath !== undefined ? { modelsJsonPath } : {}), + budgets: { + ...DEFAULT_HOST_BUDGETS, + wallTimeMs: 300_000, + totalTokens: 100_000, + maxModelCalls: 4, + maxConcurrency: 1, + maxFormatRepairs: 0, + maxImplementationRepairs: 0, + }, + gateEndpoints: [], + publicationEndpoint: null, + credentialEnvMap: { + ...(providerEnvName !== undefined ? { provider: providerEnvName } : {}), + }, + authorPrompt: turn.prompt, + scrubber: taskpackScrubber, + }; + + const candidates = resolveTaskpackModelCandidates(supervisorTaskpack, baseBindings, { + modelsConfig, + env: process.env, + scrubber: taskpackScrubber, + }); + const activeCandidate = candidates[0]; + const ephemeralEnv: Record = {}; + if (activeCandidate !== undefined && activeCandidate.usesActiveTokenEnv && activeCandidate.token !== undefined) { + ephemeralEnv[LOOPWRIGHT_ACTIVE_PROVIDER_TOKEN_ENV] = activeCandidate.token; + registerSecret(activeCandidate.token); + } + const activeProviderEnvName = activeCandidate?.providerEnvName ?? providerEnvName; + const compileBindings = { + ...baseBindings, + credentialEnvMap: { + ...(activeProviderEnvName !== undefined ? { provider: activeProviderEnvName } : {}), + }, + }; + + const compiled = await compileDeclarativeTaskpack(supervisorTaskpack, compileBindings); + const piSessionRoot = join(turn.stagingDir, 'pi-session'); + const trustedDir = join(piSessionRoot, 'trusted'); + const registryDir = join(trustedDir, 'registry'); + const configDir = join(trustedDir, 'config'); + await mkdir(registryDir, { recursive: true, mode: 0o700 }); + await mkdir(configDir, { recursive: true, mode: 0o700 }); + await chmod(trustedDir, 0o700); + await chmod(registryDir, 0o700); + await chmod(configDir, 0o700); + + const stagedSupResources: Array<{ + readonly id: string; + readonly kind: 'document'; + readonly path: string; + readonly digest: Digest; + }> = []; + for (const sf of turn.files) { + const dstPath = join(registryDir, sf.relativeResourcePath); + await mkdir(dirname(dstPath), { recursive: true, mode: 0o700 }); + const bytes = await readFile(sf.filePath); + await writeFile(dstPath, bytes, { mode: 0o400 }); + await chmod(dstPath, 0o400); + stagedSupResources.push({ + id: sf.resourceId, + kind: 'document', + path: sf.relativeResourcePath, + digest: sf.digest, + }); + } + + const finalRegistry = { + ...compiled.registry, + spec: { + ...compiled.registry.spec, + resources: [...compiled.registry.spec.resources, ...stagedSupResources], + }, + }; + const registryBytes = Buffer.from(`${JSON.stringify(finalRegistry, null, 2)}\n`, 'utf8'); + const registrySha256 = createHash('sha256').update(registryBytes).digest('hex'); + + const stagedResourceIds = stagedSupResources.map(r => r.id); + const finalTask = { + ...compiled.config.spec.task, + spec: { + ...compiled.config.spec.task.spec, + scope: { + ...compiled.config.spec.task.spec.scope, + protected: Array.from(new Set(['**', ...compiled.config.spec.task.spec.scope.protected])), + }, + roles: compiled.config.spec.task.spec.roles.map(role => ({ + ...role, + tools: ['read'], + resourceIds: Array.from(new Set([...(role.resourceIds ?? []), ...stagedResourceIds])), + })), + trustedContext: { + ...compiled.config.spec.task.spec.trustedContext, + resources: [...compiled.config.spec.task.spec.trustedContext.resources, ...stagedSupResources], + }, + }, + }; + const finalConfig = { + ...compiled.config, + spec: { + ...compiled.config.spec, + registry: { + name: finalRegistry.metadata.name, + digest: { algorithm: 'sha256' as const, hex: registrySha256 }, + }, + task: finalTask, + }, + }; + + const configBytes = Buffer.from(serializePrettyYaml(finalConfig), 'utf8'); + if ( + taskpackScrubber.containsSecret(registryBytes.toString('utf8')) + || taskpackScrubber.containsSecret(configBytes.toString('utf8')) + ) { + throw new evolution.EvolutionError( + 'SECRET_LEAK_DETECTED', + 'compiled supervisor taskpack contained a registered secret and was refused', + ); + } + const registryPath = join(registryDir, 'registry.yaml'); + const configPath = join(configDir, 'config.yaml'); + await writeFile(registryPath, registryBytes, { mode: 0o600 }); + await writeFile(configPath, configBytes, { mode: 0o600 }); + await chmod(registryPath, 0o600); + await chmod(configPath, 0o600); + + const writtenSupTaskpack: WrittenCompiledTaskpack = { + ...compiled, + registry: finalRegistry, + registryBytes, + registrySha256, + config: finalConfig, + configBytes, + trustedDirectory: trustedDir, + registryPath, + configPath, + }; + + const effectiveEnv = buildEffectiveEnv(process.env, ephemeralEnv, taskpackScrubber); + const loaded = await loadTrustedConfiguration({ + configPath, + registryPath, + registrySha256, + untrustedRoots: [workspaceDir], + environment: name => (Object.hasOwn(effectiveEnv, name) ? effectiveEnv[name] : undefined), + }); + if (!loaded.ok) { + throw new evolution.EvolutionError( + 'EVOLUTION_STORE_ERROR', + `supervisor Pi loadTrustedConfiguration failed: ${loaded.error.code} (${loaded.error.path})`, + ); + } + + const captured: { text: string | null } = { text: null }; + let latestSupCandidateGeneration: number | null = null; + let latestSupAttemptCount = 0; + let latestSupHasFormatSubmissionEvidence = false; + const supRunId = evolution.sanitizeRunId(`sup-pi-${turn.runId}`); + const supControllerRoot = join(piSessionRoot, 'controller'); + await mkdir(supControllerRoot, { recursive: true, mode: 0o700 }); + + const supCycle = await runCycleWithPorts( + { + configuration: loaded.value, + repository: workspaceDir, + runRoot: supControllerRoot, + runId: supRunId, + ...(turn.signal !== undefined ? { signal: turn.signal } : {}), + }, + { + policyProfile: 'local', + allowWorkflowWrites: false, + afterCheckpoint: async (_phase, head) => { + latestSupCandidateGeneration = head.progress.candidate.generation; + latestSupAttemptCount = head.progress.attempts.length; + const onlyFailure = head.progress.failures.length === 1 ? head.progress.failures[0] : undefined; + latestSupHasFormatSubmissionEvidence = + onlyFailure !== undefined + && onlyFailure.evidence !== null + && head.progress.submission !== null + && onlyFailure.evidence.digest.hex === head.progress.submission.digest.hex; + }, + openAdapter: createEvolutionOpenAdapter({ + writtenTaskpack: writtenSupTaskpack, + effectiveEnv, + scrubber: taskpackScrubber, + openPiHostSessionAdapterV2, + onAfterCapture: async (artifactsDirectory, sessionArtifactName) => { + const rawSession = await readFile(join(artifactsDirectory, sessionArtifactName), 'utf8').catch(() => null); + if (rawSession !== null) { + const extracted = extractLastAssistantTextFromSessionJsonl(rawSession); + if (extracted !== null) { + captured.text = extracted; + } + } + }, + }), + }, + ); + + // Keep TEAM_ENVELOPE_VIOLATION so runPlateauSupervisorTurn safely retains the incumbent + // team instead of aborting the campaign, while embedding controller error code + stage for triage. + if (!supCycle.ok) { + throw new evolution.EvolutionError( + 'TEAM_ENVELOPE_VIOLATION', + `read-only Pi supervisor execution failed (code=${supCycle.error.code}, path=${supCycle.error.path})`, + ); + } + if (supCycle.value.kind !== 'result') { + throw new evolution.EvolutionError( + 'TEAM_ENVELOPE_VIOLATION', + `read-only Pi supervisor cycle ended in incident "${supCycle.value.incident.code}"`, + ); + } + const supStatus = supCycle.value.result.spec.status; + const supDiagnostics = supCycle.value.result.spec.verification.spec.diagnostics; + // The supervisor outputs a TeamPatch JSON instead of a CandidateSubmission envelope. + // With maxFormatRepairs=0, controller ends in status="exhausted" strictly after 1 clean + // zero-mutation attempt whose sole failure is the raw TeamPatch submission; any other + // failure (provider error, incident, timeout, token/call exhaustion, mutation) fails closed. + const isExpectedTeamPatchFormatMismatch = + supStatus === 'exhausted' + && latestSupCandidateGeneration === 0 + && latestSupAttemptCount === 1 + && latestSupHasFormatSubmissionEvidence + && supDiagnostics.length === 0; + if (supStatus !== 'no_change' && supStatus !== 'completed' && !isExpectedTeamPatchFormatMismatch) { + const codes = supDiagnostics.map(d => d.code).join(',') || 'none'; + throw new evolution.EvolutionError( + 'TEAM_ENVELOPE_VIOLATION', + `read-only Pi supervisor cycle did not pass verification (status="${supStatus}", diagnostics=${codes})`, + ); + } + + if (captured.text === null || captured.text.trim().length === 0) { + throw new evolution.EvolutionError( + 'EVOLUTION_SCHEMA_INVALID', + 'read-only Pi supervisor turn produced no assistant TeamPatch response', + '/supervisorOutput', + ); + } + + return unwrapOptionalJsonCodeFence(captured.text); + }, + }); + return runner(context); + }; +} diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index 32ac2e8..9449630 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -1,6 +1,6 @@ -export { parseArguments, UsageError, type Arguments, type DigestAction, type RunnerAction, type StepAction, type SuiteAction } from './arguments.js'; +export { parseArguments, UsageError, type Arguments, type DigestAction, type EvolveAction, type RunnerAction, type StepAction, type SuiteAction } from './arguments.js'; export { canonicalPath, initDraft, writeOutput, appendStepSummary } from './draft.js'; -export { encoded, diagnosticExit, executionExit, closureExitCode, hardwareRunnerExitCode, taskpackExitCode, gitHubAppExitCode, main, type Envelope } from './main.js'; +export { encoded, diagnosticExit, executionExit, closureExitCode, evolutionExitCode, hardwareRunnerExitCode, taskpackExitCode, gitHubAppExitCode, main, type Envelope } from './main.js'; export { CLOSURE_CAPABILITY_LEDGER, CLOSURE_EVIDENCE_MISSING, diff --git a/packages/cli/src/main.ts b/packages/cli/src/main.ts index a8ec816..058034c 100644 --- a/packages/cli/src/main.ts +++ b/packages/cli/src/main.ts @@ -5,12 +5,13 @@ import { chmod, lstat, mkdir, mkdtemp, readdir, realpath, rm, writeFile } from ' import { tmpdir } from 'node:os'; import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'; import { pathToFileURL } from 'node:url'; +import { SecretScrubber as CoreSecretScrubber } from '@loopwright/core'; import { STANDARD_PI_PROVIDER_ENV } from '@loopwright/agent-pi/catalog'; import { HostMcpRegistry } from '@loopwright/agent-pi/mcp'; import { compilePlan, formatRunReport, inspectRun, loadTrustedConfiguration, parseReportOutputFormats, readStatus, reconcileCycle, resumeCycle, resumeCycleWithPorts, runCycle, runCycleWithPorts, stepCancel, stepNext, stepSubmit, type ControllerDiagnostic, type ControllerPorts, type CycleExecution, type InspectRunValue, type LoadedConfiguration, type ReportCheckItem, type ReportModelInfo, type ReportOutputFormat, type RoleModelOverride, type RunReportInput, type StepTickResult } from '@loopwright/controller'; import { alignBaselineRevisions, assertCleanArtifact, BASELINE_CONFLICT_REASON, buildDefaultAuthorPrompt, checkTaskpackSuite, collectManifestSecretEnvNames, collectMcpReferencedEnvNames, compileDeclarativeTaskpack, computeTaskpackDigests, createTaskpackDecisionPort, DEFAULT_HOST_BUDGETS, DEFAULT_LOCAL_COMMAND_GATE_ENV, discoverTaskpackUpstreamsV2, evaluateUpstreamIntakeDisposition, executeTurnkeyCycle, finalizeLocalTurnkeyMemory, formatWorkspaceResourcesManifest, insideRoot, loadDeclarativeTaskpack, loadPiModelsJson, LOOPWRIGHT_ACTIVE_PROVIDER_TOKEN_ENV, normalizeRelativePath, openStagedTaskpackStepGate, parseActionInputLimits, parseAllowedHostMounts, parseBaselineAlignmentPolicy, parseLoopwrightEnvLimits, parseYamlDocument, readBoundedRegularFile, REPOSITORY_FULL_NAME_PATTERN, resolveDefaultProviderTokenEnv, resolveDigestLockfilePath, resolveExternalMcpConfigs, resolveRepositoryAndRevisions, resolveTaskpackModelCandidates, resolveTaskpackModelSelection, resolveTaskpackSuite, runTaskpackPreflight, SecretScrubber, selectHealthyModelCandidate, serializePrettyYaml, stageCompiledInstructionResources, stageTaskpackForStep, startLocalCommandGateServer, TaskpackError, validateGateToolchainPath, verifyDigestLockfile, writeDigestLockfile, type BaselineAlignmentOverride, type BaselineAlignmentResult, type CompiledTaskpack, type ExecutionHostPolicy, type HostGateEndpointPlan, type HostRoleSelection, type HostTaskpackBindings, type LoadedTaskpackSuite, type LocalCommandGateServer, type ParsedPiModelsJson, type PiThinkingLevel, type ResolvedModelCandidate, type RunTaskpackPreflightResult, type StagedTaskpackStepGateHandle, type SuiteResolutionResult, type TaskpackErrorCode, type TaskpackManifest, type TaskpackUpstreamRecord, type TurnkeyCycleAttemptSummary, type WrittenCompiledTaskpack } from '@loopwright/taskpack'; import type { HardwareRunnerErrorCode, RunHardwareWorkerResult, WorkerJobSettlementSummary } from '@loopwright/hardware-runner'; -import { parseArguments, UsageError, type Arguments } from './arguments.js'; +import { EVOLVE_ACTIONS, parseArguments, UsageError, type Arguments } from './arguments.js'; import { appendStepSummary, initDraft, writeOutput } from './draft.js'; import { evaluateClosureMatrix, CLOSURE_FALSIFICATION_FORBIDDEN, type ClosureMatrixReport } from './closure.js'; function resolveCliVersion(): string { @@ -21,8 +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]\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 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 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`; 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'); @@ -217,6 +219,7 @@ export function hardwareRunnerExitCode(code: HardwareRunnerErrorCode): number { case 'AUTH_UNAUTHORIZED': case 'AUTH_FORBIDDEN': case 'RUNNER_SANDBOX_FAILED': + case 'WORKER_DEVICE_QUARANTINED': return 3; case 'ARTIFACT_INVALID': case 'ARTIFACT_MISSING': @@ -235,9 +238,48 @@ export function hardwareRunnerExitCode(code: HardwareRunnerErrorCode): number { } } } +type EvolutionErrorCode = import('@loopwright/evolution').EvolutionErrorCode; +/** Map every EvolutionErrorCode exhaustively to its documented CLI exit code. */ +export function evolutionExitCode(code: EvolutionErrorCode): number { + switch (code) { + case 'EVOLUTION_SCHEMA_INVALID': + return 2; + case 'TEAM_ENVELOPE_VIOLATION': + case 'EXPORT_UNVERIFIED_FORBIDDEN': + case 'EVOLUTION_SYMLINK_FORBIDDEN': + return 3; + case 'EVOLUTION_NOT_FOUND': + case 'ARTIFACT_INVALID': + case 'ARTIFACT_MISSING': + return 4; + case 'EVOLUTION_BUDGET_EXCEEDED': + return 5; + case 'EVOLUTION_CLOCK_DRIFT': + case 'EVOLUTION_LEASE_FENCED': + case 'EVOLUTION_CONFLICT': + case 'EVOLUTION_STORE_BUSY': + return 7; + case 'EVOLUTION_STORE_ERROR': + case 'EVOLUTION_STORE_CLOSED': + case 'EVOLUTION_STORE_CORRUPT': + case 'SECRET_LEAK_DETECTED': + return 8; + default: { + const _exhaustive: never = code; + return _exhaustive; + } + } +} +const BASE_CLI_SECRET_ENV_KEYS = [ + 'GITHUB_TOKEN', + 'GH_TOKEN', + 'INPUT_GITHUB-TOKEN', + 'INPUT_GITHUB-APP-PRIVATE-KEY', +] as const; + function createCliScrubber(extraKeys: readonly string[] = []): SecretScrubber { const scrubber = new SecretScrubber(); - for (const key of ['GITHUB_TOKEN', 'GH_TOKEN', 'INPUT_GITHUB-TOKEN', 'INPUT_GITHUB-APP-PRIVATE-KEY', ...extraKeys]) { + for (const key of [...BASE_CLI_SECRET_ENV_KEYS, ...extraKeys]) { const value = process.env[key]; if (typeof value === 'string' && value.length > 0) scrubber.register(value); } @@ -1805,10 +1847,322 @@ async function runRunnerCommand(args: Arguments, emit: EmitFn): Promise } } +function scrubJsonPayload(value: unknown, scrubber: SecretScrubber, depth = 0): unknown { + if (depth > 32) return '[REDACTED:DEPTH]'; + if (typeof value === 'string') return scrubber.scrub(value); + if (value === null || typeof value !== 'object') return value; + if (Array.isArray(value)) { + return value.map(item => scrubJsonPayload(item, scrubber, depth + 1)); + } + const out: Record = {}; + for (const [k, v] of Object.entries(value as Record)) { + out[k] = scrubJsonPayload(v, scrubber, depth + 1); + } + return out; +} + +async function runEvolveCommand(args: Arguments, emit: EmitFn): Promise { + const get = (key: string) => args.values.get(key)!; + const extraSecretKeys = [ + 'LOOPWRIGHT_GATE_SIGNING_SECRET', + 'BENCH_SIGNING_SECRET', + 'LOOPWRIGHT_GATE_AUTH_TOKEN', + 'LOCAL_OAI_KEY', + ...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 evolution = await import('@loopwright/evolution'); + const resolveCampaignDir = (): string => resolve(args.values.get('campaign') ?? args.values.get('campaign-dir') ?? args.values.get('root')!); + const resolveStateDir = (): string => resolve(args.values.get('state') ?? args.values.get('campaign-dir') ?? args.values.get('root')!); + const resolveSigningSecret = (): string | undefined => { + const raw = process.env['LOOPWRIGHT_GATE_SIGNING_SECRET']?.trim() + || process.env['BENCH_SIGNING_SECRET']?.trim() + || undefined; + if (raw !== undefined && raw.length > 0) { + scrubber.register(raw); + coreScrubber.register(raw); + return raw; + } + return undefined; + }; + + try { + const action = args.evolveAction!; + if (action === 'check') { + const checked = await evolution.checkEvolutionCampaign({ + manifestPath: resolve(get('campaign')), + ...(args.values.has('repo') ? { repositoryRoot: resolve(get('repo')) } : {}), + allowLoopbackHttp: true, + scrubber: coreScrubber, + }); + const payload = { + version: 1, + action: 'check', + valid: checked.valid, + campaignName: scrubber.scrub(checked.manifest.metadata.name), + manifestDigest: checked.manifestDigest, + taskpackName: scrubber.scrub(checked.taskpack.metadata.name), + targetCellId: checked.targetCellId, + modelIds: checked.modelIds, + stageMode: checked.stageMode, + specialistBucketIds: checked.specialistBucketIds, + portfolioHeldOutWorkloadId: checked.portfolioHeldOutWorkloadId, + }; + await emit( + 'plan', + payload, + scrubber.scrub(`evolve check: ok (${checked.manifest.metadata.name}, target=${checked.targetCellId}, mode=${checked.stageMode})`), + ); + return 0; + } + + if (action === 'status') { + const status = await evolution.getEvolutionCampaignStatus({ + campaignRoot: resolveCampaignDir(), + }); + await emit( + 'status', + scrubJsonPayload(status, scrubber), + scrubber.scrub( + `evolve status: ${status.campaign.campaignId} status=${status.campaign.status} gen=${status.campaign.currentGeneration} evals=${status.campaign.evaluationsUsed}`, + ), + ); + return 0; + } + + if (action === 'inspect') { + const inspection = await evolution.inspectEvolutionCampaign({ + campaignRoot: resolveCampaignDir(), + }); + const islandFilter = args.values.has('island') ? Number.parseInt(get('island'), 10) : undefined; + const individualFilter = args.values.get('individual'); + + if (islandFilter !== undefined && !inspection.islands.some(i => i.islandId === islandFilter)) { + throw new evolution.EvolutionError( + 'EVOLUTION_NOT_FOUND', + `island ${islandFilter} not found in campaign "${inspection.campaign.campaignId}"`, + '/island', + ); + } + + const islands = islandFilter !== undefined + ? inspection.islands.filter(i => i.islandId === islandFilter) + : inspection.islands; + const nicheArchives = islandFilter !== undefined + ? inspection.nicheArchives.filter(a => a.islandId === islandFilter) + : inspection.nicheArchives; + const teamConfigs = islandFilter !== undefined + ? inspection.teamConfigs.filter(tc => tc.islandId === islandFilter) + : inspection.teamConfigs; + let individuals = islandFilter !== undefined + ? inspection.individuals.filter(ind => ind.islandId === islandFilter) + : inspection.individuals; + let paretoFrontier = islandFilter !== undefined + ? inspection.paretoFrontier.filter(ind => ind.islandId === islandFilter) + : inspection.paretoFrontier; + let lineageEdges = inspection.lineageEdges; + + if (individualFilter !== undefined) { + const matched = individuals.find(ind => ind.individualId === individualFilter); + if (matched === undefined) { + throw new evolution.EvolutionError( + 'EVOLUTION_NOT_FOUND', + `individual "${individualFilter}" not found in campaign "${inspection.campaign.campaignId}"`, + '/individual', + ); + } + individuals = [matched]; + paretoFrontier = paretoFrontier.filter(ind => ind.individualId === individualFilter); + lineageEdges = lineageEdges.filter( + edge => edge.childIndividualId === individualFilter || edge.parentIndividualId === individualFilter, + ); + } + + const payload = { + ...inspection, + islands, + paretoFrontier, + nicheArchives, + teamConfigs, + individuals, + lineageEdges, + }; + await emit( + 'inspection', + scrubJsonPayload(payload, scrubber), + scrubber.scrub( + `evolve inspect: ${inspection.campaign.campaignId} individuals=${individuals.length} pareto=${paretoFrontier.length}`, + ), + ); + return 0; + } + + if (action === 'export') { + const campaignRoot = resolveCampaignDir(); + const outputDir = resolve(get('out')); + const format = args.values.get('format') as 'dir' | 'oci-layout' | undefined; + const allowSyntheticProbe = args.flags.has('allow-synthetic-probe'); + const overwrite = args.flags.has('overwrite'); + const receiptSigningSecret = resolveSigningSecret(); + + const store = await evolution.EvolutionCampaignStore.open({ + campaignRoot, + createIfMissing: false, + }); + try { + const campaigns = await store.listCampaigns(); + if (campaigns.length > 1) { + throw new evolution.EvolutionError( + 'EVOLUTION_CONFLICT', + `campaign store holds ${campaigns.length} campaigns; export requires a single campaign`, + ); + } + const target = campaigns[0]; + if (target === undefined) { + throw new evolution.EvolutionError('EVOLUTION_NOT_FOUND', 'no campaigns found in campaign.sqlite'); + } + const exported = await evolution.exportEvolutionBundle({ + store, + campaignId: target.campaignId, + outputDir, + ...(format !== undefined ? { format } : {}), + allowSyntheticProbe, + overwrite, + ...(receiptSigningSecret !== undefined ? { receiptSigningSecret } : {}), + scrubber: coreScrubber, + }); + await emit( + 'result', + scrubJsonPayload(exported, scrubber), + scrubber.scrub(`evolve export: ok (${exported.format}, individuals=${exported.exportedIndividualIds.length}, blobs=${exported.blobCount})`), + ); + return 0; + } finally { + await store.close().catch(() => undefined); + } + } + + 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'); + const receiptSigningSecret = resolveSigningSecret(); + const outDir = args.values.has('out') ? resolve(get('out')) : undefined; + const format = args.values.get('format') as 'dir' | 'oci-layout' | undefined; + const evaluator = createCliEvolutionEvaluator({ repositoryRoot, coreScrubber, taskpackScrubber: scrubber }); + + const { runResult, exportedBundle, caughtSignal } = await withSignalAbort(async (signal, getSignal) => { + const supervisorRunner = createCliEvolutionSupervisorRunner({ + coreScrubber, + taskpackScrubber: scrubber, + signal, + }); + const res = action === 'run' + ? await evolution.runEvolutionCampaign({ + campaignRoot: resolveStateDir(), + manifestPath: resolve(get('campaign')), + repositoryRoot, + evaluator, + supervisorRunner, + signal, + autoExport: outDir === undefined, + ...(format !== undefined ? { exportFormat: format } : {}), + allowSyntheticProbe, + ...(receiptSigningSecret !== undefined ? { receiptSigningSecret } : {}), + scrubber: coreScrubber, + }) + : await evolution.resumeEvolutionCampaign({ + campaignRoot: resolveCampaignDir(), + repositoryRoot, + evaluator, + supervisorRunner, + signal, + autoExport: outDir === undefined, + ...(format !== undefined ? { exportFormat: format } : {}), + allowSyntheticProbe, + ...(receiptSigningSecret !== undefined ? { receiptSigningSecret } : {}), + scrubber: coreScrubber, + }); + try { + let extraExport = res.exportedBundle; + const sig = getSignal(); + if (outDir !== undefined && res.campaign.status === 'completed' && sig === null) { + extraExport = await evolution.exportEvolutionBundle({ + store: res.store, + campaignId: res.campaign.campaignId, + outputDir: outDir, + ...(format !== undefined ? { format } : {}), + allowSyntheticProbe, + overwrite: false, + ...(receiptSigningSecret !== undefined ? { receiptSigningSecret } : {}), + scrubber: coreScrubber, + }); + } + return { runResult: res, exportedBundle: extraExport, caughtSignal: sig }; + } finally { + await res.store.close().catch(() => undefined); + } + }); + + const { store: _unusedStore, ...serializable } = runResult; + void _unusedStore; + const exportSkipped = outDir !== undefined && exportedBundle === undefined; + const payload = { + ...serializable, + ...(exportedBundle !== undefined ? { exportedBundle } : {}), + ...(exportSkipped ? { exportSkippedReason: caughtSignal !== null ? `signal:${caughtSignal}` : `campaign_${runResult.campaign.status}` } : {}), + }; + const exportNote = exportSkipped + ? ` export=skipped(${caughtSignal !== null ? caughtSignal : runResult.campaign.status})` + : ''; + await emit( + 'result', + scrubJsonPayload(payload, scrubber), + scrubber.scrub( + `evolve ${action}: ${runResult.campaign.campaignId} status=${runResult.campaign.status} evals=${runResult.campaign.evaluationsUsed} pareto=${runResult.paretoFrontier.length}${exportNote}`, + ), + ); + if (caughtSignal === 'SIGTERM') return 143; + if (caughtSignal === 'SIGINT') return 130; + if (runResult.campaign.status === 'completed') return 0; + if (runResult.campaign.status === 'paused') return 130; + return 4; + } catch (err) { + if (err instanceof evolution.EvolutionError) { + const code = err.code; + const message = scrubber.scrub(err.message); + const path = typeof err.path === 'string' && err.path.length > 0 ? scrubber.scrub(err.path) : null; + await emit( + 'diagnostic', + { version: 1, code, message, ...(path !== null ? { path } : {}) }, + `${code}: ${message}`, + ); + return evolutionExitCode(code); + } + if (err instanceof TaskpackError) { + return await emitTaskpackError(err, emit, scrubber); + } + const rawMessage = err instanceof Error ? err.message : String(err); + const message = scrubber.scrub(rawMessage); + await emit( + 'diagnostic', + { version: 1, code: 'CLI_EVOLUTION_UNAVAILABLE', message }, + `CLI_EVOLUTION_UNAVAILABLE: ${message}`, + ); + return 8; + } +} + export async function main(argv: readonly string[]): Promise { if (argv.length === 1 && argv[0] === '--help') { await stdout(HELP); return 0; } if (argv.length === 2 && argv[0] === 'runner' && argv[1] === '--help') { await stdout(RUNNER_HELP); return 0; } if (argv.length === 3 && argv[0] === 'runner' && (argv[1] === 'relay' || argv[1] === 'worker') && argv[2] === '--help') { await stdout(RUNNER_HELP); return 0; } + if (argv.length === 2 && argv[0] === 'evolve' && argv[1] === '--help') { await stdout(EVOLVE_HELP); return 0; } + if (argv.length === 3 && argv[0] === 'evolve' && (EVOLVE_ACTIONS as readonly string[]).includes(argv[1]!) && argv[2] === '--help') { await stdout(EVOLVE_HELP); return 0; } if (argv.length === 1 && argv[0] === '--version') { await stdout(`${CLI_VERSION}\n`); return 0; } let sequence = 0, runId: string | null = null, json = argv.includes('--json'); const emit = async (kind: Envelope['kind'], data: unknown, summary?: string) => { const envelope: Envelope = { version: 1, kind, sequence: ++sequence, runId, data }; if (!json && kind === 'diagnostic') { await stderr(encoded(summary ?? kind) + '\n'); return; } await stdout(json ? encoded(envelope) + '\n' : encoded(summary ?? kind) + '\n'); }; @@ -1893,6 +2247,9 @@ export async function main(argv: readonly string[]): Promise { if (args.command === 'runner') { return await runRunnerCommand(args, emit); } + if (args.command === 'evolve') { + return await runEvolveCommand(args, emit); + } if (args.command === 'step') { runId = get('run-id'); return await runStepCommand(args, json, emit); diff --git a/packages/cli/test/arguments.test.ts b/packages/cli/test/arguments.test.ts index 40a82dc..83e6343 100644 --- a/packages/cli/test/arguments.test.ts +++ b/packages/cli/test/arguments.test.ts @@ -551,3 +551,82 @@ test('cli: parseArguments validates runner relay|worker grammar and rejects inva assert.throws(() => parseArguments(bad), UsageError, `expected UsageError for ${JSON.stringify(bad)}`); } }); + +test('cli: parseArguments validates evolve check|run|resume|status|inspect|export grammar and rejects invalid shapes', () => { + const checkMin = parseArguments(['evolve', 'check', '--campaign', '.loopwright/campaign.yaml']); + assert.equal(checkMin.command, 'evolve'); + assert.equal(checkMin.evolveAction, 'check'); + assert.equal(checkMin.values.get('campaign'), '.loopwright/campaign.yaml'); + + const checkFull = parseArguments(['evolve', 'check', '--campaign', 'c.yaml', '--repo', '/repo', '--json']); + assert.equal(checkFull.evolveAction, 'check'); + assert.equal(checkFull.values.get('repo'), '/repo'); + assert.equal(checkFull.flags.has('json'), true); + + for (const stateFlag of ['state', 'campaign-dir', 'root'] as const) { + const runParsed = parseArguments([ + 'evolve', 'run', '--campaign', 'c.yaml', `--${stateFlag}`, '/state', + '--repo', '/repo', '--out', '/bundle', '--format', 'oci-layout', + '--allow-synthetic-probe', '--json', + ]); + assert.equal(runParsed.evolveAction, 'run'); + assert.equal(runParsed.values.get(stateFlag), '/state'); + assert.equal(runParsed.values.get('format'), 'oci-layout'); + assert.equal(runParsed.flags.has('allow-synthetic-probe'), true); + assert.equal(runParsed.flags.has('json'), true); + } + + for (const dirFlag of ['campaign', 'campaign-dir', 'root'] as const) { + const resumeParsed = parseArguments([ + 'evolve', 'resume', `--${dirFlag}`, '/state', '--repo', '/repo', '--out', '/out', '--format', 'dir', '--allow-synthetic-probe', '--json', + ]); + assert.equal(resumeParsed.evolveAction, 'resume'); + assert.equal(resumeParsed.values.get(dirFlag), '/state'); + + const statusParsed = parseArguments(['evolve', 'status', `--${dirFlag}`, '/state', '--json']); + assert.equal(statusParsed.evolveAction, 'status'); + + const inspectParsed = parseArguments([ + 'evolve', 'inspect', `--${dirFlag}`, '/state', '--island', '0', '--individual', 'ind-g1-i0', '--json', + ]); + assert.equal(inspectParsed.evolveAction, 'inspect'); + assert.equal(inspectParsed.values.get('island'), '0'); + assert.equal(inspectParsed.values.get('individual'), 'ind-g1-i0'); + + const exportParsed = parseArguments([ + 'evolve', 'export', `--${dirFlag}`, '/state', '--out', '/bundle', '--format', 'oci-layout', '--allow-synthetic-probe', '--overwrite', '--json', + ]); + assert.equal(exportParsed.evolveAction, 'export'); + assert.equal(exportParsed.flags.has('overwrite'), true); + } + + for (const bad of [ + ['evolve'], + ['evolve', 'bogus'], + ['evolve', '--campaign', 'c.yaml'], + ['evolve', 'check'], + ['evolve', 'check', '--campaign', ' '], + ['evolve', 'check', '--campaign', 'c.yaml', '--state', '/s'], + ['evolve', 'check', '--campaign', 'c.yaml', '--role-model', 'author=openai/gpt-5.4'], + ['evolve', 'run', '--campaign', 'c.yaml'], + ['evolve', 'run', '--campaign', 'c.yaml', '--state', '/s', '--campaign-dir', '/s2'], + ['evolve', 'run', '--campaign', 'c.yaml', '--state', '/s', '--root', '/s2'], + ['evolve', 'run', '--campaign', 'c.yaml', '--state', '/s', '--format', 'tar'], + ['evolve', 'run', '--campaign', 'c.yaml', '--state', '/s', '--overwrite'], + ['evolve', 'resume'], + ['evolve', 'resume', '--campaign', '/s', '--root', '/s2'], + ['evolve', 'status'], + ['evolve', 'status', '--campaign', '/s', '--out', '/o'], + ['evolve', 'inspect'], + ['evolve', 'inspect', '--campaign', '/s', '--island', '-1'], + ['evolve', 'inspect', '--campaign', '/s', '--island', 'abc'], + ['evolve', 'inspect', '--campaign', '/s', '--individual', 'bad id'], + ['evolve', 'export', '--campaign', '/s'], + ['evolve', 'export', '--out', '/bundle'], + ['evolve', 'export', '--campaign', '/s', '--out', '/bundle', '--format', 'zip'], + ['evolve', 'export', '--campaign', '/s', '--out', '/bundle', '--repo', '/r'], + ['evolve', 'export', '--campaign', '/s', '--out', '/bundle', 'extra'], + ]) { + assert.throws(() => parseArguments(bad), UsageError, `expected UsageError for ${JSON.stringify(bad)}`); + } +}); diff --git a/packages/cli/test/build-incremental.test.ts b/packages/cli/test/build-incremental.test.ts index 7a8b063..7538a01 100644 --- a/packages/cli/test/build-incremental.test.ts +++ b/packages/cli/test/build-incremental.test.ts @@ -20,13 +20,14 @@ const PACKAGES = [ 'taskpack', 'github-app', 'hardware-runner', + 'evolution', 'cli', ] as const; test('build.mjs: restores deleted dist outputs and invalidates tsbuildinfo when dependency declarations change', async () => { const work = await mkdtemp(join(tmpdir(), 'lw-build-inc-')); try { - // Create a minimal 11-package composite workspace using the real scripts/build.mjs and real tsconfig.json layout + // Create a minimal 12-package composite workspace using the real scripts/build.mjs and real tsconfig.json layout await mkdir(join(work, 'scripts'), { recursive: true }); await cp(join(REPO_ROOT, 'scripts', 'build.mjs'), join(work, 'scripts', 'build.mjs')); await cp(join(REPO_ROOT, 'tsconfig.json'), join(work, 'tsconfig.json')); diff --git a/packages/cli/test/check-docs-rules.test.ts b/packages/cli/test/check-docs-rules.test.ts index a22e8a9..1ef876f 100644 --- a/packages/cli/test/check-docs-rules.test.ts +++ b/packages/cli/test/check-docs-rules.test.ts @@ -984,3 +984,74 @@ test('check-docs.mjs CLI: --report exits 0, strict mode exits 1 on violations, a rmSync(root, { recursive: true, force: true }); } }); + +test('checkDocs Pretty YAML metadata rule: EvolutionCampaign requires metadata.name and rejects metadata.id', async () => { + const checkDocs = await loadCheckDocs(); + const root = buildMinimalRepoFixture(); + try { + writeFileEnsuringDir( + join(root, 'docs', 'configuration', 'task-contract.md'), + [ + '# Task Contract', + '', + 'Task contracts and campaigns enforce strict schemas.', + '', + '## Contents', + '', + '- [EvolutionCampaign](#evolutioncampaign)', + '', + '## EvolutionCampaign', + '', + '```yaml', + 'apiVersion: loopwright.dev/v1alpha1', + 'kind: EvolutionCampaign', + 'metadata:', + ' name: flash-decode', + 'spec: {}', + '```', + '', + '```yaml', + 'apiVersion: loopwright.dev/v1alpha1', + 'kind: EvolutionCampaign', + 'metadata:', + ' id: legacy-id', + 'spec: {}', + '```', + '', + '```yaml', + 'apiVersion: loopwright.dev/v1alpha1', + 'kind: EvolutionCampaign', + 'spec: {}', + '```', + '', + '---', + '', + '**See also** — [Architecture](../getting-started/architecture.md) (execution chain)', + '', + '**Next** → [Controller and Registry](controller-and-registry.md) — configure controller drafts.', + '', + ].join('\n') + ); + + const result = checkDocs({ repoRoot: root, mode: 'strict' }); + assert.equal(result.ok, false); + assert.ok( + !result.errors.some(e => e.startsWith('docs/configuration/task-contract.md:11:')), + `Valid EvolutionCampaign YAML with metadata.name must pass, got: ${result.errors.join('\n')}` + ); + assert.ok( + result.errors.some(e => e.startsWith('docs/configuration/task-contract.md:19:') && e.includes('must declare metadata.name')), + `Expected missing metadata.name error for EvolutionCampaign, got: ${result.errors.join('\n')}` + ); + assert.ok( + result.errors.some(e => e.startsWith('docs/configuration/task-contract.md:19:') && e.includes('metadata must use name only')), + `Expected metadata.id rejection for EvolutionCampaign, got: ${result.errors.join('\n')}` + ); + assert.ok( + result.errors.some(e => e.startsWith('docs/configuration/task-contract.md:27:') && e.includes('must include top-level metadata.name')), + `Expected missing metadata block error for EvolutionCampaign, got: ${result.errors.join('\n')}` + ); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); diff --git a/packages/cli/test/closure-and-failure-matrix.test.ts b/packages/cli/test/closure-and-failure-matrix.test.ts index e9f6681..3089c1c 100644 --- a/packages/cli/test/closure-and-failure-matrix.test.ts +++ b/packages/cli/test/closure-and-failure-matrix.test.ts @@ -100,6 +100,27 @@ test('closure: refuses unprovisioned external upgrades without a hash-bound rece }); assert.equal(hwForged.falsificationDetected, true); assert.ok(hwForged.diagnostics.some(diagnostic => diagnostic.code === CLOSURE_FALSIFICATION_FORBIDDEN)); + + const evoRow: ClosureCapabilityEntry = { + ...CLOSURE_CAPABILITY_LEDGER[0]!, + ownerPackage: '@loopwright/evolution', + }; + const evoAccepted = await evaluateClosureMatrix({ entries: [evoRow] }); + assert.equal(evoAccepted.falsificationDetected, false); + assert.deepEqual(evoAccepted.diagnostics, []); + + const evoExternal: ClosureCapabilityEntry = { + ...external, + ownerPackage: '@loopwright/evolution', + }; + const evoBlocked = await evaluateClosureMatrix({ entries: [evoExternal] }); + assert.equal(evoBlocked.falsificationDetected, false); + assert.deepEqual(evoBlocked.diagnostics, []); + const evoForged = await evaluateClosureMatrix({ + entries: [{ ...evoExternal, disposition: 'closed_local', verificationStatus: 'passed', unlockPrerequisite: null }], + }); + assert.equal(evoForged.falsificationDetected, true); + assert.ok(evoForged.diagnostics.some(diagnostic => diagnostic.code === CLOSURE_FALSIFICATION_FORBIDDEN)); }); test('closure: verifies evidence containment and refuses missing or symlinked files', async () => { const root = await mkdtemp(join(tmpdir(), 'lw-closure-integrity-')); diff --git a/packages/cli/test/docs-and-site.test.ts b/packages/cli/test/docs-and-site.test.ts index e398e65..ba6ad21 100644 --- a/packages/cli/test/docs-and-site.test.ts +++ b/packages/cli/test/docs-and-site.test.ts @@ -148,6 +148,7 @@ test('documentation and skills: AGENTS.md, OpenCodeReview rules, and skills exis assert.ok(rulePaths.has('packages/taskpack/**/*.ts'), 'must cover taskpack'); assert.ok(rulePaths.has('packages/github-app/**/*.ts'), 'must cover github-app'); assert.ok(rulePaths.has('packages/hardware-runner/**/*.ts'), 'must cover hardware-runner'); + assert.ok(rulePaths.has('packages/evolution/**/*.ts'), 'must cover evolution'); assert.ok(rulePaths.has('packages/cli/**/*.ts'), 'must cover cli'); assert.ok(rulePaths.has('action.yml'), 'must cover action.yml'); assert.ok(rulePaths.has('docs/**/*.md'), 'must cover docs'); diff --git a/packages/cli/test/evolve-cli.test.ts b/packages/cli/test/evolve-cli.test.ts new file mode 100644 index 0000000..0da8c65 --- /dev/null +++ b/packages/cli/test/evolve-cli.test.ts @@ -0,0 +1,1951 @@ +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, 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 { + EVOLUTION_ERROR_CODES, + parseEvolutionCampaignDocument, + verifyEvolutionBundle, + type EvolutionErrorCode, +} from '@loopwright/evolution'; +import { SecretScrubber } from '@loopwright/core'; +import { SecretScrubber as TaskpackSecretScrubber, loadDeclarativeTaskpack } from '@loopwright/taskpack'; +import { + runHardwareWorker, + startRelayServer, + type WorkerConfig, +} from '@loopwright/hardware-runner'; +import { createCliEvolutionEvaluator } from '../src/evolve.js'; +import { evolutionExitCode, main as cliMain } from '../src/main.js'; + +const MAIN = fileURLToPath(new URL('../src/main.js', import.meta.url)); +const BENCH_HMAC_SECRET = 'evolve-cli-bench-hmac-secret-0123456789abcdef'; +const WORKER_BEARER_TOKEN = 'evolve-cli-worker-token-0123456789abcdef'; +const LOCAL_OAI_KEY = 'sk-evolve-cli-test-secret-0123456789abcdef'; + +function sha256Hex(data: Uint8Array | string): string { + return createHash('sha256').update(data).digest('hex'); +} + +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 kernel'], { 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; + } + } +} + +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'); + +test('evolve-cli: help flags, zero top-level @loopwright/evolution static imports, and exhaustive exit codes', async () => { + const topHelp = spawnSync(process.execPath, [MAIN, '--help'], { + encoding: 'utf8', + timeout: 15_000, + env: { PATH: '/usr/bin:/bin' }, + }); + assert.equal(topHelp.status, 0, topHelp.stderr); + assert.match(topHelp.stdout, /evolve check --campaign FILE/); + assert.match(topHelp.stdout, /evolve run --campaign FILE --state DIR/); + assert.match(topHelp.stdout, /evolve resume --campaign DIR/); + assert.match(topHelp.stdout, /evolve status --campaign DIR/); + assert.match(topHelp.stdout, /evolve inspect --campaign DIR/); + assert.match(topHelp.stdout, /evolve export --campaign DIR --out DIR/); + + for (const helpArgv of [ + ['evolve', '--help'], + ['evolve', 'check', '--help'], + ['evolve', 'run', '--help'], + ['evolve', 'resume', '--help'], + ['evolve', 'status', '--help'], + ['evolve', 'inspect', '--help'], + ['evolve', 'export', '--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 export --campaign DIR --out DIR/); + } + + const mainSrcPath = fileURLToPath(new URL('../../../../packages/cli/src/main.ts', import.meta.url)); + const mainSrc = await readFile(mainSrcPath, 'utf8'); + assert.equal( + /^\s*import\b[^;]*@loopwright\/evolution/m.test(mainSrc), + false, + 'main.ts must not perform a top-level import of @loopwright/evolution', + ); + assert.equal( + /^\s*import\b[^;]*@loopwright\/agent-pi\/host-session/m.test(mainSrc), + false, + 'main.ts must not perform a top-level import of @loopwright/agent-pi/host-session', + ); + assert.match(mainSrc, /await import\('@loopwright\/evolution'\)/); + + const evolveSrcPath = fileURLToPath(new URL('../../../../packages/cli/src/evolve.ts', import.meta.url)); + const evolveSrc = await readFile(evolveSrcPath, 'utf8'); + assert.equal( + /^\s*import\s+(?!type\b)[^;]*@loopwright\/evolution/m.test(evolveSrc), + false, + 'evolve.ts must not perform a top-level runtime import of @loopwright/evolution', + ); + assert.equal( + /^\s*import\b[^;]*@loopwright\/agent-pi\/host-session/m.test(evolveSrc), + false, + 'evolve.ts must not perform a top-level static import of @loopwright/agent-pi/host-session', + ); + + const expectedExitCodes: Record = { + EVOLUTION_SCHEMA_INVALID: 2, + TEAM_ENVELOPE_VIOLATION: 3, + EXPORT_UNVERIFIED_FORBIDDEN: 3, + EVOLUTION_SYMLINK_FORBIDDEN: 3, + EVOLUTION_NOT_FOUND: 4, + ARTIFACT_INVALID: 4, + ARTIFACT_MISSING: 4, + EVOLUTION_BUDGET_EXCEEDED: 5, + EVOLUTION_CLOCK_DRIFT: 7, + EVOLUTION_LEASE_FENCED: 7, + EVOLUTION_CONFLICT: 7, + EVOLUTION_STORE_BUSY: 7, + EVOLUTION_STORE_ERROR: 8, + EVOLUTION_STORE_CLOSED: 8, + EVOLUTION_STORE_CORRUPT: 8, + SECRET_LEAK_DETECTED: 8, + }; + for (const code of EVOLUTION_ERROR_CODES) { + assert.equal(evolutionExitCode(code), expectedExitCodes[code], `mismatch for ${code}`); + } +}); + +test('evolve-cli: evolve check validates campaign manifests and fails closed without leaking secrets', async () => { + const realTmp = await realpath(tmpdir()); + const root = await mkdtemp(join(realTmp, 'lw-evolve-cli-check-')); + try { + const repoDir = join(root, 'repo'); + await initGitRepo(repoDir, { + '.loopwright/taskpack.yaml': { + content: [ + 'apiVersion: loopwright.dev/v1alpha1', + 'kind: Taskpack', + 'metadata:', + ' name: cli-check-tp', + 'spec:', + ' goal:', + ' candidate: Evolve kernel.', + ' noChange: No change.', + ' target:', + ' matrix:', + ' - id: cuda-sm90', + ' platform: linux/amd64', + ' variant: cuda12', + ' hardware:', + ' accelerator: sm_90a', + ' isolationMode: whole_device', + ' deviceCount: 1', + ' scope:', + ' writable: [src/kernels/**]', + ' protected: [scripts/**]', + ' models:', + ' - provider: local-oai', + ' id: mock-model', + ' apiKeyEnv: LOCAL_OAI_KEY', + ' 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-bench', + ' required: true', + ' targetCellId: cuda-sm90', + ' heldOutWorkloadId: decode-bs1-4k', + ' allowSyntheticHardwareProbe: true', + ' metricThresholds:', + ' - kind: bounds', + ' metric: max_ulp', + ' max: 2', + ' bucketScope: all_buckets', + ].join('\n'), + }, + '.loopwright/campaign.yaml': { + content: [ + 'apiVersion: loopwright.dev/v1alpha1', + 'kind: EvolutionCampaign', + 'metadata:', + ' name: cli-check-campaign', + 'spec:', + ' taskpack: .loopwright/taskpack.yaml', + ' targetCellId: cuda-sm90', + ' stages:', + ' mode: single-target', + ' population:', + ' islands: 1', + ' migrationIntervalGenerations: 2', + ' 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: deterministic-round-robin', + ' maxCrossoversPerPrompt: 1', + ' objectives:', + ' - metric: latency_us_p50', + ' direction: minimize', + ' budgets:', + ' maxGenerations: 1', + ' maxEvaluations: 1', + ' maxConcurrentEvaluations: 1', + ' scratchpadIntervalGenerations: 1', + ].join('\n'), + }, + 'src/kernels/flash_decode.cu': { content: BASELINE_KERNEL_SOURCE }, + }); + + const okRes = spawnSync( + process.execPath, + [MAIN, 'evolve', 'check', '--campaign', join(repoDir, '.loopwright', 'campaign.yaml'), '--repo', repoDir, '--json'], + { encoding: 'utf8', timeout: 10_000, env: { PATH: '/usr/bin:/bin', LOCAL_OAI_KEY } }, + ); + assert.equal(okRes.status, 0, okRes.stdout + okRes.stderr); + const okEnv = JSON.parse(okRes.stdout) as { + kind: string; + data: { valid: boolean; targetCellId: string; stageMode: string; modelIds: readonly string[] }; + }; + assert.equal(okEnv.kind, 'plan'); + assert.equal(okEnv.data.valid, true); + assert.equal(okEnv.data.targetCellId, 'cuda-sm90'); + assert.equal(okEnv.data.stageMode, 'single-target'); + assert.deepEqual(okEnv.data.modelIds, ['mock-model']); + + const badCampaign = join(root, 'bad-campaign.yaml'); + await writeFile( + badCampaign, + (await readFile(join(repoDir, '.loopwright', 'campaign.yaml'), 'utf8')).replace('targetCellId: cuda-sm90', 'targetCellId: missing-cell'), + { mode: 0o600 }, + ); + const badRes = spawnSync( + process.execPath, + [MAIN, 'evolve', 'check', '--campaign', badCampaign, '--repo', repoDir, '--json'], + { encoding: 'utf8', timeout: 10_000, env: { PATH: '/usr/bin:/bin', LOCAL_OAI_KEY } }, + ); + assert.equal(badRes.status, 2, badRes.stdout + badRes.stderr); + const badEnv = JSON.parse(badRes.stdout) as { kind: string; data: { code: string; message: string } }; + assert.equal(badEnv.kind, 'diagnostic'); + assert.equal(badEnv.data.code, 'EVOLUTION_SCHEMA_INVALID'); + + const secretCampaign = join(root, 'secret-campaign.yaml'); + await writeFile( + secretCampaign, + (await readFile(join(repoDir, '.loopwright', 'campaign.yaml'), 'utf8')).replace('targetCellId: cuda-sm90', `targetCellId: ${LOCAL_OAI_KEY}`), + { mode: 0o600 }, + ); + const secretRes = spawnSync( + process.execPath, + [MAIN, 'evolve', 'check', '--campaign', secretCampaign, '--repo', repoDir, '--json'], + { encoding: 'utf8', timeout: 10_000, env: { PATH: '/usr/bin:/bin', LOCAL_OAI_KEY } }, + ); + assert.equal(secretRes.status, 8, secretRes.stdout + secretRes.stderr); + const secretEnv = JSON.parse(secretRes.stdout) as { kind: string; data: { code: string; message: string } }; + assert.equal(secretEnv.kind, 'diagnostic'); + assert.equal(secretEnv.data.code, 'SECRET_LEAK_DETECTED'); + assert.equal(secretRes.stdout.includes(LOCAL_OAI_KEY), false); + assert.equal(secretRes.stderr.includes(LOCAL_OAI_KEY), false); + + const missingStatus = spawnSync( + process.execPath, + [MAIN, 'evolve', 'status', '--campaign', join(root, 'missing-state'), '--json'], + { encoding: 'utf8', timeout: 15_000, env: { PATH: '/usr/bin:/bin' } }, + ); + assert.equal(missingStatus.status, 4, missingStatus.stdout + missingStatus.stderr); + assert.equal(JSON.parse(missingStatus.stdout).data.code, 'EVOLUTION_NOT_FOUND'); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test('evolve-cli: end-to-end specialist-then-portfolio run, SIGINT pause + resume, status, inspect, OCI export, and tamper/probe gates', { timeout: 120000 }, async () => { + const realTmp = await realpath(tmpdir()); + const root = await mkdtemp(join(realTmp, 'lw-evolve-cli-e2e-')); + + const relayCasDir = join(root, 'relay-cas'); + const workerWorkDir = join(root, 'worker-work'); + const workloadsDir = join(root, 'workloads'); + await mkdir(workerWorkDir, { recursive: true, mode: 0o700 }); + + for (const [workloadId, lat, rps] of [ + ['decode-bs1-4k', 28, 2200] as const, + ['decode-bs16-8k', 64, 5400] as const, + ['decode-portfolio-holdout', 44, 4100] as const, + ]) { + await mkdir(join(workloadsDir, workloadId), { recursive: true, mode: 0o700 }); + const evalScript = [ + `#!${process.execPath}`, + 'const payload = {', + ' status: "approved",', + ` metrics: { latency_us_p50: ${lat}, goodput_rps: ${rps}, max_ulp: 1 },`, + ' bucketMetrics: [', + ` { bucketId: ${JSON.stringify(workloadId)}, dimensions: { bs: ${workloadId.includes('bs16') ? 16 : 1} }, metrics: { latency_us_p50: ${lat}, goodput_rps: ${rps}, max_ulp: 1 } }`, + ' ],', + ' hardwareDiagnostics: { boundPipeline: "tensor_cube", occupancyPct: 78, rooflineHeadroom: 1.12 }', + '};', + 'process.stdout.write("LOOPWRIGHT_STAGE_B_RESULT:" + JSON.stringify(payload) + "\\n");', + '', + ].join('\n'); + const evalPath = join(workloadsDir, workloadId, 'evaluate.sh'); + await writeFile(evalPath, evalScript, { mode: 0o755 }); + await chmod(evalPath, 0o755); + } + + const bs1CubinHex = buildElf64Cubin(['flash_decode_bs1_sm90a']).toString('hex'); + const bs16CubinHex = buildElf64Cubin(['flash_decode_bs16_sm90a']).toString('hex'); + const routerCubinHex = buildElf64Cubin(['flash_decode_portfolio_router_sm90a']).toString('hex'); + + const buildScript = [ + `#!${process.execPath}`, + 'const fs = require("node:fs");', + 'const path = require("node:path");', + 'const src = fs.readFileSync("src/kernels/flash_decode.cu", "utf8");', + 'const outDir = process.env.LOOPWRIGHT_STAGE_A_OUT;', + 'if (src.includes("PORTFOLIO_ROUTER_DISPATCH")) {', + ` fs.writeFileSync(path.join(outDir, "portfolio_router.cubin"), Buffer.from(${JSON.stringify(routerCubinHex)}, "hex"));`, + '} else if (src.includes("SPECIALIST_BS16")) {', + ` fs.writeFileSync(path.join(outDir, "spec_bs16.cubin"), Buffer.from(${JSON.stringify(bs16CubinHex)}, "hex"));`, + '} else {', + ` fs.writeFileSync(path.join(outDir, "spec_bs1.cubin"), Buffer.from(${JSON.stringify(bs1CubinHex)}, "hex"));`, + '}', + '', + ].join('\n'); + + const relay = await startRelayServer({ + port: 0, + casDir: relayCasDir, + controllerSigningSecret: BENCH_HMAC_SECRET, + workerTokens: [WORKER_BEARER_TOKEN], + leaseTtlMs: 30_000, + sweepIntervalMs: 150, + }); + + const workerAbort = new AbortController(); + let workerFatalError: unknown = null; + const workerPromise = runHardwareWorker({ + config: { + workerId: 'evolve-cli-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-bs1-4k', 'decode-bs16-8k', 'decode-portfolio-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; + } + }); + + // Mock loopback SSE provider returning a write tool call + completed submission + let sseTurn = 0; + let emitSigintOnSecondEval = false; + 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; + const bodyText = Buffer.concat(chunks).toString('utf8'); + res.writeHead(200, { 'content-type': 'text/event-stream' }); + if (!isSecondMessage) { + sseTurn += 1; + assert.equal( + bodyText.includes('decode-portfolio-holdout'), + false, + 'portfolioHeldOutWorkloadId must never leak to specialist or portfolio model prompts', + ); + if (emitSigintOnSecondEval && bodyText.includes('bucket: bs16-isl8k')) { + emitSigintOnSecondEval = false; + setTimeout(() => { + process.emit('SIGINT'); + }, 25); + } + let marker = 'SPECIALIST_BS1'; + if (bodyText.includes('Evolution stage: portfolio')) { + marker = 'PORTFOLIO_ROUTER_DISPATCH'; + } else if (bodyText.includes('bucket: bs16-isl8k')) { + marker = 'SPECIALIST_BS16'; + } + const nextKernel = BASELINE_KERNEL_SOURCE.replace('return 0; // baseline', `return ${sseTurn}; // ${marker}`); + const toolChunk = { + id: `chatcmpl-tool-${sseTurn}`, + object: 'chat.completion.chunk', + choices: [{ + index: 0, + delta: { + role: 'assistant', + tool_calls: [{ + index: 0, + id: `call_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-done-${sseTurn}`, + object: 'chat.completion.chunk', + choices: [{ + index: 0, + delta: { + role: 'assistant', + content: '{"version":1,"status":"completed","checks":[],"reason":"updated flash_decode.cu inside EVOLVE-BLOCK"}', + }, + finish_reason: 'stop', + }], + usage: { prompt_tokens: 25, completion_tokens: 12, total_tokens: 37 }, + }; + 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; + + 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: cli-portfolio-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"', + ' forbiddenSymbolPatterns: [cublas, cudnn]', + ' 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, bash]', + ' prompt: Mutate src/kernels/flash_decode.cu strictly 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-bs1-4k', + ' 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: cli-portfolio-e2e', + 'spec:', + ' taskpack: .loopwright/taskpack.yaml', + ' targetCellId: cuda-sm90', + ' stages:', + ' mode: specialist-then-portfolio', + ' specialistBuckets:', + ' - id: bs1-isl4k', + ' heldOutWorkloadId: decode-bs1-4k', + ' - id: bs16-isl8k', + ' heldOutWorkloadId: decode-bs16-8k', + ' portfolioHeldOutWorkloadId: decode-portfolio-holdout', + ' population:', + ' islands: 1', + ' 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.5', + ' crossover: 0.0', + ' modelBandit: deterministic-round-robin', + ' maxCrossoversPerPrompt: 1', + ' objectives:', + ' - metric: latency_us_p50', + ' direction: minimize', + ' - metric: goodput_rps', + ' direction: maximize', + ' budgets:', + ' maxGenerations: 3', + ' maxEvaluations: 6', + ' maxConcurrentEvaluations: 1', + ' scratchpadIntervalGenerations: 5', + ].join('\n'), + }, + 'src/kernels/flash_decode.cu': { content: BASELINE_KERNEL_SOURCE }, + 'scripts/build.sh': { content: buildScript, executable: true }, + }); + + const campaignFile = join(repoDir, '.loopwright', 'campaign.yaml'); + const campaignStateDir = join(root, 'campaign-state'); + 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: BENCH_HMAC_SECRET, + LOCAL_OAI_KEY, + }; + + // 1. Start `evolve run` and interrupt after first specialist evaluation via SIGINT -> exit 130 (paused) + emitSigintOnSecondEval = true; + const interruptedRun = await runCliInProcess([ + 'evolve', 'run', + '--campaign', campaignFile, + '--state', campaignStateDir, + '--repo', repoDir, + '--allow-synthetic-probe', + '--json', + ], cliEnv); + assert.equal(interruptedRun.status, 130, interruptedRun.stdout + interruptedRun.stderr); + const interruptedEnv = JSON.parse(interruptedRun.stdout.trim()) as { + kind: string; + data: { campaign: { status: string; evaluationsUsed: number } }; + }; + assert.equal(interruptedEnv.kind, 'result'); + assert.equal(interruptedEnv.data.campaign.status, 'paused'); + assert.ok(interruptedEnv.data.campaign.evaluationsUsed >= 1); + + // 2. Resume via `evolve resume` -> completes specialist + portfolio synthesis cleanly! + const resumedRun = await runCliInProcess([ + 'evolve', 'resume', + '--campaign', campaignStateDir, + '--repo', repoDir, + '--allow-synthetic-probe', + '--json', + ], cliEnv); + if (resumedRun.status !== 0) { + const diagInspect = await runCliInProcess(['evolve', 'inspect', '--campaign', campaignStateDir, '--json'], cliEnv); + assert.fail(`evolve resume exited ${resumedRun.status}: ${resumedRun.stdout}${resumedRun.stderr}\ninspect: ${diagInspect.stdout}`); + } + const resumedEnv = JSON.parse(resumedRun.stdout.trim()) as { + kind: string; + data: { campaign: { status: string; stagePhase: string }; paretoFrontier: readonly { individualId: string }[] }; + }; + assert.equal(resumedEnv.kind, 'result'); + assert.equal(resumedEnv.data.campaign.status, 'completed'); + assert.equal(resumedEnv.data.campaign.stagePhase, 'portfolio'); + assert.equal(resumedRun.stdout.includes(BENCH_HMAC_SECRET), false); + assert.equal(resumedRun.stdout.includes(LOCAL_OAI_KEY), false); + + // 3. `evolve status` + const statusRes = await runCliInProcess(['evolve', 'status', '--campaign', campaignStateDir, '--json'], cliEnv); + assert.equal(statusRes.status, 0, statusRes.stdout + statusRes.stderr); + const statusEnv = JSON.parse(statusRes.stdout.trim()) as { + kind: string; + data: { campaign: { status: string }; countsByStatus: { passed: number } }; + }; + assert.equal(statusEnv.kind, 'status'); + assert.equal(statusEnv.data.campaign.status, 'completed'); + assert.equal(statusEnv.data.countsByStatus.passed, 3); + + // 4. `evolve inspect` (full + --island + --individual + missing -> exit 4) + const inspectAll = await runCliInProcess(['evolve', 'inspect', '--campaign', campaignStateDir, '--json'], cliEnv); + assert.equal(inspectAll.status, 0, inspectAll.stdout + inspectAll.stderr); + const inspectEnv = JSON.parse(inspectAll.stdout.trim()) as { + kind: string; + data: { + individuals: readonly { individualId: string; status: string }[]; + lineageEdges: readonly { role: string }[]; + }; + }; + assert.equal(inspectEnv.kind, 'inspection'); + assert.equal(inspectEnv.data.individuals.length, 4); + assert.equal(inspectEnv.data.individuals.filter(i => i.status === 'passed').length, 3); + assert.equal(inspectEnv.data.individuals.filter(i => i.status === 'preempted').length, 1); + assert.equal(inspectEnv.data.lineageEdges.filter(e => e.role === 'portfolio_member').length, 2); + + const firstIndId = inspectEnv.data.individuals[0]!.individualId; + const inspectOne = await runCliInProcess([ + 'evolve', 'inspect', '--campaign', campaignStateDir, '--island', '0', '--individual', firstIndId, '--json', + ], cliEnv); + assert.equal(inspectOne.status, 0, inspectOne.stdout + inspectOne.stderr); + assert.equal(JSON.parse(inspectOne.stdout.trim()).data.individuals.length, 1); + + const inspectMissingIsland = await runCliInProcess([ + 'evolve', 'inspect', '--campaign', campaignStateDir, '--island', '99', '--json', + ], cliEnv); + assert.equal(inspectMissingIsland.status, 4); + assert.equal(JSON.parse(inspectMissingIsland.stdout.trim()).data.code, 'EVOLUTION_NOT_FOUND'); + + // 5a. `evolve export` without --allow-synthetic-probe -> EXPORT_UNVERIFIED_FORBIDDEN (exit 3) + const ociOutDir = join(root, 'oci-bundle'); + const unverifiedExport = await runCliInProcess([ + 'evolve', 'export', '--campaign', campaignStateDir, '--out', ociOutDir, '--format', 'oci-layout', '--json', + ], cliEnv); + assert.equal(unverifiedExport.status, 3, unverifiedExport.stdout + unverifiedExport.stderr); + assert.equal(JSON.parse(unverifiedExport.stdout.trim()).data.code, 'EXPORT_UNVERIFIED_FORBIDDEN'); + + // 5b. `evolve export --allow-synthetic-probe` WITHOUT LOOPWRIGHT_GATE_SIGNING_SECRET -> EXPORT_UNVERIFIED_FORBIDDEN (exit 3) + const missingSecretExport = await runCliInProcess([ + 'evolve', 'export', '--campaign', campaignStateDir, '--out', ociOutDir, '--format', 'oci-layout', '--allow-synthetic-probe', '--json', + ], { + ...cliEnv, + LOOPWRIGHT_GATE_SIGNING_SECRET: undefined, + BENCH_SIGNING_SECRET: undefined, + }); + assert.equal(missingSecretExport.status, 3, missingSecretExport.stdout + missingSecretExport.stderr); + assert.equal(JSON.parse(missingSecretExport.stdout.trim()).data.code, 'EXPORT_UNVERIFIED_FORBIDDEN'); + + // 6. `evolve export --format oci-layout --allow-synthetic-probe` with HMAC secret -> exit 0 + verified OCI bundle + driverConstraint + const okExport = await runCliInProcess([ + 'evolve', 'export', '--campaign', campaignStateDir, '--out', ociOutDir, '--format', 'oci-layout', '--allow-synthetic-probe', '--json', + ], cliEnv); + assert.equal(okExport.status, 0, okExport.stdout + okExport.stderr); + const exportEnv = JSON.parse(okExport.stdout.trim()) as { + kind: string; + data: { format: string; exportedIndividualIds: readonly string[]; blobCount: number }; + }; + assert.equal(exportEnv.kind, 'result'); + assert.equal(exportEnv.data.format, 'oci-layout'); + assert.equal(exportEnv.data.exportedIndividualIds.length, 3); + assert.equal(exportEnv.data.blobCount, 3); + + const verified = await verifyEvolutionBundle({ + bundleDir: ociOutDir, + allowSyntheticProbe: true, + receiptSigningSecret: BENCH_HMAC_SECRET, + }); + assert.equal(verified.format, 'oci-layout'); + assert.equal(verified.manifest.compatibility.driverConstraint, '>=550.0'); + assert.equal(verified.dispatchManifest.fallback, 'baseline'); + assert.equal(verified.receiptCount, 3); + assert.equal(verified.blobCount, 3); + + // 7. Re-exporting to existing dir without --overwrite -> EVOLUTION_CONFLICT (exit 7); with --overwrite -> exit 0 + const conflictExport = await runCliInProcess([ + 'evolve', 'export', '--campaign', campaignStateDir, '--out', ociOutDir, '--format', 'oci-layout', '--allow-synthetic-probe', '--json', + ], cliEnv); + assert.equal(conflictExport.status, 7, conflictExport.stdout + conflictExport.stderr); + assert.equal(JSON.parse(conflictExport.stdout.trim()).data.code, 'EVOLUTION_CONFLICT'); + + const overwriteExport = await runCliInProcess([ + 'evolve', 'export', '--campaign', campaignStateDir, '--out', ociOutDir, '--format', 'oci-layout', '--allow-synthetic-probe', '--overwrite', '--json', + ], cliEnv); + assert.equal(overwriteExport.status, 0, overwriteExport.stdout + overwriteExport.stderr); + + // 8. Tamper 1 byte of a CAS .cubin blob -> evolve export fails closed with ARTIFACT_INVALID (exit 4) + const bs1Digest = sha256Hex(Buffer.from(bs1CubinHex, 'hex')); + const casBlobPath = join(campaignStateDir, 'cas', 'sha256', bs1Digest); + const originalBlob = await readFile(casBlobPath); + const tamperedBlob = Buffer.from(originalBlob); + tamperedBlob[0] = tamperedBlob[0]! ^ 0xff; + await chmod(casBlobPath, 0o600); + await writeFile(casBlobPath, tamperedBlob); + await chmod(casBlobPath, 0o400); + + const tamperedExport = await runCliInProcess([ + 'evolve', 'export', + '--campaign', campaignStateDir, + '--out', join(root, 'tampered-bundle'), + '--format', 'oci-layout', + '--allow-synthetic-probe', + '--json', + ], cliEnv); + assert.equal(tamperedExport.status, 4, tamperedExport.stdout + tamperedExport.stderr); + assert.equal(JSON.parse(tamperedExport.stdout.trim()).data.code, 'ARTIFACT_INVALID'); + } finally { + workerAbort.abort(); + await workerPromise; + await relay.close(); + await new Promise(resolveClose => sseServer.close(() => resolveClose())); + await rm(root, { recursive: true, force: true }); + } + assert.equal(workerFatalError, null); +}); + +test('evolve-cli: overlapping --state inside --repo fails closed with EVOLUTION_SCHEMA_INVALID (exit 2)', async () => { + const realTmp = await realpath(tmpdir()); + const root = await mkdtemp(join(realTmp, 'lw-evolve-cli-disjoint-')); + try { + const repoDir = join(root, 'repo'); + await initGitRepo(repoDir, { + '.loopwright/taskpack.yaml': { + content: [ + 'apiVersion: loopwright.dev/v1alpha1', + 'kind: Taskpack', + 'metadata:', + ' name: cli-disjoint-tp', + 'spec:', + ' goal:', + ' candidate: Evolve kernel.', + ' noChange: No change.', + ' target:', + ' matrix:', + ' - id: cuda-sm90', + ' platform: linux/amd64', + ' variant: cuda12', + ' hardware:', + ' accelerator: sm_90a', + ' isolationMode: whole_device', + ' deviceCount: 1', + ' scope:', + ' writable: [src/kernels/**]', + ' protected: [scripts/**]', + ' models:', + ' - provider: local-oai', + ' id: mock-model', + ' apiKeyEnv: LOCAL_OAI_KEY', + ' 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-bench', + ' required: true', + ' targetCellId: cuda-sm90', + ' heldOutWorkloadId: decode-bs1-4k', + ' allowSyntheticHardwareProbe: true', + ' publication:', + ' mode: disabled', + ].join('\n'), + }, + '.loopwright/campaign.yaml': { + content: [ + 'apiVersion: loopwright.dev/v1alpha1', + 'kind: EvolutionCampaign', + 'metadata:', + ' name: cli-disjoint-camp', + 'spec:', + ' taskpack: .loopwright/taskpack.yaml', + ' targetCellId: cuda-sm90', + ' stages:', + ' mode: single-target', + ' population:', + ' islands: 1', + ' migrationIntervalGenerations: 2', + ' 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: deterministic-round-robin', + ' maxCrossoversPerPrompt: 1', + ' objectives:', + ' - metric: latency_us_p50', + ' direction: minimize', + ' budgets:', + ' maxGenerations: 1', + ' maxEvaluations: 1', + ' maxConcurrentEvaluations: 1', + ' scratchpadIntervalGenerations: 1', + ].join('\n'), + }, + 'src/kernels/flash_decode.cu': { content: BASELINE_KERNEL_SOURCE }, + }); + + const overlapRes = await runCliInProcess([ + 'evolve', 'run', + '--campaign', join(repoDir, '.loopwright', 'campaign.yaml'), + '--state', join(repoDir, 'campaign-state'), + '--repo', repoDir, + '--json', + ], { PATH: '/usr/bin:/bin', LOCAL_OAI_KEY }); + assert.equal(overlapRes.status, 2, overlapRes.stdout + overlapRes.stderr); + const env = JSON.parse(overlapRes.stdout.trim()) as { kind: string; data: { code: string } }; + assert.equal(env.kind, 'diagnostic'); + assert.equal(env.data.code, 'EVOLUTION_SCHEMA_INVALID'); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test('evolve-cli: teamEvolution.enabled triggers isolated read-only LocalRunStore Pi supervisor on stall', { timeout: 120000 }, async () => { + const realTmp = await realpath(tmpdir()); + const root = await mkdtemp(join(realTmp, 'lw-evolve-cli-team-sup-')); + + 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-bs1-4k'), { recursive: true, mode: 0o700 }); + + const evalScript = [ + `#!${process.execPath}`, + 'const payload = {', + ' status: "approved",', + ' metrics: { latency_us_p50: 40, goodput_rps: 2000, max_ulp: 1 },', + ' bucketMetrics: [', + ' { bucketId: "decode-bs1-4k", dimensions: { bs: 1 }, metrics: { latency_us_p50: 40, goodput_rps: 2000, max_ulp: 1 } }', + ' ],', + ' hardwareDiagnostics: { boundPipeline: "tensor_cube", occupancyPct: 75, rooflineHeadroom: 1.25 }', + '};', + 'process.stdout.write("LOOPWRIGHT_STAGE_B_RESULT:" + JSON.stringify(payload) + "\\n");', + '', + ].join('\n'); + const evalPath = join(workloadsDir, 'decode-bs1-4k', 'evaluate.sh'); + await writeFile(evalPath, evalScript, { mode: 0o755 }); + await chmod(evalPath, 0o755); + + const cubinHex = buildElf64Cubin(['flash_decode_team_sm90a']).toString('hex'); + const buildScript = [ + `#!${process.execPath}`, + 'const fs = require("node:fs");', + 'const path = require("node:path");', + 'const outDir = process.env.LOOPWRIGHT_STAGE_A_OUT;', + `fs.writeFileSync(path.join(outDir, "team_kernel.cubin"), Buffer.from(${JSON.stringify(cubinHex)}, "hex"));`, + '', + ].join('\n'); + + const relay = await startRelayServer({ + port: 0, + casDir: relayCasDir, + controllerSigningSecret: BENCH_HMAC_SECRET, + workerTokens: [WORKER_BEARER_TOKEN], + leaseTtlMs: 30_000, + sweepIntervalMs: 150, + }); + + const workerAbort = new AbortController(); + let workerFatalError: unknown = null; + const workerPromise = runHardwareWorker({ + config: { + workerId: 'evolve-cli-team-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-bs1-4k'], + }, + 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; + }); + + let mutateTurn = 0; + let supervisorCalls = 0; + let probeRoleCalls = 0; + const synthesizedTeamPatch = { + kind: 'TeamPatch', + schemaVersion: 'team-patch.v1', + diagnosis: { + summary: 'Island stalled on flat HBM roofline; split read-only probe from mutator', + plateauCategory: 'coupled_responsibilities', + rationale: 'Add a read-only probe step before mutating flash_decode.cu', + }, + roles: [ + { + id: 'probe-worker', + archetypeRoleId: 'probe-readonly', + purpose: 'task', + tools: ['read'], + model: 'mock-model', + prompt: 'Inspect kernel bottleneck in read-only mode.', + }, + { + id: 'mutator-worker', + archetypeRoleId: 'mutator', + purpose: 'task', + tools: ['read', 'write', 'edit'], + model: 'mock-model', + prompt: 'Mutate src/kernels/flash_decode.cu inside EVOLVE-BLOCK markers.', + }, + ], + steps: [ + { id: 'step-probe', roleId: 'probe-worker', dependsOn: [] }, + { id: 'step-mutate', roleId: 'mutator-worker', dependsOn: ['step-probe'] }, + ], + }; + + const sseServer = createServer((req, res) => { + const chunks: Buffer[] = []; + req.on('data', (c: Buffer) => chunks.push(c)); + req.on('end', () => { + const bodyText = Buffer.concat(chunks).toString('utf8'); + const parsedBody = JSON.parse(bodyText) as { + readonly messages?: readonly { readonly role?: string }[]; + }; + const isAfterTool = parsedBody.messages?.some(m => m.role === 'tool') ?? false; + res.writeHead(200, { 'content-type': 'text/event-stream' }); + + if (bodyText.includes('Diagnose island 0 plateau')) { + supervisorCalls += 1; + assert.equal(bodyText.includes('decode-bs1-4k'), false, 'heldOutWorkloadId must never enter Pi supervisor prompt'); + const supChunk = { + id: `chatcmpl-sup-${supervisorCalls}`, + object: 'chat.completion.chunk', + choices: [{ + index: 0, + delta: { role: 'assistant', content: JSON.stringify(synthesizedTeamPatch) }, + finish_reason: 'stop', + }], + usage: { prompt_tokens: 30, completion_tokens: 40, total_tokens: 70 }, + }; + res.end(`data: ${JSON.stringify(supChunk)}\n\ndata: [DONE]\n\n`); + return; + } + + if (bodyText.includes('Inspect kernel bottleneck in read-only mode.')) { + probeRoleCalls += 1; + const probeChunk = { + id: `chatcmpl-probe-${probeRoleCalls}`, + object: 'chat.completion.chunk', + choices: [{ + index: 0, + delta: { + role: 'assistant', + content: '{"version":1,"status":"completed","checks":[],"reason":"probe completed read-only analysis"}', + }, + finish_reason: 'stop', + }], + usage: { prompt_tokens: 20, completion_tokens: 15, total_tokens: 35 }, + }; + res.end(`data: ${JSON.stringify(probeChunk)}\n\ndata: [DONE]\n\n`); + return; + } + + if (!isAfterTool) { + mutateTurn += 1; + const nextKernel = BASELINE_KERNEL_SOURCE.replace('return 0; // baseline', `return ${mutateTurn * 10 + 1}; // team_gen_${mutateTurn}`); + const toolChunk = { + id: `chatcmpl-mut-tool-${mutateTurn}`, + object: 'chat.completion.chunk', + choices: [{ + index: 0, + delta: { + role: 'assistant', + tool_calls: [{ + index: 0, + id: `call_team_write_${mutateTurn}`, + 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-mut-done-${mutateTurn}`, + object: 'chat.completion.chunk', + choices: [{ + index: 0, + delta: { + role: 'assistant', + content: '{"version":1,"status":"completed","checks":[],"reason":"mutated kernel"}', + }, + 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; + + 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: cli-team-sup-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', + ' 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.', + ' - id: probe-readonly', + ' provider: local-oai', + ' model: mock-model', + ' purpose: task', + ' tools: [read]', + ' prompt: Read-only probe archetype.', + ' - id: supervisor', + ' provider: local-oai', + ' model: mock-model', + ' purpose: task', + ' tools: [read]', + ' prompt: Read-only plateau supervisor.', + ' 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-bs1-4k', + ' allowSyntheticHardwareProbe: true', + ' publication:', + ' mode: disabled', + ].join('\n'), + }, + '.loopwright/campaign.yaml': { + content: [ + 'apiVersion: loopwright.dev/v1alpha1', + 'kind: EvolutionCampaign', + 'metadata:', + ' name: cli-team-sup-camp', + 'spec:', + ' taskpack: .loopwright/taskpack.yaml', + ' targetCellId: cuda-sm90', + ' stages:', + ' mode: single-target', + ' 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: deterministic-round-robin', + ' maxCrossoversPerPrompt: 1', + ' teamEvolution:', + ' enabled: true', + ' supervisorRoleId: supervisor', + ' allowedArchetypeRoles: [probe-readonly, mutator]', + ' stallGenerations: 1', + ' trialGenerations: 2', + ' maxTeamSize: 2', + ' maxTeamSteps: 2', + ' objectives:', + ' - metric: latency_us_p50', + ' direction: minimize', + ' budgets:', + ' maxGenerations: 3', + ' maxEvaluations: 6', + ' maxConcurrentEvaluations: 1', + ' scratchpadIntervalGenerations: 5', + ].join('\n'), + }, + 'src/kernels/flash_decode.cu': { content: BASELINE_KERNEL_SOURCE }, + 'scripts/build.sh': { content: buildScript, executable: true }, + }); + + const stateDir = join(root, 'campaign-state'); + 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: BENCH_HMAC_SECRET, + LOCAL_OAI_KEY, + }; + + const runRes = await runCliInProcess([ + 'evolve', 'run', + '--campaign', join(repoDir, '.loopwright', 'campaign.yaml'), + '--state', stateDir, + '--repo', repoDir, + '--allow-synthetic-probe', + '--json', + ], cliEnv); + assert.equal(runRes.status, 0, runRes.stdout + runRes.stderr); + assert.equal(supervisorCalls, 1, 'isolated read-only Pi supervisor must trigger exactly once on stall'); + assert.ok(probeRoleCalls >= 1, 'synthesized read-only probe role must execute on subsequent trial generation'); + + const inspectRes = await runCliInProcess(['evolve', 'inspect', '--campaign', stateDir, '--json'], cliEnv); + assert.equal(inspectRes.status, 0, inspectRes.stdout + inspectRes.stderr); + const inspectEnv = JSON.parse(inspectRes.stdout.trim()) as { + data: { + teamConfigs: readonly { teamConfigId: string; status: string; patchCasDigest: unknown }[]; + }; + }; + assert.equal(inspectEnv.data.teamConfigs.length, 2, 'incumbent + synthesized trial team must be recorded'); + assert.ok(inspectEnv.data.teamConfigs.some(tc => tc.patchCasDigest !== null)); + } finally { + workerAbort.abort(); + await workerPromise; + await relay.close(); + await new Promise(resolveClose => sseServer.close(() => resolveClose())); + await rm(root, { recursive: true, force: true }); + } + assert.equal(workerFatalError, null); +}); + +test('evolve-cli: exact whitespace/comment clone edit is rejected with NOVELTY_CLONE_REJECTED and 0 hardware benchmark dispatches', { timeout: 120000 }, async () => { + const realTmp = await realpath(tmpdir()); + const root = await mkdtemp(join(realTmp, 'lw-evolve-cli-novelty-')); + + 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-bs1-4k'), { recursive: true, mode: 0o700 }); + + const evalScript = [ + `#!${process.execPath}`, + 'const payload = {', + ' status: "approved",', + ' metrics: { latency_us_p50: 32, goodput_rps: 2800, max_ulp: 1 },', + ' bucketMetrics: [', + ' { bucketId: "decode-bs1-4k", dimensions: { bs: 1 }, metrics: { latency_us_p50: 32, goodput_rps: 2800, 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-bs1-4k', 'evaluate.sh'); + await writeFile(evalPath, evalScript, { mode: 0o755 }); + await chmod(evalPath, 0o755); + + const cubinHex = buildElf64Cubin(['flash_decode_novelty_sm90a']).toString('hex'); + const buildScript = [ + `#!${process.execPath}`, + 'const fs = require("node:fs");', + 'const path = require("node:path");', + 'const outDir = process.env.LOOPWRIGHT_STAGE_A_OUT;', + `fs.writeFileSync(path.join(outDir, "novelty_kernel.cubin"), Buffer.from(${JSON.stringify(cubinHex)}, "hex"));`, + '', + ].join('\n'); + + const relay = await startRelayServer({ + port: 0, + casDir: relayCasDir, + controllerSigningSecret: BENCH_HMAC_SECRET, + workerTokens: [WORKER_BEARER_TOKEN], + leaseTtlMs: 30_000, + sweepIntervalMs: 150, + }); + + let workerJobsProcessed = 0; + const workerAbort = new AbortController(); + let workerFatalError: unknown = null; + const workerPromise = runHardwareWorker({ + config: { + workerId: 'evolve-cli-novelty-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-bs1-4k'], + }, + 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, + onJobSettled: () => { + workerJobsProcessed += 1; + }, + }).catch((err: unknown) => { + if (!workerAbort.signal.aborted) workerFatalError = err; + }); + + 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 isAfterTool = parsedBody.messages?.some(m => m.role === 'tool') ?? false; + res.writeHead(200, { 'content-type': 'text/event-stream' }); + if (!isAfterTool) { + sseTurn += 1; + // Gen 1 writes return 42; Gen 2 writes an exact whitespace/comment clone of Gen 1! + const nextKernel = sseTurn === 1 + ? BASELINE_KERNEL_SOURCE.replace('return 0; // baseline', 'return 42; // gen 1 original') + : BASELINE_KERNEL_SOURCE.replace('return 0; // baseline', ' return 42; /* gen 2 whitespace/comment clone */'); + const toolChunk = { + id: `chatcmpl-nov-tool-${sseTurn}`, + object: 'chat.completion.chunk', + choices: [{ + index: 0, + delta: { + role: 'assistant', + tool_calls: [{ + index: 0, + id: `call_nov_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-nov-done-${sseTurn}`, + object: 'chat.completion.chunk', + choices: [{ + index: 0, + delta: { + role: 'assistant', + content: '{"version":1,"status":"completed","checks":[],"reason":"wrote kernel variant"}', + }, + 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; + + 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: cli-novelty-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', + ' 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-bs1-4k', + ' allowSyntheticHardwareProbe: true', + ' publication:', + ' mode: disabled', + ].join('\n'), + }, + '.loopwright/campaign.yaml': { + content: [ + 'apiVersion: loopwright.dev/v1alpha1', + 'kind: EvolutionCampaign', + 'metadata:', + ' name: cli-novelty-camp', + 'spec:', + ' taskpack: .loopwright/taskpack.yaml', + ' targetCellId: cuda-sm90', + ' stages:', + ' mode: single-target', + ' 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: deterministic-round-robin', + ' maxCrossoversPerPrompt: 1', + ' objectives:', + ' - metric: latency_us_p50', + ' direction: minimize', + ' budgets:', + ' maxGenerations: 2', + ' maxEvaluations: 4', + ' maxConcurrentEvaluations: 1', + ' scratchpadIntervalGenerations: 5', + ].join('\n'), + }, + 'src/kernels/flash_decode.cu': { content: BASELINE_KERNEL_SOURCE }, + 'scripts/build.sh': { content: buildScript, executable: true }, + }); + + const stateDir = join(root, 'campaign-state'); + 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: BENCH_HMAC_SECRET, + LOCAL_OAI_KEY, + }; + + const runRes = await runCliInProcess([ + 'evolve', 'run', + '--campaign', join(repoDir, '.loopwright', 'campaign.yaml'), + '--state', stateDir, + '--repo', repoDir, + '--allow-synthetic-probe', + '--json', + ], cliEnv); + assert.equal(runRes.status, 0, runRes.stdout + runRes.stderr); + assert.equal(workerJobsProcessed, 1, 'clone candidate must trigger 0 hardware benchmark dispatches'); + + const runEnv = JSON.parse(runRes.stdout.trim()) as { + data: { + campaign: { evaluationsUsed: number }; + noveltyRejectionsCount: number; + }; + }; + assert.equal(runEnv.data.noveltyRejectionsCount, 1); + assert.equal(runEnv.data.campaign.evaluationsUsed, 1, 'NOVELTY_CLONE_REJECTED must not consume evaluation budget'); + + const inspectRes = await runCliInProcess(['evolve', 'inspect', '--campaign', stateDir, '--json'], cliEnv); + assert.equal(inspectRes.status, 0, inspectRes.stdout + inspectRes.stderr); + const inspectEnv = JSON.parse(inspectRes.stdout.trim()) as { + data: { + individuals: readonly { status: string; failureReason: string | null }[]; + }; + }; + assert.equal(inspectEnv.data.individuals.length, 2); + assert.equal(inspectEnv.data.individuals.filter(i => i.status === 'passed').length, 1); + assert.equal( + inspectEnv.data.individuals.filter(i => i.status === 'failed' && i.failureReason === 'NOVELTY_CLONE_REJECTED').length, + 1, + ); + } finally { + workerAbort.abort(); + await workerPromise; + await relay.close(); + await new Promise(resolveClose => sseServer.close(() => resolveClose())); + await rm(root, { recursive: true, force: true }); + } + assert.equal(workerFatalError, null); +}); + +test('evolve-cli: 1-role cross-provider TeamPatch binds OPENAI_API_KEY and never leaks ANTHROPIC_API_KEY to openai endpoint', async () => { + const root = await mkdtemp(join(await realpath(tmpdir()), 'lw-evolve-cli-xprov-')); + const observedOpenAiAuths: string[] = []; + const sseServer = createServer((req, res) => { + const auth = req.headers.authorization ?? ''; + if (req.url?.startsWith('/openai/')) { + observedOpenAiAuths.push(auth); + } + const chunks: Buffer[] = []; + req.on('data', (c: Buffer) => chunks.push(c)); + req.on('end', () => { + res.writeHead(200, { 'content-type': 'text/event-stream' }); + const doneChunk = { + id: 'chatcmpl-xprov-1', + object: 'chat.completion.chunk', + choices: [{ + index: 0, + delta: { + role: 'assistant', + content: '{"version":1,"status":"no_change","checks":[],"reason":"checked cross-provider auth"}', + }, + finish_reason: 'stop', + }], + usage: { prompt_tokens: 10, completion_tokens: 10, total_tokens: 20 }, + }; + 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 prevAnth = process.env['ANTHROPIC_API_KEY']; + const prevOai = process.env['OPENAI_API_KEY']; + const prevModelsJson = process.env['LOOPWRIGHT_MODELS_JSON']; + const prevAllowCustomUrl = process.env['LOOPWRIGHT_ALLOW_MANIFEST_CUSTOM_BASE_URL']; + const prevBenchUrl = process.env['LOOPWRIGHT_BENCHMARK_GATE_URL']; + const prevGateSecret = process.env['LOOPWRIGHT_GATE_SIGNING_SECRET']; + + try { + const modelsJsonPath = join(root, 'models.json'); + await writeFile( + modelsJsonPath, + JSON.stringify({ + providers: { + anthropic: { + baseUrl: `http://127.0.0.1:${ssePort}/anthropic`, + api: 'openai-completions', + models: [{ id: 'claude-sonnet-4-6', contextWindow: 128_000, maxTokens: 4_096 }], + }, + openai: { + baseUrl: `http://127.0.0.1:${ssePort}/openai`, + api: 'openai-completions', + models: [{ id: 'gpt-5.4', contextWindow: 128_000, maxTokens: 4_096 }], + }, + }, + }), + { mode: 0o600 }, + ); + + const taskpackYaml = [ + 'apiVersion: loopwright.dev/v1alpha1', + 'kind: Taskpack', + 'metadata:', + ' name: xprov-tp', + 'spec:', + ' goal:', + ' candidate: Optimize decode kernel.', + ' noChange: No change.', + ' target:', + ' matrix:', + ' - id: cuda-sm90', + ' platform: linux/amd64', + ' variant: cuda12', + ' hardware:', + ' accelerator: sm_90a', + ' isolationMode: whole_device', + ' deviceCount: 1', + ' scope:', + ' writable: [src/kernels/**]', + ' protected: [scripts/**]', + ' models:', + ' - provider: anthropic', + ' id: claude-sonnet-4-6', + ' - provider: openai', + ' id: gpt-5.4', + ' roles:', + ' - id: mutator', + ' provider: anthropic', + ' model: claude-sonnet-4-6', + ' purpose: task', + ' tools: [read, edit]', + ' prompt: Edit kernel.', + ' 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-bs1-4k', + ' allowSyntheticHardwareProbe: true', + ' publication:', + ' mode: disabled', + ].join('\n'); + + const campaignYaml = [ + 'apiVersion: loopwright.dev/v1alpha1', + 'kind: EvolutionCampaign', + 'metadata:', + ' name: xprov-camp', + 'spec:', + ' taskpack: .loopwright/taskpack.yaml', + ' targetCellId: cuda-sm90', + ' stages:', + ' mode: single-target', + ' population:', + ' islands: 1', + ' migrationIntervalGenerations: 4', + ' maxMigrationElites: 1', + ' nicheAxes:', + ' - id: bound_pipeline', + ' kind: enum', + ' values: [hbm, tensor_cube]', + ' sampling:', + ' noveltyDecayLambda: 1.0', + ' mutationWeights:', + ' diff_tune: 1.0', + ' full_rewrite: 0.0', + ' crossover: 0.0', + ' maxCrossoversPerPrompt: 1', + ' objectives:', + ' - metric: latency_us_p50', + ' direction: minimize', + ' budgets:', + ' maxGenerations: 1', + ' maxEvaluations: 1', + ' maxConcurrentEvaluations: 1', + ' scratchpadIntervalGenerations: 5', + ].join('\n'); + + const repoDir = join(root, 'repo'); + const baseRevision = await initGitRepo(repoDir, { + '.loopwright/taskpack.yaml': { content: taskpackYaml }, + '.loopwright/campaign.yaml': { content: campaignYaml }, + 'src/kernels/flash_decode.cu': { content: BASELINE_KERNEL_SOURCE }, + }); + + process.env['ANTHROPIC_API_KEY'] = 'sk-anth-DO-NOT-LEAK-TO-OPENAI-0123456789'; + process.env['OPENAI_API_KEY'] = 'sk-oai-EXPECTED-KEY-0123456789abcdef'; + process.env['LOOPWRIGHT_MODELS_JSON'] = modelsJsonPath; + process.env['LOOPWRIGHT_ALLOW_MANIFEST_CUSTOM_BASE_URL'] = 'true'; + process.env['LOOPWRIGHT_BENCHMARK_GATE_URL'] = `http://127.0.0.1:${ssePort}/bench`; + process.env['LOOPWRIGHT_GATE_SIGNING_SECRET'] = BENCH_HMAC_SECRET; + + const manifest = parseEvolutionCampaignDocument(campaignYaml); + const taskpack = await loadDeclarativeTaskpack({ + bytes: Buffer.from(taskpackYaml, 'utf8'), + format: 'yaml', + allowLoopbackHttp: true, + }); + + const coreScrubber = new SecretScrubber(); + const taskpackScrubber = new TaskpackSecretScrubber(); + const evaluator = createCliEvolutionEvaluator({ + repositoryRoot: repoDir, + coreScrubber, + taskpackScrubber, + }); + + const campRoot = join(root, 'camp-state'); + const childRunDir = join(campRoot, 'runs', 'ind-xprov-1'); + await mkdir(childRunDir, { recursive: true, mode: 0o700 }); + + await evaluator({ + campaignId: 'camp-xprov', + campaignRoot: campRoot, + childRunDir, + baseRevision, + individualId: 'ind-xprov-1', + islandId: 0, + generation: 1, + stagePhase: 'single-target', + bucketId: null, + heldOutWorkloadId: 'decode-bs1-4k', + teamConfigId: 'team-xprov-1', + modelId: 'claude-sonnet-4-6', + trackId: 'triton', + mutationKind: 'diff_tune', + parents: [], + stagedParentFiles: [], + manifest, + taskpack, + teamPatch: { + kind: 'TeamPatch', + schemaVersion: 'team-patch.v1', + diagnosis: { + summary: 'Switch single mutator role to openai/gpt-5.4', + plateauCategory: 'coupled_responsibilities', + rationale: 'Use openai provider even when bandit slot selected anthropic modelId', + }, + roles: [ + { + id: 'mutator-oai', + archetypeRoleId: 'mutator', + purpose: 'task', + tools: ['read', 'edit'], + model: 'openai/gpt-5.4', + prompt: 'Inspect kernel.', + }, + ], + steps: [{ id: 'step-mut', roleId: 'mutator-oai', dependsOn: [] }], + }, + }); + + assert.ok(observedOpenAiAuths.length >= 1, 'openai endpoint must receive the 1-role cross-provider request'); + assert.ok( + observedOpenAiAuths.every(h => h === 'Bearer sk-oai-EXPECTED-KEY-0123456789abcdef'), + `expected OPENAI_API_KEY on openai endpoint, got ${JSON.stringify(observedOpenAiAuths)}`, + ); + assert.ok( + observedOpenAiAuths.every(h => !h.includes('sk-anth-DO-NOT-LEAK')), + 'ANTHROPIC_API_KEY must never be sent to openai endpoint', + ); + } finally { + if (prevAnth === undefined) delete process.env['ANTHROPIC_API_KEY']; + else process.env['ANTHROPIC_API_KEY'] = prevAnth; + if (prevOai === undefined) delete process.env['OPENAI_API_KEY']; + else process.env['OPENAI_API_KEY'] = prevOai; + if (prevModelsJson === undefined) delete process.env['LOOPWRIGHT_MODELS_JSON']; + else process.env['LOOPWRIGHT_MODELS_JSON'] = prevModelsJson; + if (prevAllowCustomUrl === undefined) delete process.env['LOOPWRIGHT_ALLOW_MANIFEST_CUSTOM_BASE_URL']; + else process.env['LOOPWRIGHT_ALLOW_MANIFEST_CUSTOM_BASE_URL'] = prevAllowCustomUrl; + if (prevBenchUrl === undefined) delete process.env['LOOPWRIGHT_BENCHMARK_GATE_URL']; + else process.env['LOOPWRIGHT_BENCHMARK_GATE_URL'] = prevBenchUrl; + if (prevGateSecret === undefined) delete process.env['LOOPWRIGHT_GATE_SIGNING_SECRET']; + else process.env['LOOPWRIGHT_GATE_SIGNING_SECRET'] = prevGateSecret; + await new Promise(resolveClose => sseServer.close(() => resolveClose())); + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/packages/cli/test/npm-pack.test.ts b/packages/cli/test/npm-pack.test.ts index 53187ed..c7b47e2 100644 --- a/packages/cli/test/npm-pack.test.ts +++ b/packages/cli/test/npm-pack.test.ts @@ -85,10 +85,11 @@ test('pack-npm: builds single @gpustack/loopwright tarball, keeps workspace pack }; assert.equal(installedManifest.name, '@gpustack/loopwright'); assert.equal(installedManifest.version, '0.1.0-rc1'); - assert.equal(installedManifest.bundledDependencies.length, 11); + assert.equal(installedManifest.bundledDependencies.length, 12); assert.ok(installedManifest.bundledDependencies.includes('@loopwright/taskpack')); assert.ok(installedManifest.bundledDependencies.includes('@loopwright/github-app')); assert.ok(installedManifest.bundledDependencies.includes('@loopwright/hardware-runner')); + assert.ok(installedManifest.bundledDependencies.includes('@loopwright/evolution')); assert.equal(installedManifest.dependencies['minimatch'], '11.0.1'); const resolveCheck = spawnSync( @@ -96,7 +97,7 @@ test('pack-npm: builds single @gpustack/loopwright tarball, keeps workspace pack [ '--input-type=module', '-e', - "const tp = await import('@loopwright/taskpack'); const gh = await import('@loopwright/github-app'); const hr = await import('@loopwright/hardware-runner'); if (tp.TaskpackError !== gh.GitHubAppError) throw new Error('error identity mismatch'); if (hr.HARDWARE_RUNNER_PACKAGE_NAME !== '@loopwright/hardware-runner') throw new Error('hardware-runner export mismatch');", + "const tp = await import('@loopwright/taskpack'); const gh = await import('@loopwright/github-app'); const hr = await import('@loopwright/hardware-runner'); const ev = await import('@loopwright/evolution'); if (tp.TaskpackError !== gh.GitHubAppError) throw new Error('error identity mismatch'); if (hr.HARDWARE_RUNNER_PACKAGE_NAME !== '@loopwright/hardware-runner') throw new Error('hardware-runner export mismatch'); if (ev.EVOLUTION_PACKAGE_NAME !== '@loopwright/evolution') throw new Error('evolution export mismatch');", ], { cwd: installedPkgRoot, encoding: 'utf8', timeout: 10000 }, ); diff --git a/packages/cli/test/runner-cli.test.ts b/packages/cli/test/runner-cli.test.ts index f304298..ba86f33 100644 --- a/packages/cli/test/runner-cli.test.ts +++ b/packages/cli/test/runner-cli.test.ts @@ -130,7 +130,7 @@ function makeRelayBenchmarkRequest( test('runner-cli: help flags, HELP text, and dynamic import isolation', async () => { const topHelp = spawnSync(process.execPath, [MAIN, '--help'], { encoding: 'utf8', - timeout: 5_000, + timeout: 15_000, env: { PATH: '/usr/bin:/bin' }, }); assert.equal(topHelp.status, 0, topHelp.stderr); @@ -144,7 +144,7 @@ test('runner-cli: help flags, HELP text, and dynamic import isolation', async () ]) { const res = spawnSync(process.execPath, [MAIN, ...helpArgv], { encoding: 'utf8', - timeout: 5_000, + timeout: 15_000, env: { PATH: '/usr/bin:/bin' }, }); assert.equal(res.status, 0, res.stderr); @@ -169,6 +169,7 @@ test('runner-cli: hardwareRunnerExitCode covers every HardwareRunnerErrorCode ex AUTH_UNAUTHORIZED: 3, AUTH_FORBIDDEN: 3, RUNNER_SANDBOX_FAILED: 3, + WORKER_DEVICE_QUARANTINED: 3, ARTIFACT_INVALID: 4, ARTIFACT_MISSING: 4, NOT_FOUND: 4, diff --git a/packages/cli/tsconfig.json b/packages/cli/tsconfig.json index 23b6c6a..ed42bd6 100644 --- a/packages/cli/tsconfig.json +++ b/packages/cli/tsconfig.json @@ -15,6 +15,7 @@ { "path": "../controller" }, { "path": "../core" }, { "path": "../decisions" }, + { "path": "../evolution" }, { "path": "../github-app" }, { "path": "../hardware-runner" }, { "path": "../memory" }, diff --git a/packages/controller/src/benchmark-gate.ts b/packages/controller/src/benchmark-gate.ts index 9c42328..58beeab 100644 --- a/packages/controller/src/benchmark-gate.ts +++ b/packages/controller/src/benchmark-gate.ts @@ -8,15 +8,20 @@ import { VERIFIER_ARTIFACT_LIMITS, bindSubject, digestArtifactFromMetadata, + evaluateMetricThresholds, isVerifierNamespacePath, matchesHardwareTarget, + validateBucketMetrics, validateDocument, + validateHardwareDiagnostics, validateRelativePath, type ArtifactManifest, type ArtifactRef, type BaseTreeAnchor, + type BucketMetricEntry, type Digest, type Evidence, + type HardwareDiagnostics, type HardwareProvenance, type HardwareTargetSpec, type MetricThresholdRule, @@ -153,6 +158,8 @@ export interface BenchmarkVerdict { readonly metrics?: MetricsMap; readonly findings?: readonly StructuredFinding[]; readonly hardwareProvenance?: HardwareProvenance; + readonly bucketMetrics?: readonly BucketMetricEntry[]; + readonly hardwareDiagnostics?: HardwareDiagnostics; readonly outputArtifacts?: readonly BenchmarkOutputArtifact[]; } @@ -280,43 +287,12 @@ export function checkedVerifierArtifactRef( return freeze(res.value); } -function readFiniteMetric(metrics: MetricsMap, key: string): number | undefined { - if (!Object.hasOwn(metrics, key)) return undefined; - const raw = metrics[key]; - if (typeof raw !== 'number' || !Number.isFinite(raw)) return undefined; - return Object.is(raw, -0) ? 0 : raw; -} - export function evaluateBenchmarkThresholds( rules: readonly MetricThresholdRule[], metrics: MetricsMap | undefined, + bucketMetrics?: readonly BucketMetricEntry[], ): boolean { - if (rules.length === 0) return true; - if (metrics === undefined) return false; - for (const rule of rules) { - const value = readFiniteMetric(metrics, rule.metric); - if (value === undefined) return false; - if (rule.kind === 'bounds') { - if (rule.min !== undefined && value < rule.min) return false; - if (rule.max !== undefined && value > rule.max) return false; - continue; - } - const baseline = readFiniteMetric(metrics, rule.baselineMetric); - if (baseline === undefined) return false; - if (rule.operator === 'min_ratio') { - if (!(baseline > 0)) return false; - const ratio = value / baseline; - if (Number.isNaN(ratio) || ratio < rule.threshold) return false; - } else if (rule.operator === 'max_ratio') { - if (!(baseline > 0)) return false; - const ratio = value / baseline; - if (Number.isNaN(ratio) || ratio > rule.threshold) return false; - } else { - const delta = value - baseline; - if (Number.isNaN(delta) || delta > rule.threshold) return false; - } - } - return true; + return evaluateMetricThresholds(rules, metrics, bucketMetrics); } function checkedPrintableText(raw: unknown, max: number): string { @@ -459,6 +435,8 @@ export function checkedBenchmarkVerdict(raw: unknown, expected: Record 0 ? expected.slotId @@ -566,6 +558,8 @@ export function checkedBenchmarkVerdict(raw: unknown, expected: Record - rule.kind === 'bounds' + (check.metricThresholds ?? []).map(rule => { + const bucketScopeField = rule.bucketScope !== undefined + ? { + bucketScope: + typeof rule.bucketScope === 'string' + ? rule.bucketScope + : freeze({ bucketId: rule.bucketScope.bucketId }), + } + : {}; + return rule.kind === 'bounds' ? freeze({ kind: 'bounds' as const, metric: rule.metric, ...(rule.min !== undefined ? { min: rule.min } : {}), ...(rule.max !== undefined ? { max: rule.max } : {}), + ...bucketScopeField, }) : freeze({ kind: 'comparative' as const, @@ -632,8 +640,9 @@ export function resolveBenchmarkSlotMetadata(plan: CompiledPlan, slot: VerifierS baselineMetric: rule.baselineMetric, operator: rule.operator, threshold: rule.threshold, - }), - ), + ...bucketScopeField, + }); + }), ); return { gateId, @@ -1552,7 +1561,7 @@ export function shouldPullBenchmarkOutputs(input: { input.allowSyntheticHardwareProbe, verdict.hardwareProvenance, ) - && evaluateBenchmarkThresholds(input.metricThresholds, verdict.metrics) + && evaluateBenchmarkThresholds(input.metricThresholds, verdict.metrics, verdict.bucketMetrics) ); } return false; @@ -1680,7 +1689,7 @@ export function computeBenchmarkDisposition(input: { ) { return freeze({ status: 'blocked', reason: 'HARDWARE_PROVENANCE_MISMATCH', method: 'benchmark-gate.v1', ...preemptionField }); } - if (!evaluateBenchmarkThresholds(input.metricThresholds, verdict.metrics)) { + if (!evaluateBenchmarkThresholds(input.metricThresholds, verdict.metrics, verdict.bucketMetrics)) { return freeze({ status: 'blocked', reason: 'METRIC_THRESHOLD_FAILED', method: 'benchmark-gate.v1', ...preemptionField }); } if (input.casOutcome === 'gate_timeout') { @@ -1994,6 +2003,8 @@ export async function validateStoredBenchmarkProof(input: { ...(verdict?.metrics !== undefined ? { metrics: verdict.metrics } : {}), ...(verdict?.findings !== undefined ? { findings: verdict.findings } : {}), ...(verdict?.hardwareProvenance !== undefined ? { hardwareProvenance: verdict.hardwareProvenance } : {}), + ...(verdict?.bucketMetrics !== undefined ? { bucketMetrics: verdict.bucketMetrics } : {}), + ...(verdict?.hardwareDiagnostics !== undefined ? { hardwareDiagnostics: verdict.hardwareDiagnostics } : {}), }; const evidence = validateDocument( { apiVersion: 'loopwright.dev/v1alpha1', kind: 'Evidence', metadata: { id: 'evidence.' + suffix }, spec: evidenceSpec }, @@ -2884,6 +2895,8 @@ export class BenchmarkGate { ...(settledVerdict?.metrics !== undefined ? { metrics: settledVerdict.metrics } : {}), ...(settledVerdict?.findings !== undefined ? { findings: settledVerdict.findings } : {}), ...(settledVerdict?.hardwareProvenance !== undefined ? { hardwareProvenance: settledVerdict.hardwareProvenance } : {}), + ...(settledVerdict?.bucketMetrics !== undefined ? { bucketMetrics: settledVerdict.bucketMetrics } : {}), + ...(settledVerdict?.hardwareDiagnostics !== undefined ? { hardwareDiagnostics: settledVerdict.hardwareDiagnostics } : {}), }; const evidenceResult = validateDocument( { apiVersion: 'loopwright.dev/v1alpha1', kind: 'Evidence', metadata: { id: 'evidence.' + suffix }, spec: evidenceSpec }, @@ -2982,6 +2995,8 @@ export class BenchmarkGate { ...(settledVerdict?.metrics !== undefined ? { metrics: settledVerdict.metrics } : {}), ...(settledVerdict?.findings !== undefined ? { findings: settledVerdict.findings } : {}), ...(settledVerdict?.hardwareProvenance !== undefined ? { hardwareProvenance: settledVerdict.hardwareProvenance } : {}), + ...(settledVerdict?.bucketMetrics !== undefined ? { bucketMetrics: settledVerdict.bucketMetrics } : {}), + ...(settledVerdict?.hardwareDiagnostics !== undefined ? { hardwareDiagnostics: settledVerdict.hardwareDiagnostics } : {}), }; const expiredEvidenceRes = validateDocument( { apiVersion: 'loopwright.dev/v1alpha1', kind: 'Evidence', metadata: { id: 'evidence.' + suffix }, spec: expiredEvidenceSpec }, @@ -3392,6 +3407,8 @@ export class BenchmarkGate { ...(validated.verdict?.metrics !== undefined ? { metrics: validated.verdict.metrics } : {}), ...(validated.verdict?.findings !== undefined ? { findings: validated.verdict.findings } : {}), ...(validated.verdict?.hardwareProvenance !== undefined ? { hardwareProvenance: validated.verdict.hardwareProvenance } : {}), + ...(validated.verdict?.bucketMetrics !== undefined ? { bucketMetrics: validated.verdict.bucketMetrics } : {}), + ...(validated.verdict?.hardwareDiagnostics !== undefined ? { hardwareDiagnostics: validated.verdict.hardwareDiagnostics } : {}), }; const evidenceResult = validateDocument( { apiVersion: 'loopwright.dev/v1alpha1', kind: 'Evidence', metadata: { id: 'evidence.' + suffix }, spec: evidenceSpec }, diff --git a/packages/controller/src/config.ts b/packages/controller/src/config.ts index 344f8dd..feef038 100644 --- a/packages/controller/src/config.ts +++ b/packages/controller/src/config.ts @@ -1,5 +1,6 @@ import { dirname, extname, isAbsolute, resolve } from 'node:path'; import { realpath } from 'node:fs/promises'; +import { types } from 'node:util'; import { digestArtifact, validateDocument } from '@loopwright/core'; import { readBoundedFile, inside } from './files.js'; import { parseDocumentBytes, DOCUMENT_BYTES } from './parser.js'; @@ -10,7 +11,9 @@ import { result, refuse } from './errors.js'; import { digestValue, freeze, hash, id, integer, list, record, same, text } from './schema.js'; import { CONTROLLER_API_VERSION, type ControllerConfiguration, type LoadedConfiguration, type LoadConfigurationInput, type RegistryResource, type PublicationConfig, type RoleModelOverride, type RoleSelectionOverride } from './types.js'; export interface ApprovedState { - readonly input: LoadConfigurationInput; readonly vault: CredentialVault; + readonly input: LoadConfigurationInput; + readonly environment: (name: string) => string | undefined; + readonly vault: CredentialVault; readonly resources: readonly { readonly id: string; readonly kind: RegistryResource['kind']; readonly ref: import('@loopwright/core').ArtifactRef; readonly bytes: Uint8Array }[]; } const approved = new WeakMap(); @@ -209,8 +212,57 @@ export function loadConfiguration(unowned: LoadConfigurationInput, ports: Config } const loaded: LoadedConfiguration = freeze({ version: 1, configuration, registry, sourceDigest: hash(source), registryDigest }); vault.assertClean(loaded); - approved.set(loaded, { input: freeze({ configPath, registryPath, registrySha256, untrustedRoots: roots, ...(roleModelOverrides !== undefined ? { roleModelOverrides } : {}) }), vault, resources }); + approved.set(loaded, { + input: freeze({ configPath, registryPath, registrySha256, untrustedRoots: roots, ...(roleModelOverrides !== undefined ? { roleModelOverrides } : {}) }), + environment: ports.environment, + vault, + resources, + }); return loaded; }); } -export function loadTrustedConfiguration(input: LoadConfigurationInput) { return loadConfiguration(input, { environment: name => process.env[name] }); } +export function loadTrustedConfiguration( + input: LoadConfigurationInput & { readonly environment?: ((name: string) => string | undefined) | undefined }, +) { + if ( + input === null + || typeof input !== 'object' + || Array.isArray(input) + || types.isProxy(input) + || ![Object.prototype, null].includes(Object.getPrototypeOf(input)) + ) { + return loadConfiguration(input as unknown as LoadConfigurationInput, { environment: name => process.env[name] }); + } + const envDescriptor = Object.getOwnPropertyDescriptor(input, 'environment'); + if (envDescriptor === undefined) { + return loadConfiguration(input, { environment: name => process.env[name] }); + } + if (!('value' in envDescriptor) || (envDescriptor.value !== undefined && typeof envDescriptor.value !== 'function')) { + return result(async (): Promise => { + refuse('CONFIG_SCHEMA'); + }); + } + const rawEnvironment = envDescriptor.value as ((name: string) => string | undefined) | undefined; + /** + * Trusted host-caller boundary: `loadTrustedConfiguration` accepts an optional environment + * lookup callback strictly from trusted in-process hosts (CLI / taskpack / evolution) to avoid + * mutating global `process.env`. Bound key/value types and length defensively here. + */ + const environment: (name: string) => string | undefined = rawEnvironment === undefined + ? (name => process.env[name]) + : (name => { + if (typeof name !== 'string' || name.length === 0 || name.length > 256) return undefined; + let value: unknown; + try { + value = rawEnvironment(name); + } catch { + return undefined; + } + if (typeof value !== 'string' || value.length > 65_536) return undefined; + return value; + }); + const descriptors = Object.getOwnPropertyDescriptors(input); + Reflect.deleteProperty(descriptors, 'environment'); + const sanitized = Object.defineProperties(Object.create(null) as object, descriptors) as LoadConfigurationInput; + return loadConfiguration(sanitized, { environment }); +} diff --git a/packages/controller/src/controller.ts b/packages/controller/src/controller.ts index 3902a50..0db340d 100644 --- a/packages/controller/src/controller.ts +++ b/packages/controller/src/controller.ts @@ -37,7 +37,7 @@ import { type Submission, type RetainedSubmission, } from './submission.js'; -import { prepareVerification, preflightVerification, Verifier, authenticatedCheck, type PreflightRefusal, type VerifiedCheck, type ByteInventory, type PreparedVerification } from './verification.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 { prepareBenchmarkGate, @@ -214,7 +214,7 @@ export async function createCycle(input: RunCycleInput, ports: ControllerPorts): 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); - const jsonPaths = plan.verifierSlots.filter(slot => ['json-artifact.v1', 'json-keys-guard.v1', 'line-section-guard.v1'].includes(slot.handler.implementation)).map(slot => text(slot.handler.parameters.path)); + const jsonPaths = verifierProofPaths(plan.verifierSlots); const source = await freezeSource(repository, plan.task, owner, artifacts, jsonPaths); 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 }); diff --git a/packages/controller/src/handlers.ts b/packages/controller/src/handlers.ts index cd4a749..8a97229 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', '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'] as Implementation[]) .map(implementation => [implementation, hash('loopwright.dev/controller/handler/v1\0' + canonical({ implementation, inventory }))])) as Record>; } diff --git a/packages/controller/src/reconcile.ts b/packages/controller/src/reconcile.ts index 286c108..0e774e5 100644 --- a/packages/controller/src/reconcile.ts +++ b/packages/controller/src/reconcile.ts @@ -10,6 +10,7 @@ import { ControllerFailure, refuse, result } from './errors.js'; import { ControllerOwner } from './ownership.js'; import { admitRetainedRun, readRetained, validatePortPolicyFields, validatePortsAgainstHostPolicy } from './retained.js'; import { resumeCycleWithPorts } from './recovery.js'; +import { verifierProofPaths } from './verification.js'; import { overlayManifestBounds, restoreSource } from './source.js'; import { ArtifactStore, checkedRef, overwriteAtomicMarker, publishAtomicMarker, stateValue } from './storage.js'; import { readBoundedFile } from './files.js'; @@ -72,7 +73,7 @@ export function reconcileCycle(input: ReconcileCycleInput, ports: ControllerPort try { const retained = await readRetained({ runRoot: input.runRoot, runId: input.runId }); if (retained.descriptor.configuration.roleModelOverrides !== undefined && state.input.roleModelOverrides === undefined) { - const reloaded = await loadConfiguration({ ...state.input, roleModelOverrides: retained.descriptor.configuration.roleModelOverrides }, { environment: name => process.env[name] }); + const reloaded = await loadConfiguration({ ...state.input, roleModelOverrides: retained.descriptor.configuration.roleModelOverrides }, { environment: state.environment }); if (reloaded.ok) { effectiveConfig = reloaded.value; state = approvedState(effectiveConfig); } } } catch { /* admit() below will validate retained run and report the canonical diagnostic */ } @@ -88,7 +89,7 @@ export function reconcileCycle(input: ReconcileCycleInput, ports: ControllerPort } /** Shared retained-run admission for both reconciliation paths. */ async function admit(input: ReconcileCycleInput, plan: import('./types.js').CompiledPlan, ports: ControllerPorts) { - const admitted = await admitRetainedRun({ runRoot: input.runRoot, runId: input.runId, configuration: input.configuration, phase: 'recovery' }); + const admitted = await admitRetainedRun({ runRoot: input.runRoot, runId: input.runId, configuration: input.configuration, environment: approvedState(input.configuration).environment, phase: 'recovery' }); if (!same(plan, admitted.plan)) refuse('RECOVERY_REQUIRED', '', 'recovery'); const effectivePorts = validatePortsAgainstHostPolicy(ports, admitted.hostPolicy, 'recovery'); return { ...admitted, effectivePorts }; @@ -296,7 +297,16 @@ async function reconcileBenchmarkGate( const rawReceipt = parsePrivateJson(receiptBytes, RECEIPT_BYTES); if (!isRecord(rawReceipt)) refuse('EVIDENCE_UNAVAILABLE', '/receipt', 'recovery'); const optionalVerdictKeys = ( - ['retryablePreemption', 'detail', 'metrics', 'findings', 'hardwareProvenance', 'outputArtifacts'] as const + [ + 'retryablePreemption', + 'detail', + 'metrics', + 'findings', + 'hardwareProvenance', + 'bucketMetrics', + 'hardwareDiagnostics', + 'outputArtifacts', + ] as const ).filter(key => Object.hasOwn(rawReceipt, key) && rawReceipt[key] !== undefined); let file: Record; try { @@ -537,13 +547,7 @@ async function reconcileBenchmarkGate( let baseTreeBundle: Awaited>; const entryModes = new Map(); if (rowManifest.spec.baseTree !== undefined || rowManifest.spec.entries.length > 0) { - const jsonPaths = [ - ...new Set( - plan.verifierSlots - .filter(s => ['json-artifact.v1', 'json-keys-guard.v1', 'line-section-guard.v1'].includes(s.handler.implementation)) - .map(s => text(s.handler.parameters.path)), - ), - ]; + const jsonPaths = verifierProofPaths(plan.verifierSlots); const source = await restoreSource( descriptor.repository, plan.task, @@ -702,6 +706,8 @@ async function reconcileBenchmarkGate( ...(parsedVerdict.metrics !== undefined ? { metrics: parsedVerdict.metrics } : {}), ...(parsedVerdict.findings !== undefined ? { findings: parsedVerdict.findings } : {}), ...(parsedVerdict.hardwareProvenance !== undefined ? { hardwareProvenance: parsedVerdict.hardwareProvenance } : {}), + ...(parsedVerdict.bucketMetrics !== undefined ? { bucketMetrics: parsedVerdict.bucketMetrics } : {}), + ...(parsedVerdict.hardwareDiagnostics !== undefined ? { hardwareDiagnostics: parsedVerdict.hardwareDiagnostics } : {}), }; const evidenceResult = validateDocument( { apiVersion: 'loopwright.dev/v1alpha1', kind: 'Evidence', metadata: { id: 'evidence.' + suffix }, spec: evidenceSpec }, diff --git a/packages/controller/src/recovery.ts b/packages/controller/src/recovery.ts index 7a487a9..9b814be 100644 --- a/packages/controller/src/recovery.ts +++ b/packages/controller/src/recovery.ts @@ -19,8 +19,8 @@ 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, text } from './schema.js'; -import { Verifier, prepareVerification, type ByteInventory } from './verification.js'; +import { freeze, 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 { BenchmarkGate, @@ -210,7 +210,7 @@ export function resumeCycleWithPorts(input: RunCycleInput, ports: ControllerPort authority = stateValue(store.claim({ ownerId: 'controller.' + owner.nonce, expectedGeneration: original.owner.generation, expectedRevision: original.revision, mode: 'recovery' })).authority; const artifacts = new ArtifactStore(join(directory, 'artifacts'), owner, state.vault); await artifacts.cleanCasTempFiles(); - const jsonPaths = [...new Set(plan.verifierSlots.filter(slot => ['json-artifact.v1', 'json-keys-guard.v1', 'line-section-guard.v1'].includes(slot.handler.implementation)).map(slot => text(slot.handler.parameters.path)))]; + const jsonPaths = verifierProofPaths(plan.verifierSlots); const source = await restoreSource(resolve(input.repository), plan.task, owner, artifacts, descriptor.source, descriptor.sourceWorkspace, jsonPaths); let progress = new ProgressStore(store, authority, artifacts, plan, lock, descriptor.plan, descriptor.source); const head = await progress.read(); let context: CycleContext = { loaded: effectiveConfig, plan, lock, directory, source, store, authority, owner, artifacts, progress, descriptor, signal: input.signal ?? new AbortController().signal, onEvent: input.onEvent, ports: effectivePorts }; diff --git a/packages/controller/src/refusal-record.ts b/packages/controller/src/refusal-record.ts index ca4ee13..d55e2fb 100644 --- a/packages/controller/src/refusal-record.ts +++ b/packages/controller/src/refusal-record.ts @@ -133,10 +133,26 @@ export function checkedRefusalRecord(input: unknown, plan: CompiledPlan, lock: T const overlay = lock.spec.contract.spec.budgets.overlay; const bounds = overlayProtocolBounds(overlay); const impl = slot?.handler.implementation; - const isFileHandler = impl === 'json-artifact.v1' || impl === 'json-keys-guard.v1' || impl === 'line-section-guard.v1'; - const payloadKind: VerifierHeader['payloadKind'] = - impl === 'json-artifact.v1' ? 'json' : impl === 'json-keys-guard.v1' || impl === 'line-section-guard.v1' ? 'guard' : 'inventories'; - const packetAllowed = maxPacketBytes({ payloadKind, ...(overlay ? { overlay } : {}) }); + const isFileHandler = + impl === 'json-artifact.v1' || + impl === 'json-keys-guard.v1' || + impl === 'line-section-guard.v1' || + impl === 'evolve-block-guard.v1'; + let payloadKind: VerifierHeader['payloadKind'] = 'inventories'; + if (impl === 'json-artifact.v1') { + payloadKind = 'json'; + } else if ( + impl === 'json-keys-guard.v1' + || impl === 'line-section-guard.v1' + || impl === 'evolve-block-guard.v1' + ) { + payloadKind = 'guard'; + } + const packetAllowed = maxPacketBytes({ + payloadKind, + ...(impl === 'evolve-block-guard.v1' ? { handler: impl } : {}), + ...(overlay ? { overlay } : {}), + }); const expectedAllowed = limits.reason === 'json_file_bytes' diff --git a/packages/controller/src/registry.ts b/packages/controller/src/registry.ts index 6d055c1..8dd95db 100644 --- a/packages/controller/src/registry.ts +++ b/packages/controller/src/registry.ts @@ -7,8 +7,13 @@ import { CONTROLLER_API_VERSION, type TrustedRegistry, type RoleProfile, type Ha 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'; -import { RFC6901_POINTER_PATTERN } 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', 'no-change.v1', 'gate.v1', 'benchmark-gate.v1']; +import { + EVOLVE_BLOCK_LIMITS, + RFC6901_POINTER_PATTERN, + 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']; 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 { @@ -81,6 +86,53 @@ export function validateHandler(raw: unknown, path: string): Handler { ) { refuse('CONFIG_SCHEMA', path + '/parameters'); } + } else if (implementation === 'evolve-block-guard.v1') { + if (!isRecord(value.parameters)) refuse('CONFIG_SCHEMA', path + '/parameters'); + const hasAllowedBlockIds = Object.hasOwn(value.parameters, 'allowedBlockIds'); + const hasMaxBlockBytes = Object.hasOwn(value.parameters, 'maxBlockBytes'); + const parameters = record( + value.parameters, + [ + 'checkId', + 'files', + ...(hasAllowedBlockIds ? ['allowedBlockIds' as const] : []), + ...(hasMaxBlockBytes ? ['maxBlockBytes' as const] : []), + ], + path + '/parameters', + ); + id(parameters.checkId, path + '/parameters/checkId'); + const files = list(parameters.files, path + '/parameters/files', EVOLVE_BLOCK_LIMITS.maxFiles).map((item, idx) => + text(item, `${path}/parameters/files/${idx}`, 1024), + ); + if (files.length < 1) refuse('CONFIG_SCHEMA', path + '/parameters/files'); + const seenFiles = new Set(); + for (let idx = 0; idx < files.length; idx++) { + const file = files[idx]!; + const folded = file.normalize('NFC').toLowerCase(); + if (!isValidEvolveGuardPath(file) || seenFiles.has(folded)) { + refuse('CONFIG_SCHEMA', `${path}/parameters/files/${idx}`); + } + seenFiles.add(folded); + } + if (hasAllowedBlockIds) { + const allowedBlockIds = list( + parameters.allowedBlockIds, + path + '/parameters/allowedBlockIds', + EVOLVE_BLOCK_LIMITS.maxAllowedBlockIds, + ).map((item, idx) => text(item, `${path}/parameters/allowedBlockIds/${idx}`, EVOLVE_BLOCK_LIMITS.maxBlockIdLength)); + if (allowedBlockIds.length < 1) refuse('CONFIG_SCHEMA', path + '/parameters/allowedBlockIds'); + const seenBlockIds = new Set(); + for (let idx = 0; idx < allowedBlockIds.length; idx++) { + const blockId = allowedBlockIds[idx]!; + if (!isValidEvolveBlockId(blockId) || seenBlockIds.has(blockId)) { + refuse('CONFIG_SCHEMA', `${path}/parameters/allowedBlockIds/${idx}`); + } + seenBlockIds.add(blockId); + } + } + if (hasMaxBlockBytes) { + integer(parameters.maxBlockBytes, 1, Number.MAX_SAFE_INTEGER, path + '/parameters/maxBlockBytes'); + } } else { const fields = implementation === 'json-artifact.v1' ? ['checkId', 'path', 'required', 'equals'] : ['checkId']; const parameters = record(value.parameters, fields, path + '/parameters'); diff --git a/packages/controller/src/retained.ts b/packages/controller/src/retained.ts index 3513be7..504de5b 100644 --- a/packages/controller/src/retained.ts +++ b/packages/controller/src/retained.ts @@ -194,7 +194,10 @@ export async function admitRetainedRun(input: { } else { const state0 = approvedState(effectiveConfig); if (descriptor.configuration.roleModelOverrides !== undefined && state0.input.roleModelOverrides === undefined) { - const reloaded = await loadConfiguration({ ...state0.input, roleModelOverrides: descriptor.configuration.roleModelOverrides }, { environment: envFn }); + const reloaded = await loadConfiguration( + { ...state0.input, roleModelOverrides: descriptor.configuration.roleModelOverrides }, + { environment: input.environment ?? state0.environment }, + ); if (!reloaded.ok) throw new ControllerFailure(reloaded.error); effectiveConfig = reloaded.value; } diff --git a/packages/controller/src/step.ts b/packages/controller/src/step.ts index dc7afb0..c64a9d7 100644 --- a/packages/controller/src/step.ts +++ b/packages/controller/src/step.ts @@ -22,6 +22,7 @@ import { validatePortsAgainstHostPolicy, } from './retained.js'; import { reconcileInterruptedOperations, restoredCandidate, retainedPrimary } from './recovery.js'; +import { verifierProofPaths } from './verification.js'; import { ProgressStore, journal, stableId, type ProgressHead } from './progress.js'; import { adoptDelegatedCapture, @@ -1059,7 +1060,7 @@ async function reopenStepContext(input: { ).authority; const artifacts = new ArtifactStore(join(directory, 'artifacts'), owner, state.vault); await artifacts.cleanCasTempFiles(); - const jsonPaths = [...new Set(plan.verifierSlots.filter(slot => ['json-artifact.v1', 'json-keys-guard.v1', 'line-section-guard.v1'].includes(slot.handler.implementation)).map(slot => text(slot.handler.parameters.path)))]; + const jsonPaths = verifierProofPaths(plan.verifierSlots); const source = await restoreSource(descriptor.repository, plan.task, owner, artifacts, descriptor.source, descriptor.sourceWorkspace, jsonPaths); const progress = new ProgressStore(store, authority, artifacts, plan, lock, descriptor.plan, descriptor.source); let head = await progress.read(); diff --git a/packages/controller/src/types.ts b/packages/controller/src/types.ts index d0360df..1c586b9 100644 --- a/packages/controller/src/types.ts +++ b/packages/controller/src/types.ts @@ -45,6 +45,7 @@ export type Implementation = | 'json-artifact.v1' | 'json-keys-guard.v1' | 'line-section-guard.v1' + | 'evolve-block-guard.v1' | 'no-change.v1' | 'gate.v1' | 'benchmark-gate.v1'; diff --git a/packages/controller/src/verification.ts b/packages/controller/src/verification.ts index 0037bb0..3bf2631 100644 --- a/packages/controller/src/verification.ts +++ b/packages/controller/src/verification.ts @@ -25,8 +25,11 @@ import { descriptor, encodeInventory, encodePacket, + EVOLVE_BLOCK_LIMITS, fileHash, inventoryEncodedBytes, + isValidEvolveBlockId, + isValidEvolveGuardPath, JSON_FILE_BYTES, maxPacketBytes, overlayProtocolBounds, @@ -242,6 +245,21 @@ function writeProofSection(payload: Uint8Array, view: DataView, startOffset: num return offset; } +export function verifierProofPaths(slots: readonly VerifierSlot[]): readonly string[] { + const paths: string[] = []; + for (const slot of slots) { + const impl = slot.handler.implementation; + if (impl === 'json-artifact.v1' || impl === 'json-keys-guard.v1' || impl === 'line-section-guard.v1') { + paths.push(text(slot.handler.parameters.path)); + } else if (impl === 'evolve-block-guard.v1') { + for (const item of list(slot.handler.parameters.files, '', EVOLVE_BLOCK_LIMITS.maxFiles)) { + paths.push(text(item, '', 1024)); + } + } + } + return [...new Set(paths)]; +} + /** Pure byte preflight: no owner, state intent, Worker, timer, credential or network operation. */ export function prepareVerification( plan: CompiledPlan, @@ -517,6 +535,192 @@ export function prepareVerification( return value; } + if (handler === 'evolve-block-guard.v1') { + payloadKind = 'guard'; + const rawParams = slot.handler.parameters; + const filesParam = list(rawParams.files, '', EVOLVE_BLOCK_LIMITS.maxFiles).map(item => text(item, '', 1024)); + const hasAllowedBlockIds = Object.hasOwn(rawParams, 'allowedBlockIds'); + const hasMaxBlockBytes = Object.hasOwn(rawParams, 'maxBlockBytes'); + const baseTree = candidate.manifest.spec.baseTree; + + interface PreparedEvolveFile { + readonly spec: { readonly baseline: Record; readonly candidate: Record }; + readonly baseProof: ValidatedProof | null; + readonly baseOverlayBytes: Uint8Array | null | undefined; + readonly hasBaseOverlay: boolean; + readonly candOverlayBytes: Uint8Array | null | undefined; + readonly hasCandOverlay: boolean; + readonly sectionBytes: number; + readonly maxLogicalBytes: number; + } + + const preparedFiles: PreparedEvolveFile[] = []; + let maxLogicalFileBytes = 0; + let totalFilesPayloadBytes = 0; + let maxMerkleTreeCount = 0; + let totalMerkleProofBytes = 0; + let sawMerkle = false; + + for (const path of filesParam) { + const sourceSelected = source.manifest.spec.entries.find(entry => entry.name === path) ?? null; + const sourceDeleted = (source.manifest.spec.deleted ?? []).includes(path); + const candSelected = candidate.manifest.spec.entries.find(entry => entry.name === path) ?? null; + const candDeleted = (candidate.manifest.spec.deleted ?? []).includes(path); + + let baselineParam: Record; + let baseOverlayBytes: Uint8Array | null | undefined; + let hasBaseOverlay = false; + let validatedProof: ValidatedProof | null = null; + let baseLogicalBytes = 0; + + if (sourceSelected !== null) { + const sourceFileEntry = sourceFiles.get(path); + if (sourceFileEntry === undefined) { + refuse('ARTIFACT_INVALID', `/spec/parameters/files/${path}`, 'verification'); + } + const resolved = resolveTargetOverlayFileSync(sourceFileEntry); + baseOverlayBytes = resolved.bytes; + hasBaseOverlay = true; + baselineParam = { kind: 'overlay' }; + baseLogicalBytes = resolved.logicalBytes; + } else if (!baseTree || sourceDeleted) { + baselineParam = { kind: 'missing' }; + } else { + const rawProof = + source.baselineProofs && Object.hasOwn(source.baselineProofs, path) ? source.baselineProofs[path] ?? null : null; + if (rawProof === null) { + baselineParam = { kind: 'missing' }; + } else { + validatedProof = validateBaselineProof(rawProof, source.manifest.spec.baseTree!); + baselineParam = { + kind: 'merkle_blob', + mode: validatedProof.mode, + oid: validatedProof.oid, + byteLength: validatedProof.byteLength, + }; + baseLogicalBytes = validatedProof.logicalBytes; + sawMerkle = true; + maxMerkleTreeCount = Math.max(maxMerkleTreeCount, validatedProof.merkle.treeCount); + totalMerkleProofBytes += validatedProof.merkle.treeProofBytes; + if (totalMerkleProofBytes > EVOLVE_BLOCK_LIMITS.maxMerkleTreeProofBytes) { + refuse('ARTIFACT_INVALID', `/spec/parameters/files/${path}`, 'verification'); + } + } + } + + let candidateParam: Record; + let candOverlayBytes: Uint8Array | null | undefined; + let hasCandOverlay = false; + let candLogicalBytes = 0; + + if (candSelected !== null) { + const candFileEntry = files.get(path); + if (candFileEntry === undefined) { + refuse('ARTIFACT_INVALID', `/spec/parameters/files/${path}`, 'verification'); + } + const resolved = resolveTargetOverlayFileSync(candFileEntry); + candOverlayBytes = resolved.bytes; + hasCandOverlay = true; + candidateParam = { kind: 'overlay' }; + candLogicalBytes = resolved.logicalBytes; + } else if (!baseTree) { + candidateParam = { kind: 'missing' }; + } else if (candDeleted) { + candidateParam = { kind: 'deleted' }; + } else { + candidateParam = { kind: 'unchanged_baseline' }; + } + + const maxLogical = Math.max(baseLogicalBytes, candLogicalBytes); + maxLogicalFileBytes = Math.max(maxLogicalFileBytes, maxLogical); + const baseSectionBytes = + validatedProof !== null + ? 4 + validatedProof.blob.byteLength + 4 + validatedProof.trees.reduce((sum, tree) => sum + 4 + tree.byteLength, 0) + : hasBaseOverlay + ? 4 + baseLogicalBytes + : 0; + const candSectionBytes = hasCandOverlay ? 4 + candLogicalBytes : 0; + const sectionBytes = baseSectionBytes + candSectionBytes; + totalFilesPayloadBytes += sectionBytes; + + preparedFiles.push({ + spec: { baseline: baselineParam, candidate: candidateParam }, + baseProof: validatedProof, + baseOverlayBytes, + hasBaseOverlay, + candOverlayBytes, + hasCandOverlay, + sectionBytes, + maxLogicalBytes: maxLogical, + }); + } + + if (sawMerkle) { + merkle = { treeCount: maxMerkleTreeCount, treeProofBytes: totalMerkleProofBytes }; + } + jsonBytes = maxLogicalFileBytes; + parameters = { + files: filesParam, + fileSpecs: preparedFiles.map(item => item.spec), + ...(hasAllowedBlockIds ? { allowedBlockIds: rawParams.allowedBlockIds } : {}), + ...(hasMaxBlockBytes ? { maxBlockBytes: rawParams.maxBlockBytes } : {}), + } as unknown as VerifierHeader['parameters']; + + const sizedPayloadBytes = firstInvBytes + secondInvBytes + totalFilesPayloadBytes; + const header = checkedHeader({ + version: 1, + jobId: 'job.' + hash(operationId + '\0' + producerNonce).hex.slice(0, 40), + handler, + handlerVersion: 1, + handlerDigest: slot.handler.digest, + checkId: slot.checkId, + producerNonce, + operationId, + dispatchId: 'unbound', + generation, + subject: subject.value, + source: descriptor(source.manifest, source.ref, overlay), + candidate: descriptor(candidate.manifest, candidate.ref, overlay), + parameters, + payloadKind, + ...(overlay !== undefined ? { overlay } : {}), + }); + sizeJob(header, sizedPayloadBytes, jsonBytes, merkle, invSizing); + + const firstInv = encodeInventory(source.manifest, overlay); + const secondInv = encodeInventory(candidate.manifest, overlay); + payload = new Uint8Array(sizedPayloadBytes); + const view = new DataView(payload.buffer); + let offset = 0; + payload.set(firstInv, offset); + offset += firstInv.byteLength; + payload.set(secondInv, offset); + offset += secondInv.byteLength; + for (const item of preparedFiles) { + if (item.baseProof !== null) { + offset = writeProofSection(payload, view, offset, item.baseProof); + } else if (item.baseOverlayBytes) { + view.setUint32(offset, item.baseOverlayBytes.byteLength); + offset += 4; + payload.set(item.baseOverlayBytes, offset); + offset += item.baseOverlayBytes.byteLength; + } + if (item.candOverlayBytes) { + view.setUint32(offset, item.candOverlayBytes.byteLength); + offset += 4; + payload.set(item.candOverlayBytes, offset); + offset += item.candOverlayBytes.byteLength; + } + } + + const packetBytes = packetSize(header, payload.byteLength); + const requestDigest = hash('loopwright.dev/controller/verifier-request/v1\0' + canonical({ planDigest: plan.planDigest, header, payloadDigest: hash(payload) })); + const sealed = freeze(checkedHeader(parsePrivateJson(Buffer.from(canonical(header)), HEADER_BYTES))); + const value: PreparedVerification = freeze({ version: 1, slotId, generation, operationId, producerNonce, packetBytes, requestDigest }); + preparedJobs.set(value, { header: sealed, payload, slot }); + return value; + } + if (!['scope.v1', 'no-change.v1'].includes(handler)) refuse('CAPABILITY_UNSUPPORTED', '', 'verification'); payloadKind = 'inventories'; parameters = handler === 'scope.v1' ? ({ contract: plan.task } as unknown as VerifierHeader['parameters']) : {}; @@ -636,6 +840,39 @@ export function preflightVerification( ) { refuse('CAPABILITY_UNSUPPORTED', '', 'verification'); } + } else if (slot.handler.implementation === 'evolve-block-guard.v1') { + if (!isRecord(parameters)) refuse('CAPABILITY_UNSUPPORTED', '', 'verification'); + const hasAllowedBlockIds = Object.hasOwn(parameters, 'allowedBlockIds'); + const hasMaxBlockBytes = Object.hasOwn(parameters, 'maxBlockBytes'); + record(parameters, [ + 'checkId', + 'files', + ...(hasAllowedBlockIds ? ['allowedBlockIds' as const] : []), + ...(hasMaxBlockBytes ? ['maxBlockBytes' as const] : []), + ]); + if (parameters.checkId !== slot.checkId) refuse('CAPABILITY_UNSUPPORTED', '', 'verification'); + const files = list(parameters.files, '', EVOLVE_BLOCK_LIMITS.maxFiles).map(item => text(item, '', 1024)); + if (files.length < 1) refuse('CAPABILITY_UNSUPPORTED', '', 'verification'); + const seenFiles = new Set(); + for (const file of files) { + const folded = file.normalize('NFC').toLowerCase(); + if (!isValidEvolveGuardPath(file) || seenFiles.has(folded)) refuse('CAPABILITY_UNSUPPORTED', '', 'verification'); + seenFiles.add(folded); + } + if (hasAllowedBlockIds) { + const ids = list(parameters.allowedBlockIds, '', EVOLVE_BLOCK_LIMITS.maxAllowedBlockIds).map(item => + text(item, '', EVOLVE_BLOCK_LIMITS.maxBlockIdLength), + ); + if (ids.length < 1) refuse('CAPABILITY_UNSUPPORTED', '', 'verification'); + const seenIds = new Set(); + for (const blockId of ids) { + if (!isValidEvolveBlockId(blockId) || seenIds.has(blockId)) refuse('CAPABILITY_UNSUPPORTED', '', 'verification'); + seenIds.add(blockId); + } + } + if (hasMaxBlockBytes) { + integer(parameters.maxBlockBytes, 1, Number.MAX_SAFE_INTEGER); + } } else { record(parameters, ['checkId']); if ( @@ -864,6 +1101,7 @@ const EXPECTED_METHODS: Readonly> = { 'json-artifact.v1': 'verify_json', 'json-keys-guard.v1': 'verify_json_keys_guard', 'line-section-guard.v1': 'verify_line_section_guard', + 'evolve-block-guard.v1': 'verify_evolve_block_guard', }; const ALLOWED_REASONS: Readonly> = { @@ -872,6 +1110,17 @@ const ALLOWED_REASONS: Readonly> 'json-artifact.v1': ['missing_file', 'invalid_json', 'property_missing', 'property_mismatch'], 'json-keys-guard.v1': ['missing_file', 'invalid_json', 'disallowed_json_pointer'], 'line-section-guard.v1': ['missing_file', 'invalid_utf8', 'missing_markers', 'unbalanced_markers', 'outside_section_modified'], + 'evolve-block-guard.v1': [ + 'missing_file', + 'invalid_utf8', + 'missing_markers', + 'unbalanced_markers', + 'duplicate_block_id', + 'block_limit_exceeded', + 'outside_block_modified', + 'disallowed_block_id', + 'block_bytes_exceeded', + ], }; function checkedReply(input: unknown, header: VerifierHeader, packetDigest: Digest): Disposition { diff --git a/packages/controller/src/verifier-protocol.ts b/packages/controller/src/verifier-protocol.ts index f26a888..80ee873 100644 --- a/packages/controller/src/verifier-protocol.ts +++ b/packages/controller/src/verifier-protocol.ts @@ -4,6 +4,7 @@ import { LIMITS, OVERLAY_LIMITS, admitTask, + digestArtifact, identifyManifest, isWritablePath, resolveOverlayLimits, @@ -36,12 +37,43 @@ const NAME_LEN_MASK = 0x3fff; export const RFC6901_POINTER_PATTERN = /^(?:\/(?:[^~/]|~[01])*)+$/; const LONE_SURROGATE_PATTERN = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(? 1024) return false; + if (filePath.startsWith('/') || filePath.startsWith('\\')) return false; + if (!validateRelativePath(filePath).ok) return false; + if (!digestArtifact(filePath, new Uint8Array()).ok) return false; + const segments = filePath.split('/'); + if (segments.some(seg => seg.toLowerCase() === '.git')) return false; + if (segments[0]?.toLowerCase() === '.github' && segments[1]?.toLowerCase() === 'workflows') return false; + return true; +} + +export function isValidEvolveBlockId(blockId: string): boolean { + return ( + typeof blockId === 'string' && + blockId.length >= 1 && + blockId.length <= EVOLVE_BLOCK_LIMITS.maxBlockIdLength && + /^[\x21-\x7E]+$/.test(blockId) && + !blockId.includes('/*') && + !blockId.includes('*/') + ); +} + export type ByteHandler = | 'scope.v1' | 'no-change.v1' | 'json-artifact.v1' | 'json-keys-guard.v1' - | 'line-section-guard.v1'; + | 'line-section-guard.v1' + | 'evolve-block-guard.v1'; export type VerifierReason = | 'outside_scope' @@ -54,14 +86,20 @@ export type VerifierReason = | 'invalid_utf8' | 'missing_markers' | 'unbalanced_markers' - | 'outside_section_modified'; + | 'outside_section_modified' + | 'duplicate_block_id' + | 'block_limit_exceeded' + | 'outside_block_modified' + | 'disallowed_block_id' + | 'block_bytes_exceeded'; export type VerifierMethod = | 'verify_scope' | 'verify_no_change' | 'verify_json' | 'verify_json_keys_guard' - | 'verify_line_section_guard'; + | 'verify_line_section_guard' + | 'verify_evolve_block_guard'; export interface ManifestDescriptor { readonly metadataId: string; @@ -159,13 +197,26 @@ export function overlayProtocolBounds(overlay?: OverlayLimitsInput): OverlayProt }; } -export function maxPacketBytes(header: Pick): number { +export function maxPacketBytes( + header: Pick & { readonly handler?: ByteHandler }, +): number { const bounds = overlayProtocolBounds(header.overlay); const inventoriesBytes = 4 + HEADER_BYTES + 2 * bounds.inventoryMaxBytes; if (header.payloadKind === 'inventories') return Math.min(MAX_ABSOLUTE_PACKET_BYTES, inventoriesBytes); if (header.payloadKind === 'json') { return Math.min(MAX_ABSOLUTE_PACKET_BYTES, inventoriesBytes + 4 + JSON_FILE_BYTES + 262_212); } + if (header.handler === 'evolve-block-guard.v1') { + // Bounded by ArtifactStore.put / readArtifact's 96 MiB (100_663_296 B) single-artifact cap. + return Math.min( + MAX_ABSOLUTE_PACKET_BYTES, + 100_663_296, + inventoriesBytes + + EVOLVE_BLOCK_LIMITS.maxFiles * 2 * (4 + JSON_FILE_BYTES) + + EVOLVE_BLOCK_LIMITS.maxMerkleTreeProofBytes + + 68, + ); + } return Math.min(MAX_ABSOLUTE_PACKET_BYTES, inventoriesBytes + 2 * (4 + JSON_FILE_BYTES) + 262_212); } @@ -175,7 +226,12 @@ export function packetAllocationLimit(bytes: Uint8Array): number { if (!len || len > HEADER_BYTES) return ALLOCATION_BYTES; try { const header = checkedHeader(parsePrivateJson(bytes.subarray(4, 4 + len), HEADER_BYTES, 256)); - return overlayProtocolBounds(header.overlay).allocationMaxBytes; + const bounds = overlayProtocolBounds(header.overlay); + if (header.handler === 'evolve-block-guard.v1') { + const guardMaxPacket = maxPacketBytes(header); + return Math.max(bounds.allocationMaxBytes, guardMaxPacket + 2 * bounds.manifestMaxBytes + 4_194_304); + } + return bounds.allocationMaxBytes; } catch { return ALLOCATION_BYTES; } @@ -505,7 +561,7 @@ function checkedOverlayField(raw: unknown): OverlayLimits { function expectedPayloadKind(handler: ByteHandler): VerifierHeader['payloadKind'] { if (handler === 'json-artifact.v1') return 'json'; - if (handler === 'json-keys-guard.v1' || handler === 'line-section-guard.v1') return 'guard'; + if (handler === 'json-keys-guard.v1' || handler === 'line-section-guard.v1' || handler === 'evolve-block-guard.v1') return 'guard'; return 'inventories'; } @@ -521,7 +577,7 @@ export function checkedHeader(raw: unknown): VerifierHeader { if ( value.version !== 1 || value.handlerVersion !== 1 || - !['scope.v1', 'no-change.v1', 'json-artifact.v1', 'json-keys-guard.v1', 'line-section-guard.v1'].includes(handlerStr) || + !['scope.v1', 'no-change.v1', 'json-artifact.v1', 'json-keys-guard.v1', 'line-section-guard.v1', 'evolve-block-guard.v1'].includes(handlerStr) || !/^[a-f0-9]{32}$/.test(text(value.producerNonce)) || value.payloadKind !== expectedPayloadKind(handlerStr as ByteHandler) ) { @@ -623,7 +679,7 @@ function verifyMerkleBlobSlice( baseTree: BaseTreeAnchor, expectedRaw: unknown, quota: AllocationQuota, -): { readonly blobSlice: Uint8Array; readonly nextPos: number } { +): { readonly blobSlice: Uint8Array; readonly nextPos: number; readonly treeProofBytes: number } { const expected = record(expectedRaw, ['mode', 'oid', 'byteLength', ...(isRecord(expectedRaw) && Object.hasOwn(expectedRaw, 'baseline') ? ['baseline' as const] : []), ...(isRecord(expectedRaw) && Object.hasOwn(expectedRaw, 'kind') ? ['kind' as const] : [])]); const expectedMode = expected.mode; const expectedOid = text(expected.oid); @@ -670,7 +726,7 @@ function verifyMerkleBlobSlice( if (gitObjectOid(baseTree.objectFormat, 'blob', blobSlice) !== match.oid) refuse('ARTIFACT_INVALID', '', 'verification'); } } - return { blobSlice, nextPos: pos }; + return { blobSlice, nextPos: pos, treeProofBytes: totalTreeBytes }; } type GuardJson = null | boolean | number | string | readonly GuardJson[] | { readonly [key: string]: GuardJson }; @@ -1094,6 +1150,381 @@ function evaluateLineSectionGuard( return { reason: null }; } +type EvolveCommentStyle = '//' | '#' | '/*'; + +interface ParsedEvolveMarker { + readonly kind: 'START' | 'END'; + readonly blockId: string; + readonly style: EvolveCommentStyle; +} + +interface ParsedEvolveBlock { + readonly blockId: string; + readonly style: EvolveCommentStyle; + readonly startLine: number; + readonly endLine: number; + readonly interiorBytes: Uint8Array; +} + +interface ParsedEvolveFile { + readonly blocks: readonly ParsedEvolveBlock[]; + readonly outsideSegments: readonly Uint8Array[]; + readonly outsideSegmentStartLines: readonly number[]; + readonly outsideDigest: string; +} + +const EVOLVE_MARKER_SLASH_RE = /^[ \t]*\/\/[ \t]*EVOLVE-BLOCK-(START|END):[ \t]*([\x21-\x7E]+)[ \t]*$/; +const EVOLVE_MARKER_HASH_RE = /^[ \t]*#[ \t]*EVOLVE-BLOCK-(START|END):[ \t]*([\x21-\x7E]+)[ \t]*$/; +const EVOLVE_MARKER_BLOCK_COMMENT_RE = /^[ \t]*\/\*[ \t]*EVOLVE-BLOCK-(START|END):[ \t]*([\x21-\x7E]+)[ \t]*\*\/[ \t]*$/; +const EVOLVE_MARKER_CANDIDATE_COMMENT_RE = /^[ \t]*(?:\/\/|#|\/\*)[ \t]*EVOLVE-BLOCK-(?:START|END)\b/; + +function parseEvolveMarkerLine( + lineText: string, +): { readonly kind: 'none' } | { readonly kind: 'valid'; readonly marker: ParsedEvolveMarker } | { readonly kind: 'malformed' } { + let match = EVOLVE_MARKER_SLASH_RE.exec(lineText); + let style: EvolveCommentStyle = '//'; + if (!match) { + match = EVOLVE_MARKER_HASH_RE.exec(lineText); + style = '#'; + } + if (!match) { + match = EVOLVE_MARKER_BLOCK_COMMENT_RE.exec(lineText); + style = '/*'; + } + if (match) { + const markerKind = match[1] as 'START' | 'END'; + const blockId = match[2]!; + if (!isValidEvolveBlockId(blockId)) return { kind: 'malformed' }; + return { kind: 'valid', marker: { kind: markerKind, blockId, style } }; + } + if (EVOLVE_MARKER_CANDIDATE_COMMENT_RE.test(lineText)) { + return { kind: 'malformed' }; + } + return { kind: 'none' }; +} + +function computeOutsideDigest( + blocks: readonly ParsedEvolveBlock[], + outsideSegments: readonly Uint8Array[], +): string { + const hasher = createHash('sha256'); + hasher.update('loopwright.dev/controller/evolve-block-outside/v1\0'); + const countBuf = Buffer.alloc(4); + countBuf.writeUInt32BE(blocks.length, 0); + hasher.update(countBuf); + const lenBuf = Buffer.alloc(4); + for (let i = 0; i < outsideSegments.length; i++) { + const seg = outsideSegments[i]!; + lenBuf.writeUInt32BE(seg.byteLength, 0); + hasher.update(lenBuf); + hasher.update(seg); + if (i < blocks.length) { + const idBytes = Buffer.from(blocks[i]!.blockId, 'utf8'); + lenBuf.writeUInt32BE(idBytes.byteLength, 0); + hasher.update(lenBuf); + hasher.update(idBytes); + } + } + return hasher.digest('hex'); +} + +function parseEvolveBlocks( + fileBytes: Uint8Array, + label: 'baseline' | 'candidate', + path: string, +): { readonly ok: true; readonly parsed: ParsedEvolveFile } | { readonly ok: false; readonly reason: VerifierReason; readonly detail: string; readonly finding: StructuredFinding } { + const decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }); + try { + decoder.decode(fileBytes); + } catch { + const msg = `${label === 'baseline' ? 'Baseline' : 'Candidate'} file "${path}" is not valid UTF-8`; + return { + ok: false, + reason: 'invalid_utf8', + detail: clipText(msg, 1024), + finding: makeGuardFinding(`Invalid UTF-8 in ${label} file`, path, msg, 1), + }; + } + + const blocks: ParsedEvolveBlock[] = []; + const outsideSegments: Uint8Array[] = []; + const outsideSegmentStartLines: number[] = []; + const seenBlockIds = new Set(); + + let openBlock: { + readonly blockId: string; + readonly style: EvolveCommentStyle; + readonly startLine: number; + readonly interiorStartByte: number; + } | null = null; + let outsideStartByte = 0; + let outsideStartLine = 1; + + let pos = 0; + let lineNo = 0; + while (pos < fileBytes.byteLength) { + lineNo++; + const nl = fileBytes.indexOf(0x0a, pos); + const lineEnd = nl === -1 ? fileBytes.byteLength : nl + 1; + let textEnd = nl === -1 ? fileBytes.byteLength : nl; + if (textEnd > pos && fileBytes[textEnd - 1] === 0x0d) textEnd--; + const lineText = decoder.decode(fileBytes.subarray(pos, textEnd)); + const parsedMarker = parseEvolveMarkerLine(lineText); + + if (parsedMarker.kind === 'malformed') { + const msg = `Malformed EVOLVE-BLOCK marker in ${label} "${path}" at line ${lineNo}`; + return { + ok: false, + reason: 'unbalanced_markers', + detail: clipText(msg, 1024), + finding: makeGuardFinding('Malformed EVOLVE-BLOCK marker', path, msg, lineNo), + }; + } + + if (parsedMarker.kind === 'valid') { + const { kind, blockId, style } = parsedMarker.marker; + if (kind === 'START') { + if (openBlock !== null) { + const msg = `Nested EVOLVE-BLOCK-START "${blockId}" inside "${openBlock.blockId}" (opened at line ${openBlock.startLine}) in ${label} "${path}" at line ${lineNo}`; + return { + ok: false, + reason: 'unbalanced_markers', + detail: clipText(msg, 1024), + finding: makeGuardFinding('Nested EVOLVE-BLOCK marker', path, msg, lineNo), + }; + } + if (seenBlockIds.has(blockId)) { + const msg = `Duplicate EVOLVE-BLOCK id "${blockId}" in ${label} "${path}" at line ${lineNo}`; + return { + ok: false, + reason: 'duplicate_block_id', + detail: clipText(msg, 1024), + finding: makeGuardFinding('Duplicate EVOLVE-BLOCK id', path, msg, lineNo), + }; + } + if (blocks.length >= EVOLVE_BLOCK_LIMITS.maxBlocksPerFile) { + const msg = `EVOLVE-BLOCK count exceeds maximum of ${EVOLVE_BLOCK_LIMITS.maxBlocksPerFile} in ${label} "${path}" at line ${lineNo}`; + return { + ok: false, + reason: 'block_limit_exceeded', + detail: clipText(msg, 1024), + finding: makeGuardFinding('EVOLVE-BLOCK count limit exceeded', path, msg, lineNo), + }; + } + seenBlockIds.add(blockId); + outsideSegments.push(fileBytes.subarray(outsideStartByte, lineEnd)); + outsideSegmentStartLines.push(outsideStartLine); + openBlock = { blockId, style, startLine: lineNo, interiorStartByte: lineEnd }; + } else { + if (openBlock === null) { + const msg = `Unmatched EVOLVE-BLOCK-END "${blockId}" without START in ${label} "${path}" at line ${lineNo}`; + return { + ok: false, + reason: 'unbalanced_markers', + detail: clipText(msg, 1024), + finding: makeGuardFinding('Unmatched EVOLVE-BLOCK-END marker', path, msg, lineNo), + }; + } + if (openBlock.blockId !== blockId || openBlock.style !== style) { + const msg = `Mismatched EVOLVE-BLOCK-END "${blockId}" for START "${openBlock.blockId}" (opened at line ${openBlock.startLine}) in ${label} "${path}" at line ${lineNo}`; + return { + ok: false, + reason: 'unbalanced_markers', + detail: clipText(msg, 1024), + finding: makeGuardFinding('Mismatched EVOLVE-BLOCK marker', path, msg, lineNo), + }; + } + blocks.push({ + blockId: openBlock.blockId, + style: openBlock.style, + startLine: openBlock.startLine, + endLine: lineNo, + interiorBytes: fileBytes.subarray(openBlock.interiorStartByte, pos), + }); + openBlock = null; + outsideStartByte = pos; + outsideStartLine = lineNo; + } + } + pos = lineEnd; + } + + if (openBlock !== null) { + const msg = `Unclosed EVOLVE-BLOCK-START "${openBlock.blockId}" opened at line ${openBlock.startLine} in ${label} "${path}"`; + return { + ok: false, + reason: 'unbalanced_markers', + detail: clipText(msg, 1024), + finding: makeGuardFinding('Unclosed EVOLVE-BLOCK-START marker', path, msg, openBlock.startLine), + }; + } + if (blocks.length === 0) { + const msg = `Guarded file "${path}" contains zero EVOLVE-BLOCK mutable regions in ${label}`; + return { + ok: false, + reason: 'missing_markers', + detail: clipText(msg, 1024), + finding: makeGuardFinding('Missing EVOLVE-BLOCK markers', path, msg, 1), + }; + } + outsideSegments.push(fileBytes.subarray(outsideStartByte, fileBytes.byteLength)); + outsideSegmentStartLines.push(outsideStartLine); + + const outsideDigest = computeOutsideDigest(blocks, outsideSegments); + return { ok: true, parsed: { blocks, outsideSegments, outsideSegmentStartLines, outsideDigest } }; +} + +function firstDifferingLineInSegment(baseSeg: Uint8Array, candSeg: Uint8Array, candStartLine: number): number { + const minLen = Math.min(baseSeg.byteLength, candSeg.byteLength); + let line = candStartLine; + for (let idx = 0; idx < minLen; idx++) { + if (baseSeg[idx] !== candSeg[idx]) return line; + if (candSeg[idx] === 0x0a) line++; + } + return line; +} + +function evaluateSingleEvolveFile( + path: string, + baselineBytes: Uint8Array | null, + candidateBytes: Uint8Array | null, + allowedBlockSet: ReadonlySet | null, + maxBlockBytes: number | undefined, +): { readonly reason: VerifierReason | null; readonly detail?: string; readonly finding?: StructuredFinding } { + if (baselineBytes === null || candidateBytes === null) { + const which = baselineBytes === null ? 'baseline' : 'candidate'; + const msg = `Guarded file "${path}" is missing in ${which}`; + return { + reason: 'missing_file', + detail: msg, + finding: makeGuardFinding(`Missing guarded file (${which})`, path, msg, 1), + }; + } + + const baseRes = parseEvolveBlocks(baselineBytes, 'baseline', path); + if (!baseRes.ok) return { reason: baseRes.reason, detail: baseRes.detail, finding: baseRes.finding }; + const candRes = parseEvolveBlocks(candidateBytes, 'candidate', path); + if (!candRes.ok) return { reason: candRes.reason, detail: candRes.detail, finding: candRes.finding }; + + const base = baseRes.parsed; + const cand = candRes.parsed; + + if (base.outsideDigest !== cand.outsideDigest) { + if (base.blocks.length !== cand.blocks.length) { + const lineNo = cand.blocks[Math.min(base.blocks.length, cand.blocks.length) - 1]?.startLine ?? 1; + const msg = `EVOLVE-BLOCK count changed in "${path}" (baseline: ${base.blocks.length}, candidate: ${cand.blocks.length}; outside sha256 expected ${base.outsideDigest.slice(0, 16)}, got ${cand.outsideDigest.slice(0, 16)})`; + return { + reason: 'outside_block_modified', + detail: clipText(msg, 1024), + finding: makeGuardFinding('EVOLVE-BLOCK structure modified', path, msg, lineNo), + }; + } + for (let i = 0; i < base.blocks.length; i++) { + if (base.blocks[i]!.blockId !== cand.blocks[i]!.blockId || base.blocks[i]!.style !== cand.blocks[i]!.style) { + const lineNo = cand.blocks[i]!.startLine; + const msg = `EVOLVE-BLOCK ordering, style, or id changed in "${path}" at line ${lineNo}: expected "${base.blocks[i]!.blockId}" (${base.blocks[i]!.style}), got "${cand.blocks[i]!.blockId}" (${cand.blocks[i]!.style})`; + return { + reason: 'outside_block_modified', + detail: clipText(msg, 1024), + finding: makeGuardFinding('EVOLVE-BLOCK ordering modified', path, msg, lineNo), + }; + } + } + let diffLine = 1; + for (let s = 0; s < base.outsideSegments.length; s++) { + const bSeg = base.outsideSegments[s]!; + const cSeg = cand.outsideSegments[s]!; + if (bSeg.byteLength !== cSeg.byteLength || !Buffer.from(bSeg).equals(cSeg)) { + diffLine = firstDifferingLineInSegment(bSeg, cSeg, cand.outsideSegmentStartLines[s] ?? 1); + break; + } + } + const msg = `Immutable bytes outside EVOLVE-BLOCK modified in "${path}" at line ${diffLine} (outside sha256 expected ${base.outsideDigest}, got ${cand.outsideDigest})`; + return { + reason: 'outside_block_modified', + detail: clipText(msg, 1024), + finding: makeGuardFinding('Mutation outside EVOLVE-BLOCK', path, msg, diffLine), + }; + } + + let mutableBlockCount = 0; + for (let i = 0; i < cand.blocks.length; i++) { + const baseBlock = base.blocks[i]!; + const candBlock = cand.blocks[i]!; + const isMutable = allowedBlockSet === null || allowedBlockSet.has(candBlock.blockId); + if (!isMutable) { + if ( + baseBlock.interiorBytes.byteLength !== candBlock.interiorBytes.byteLength || + !same(fileHash(baseBlock.interiorBytes), fileHash(candBlock.interiorBytes)) + ) { + const msg = `EVOLVE-BLOCK "${candBlock.blockId}" in "${path}" at line ${candBlock.startLine} is not listed in allowedBlockIds and cannot be modified`; + return { + reason: 'disallowed_block_id', + detail: clipText(msg, 1024), + finding: makeGuardFinding('Disallowed EVOLVE-BLOCK modified', path, msg, candBlock.startLine), + }; + } + continue; + } + mutableBlockCount++; + if (maxBlockBytes !== undefined && candBlock.interiorBytes.byteLength > maxBlockBytes) { + const msg = `EVOLVE-BLOCK "${candBlock.blockId}" in "${path}" at line ${candBlock.startLine} exceeds maxBlockBytes (${candBlock.interiorBytes.byteLength} > ${maxBlockBytes} UTF-8 bytes)`; + return { + reason: 'block_bytes_exceeded', + detail: clipText(msg, 1024), + finding: makeGuardFinding('EVOLVE-BLOCK byte limit exceeded', path, msg, candBlock.startLine), + }; + } + } + + if (allowedBlockSet !== null && mutableBlockCount === 0) { + const firstLine = cand.blocks[0]?.startLine ?? 1; + const msg = `Guarded file "${path}" has zero mutable EVOLVE-BLOCK regions matching allowedBlockIds`; + return { + reason: 'disallowed_block_id', + detail: clipText(msg, 1024), + finding: makeGuardFinding('No allowed EVOLVE-BLOCK in guarded file', path, msg, firstLine), + }; + } + + return { reason: null }; +} + +function evaluateEvolveBlockGuard( + fileEntries: readonly { + readonly path: string; + readonly baselineBytes: Uint8Array | null; + readonly candidateBytes: Uint8Array | null; + }[], + allowedBlockIds: readonly string[] | undefined, + maxBlockBytes: number | undefined, +): { readonly reason: VerifierReason | null; readonly detail?: string; readonly findings?: readonly StructuredFinding[] } { + const allowedSet = allowedBlockIds !== undefined ? new Set(allowedBlockIds) : null; + let firstReason: VerifierReason | null = null; + let firstDetail: string | undefined; + const findings: StructuredFinding[] = []; + + for (const item of fileEntries) { + const res = evaluateSingleEvolveFile(item.path, item.baselineBytes, item.candidateBytes, allowedSet, maxBlockBytes); + if (res.reason !== null) { + if (firstReason === null) { + firstReason = res.reason; + firstDetail = res.detail; + } + if (res.finding !== undefined && findings.length < LIMITS.findings) { + findings.push(res.finding); + } + } + } + + if (firstReason === null) return { reason: null }; + return { + reason: firstReason, + ...(firstDetail !== undefined ? { detail: firstDetail } : {}), + findings: boundGuardFindings(findings), + }; +} + export function evaluatePacket(bytes: Uint8Array): VerifierReply { if ( !(bytes instanceof Uint8Array) || @@ -1218,6 +1649,165 @@ export function evaluatePacket(bytes: Uint8Array): VerifierReply { if (verified.nextPos !== bytes.byteLength) refuse('ARTIFACT_INVALID', '', 'verification'); reason = verifyJsonPayload(verified.blobSlice, required, equals as Readonly>); } + } else if (header.handler === 'evolve-block-guard.v1') { + if (!isRecord(header.parameters)) refuse('ARTIFACT_INVALID', '', 'verification'); + const hasAllowedBlockIds = Object.hasOwn(header.parameters, 'allowedBlockIds'); + const hasMaxBlockBytes = Object.hasOwn(header.parameters, 'maxBlockBytes'); + const parameters = record(header.parameters, [ + 'files', + 'fileSpecs', + ...(hasAllowedBlockIds ? ['allowedBlockIds' as const] : []), + ...(hasMaxBlockBytes ? ['maxBlockBytes' as const] : []), + ]); + const files = list(parameters.files, '', EVOLVE_BLOCK_LIMITS.maxFiles).map(item => text(item, '', 1024)); + if (files.length < 1) refuse('ARTIFACT_INVALID', '', 'verification'); + const seenFiles = new Set(); + for (const file of files) { + const folded = file.normalize('NFC').toLowerCase(); + if (!isValidEvolveGuardPath(file) || seenFiles.has(folded)) refuse('ARTIFACT_INVALID', '', 'verification'); + seenFiles.add(folded); + } + let allowedBlockIds: readonly string[] | undefined; + if (hasAllowedBlockIds) { + const ids = list(parameters.allowedBlockIds, '', EVOLVE_BLOCK_LIMITS.maxAllowedBlockIds).map(item => + text(item, '', EVOLVE_BLOCK_LIMITS.maxBlockIdLength), + ); + if (ids.length < 1) refuse('ARTIFACT_INVALID', '', 'verification'); + const seenIds = new Set(); + for (const blockId of ids) { + if (!isValidEvolveBlockId(blockId) || seenIds.has(blockId)) refuse('ARTIFACT_INVALID', '', 'verification'); + seenIds.add(blockId); + } + allowedBlockIds = ids; + } + const maxBlockBytes = hasMaxBlockBytes + ? integer(parameters.maxBlockBytes, 1, Number.MAX_SAFE_INTEGER) + : undefined; + + const fileSpecs = list(parameters.fileSpecs, '', EVOLVE_BLOCK_LIMITS.maxFiles); + if (fileSpecs.length !== files.length) refuse('ARTIFACT_INVALID', '', 'verification'); + + const baseTree = candidate.spec.baseTree; + let pos = second.offset; + let totalMerkleTreeBytes = 0; + const resolvedEntries: { + readonly path: string; + readonly baselineBytes: Uint8Array | null; + readonly candidateBytes: Uint8Array | null; + }[] = []; + + for (let i = 0; i < files.length; i++) { + const path = files[i]!; + const spec = record(fileSpecs[i], ['baseline', 'candidate']); + const sourceSelected = source.spec.entries.find(entry => entry.name === path) ?? null; + const sourceDeleted = (source.spec.deleted ?? []).includes(path); + const candSelected = candidate.spec.entries.find(entry => entry.name === path) ?? null; + const candDeleted = (candidate.spec.deleted ?? []).includes(path); + + let baselineBytes: Uint8Array | null = null; + if (!isRecord(spec.baseline)) refuse('ARTIFACT_INVALID', '', 'verification'); + const baseKind = text(spec.baseline.kind, '', 32); + if (!baseTree) { + if (baseKind === 'missing') { + record(spec.baseline, ['kind']); + if (sourceSelected !== null) refuse('ARTIFACT_INVALID', '', 'verification'); + } else if (baseKind === 'overlay') { + record(spec.baseline, ['kind']); + if (sourceSelected === null || pos + 4 > bytes.byteLength) refuse('ARTIFACT_INVALID', '', 'verification'); + const len = view.getUint32(pos); + pos += 4; + if (len > JSON_FILE_BYTES || len !== sourceSelected.byteLength || pos + len > bytes.byteLength) { + refuse('ARTIFACT_INVALID', '', 'verification'); + } + const slice = bytes.subarray(pos, pos + len); + pos += len; + if (!same(fileHash(slice), sourceSelected.digest)) refuse('ARTIFACT_INVALID', '', 'verification'); + baselineBytes = slice; + } else { + refuse('ARTIFACT_INVALID', '', 'verification'); + } + } else if (sourceSelected !== null) { + record(spec.baseline, ['kind']); + if (baseKind !== 'overlay' || pos + 4 > bytes.byteLength) refuse('ARTIFACT_INVALID', '', 'verification'); + const len = view.getUint32(pos); + pos += 4; + if (len > JSON_FILE_BYTES || len !== sourceSelected.byteLength || pos + len > bytes.byteLength) { + refuse('ARTIFACT_INVALID', '', 'verification'); + } + const slice = bytes.subarray(pos, pos + len); + pos += len; + if (!same(fileHash(slice), sourceSelected.digest)) refuse('ARTIFACT_INVALID', '', 'verification'); + baselineBytes = slice; + } else if (sourceDeleted) { + record(spec.baseline, ['kind']); + if (baseKind !== 'missing') refuse('ARTIFACT_INVALID', '', 'verification'); + } else if (baseKind === 'missing') { + record(spec.baseline, ['kind']); + } else if (baseKind === 'merkle_blob') { + const verified = verifyMerkleBlobSlice(bytes, view, pos, path, source.spec.baseTree!, spec.baseline, quota); + if ((totalMerkleTreeBytes += verified.treeProofBytes) > EVOLVE_BLOCK_LIMITS.maxMerkleTreeProofBytes) { + refuse('ARTIFACT_INVALID', '', 'verification'); + } + baselineBytes = verified.blobSlice; + pos = verified.nextPos; + } else { + refuse('ARTIFACT_INVALID', '', 'verification'); + } + + let candidateBytes: Uint8Array | null = null; + if (!isRecord(spec.candidate)) refuse('ARTIFACT_INVALID', '', 'verification'); + const candKind = text(spec.candidate.kind, '', 32); + if (!baseTree) { + if (candKind === 'missing') { + record(spec.candidate, ['kind']); + if (candSelected !== null) refuse('ARTIFACT_INVALID', '', 'verification'); + } else if (candKind === 'overlay') { + record(spec.candidate, ['kind']); + if (candSelected === null || pos + 4 > bytes.byteLength) refuse('ARTIFACT_INVALID', '', 'verification'); + const len = view.getUint32(pos); + pos += 4; + if (len > JSON_FILE_BYTES || len !== candSelected.byteLength || pos + len > bytes.byteLength) { + refuse('ARTIFACT_INVALID', '', 'verification'); + } + const slice = bytes.subarray(pos, pos + len); + pos += len; + if (!same(fileHash(slice), candSelected.digest)) refuse('ARTIFACT_INVALID', '', 'verification'); + candidateBytes = slice; + } else { + refuse('ARTIFACT_INVALID', '', 'verification'); + } + } else if (candSelected !== null) { + record(spec.candidate, ['kind']); + if (candKind !== 'overlay' || pos + 4 > bytes.byteLength) refuse('ARTIFACT_INVALID', '', 'verification'); + const len = view.getUint32(pos); + pos += 4; + if (len > JSON_FILE_BYTES || len !== candSelected.byteLength || pos + len > bytes.byteLength) { + refuse('ARTIFACT_INVALID', '', 'verification'); + } + const slice = bytes.subarray(pos, pos + len); + pos += len; + if (!same(fileHash(slice), candSelected.digest)) refuse('ARTIFACT_INVALID', '', 'verification'); + candidateBytes = slice; + } else if (candDeleted) { + record(spec.candidate, ['kind']); + if (candKind !== 'deleted') refuse('ARTIFACT_INVALID', '', 'verification'); + candidateBytes = null; + } else { + record(spec.candidate, ['kind']); + if (candKind !== 'unchanged_baseline') refuse('ARTIFACT_INVALID', '', 'verification'); + candidateBytes = baselineBytes; + } + + resolvedEntries.push({ path, baselineBytes, candidateBytes }); + } + + if (pos !== bytes.byteLength) refuse('ARTIFACT_INVALID', '', 'verification'); + + method = 'verify_evolve_block_guard'; + const guardRes = evaluateEvolveBlockGuard(resolvedEntries, allowedBlockIds, maxBlockBytes); + reason = guardRes.reason; + detail = guardRes.detail; + findings = guardRes.findings; } else { const isJsonKeys = header.handler === 'json-keys-guard.v1'; const parameters = record( diff --git a/packages/controller/test/config-loader.test.ts b/packages/controller/test/config-loader.test.ts index 482f8d5..61d182f 100644 --- a/packages/controller/test/config-loader.test.ts +++ b/packages/controller/test/config-loader.test.ts @@ -4,7 +4,7 @@ import { chmod, writeFile, symlink, link, readFile } from 'node:fs/promises'; import { join } from 'node:path'; import { stringify } from 'yaml'; import { compilePlan, checkpointCapacity } from '../src/compile.js'; -import { approvedState } from '../src/config.js'; +import { approvedState, loadTrustedConfiguration } from '../src/config.js'; import type { ControllerResult } from '../src/errors.js'; import type { LoadedConfiguration } from '../src/types.js'; import { hash } from '../src/schema.js'; @@ -339,3 +339,44 @@ test('registry validates json-keys-guard.v1 and line-section-guard.v1 parameters } finally { await fBad.cleanup(); } } }); + +test('loadTrustedConfiguration binds vault credentials and approvedState.environment strictly to the provided environment lookup', async () => { + const f = await configurationFixture(); + const previous = process.env.PROVIDER_TOKEN; + const hostToken = 'S04_HOST_PROCESS_TOKEN_DO_NOT_READ_Aa11'; + const isolatedToken = 'S04_ISOLATED_VAULT_TOKEN_Bb22Cc33'; + try { + process.env.PROVIDER_TOKEN = hostToken; + const envFn = (name: string): string | undefined => (name === 'PROVIDER_TOKEN' ? isolatedToken : undefined); + const loaded = good(await loadTrustedConfiguration({ ...f.input, environment: envFn })); + const plan = good(await compilePlan(loaded)); + const state = approvedState(loaded); + assert.equal(state.environment('PROVIDER_TOKEN'), isolatedToken); + assert.equal(state.environment('UNRELATED_KEY'), undefined); + assert.equal(state.environment('x'.repeat(300)), undefined); + const resolvers = state.vault.bind({ + runId: 'run-env-iso', + roleId: 'builder', + stepId: 'build', + providerCredentialRef: 'copilot', + selection: plan.roles[0]!.policy.selection, + mcp: plan.roles[0]!.policy.mcp, + }); + const resolved = await resolvers.resolveCredential({ + provider: 'github-copilot', + model: 'claude-sonnet-5.5', + destination: 'https://api.individual.githubcopilot.com/v1/messages?beta=true', + purpose: 'task', + runId: 'run-env-iso', + roleId: 'builder', + stepId: 'build', + notAfterMonotonicMs: '1000', + signal: new AbortController().signal, + }); + assert.equal(resolved.bearerToken, isolatedToken); + assert.equal(process.env.PROVIDER_TOKEN, hostToken); + } finally { + if (previous === undefined) delete process.env.PROVIDER_TOKEN; else process.env.PROVIDER_TOKEN = previous; + await f.cleanup(); + } +}); diff --git a/packages/controller/test/config-public.test.ts b/packages/controller/test/config-public.test.ts index 92c2f09..e18bc54 100644 --- a/packages/controller/test/config-public.test.ts +++ b/packages/controller/test/config-public.test.ts @@ -29,3 +29,69 @@ test('public plans retain command digests while withholding private role prompt assert.match(String(plan.value.orderedDAG[0]!.handler.parameters.prompt), /^\[private command sha256:[a-f0-9]{64}\]$/); } finally { if (previous === undefined) delete process.env.PROVIDER_TOKEN; else process.env.PROVIDER_TOKEN = previous; await f.cleanup(); } }); + +test('loadTrustedConfiguration with explicit environment resolves strictly from environment without reading or mutating process.env', async () => { + const f = await configurationFixture(); + const previous = process.env.PROVIDER_TOKEN; + const hostSentinel = 'S04_HOST_PROCESS_ENV_SENTINEL_Xx11Yy22'; + const isolatedToken = 'S04_ISOLATED_ENV_CANARY_Zz33Ww44'; + try { + process.env.PROVIDER_TOKEN = hostSentinel; + const lookedUp: string[] = []; + const loaded = await loadTrustedConfiguration({ + ...f.input, + environment: name => { + lookedUp.push(name); + return name === 'PROVIDER_TOKEN' ? isolatedToken : undefined; + }, + }); + assert.equal(loaded.ok, true, loaded.ok ? '' : JSON.stringify(loaded.error)); + if (!loaded.ok) return; + assert.deepEqual(lookedUp, ['PROVIDER_TOKEN']); + assert.equal(process.env.PROVIDER_TOKEN, hostSentinel); + const compiled = await compilePlan(loaded.value); + assert.equal(compiled.ok, true); + assert.ok(!JSON.stringify({ loaded, compiled }).includes(isolatedToken)); + assert.ok(!JSON.stringify({ loaded, compiled }).includes(hostSentinel)); + + // When custom environment returns undefined, loadTrustedConfiguration MUST NOT fall back to process.env. + const missing = await loadTrustedConfiguration({ + ...f.input, + environment: () => undefined, + }); + assert.equal(missing.ok, false); + if (!missing.ok) assert.equal(missing.error.code, 'CONFIG_ENV_MISSING'); + assert.equal(process.env.PROVIDER_TOKEN, hostSentinel); + + // Null-prototype input with custom environment is accepted; invalid or accessor environment is refused. + const nullProtoInput = Object.assign(Object.create(null) as Record, { + ...f.input, + environment: (name: string) => (name === 'PROVIDER_TOKEN' ? isolatedToken : undefined), + }) as Parameters[0]; + const nullProtoLoaded = await loadTrustedConfiguration(nullProtoInput); + assert.equal(nullProtoLoaded.ok, true, nullProtoLoaded.ok ? '' : JSON.stringify(nullProtoLoaded.error)); + + const badEnv = await loadTrustedConfiguration({ + ...f.input, + environment: 'not-a-function' as unknown as (name: string) => string | undefined, + }); + assert.equal(badEnv.ok, false); + if (!badEnv.ok) { + assert.equal(badEnv.error.code, 'CONFIG_SCHEMA'); + } + + const getterInput = { ...f.input }; + Object.defineProperty(getterInput, 'environment', { + enumerable: true, + get: () => () => isolatedToken, + }); + const getterRes = await loadTrustedConfiguration(getterInput as Parameters[0]); + assert.equal(getterRes.ok, false); + if (!getterRes.ok) { + assert.equal(getterRes.error.code, 'CONFIG_SCHEMA'); + } + } finally { + if (previous === undefined) delete process.env.PROVIDER_TOKEN; else process.env.PROVIDER_TOKEN = previous; + await f.cleanup(); + } +}); diff --git a/packages/controller/test/evolve-block-guard-and-benchmark-forwarding.test.ts b/packages/controller/test/evolve-block-guard-and-benchmark-forwarding.test.ts new file mode 100644 index 0000000..6a6de06 --- /dev/null +++ b/packages/controller/test/evolve-block-guard-and-benchmark-forwarding.test.ts @@ -0,0 +1,1153 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'; +import { execFileSync } from 'node:child_process'; +import { chmod, mkdir, symlink, writeFile } from 'node:fs/promises'; +import { join } from 'node:path'; +import { + admitTask, + bindSubject, + digestArtifact, + type ArtifactManifest, + type BucketMetricEntry, + type HardwareDiagnostics, + type HardwareProvenance, + type HardwareTargetSpec, + type MetricThresholdRule, +} from '@loopwright/core'; +import { contract } from '../../core/test/fixtures.js'; +import { createLocalRun } from '@loopwright/state'; +import { configurationFixture } from './config-fixtures.js'; +import { retainedFixture, setFixture } from './progress-fixtures.js'; +import { retainInventoryInputs } from './verification-fixtures.js'; +import { evaluateControllerAcceptance } from '../src/acceptance.js'; +import { + authenticatedBenchmarkGate, + BenchmarkGate, + checkedBenchmarkVerdict, + computeBenchmarkDisposition, + expectedBenchmarkRequest, + prepareBenchmarkGate, + signBenchmarkVerdict, +} from '../src/benchmark-gate.js'; +import { compilePlan } from '../src/compile.js'; +import { approvedState } from '../src/config.js'; +import { runCycleWithPorts } from '../src/controller.js'; +import { installedHandlerDigests } from '../src/handlers.js'; +import { ControllerOwner } from '../src/ownership.js'; +import { reconcileCycle } from '../src/reconcile.js'; +import { validateHandler } from '../src/registry.js'; +import { canonical } from '../src/schema.js'; +import { freezeSource, overlayManifestBounds } from '../src/source.js'; +import { stepNext, stepSubmit } from '../src/step.js'; +import { ArtifactStore, stateValue } from '../src/storage.js'; +import { normalizeSubmission } from '../src/submission.js'; +import { authenticatedCheck, preflightVerification, prepareVerification, Verifier, type ByteInventory } from '../src/verification.js'; +import { EVOLVE_BLOCK_LIMITS, JSON_FILE_BYTES, maxPacketBytes } from '../src/verifier-protocol.js'; +import { signPayload } from '../src/gate.js'; + +const BENCH_SECRET = 'BENCH_SIGNING_SECRET_Aa11Bb22Cc33'; +const WORKLOAD_DIGEST = { algorithm: 'sha256' as const, hex: 'a'.repeat(64) }; + +async function initGitRepo(directory: string, files: Readonly>): Promise { + await mkdir(directory, { recursive: true, mode: 0o700 }); + const git = (args: string[]) => + execFileSync('/usr/bin/git', ['-c', 'core.hooksPath=/dev/null', ...args], { + cwd: directory, + 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', + }, + timeout: 10_000, + encoding: 'utf8', + }); + git(['init', '-q']); + for (const [rel, content] of Object.entries(files)) { + const abs = join(directory, rel); + await mkdir(join(abs, '..'), { recursive: true, mode: 0o700 }); + await writeFile(abs, content, { mode: 0o600 }); + } + git(['add', '.']); + git(['-c', 'user.name=Test', '-c', 'user.email=test@localhost.invalid', 'commit', '-qm', 'initial']); + return git(['rev-parse', 'HEAD']).trim(); +} + +function sampleProvenance(cellId = 'cuda-h100-whole'): HardwareProvenance { + return { + targetCellId: cellId, + probeKind: 'synthetic_fixture', + vendor: 'NVIDIA', + deviceModel: 'H100-SXM5-80GB', + accelerator: 'sm_90a', + isolationMode: 'whole_device', + deviceCount: 1, + driverVersion: '550.54.15', + runtimeVersion: '12.4', + workloadDigest: WORKLOAD_DIGEST, + clockLockMode: 'locked', + }; +} + +function sampleBucketMetrics(overrides?: { readonly secondUlp?: number }): readonly BucketMetricEntry[] { + return [ + { + bucketId: 'bs1-isl4k', + dimensions: { batch_size: 1, isl: 4096, dtype: 'bf16' }, + metrics: { latency_us_p50: 42.5, goodput_rps: 1850, max_ulp: 0.5, token_force_max_delta: 0.005 }, + }, + { + bucketId: 'bs16-isl8k', + dimensions: { batch_size: 16, isl: 8192, dtype: 'bf16' }, + metrics: { latency_us_p50: 190.2, goodput_rps: 940, max_ulp: overrides?.secondUlp ?? 0.75, token_force_max_delta: 0.01 }, + }, + ]; +} + +function sampleHardwareDiagnostics(): HardwareDiagnostics { + return { + boundPipeline: 'tensor_cube', + rooflineHeadroom: 1.18, + achievedSolPct: 74.5, + arithmeticIntensity: 192.4, + occupancyPct: 62.5, + registerCount: 96, + sharedMemBytes: 49_152, + localSpillBytes: 0, + l2HitPct: 81.2, + bankConflictPct: 1.5, + topStallReasons: [ + { reason: 'stall_long_scoreboard', pct: 34.2 }, + { reason: 'stall_wait', pct: 12.1 }, + ], + }; +} + +test('installedHandlerDigests registers evolve-block-guard.v1 and validateHandler enforces strict parameter bounds', async () => { + const digests = await installedHandlerDigests(); + assert.equal(digests['evolve-block-guard.v1'].algorithm, 'sha256'); + assert.match(digests['evolve-block-guard.v1'].hex, /^[0-9a-f]{64}$/); + assert.notEqual(digests['evolve-block-guard.v1'].hex, digests['line-section-guard.v1'].hex); + assert.notEqual(digests['evolve-block-guard.v1'].hex, digests['scope.v1'].hex); + + // Legacy workflows that omit evolve-block-guard.v1 preserve identical TaskContract / TaskLock digests + const baseTask = contract(); + const lock1 = admitTask(baseTask, { admissionId: 'adm-parity', runId: 'run-parity' }); + const lock2 = admitTask(structuredClone(baseTask), { admissionId: 'adm-parity', runId: 'run-parity' }); + assert.equal(lock1.ok, true); + assert.equal(lock2.ok, true); + if (lock1.ok && lock2.ok) { + assert.deepEqual(lock1.value.spec.contractHash, lock2.value.spec.contractHash); + assert.deepEqual(lock1.value.spec.lockHash, lock2.value.spec.lockHash); + } + + const valid = { + id: 'evolve-guard', + version: 1, + digest: digests['evolve-block-guard.v1'], + kind: 'check', + implementation: 'evolve-block-guard.v1', + parameters: { + checkId: 'evolve-guard', + files: ['kernels/flash_decode.cu', 'kernels/triton_impl.py'], + allowedBlockIds: ['tile_loop', 'epilogue'], + maxBlockBytes: 4096, + }, + capabilities: ['inert_bytes', 'read_only'], + }; + assert.equal(validateHandler(valid, '/h').implementation, 'evolve-block-guard.v1'); + + // Optional fields omitted -> valid + assert.equal( + validateHandler( + { + ...valid, + parameters: { checkId: 'evolve-guard', files: ['kernels/flash_decode.cu'] }, + }, + '/h', + ).implementation, + 'evolve-block-guard.v1', + ); + + // Null-prototype parameters accepted cleanly + const nullProtoParams = Object.create(null) as Record; + nullProtoParams.checkId = 'evolve-guard'; + nullProtoParams.files = ['kernels/flash_decode.cu']; + assert.equal(validateHandler({ ...valid, parameters: nullProtoParams }, '/h').implementation, 'evolve-block-guard.v1'); + + // Reject invalid parameter combinations + const badParameters: unknown[] = [ + { checkId: 'evolve-guard', files: [] }, + { checkId: 'evolve-guard', files: Array.from({ length: 65 }, (_, i) => `kernels/f${i}.cu`) }, + { checkId: 'evolve-guard', files: ['kernels/a.cu', 'kernels/a.cu'] }, + { checkId: 'evolve-guard', files: ['kernels/A.cu', 'kernels/a.cu'] }, + { checkId: 'evolve-guard', files: ['../escape.cu'] }, + { checkId: 'evolve-guard', files: ['kernels/../escape.cu'] }, + { checkId: 'evolve-guard', files: ['/abs/path/kernel.cu'] }, + { checkId: 'evolve-guard', files: ['.github/workflows/ci.yml'] }, + { checkId: 'evolve-guard', files: ['.GitHub/Workflows/release.yaml'] }, + { checkId: 'evolve-guard', files: ['.git/config'] }, + { checkId: 'evolve-guard', files: ['kernels/a.cu'], allowedBlockIds: [] }, + { checkId: 'evolve-guard', files: ['kernels/a.cu'], allowedBlockIds: Array.from({ length: 65 }, (_, i) => `blk_${i}`) }, + { checkId: 'evolve-guard', files: ['kernels/a.cu'], allowedBlockIds: ['dup', 'dup'] }, + { checkId: 'evolve-guard', files: ['kernels/a.cu'], allowedBlockIds: ['has space'] }, + { checkId: 'evolve-guard', files: ['kernels/a.cu'], allowedBlockIds: ['non_ascii_\u00e9'] }, + { checkId: 'evolve-guard', files: ['kernels/a.cu'], allowedBlockIds: ['bad*/id'] }, + { checkId: 'evolve-guard', files: ['kernels/a.cu'], maxBlockBytes: 0 }, + { checkId: 'evolve-guard', files: ['kernels/a.cu'], maxBlockBytes: -1 }, + { checkId: 'evolve-guard', files: ['kernels/a.cu'], maxBlockBytes: -0 }, + { checkId: 'evolve-guard', files: ['kernels/a.cu'], maxBlockBytes: 12.5 }, + { checkId: 'evolve-guard', files: ['kernels/a.cu'], maxBlockBytes: Number.NaN }, + { checkId: 'evolve-guard', files: ['kernels/a.cu'], maxBlockBytes: Number.POSITIVE_INFINITY }, + { checkId: 'evolve-guard', files: ['kernels/a.cu'], extraKey: true }, + ]; + for (const params of badParameters) { + assert.throws(() => validateHandler({ ...valid, parameters: params }, '/h'), `should reject ${JSON.stringify(params)}`); + } + assert.throws(() => validateHandler({ ...valid, capabilities: ['hardware_execution', 'read_only'] }, '/h')); + assert.throws(() => validateHandler({ ...valid, kind: 'agent' }, '/h')); +}); + +test('evolve-block-guard.v1 enforces //, #, /* */ blocks, outside-byte SHA-256 invariance, marker errors, allowedBlockIds, and maxBlockBytes', async () => { + const baseCu = [ + '__global__ void flash_decode(float* out) {', + ' // EVOLVE-BLOCK-START: tile_loop', + ' out[0] = 1.0f;', + ' // EVOLVE-BLOCK-END: tile_loop', + ' __syncthreads();', + ' // EVOLVE-BLOCK-START: epilogue', + ' out[1] = 2.0f;', + ' // EVOLVE-BLOCK-END: epilogue', + '}', + '', + ].join('\n'); + + const basePy = [ + 'def run_kernel(x):', + ' # EVOLVE-BLOCK-START: py_body', + ' y = x + 1', + ' # EVOLVE-BLOCK-END: py_body', + ' return y', + '', + ].join('\n'); + + const baseC = [ + 'int helper(int a) {', + ' /* EVOLVE-BLOCK-START: c_inner */', + ' return a * 2;', + ' /* EVOLVE-BLOCK-END: c_inner */', + '}', + '', + ].join('\n'); + + const installed = await installedHandlerDigests(); + const f = await retainedFixture(1, 20, 18, 60_000, fixture => { + setFixture(fixture.config, ['spec', 'task', 'spec', 'budgets', 'maxModelCalls'], 32); + setFixture(fixture.registry, ['spec', 'roleProfiles', 0, 'tools'], ['read', 'write', 'edit', 'delete']); + setFixture(fixture.config, ['spec', 'task', 'spec', 'roles', 0, 'tools'], ['read', 'write', 'edit', 'delete']); + setFixture(fixture.registry, ['spec', 'handlers'], [ + ...fixture.registry.spec.handlers.filter(h => h.id !== 'tests'), + { + id: 'evolve-guard', + kind: 'check', + implementation: 'evolve-block-guard.v1', + version: 1, + digest: installed['evolve-block-guard.v1'], + parameters: { + checkId: 'evolve-guard', + files: ['packages/kernel.cu', 'packages/kernel.py', 'packages/helper.c'], + allowedBlockIds: ['tile_loop', 'py_body', 'c_inner'], + maxBlockBytes: 96, + }, + capabilities: ['inert_bytes', 'read_only'], + }, + ]); + setFixture(fixture.config, ['spec', 'task', 'spec', 'acceptance'], { + required: ['evolve-guard'], + checks: [{ id: 'evolve-guard', allowedEvidenceLevels: ['local_execution'] }], + }); + }); + + try { + const makeInv = async (files: readonly { readonly name: string; readonly bytes: Buffer }[]): Promise => { + const sorted = [...files].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)); + const entries = sorted.map(file => { + const r = digestArtifact(file.name, file.bytes); + assert.equal(r.ok, true); + if (!r.ok) throw new Error('digest failed'); + return r.value; + }); + const manifest: ArtifactManifest = { + apiVersion: 'loopwright.dev/v1alpha1', + kind: 'ArtifactManifest', + metadata: { id: 'candidate' }, + spec: { entries }, + }; + const ref = await f.artifacts.json('manifest', manifest, 32_768); + await retainInventoryInputs(f.artifacts, manifest, ref, sorted); + return { manifest, ref, files: sorted }; + }; + + const source = await makeInv([ + { name: 'packages/kernel.cu', bytes: Buffer.from(baseCu, 'utf8') }, + { name: 'packages/kernel.py', bytes: Buffer.from(basePy, 'utf8') }, + { name: 'packages/helper.c', bytes: Buffer.from(baseC, 'utf8') }, + ]); + + const runCase = async ( + overrides: { readonly cu?: string | Buffer | null; readonly py?: string | Buffer | null; readonly c?: string | Buffer | null }, + generation: number, + ) => { + const listFiles: { name: string; bytes: Buffer }[] = []; + const add = (name: string, val: string | Buffer | null | undefined, fallback: string) => { + if (val === null) return; + const effective = val === undefined ? fallback : val; + listFiles.push({ name, bytes: Buffer.isBuffer(effective) ? effective : Buffer.from(effective, 'utf8') }); + }; + add('packages/kernel.cu', overrides.cu, baseCu); + add('packages/kernel.py', overrides.py, basePy); + add('packages/helper.c', overrides.c, baseC); + const candidate = await makeInv(listFiles); + const bound = bindSubject(f.lock, candidate.manifest); + assert.equal(bound.ok, true); + if (!bound.ok) throw new Error('bind failed'); + const verifier = new Verifier(f.store, f.authority, f.artifacts, f.plan, f.lock, () => bound.value); + const checks = []; + for (const [idx, slot] of f.plan.verifierSlots.entries()) { + const prep = prepareVerification( + f.plan, + f.lock, + slot.id, + source, + candidate, + generation, + `${(generation + 1).toString(16).padStart(16, '0')}${idx.toString(16).padStart(16, '0')}`, + ); + checks.push(await verifier.run(prep, new AbortController().signal)); + } + const sub = normalizeSubmission(Buffer.from(JSON.stringify({ version: 1, status: 'completed', checks: [], reason: null })), f.plan.task); + const accepted = evaluateControllerAcceptance(f.plan, f.lock, candidate.manifest, candidate.files, generation, checks, sub, f.store); + const guardCheck = checks.find(c => c.checkId === 'evolve-guard')!; + return { guardCheck, evidence: authenticatedCheck(guardCheck).evidence, accepted }; + }; + + // 1. Happy path: mutate allowed blocks in all 3 comment styles (//, #, /* */) including empty interior & multi-line + const happy = await runCase( + { + cu: baseCu.replace(' out[0] = 1.0f;', ' float acc = 3.0f;\n out[0] = acc;'), + py: basePy.replace(' y = x + 1\n', ''), + c: baseC.replace(' return a * 2;', ' return (a << 1) + 0;'), + }, + 0, + ); + assert.equal(happy.guardCheck.status, 'passed'); + assert.equal(happy.accepted.result.spec.status, 'completed'); + + // 2. Single-character mutation outside mutable blocks -> outside_block_modified + const singleCharOutside = await runCase( + { cu: baseCu.replace('__syncthreads();', '__syncthreads() ;') }, + 1, + ); + assert.equal(singleCharOutside.guardCheck.status, 'failed'); + assert.equal(singleCharOutside.guardCheck.reason, 'outside_block_modified'); + assert.equal(singleCharOutside.evidence.spec.findings?.[0]?.path, 'packages/kernel.cu'); + assert.equal(singleCharOutside.evidence.spec.findings?.[0]?.line, 5); + + // 3. Single-byte EOL flip outside block (\n -> \r\n on immutable line) -> outside_block_modified + const eolOutside = await runCase( + { c: baseC.replace('int helper(int a) {\n', 'int helper(int a) {\r\n') }, + 2, + ); + assert.equal(eolOutside.guardCheck.status, 'failed'); + assert.equal(eolOutside.guardCheck.reason, 'outside_block_modified'); + + // 4. Marker deletion -> missing_markers (if 0 left) or unbalanced_markers / outside_block_modified + const deletedAllMarkers = await runCase( + { py: 'def run_kernel(x):\n y = x + 1\n return y\n' }, + 3, + ); + assert.equal(deletedAllMarkers.guardCheck.status, 'failed'); + assert.equal(deletedAllMarkers.guardCheck.reason, 'missing_markers'); + + // 5. Nested markers -> unbalanced_markers + const nested = await runCase( + { + cu: baseCu.replace( + ' out[0] = 1.0f;', + ' // EVOLVE-BLOCK-START: inner\n out[0] = 1.0f;\n // EVOLVE-BLOCK-END: inner', + ), + }, + 4, + ); + assert.equal(nested.guardCheck.status, 'failed'); + assert.equal(nested.guardCheck.reason, 'unbalanced_markers'); + + // 6. Duplicate blockId within the same file -> duplicate_block_id + const duplicate = await runCase( + { + cu: baseCu.replace('epilogue', 'tile_loop').replace('epilogue', 'tile_loop'), + }, + 5, + ); + assert.equal(duplicate.guardCheck.status, 'failed'); + assert.equal(duplicate.guardCheck.reason, 'duplicate_block_id'); + + // 7. Reordered blocks (epilogue before tile_loop) -> outside_block_modified + const reordered = await runCase( + { + cu: [ + '__global__ void flash_decode(float* out) {', + ' // EVOLVE-BLOCK-START: epilogue', + ' out[1] = 2.0f;', + ' // EVOLVE-BLOCK-END: epilogue', + ' __syncthreads();', + ' // EVOLVE-BLOCK-START: tile_loop', + ' out[0] = 1.0f;', + ' // EVOLVE-BLOCK-END: tile_loop', + '}', + '', + ].join('\n'), + }, + 6, + ); + assert.equal(reordered.guardCheck.status, 'failed'); + assert.equal(reordered.guardCheck.reason, 'outside_block_modified'); + + // 8. Unclosed marker -> unbalanced_markers + const unclosed = await runCase( + { py: 'def run_kernel(x):\n # EVOLVE-BLOCK-START: py_body\n y = x + 1\n return y\n' }, + 7, + ); + assert.equal(unclosed.guardCheck.status, 'failed'); + assert.equal(unclosed.guardCheck.reason, 'unbalanced_markers'); + + // 9. Mismatched START/END ID -> unbalanced_markers + const mismatchedId = await runCase( + { c: baseC.replace('EVOLVE-BLOCK-END: c_inner', 'EVOLVE-BLOCK-END: other_id') }, + 8, + ); + assert.equal(mismatchedId.guardCheck.status, 'failed'); + assert.equal(mismatchedId.guardCheck.reason, 'unbalanced_markers'); + + // 10. allowedBlockIds violation (mutating 'epilogue' which is NOT in allowedBlockIds) -> disallowed_block_id + const disallowedBlock = await runCase( + { cu: baseCu.replace(' out[1] = 2.0f;', ' out[1] = 999.0f;') }, + 9, + ); + assert.equal(disallowedBlock.guardCheck.status, 'failed'); + assert.equal(disallowedBlock.guardCheck.reason, 'disallowed_block_id'); + assert.match(disallowedBlock.evidence.spec.findings?.[0]?.evidence ?? '', /epilogue/); + + // 11. maxBlockBytes exact boundary passes (96 UTF-8 bytes) and 97 UTF-8 bytes (multi-byte UTF-8) fails + const exact96 = 'a'.repeat(95) + '\n'; + assert.equal(Buffer.byteLength(exact96, 'utf8'), 96); + const pass96 = await runCase( + { py: basePy.replace(' y = x + 1\n', exact96) }, + 10, + ); + assert.equal(pass96.guardCheck.status, 'passed'); + + const over97Utf8 = '# ' + '\u00e9'.repeat(47) + '\n'; // 2 + 94 + 1 = 97 UTF-8 bytes (50 chars!) + assert.equal(Buffer.byteLength(over97Utf8, 'utf8'), 97); + const fail97 = await runCase( + { py: basePy.replace(' y = x + 1\n', over97Utf8) }, + 11, + ); + assert.equal(fail97.guardCheck.status, 'failed'); + assert.equal(fail97.guardCheck.reason, 'block_bytes_exceeded'); + assert.equal(fail97.evidence.spec.findings?.[0]?.path, 'packages/kernel.py'); + + // 12. Missing candidate file -> missing_file + const missing = await runCase({ c: null }, 12); + assert.equal(missing.guardCheck.status, 'failed'); + assert.equal(missing.guardCheck.reason, 'missing_file'); + + // 13. Invalid UTF-8 bytes -> invalid_utf8 + const invalidUtf8 = await runCase({ c: Buffer.from([0xff, 0xfe, 0x00]) }, 13); + assert.equal(invalidUtf8.guardCheck.status, 'failed'); + assert.equal(invalidUtf8.guardCheck.reason, 'invalid_utf8'); + + // 14. Prose comment mentioning EVOLVE-BLOCK-START does not poison unchanged file, while malformed directive fails closed + const proseMentionFile = [ + '// Note: keep edits inside EVOLVE-BLOCK-START blocks below', + 'int helper(int a) {', + ' /* EVOLVE-BLOCK-START: c_inner */', + ' return a * 2;', + ' /* EVOLVE-BLOCK-END: c_inner */', + '}', + '', + ].join('\n'); + const sourceProse = await makeInv([ + { name: 'packages/kernel.cu', bytes: Buffer.from(baseCu, 'utf8') }, + { name: 'packages/kernel.py', bytes: Buffer.from(basePy, 'utf8') }, + { name: 'packages/helper.c', bytes: Buffer.from(proseMentionFile, 'utf8') }, + ]); + const guardSlot = f.plan.verifierSlots.find(s => s.checkId === 'evolve-guard')!; + const boundProse = bindSubject(f.lock, sourceProse.manifest); + assert.equal(boundProse.ok, true); + if (boundProse.ok) { + const verifierProse = new Verifier(f.store, f.authority, f.artifacts, f.plan, f.lock, () => boundProse.value); + const prepProse = prepareVerification(f.plan, f.lock, guardSlot.id, sourceProse, sourceProse, 16, 'a'.repeat(32)); + const proseCheck = await verifierProse.run(prepProse, new AbortController().signal); + assert.equal(proseCheck.status, 'passed'); + } + const malformedDirective = await runCase( + { cu: baseCu.replace('// EVOLVE-BLOCK-START: tile_loop', '// EVOLVE-BLOCK-START') }, + 17, + ); + assert.equal(malformedDirective.guardCheck.status, 'failed'); + assert.equal(malformedDirective.guardCheck.reason, 'unbalanced_markers'); + + // Multi-file evolve-block-guard.v1 packet bound scales beyond single-file guard limit + const singleFileGuardLimit = maxPacketBytes({ payloadKind: 'guard', handler: 'line-section-guard.v1' }); + const evolveGuardLimit = maxPacketBytes({ payloadKind: 'guard', handler: 'evolve-block-guard.v1' }); + assert.ok(evolveGuardLimit > singleFileGuardLimit); + assert.ok(evolveGuardLimit >= EVOLVE_BLOCK_LIMITS.maxFiles * JSON_FILE_BYTES); + + // 14b. Guarded file with zero blocks matching allowedBlockIds fails closed with disallowed_block_id + const nonMatchingFile = [ + 'int helper(int a) {', + ' /* EVOLVE-BLOCK-START: locked_only */', + ' return a * 2;', + ' /* EVOLVE-BLOCK-END: locked_only */', + '}', + '', + ].join('\n'); + const sourceNoMatch = await makeInv([ + { name: 'packages/kernel.cu', bytes: Buffer.from(baseCu, 'utf8') }, + { name: 'packages/kernel.py', bytes: Buffer.from(basePy, 'utf8') }, + { name: 'packages/helper.c', bytes: Buffer.from(nonMatchingFile, 'utf8') }, + ]); + const boundNoMatch = bindSubject(f.lock, sourceNoMatch.manifest); + assert.equal(boundNoMatch.ok, true); + if (boundNoMatch.ok) { + const verifierNoMatch = new Verifier(f.store, f.authority, f.artifacts, f.plan, f.lock, () => boundNoMatch.value); + const prepNoMatch = prepareVerification(f.plan, f.lock, guardSlot.id, sourceNoMatch, sourceNoMatch, 14, 'e'.repeat(32)); + const noMatchCheck = await verifierNoMatch.run(prepNoMatch, new AbortController().signal); + assert.equal(noMatchCheck.status, 'failed'); + assert.equal(noMatchCheck.reason, 'disallowed_block_id'); + } + + // 15. preflightVerification + Verifier.restore() parity and O_NOFOLLOW symlink rejection on CAS blob + const pre = preflightVerification(f.plan, f.lock, guardSlot.id, source, source, 15, 'c'.repeat(32)); + assert.equal(pre.kind, 'ready'); + if (pre.kind === 'ready') { + const boundSrc = bindSubject(f.lock, source.manifest); + assert.equal(boundSrc.ok, true); + if (boundSrc.ok) { + const verifier = new Verifier(f.store, f.authority, f.artifacts, f.plan, f.lock, () => boundSrc.value); + const ran = await verifier.run(pre.job, new AbortController().signal); + assert.equal(ran.status, 'passed'); + const restored = await verifier.restore(pre.job); + assert.equal(canonical(restored), canonical(ran)); + } + } + + // Symlink blobPath fails closed via O_NOFOLLOW in prepareVerification + const realTarget = join(f.root, 'real-blob.cu'); + await writeFile(realTarget, baseCu, { mode: 0o400 }); + const symlinkBlob = join(f.root, 'symlink-blob.cu'); + await symlink(realTarget, symlinkBlob); + const cuEntry = source.manifest.spec.entries.find(e => e.name === 'packages/kernel.cu')!; + const symlinkCandidate: ByteInventory = { + manifest: source.manifest, + ref: source.ref, + files: source.files.map(file => + file.name === 'packages/kernel.cu' + ? { name: file.name, byteLength: cuEntry.byteLength, digest: cuEntry.digest, blobPath: symlinkBlob } + : file, + ), + }; + assert.throws(() => prepareVerification(f.plan, f.lock, guardSlot.id, source, symlinkCandidate, 16, 'd'.repeat(32))); + } finally { + await f.close(); + } +}); + +test('evolve-block-guard.v1 enforces 1..32 block count limit and works via baseTree Merkle proofs in stepNext/stepSubmit and restore()', async () => { + const makeBlocks = (count: number) => { + const lines = ['// header']; + for (let i = 0; i < count; i++) { + lines.push(`// EVOLVE-BLOCK-START: blk_${i}`); + lines.push(`const v_${i} = ${i};`); + lines.push(`// EVOLVE-BLOCK-END: blk_${i}`); + } + lines.push('// footer', ''); + return lines.join('\n'); + }; + + const cfg = await configurationFixture(); + try { + const repoDir = join(cfg.root, 'repo-evolve'); + const baseFiles: Record = { + 'packages/ok32.ts': makeBlocks(32), + 'packages/over33.ts': makeBlocks(33), + }; + for (let i = 0; i < 135; i++) { + baseFiles[`lib/pad-${String(i).padStart(3, '0')}.ts`] = `export const p${i} = ${i};\n`; + } + const rev = await initGitRepo(repoDir, baseFiles); + const installed = await installedHandlerDigests(); + + setFixture(cfg.registry, ['spec', 'roleProfiles'], [ + { + id: 'builder', + adapter: 'delegated', + selection: { provider: 'claude-code', model: 'claude-sonnet-4-6', thinking: 'high' }, + tools: ['read', 'write', 'edit'], + runtimeRef: null, + providerCredentialRef: null, + mcp: null, + }, + ]); + setFixture(cfg.registry, ['spec', 'credentialBindings'], []); + setFixture(cfg.registry, ['spec', 'environmentBindings'], []); + setFixture(cfg.registry, ['spec', 'handlers'], [ + { id: 'author.h', kind: 'agent', implementation: 'pi.agent.v1', version: 1, digest: installed['pi.agent.v1'], parameters: { prompt: 'Evolve kernel.', purpose: 'task' }, capabilities: ['pi'] }, + { id: 'guard-32', kind: 'check', implementation: 'evolve-block-guard.v1', version: 1, digest: installed['evolve-block-guard.v1'], parameters: { checkId: 'guard-32', files: ['packages/ok32.ts'] }, capabilities: ['inert_bytes', 'read_only'] }, + { id: 'guard-33', kind: 'check', implementation: 'evolve-block-guard.v1', version: 1, digest: installed['evolve-block-guard.v1'], parameters: { checkId: 'guard-33', files: ['packages/over33.ts'] }, capabilities: ['inert_bytes', 'read_only'] }, + ...cfg.registry.spec.handlers.filter(h => h.id === 'scope' || h.id === 'no-change'), + ]); + setFixture(cfg.config, ['spec', 'credentials'], []); + setFixture(cfg.config, ['spec', 'task', 'spec', 'target', 'baseRevision'], rev); + setFixture(cfg.config, ['spec', 'task', 'spec', 'target', 'sourceRevision'], rev); + setFixture(cfg.config, ['spec', 'task', 'spec', 'scope'], { writable: ['packages/**'], protected: [] }); + setFixture(cfg.config, ['spec', 'task', 'spec', 'roles'], [ + { id: 'builder', adapter: 'delegated', provider: 'claude-code', model: 'claude-sonnet-4-6', thinking: 'high', tools: ['read', 'write', 'edit'] }, + ]); + setFixture(cfg.config, ['spec', 'task', 'spec', 'budgets', 'maxImplementationRepairs'], 0); + setFixture(cfg.config, ['spec', 'controls', 'maxAttempts'], 1); + setFixture(cfg.config, ['spec', 'task', 'spec', 'steps'], [ + { id: 'evolve', kind: 'agent', uses: 'author.h', roleId: 'builder', dependsOn: [] }, + ]); + setFixture(cfg.config, ['spec', 'profiles', 'steps'], [{ stepId: 'evolve', handlerRef: 'author.h' }]); + setFixture(cfg.config, ['spec', 'task', 'spec', 'acceptance'], { + required: ['guard-32'], + checks: [{ id: 'guard-32', allowedEvidenceLevels: ['local_execution'] }], + }); + cfg.input.untrustedRoots = [cfg.taskDirectory, repoDir]; + await cfg.save(); + + const loaded32 = await cfg.load(); + assert.equal(loaded32.ok, true, JSON.stringify(loaded32)); + if (!loaded32.ok) return; + + const runRoot = join(cfg.root, 'runs'); + const y1 = await stepNext({ configuration: loaded32.value, repository: repoDir, runRoot, runId: 'run-evolve-32' }); + assert.equal(y1.ok, true, JSON.stringify(y1)); + if (!y1.ok || y1.value.kind !== 'step') assert.fail('expected step yield'); + + // Mutate inside blk_0 of ok32.ts -> passes on >128-file baseTree Merkle repo + await chmod(join(y1.value.candidateDir, 'packages/ok32.ts'), 0o600); + await writeFile( + join(y1.value.candidateDir, 'packages/ok32.ts'), + makeBlocks(32).replace('const v_0 = 0;', 'const v_0 = 42;'), + { mode: 0o600 }, + ); + const s1 = await stepSubmit({ runRoot, runId: 'run-evolve-32', leaseToken: y1.value.leaseToken, status: 'completed' }); + assert.equal(s1.ok, true, JSON.stringify(s1)); + const fin1 = await stepNext({ runRoot, runId: 'run-evolve-32' }); + assert.equal(fin1.ok, true, JSON.stringify(fin1)); + if (!fin1.ok || fin1.value.kind !== 'result') assert.fail('expected result'); + assert.equal(fin1.value.result.spec.status, 'completed'); + + // Now test 33-block file -> fails closed with block_limit_exceeded + setFixture(cfg.config, ['spec', 'task', 'spec', 'acceptance'], { + required: ['guard-33'], + checks: [{ id: 'guard-33', allowedEvidenceLevels: ['local_execution'] }], + }); + setFixture(cfg.config, ['spec', 'task', 'spec', 'steps'], [ + { id: 'check-33', kind: 'check', uses: 'guard-33', roleId: null, dependsOn: [] }, + ]); + setFixture(cfg.config, ['spec', 'profiles', 'steps'], [{ stepId: 'check-33', handlerRef: 'guard-33' }]); + await cfg.save(); + const loaded33 = await cfg.load(); + assert.equal(loaded33.ok, true); + if (!loaded33.ok) return; + + const run33 = await runCycleWithPorts({ + configuration: loaded33.value, + repository: repoDir, + runRoot, + runId: 'run-evolve-33', + }); + assert.equal(run33.ok, true); + if (!run33.ok || run33.value.kind !== 'result') assert.fail('expected result'); + assert.equal(run33.value.result.spec.status, 'failed'); + assert.equal(run33.value.result.spec.verification.spec.required[0]?.status, 'failed'); + assert.match( + run33.value.result.spec.verification.spec.required[0]?.findings?.[0]?.evidence ?? '', + /exceeds maximum of 32/, + ); + } finally { + await cfg.cleanup(); + } +}); + +test('benchmark-gate.v1 forwards Stage A static audit fields, bucketScope, bucketMetrics, and hardwareDiagnostics while keeping legacy digests byte-identical', async () => { + // 1. Legacy digest parity: omitting Stage A audit fields & bucketMetrics/hardwareDiagnostics keeps exact legacy keys + const cfgLegacy = await configurationFixture(); + const cfgAudit = await configurationFixture(); + try { + const installed = await installedHandlerDigests(); + const setupBench = async ( + f: Awaited>, + relayUrl: string, + hardware: HardwareTargetSpec, + metricThresholds: readonly MetricThresholdRule[], + ) => { + f.environment.BENCH_SECRET = BENCH_SECRET; + setFixture(f.registry, ['spec', 'credentialBindings'], [ + ...f.registry.spec.credentialBindings, + { id: 'bench-signer', consumer: 'gate', destinationRef: 'bench-relay', environmentNames: ['BENCH_SECRET'], template: '${BENCH_SECRET}' }, + ]); + setFixture(f.registry, ['spec', 'environmentBindings'], [ + { name: 'PROVIDER_TOKEN', classification: 'credential', paths: [] }, + { name: 'BENCH_SECRET', classification: 'credential', paths: ['/spec/credentials/0/template'] }, + ]); + setFixture(f.config, ['spec', 'credentials'], [{ ref: 'bench-signer', template: '${BENCH_SECRET}' }]); + setFixture(f.registry, ['spec', 'gateEndpoints'], [ + { + id: 'gpu-relay', + url: relayUrl, + signingCredentialRef: 'bench-signer', + authCredentialRef: null, + timeoutMs: 2000, + maxPollMs: 8000, + pollInitialMs: 100, + pollMaxMs: 200, + jitter: 0, + }, + ]); + setFixture(f.registry, ['spec', 'handlers'], [ + f.registry.spec.handlers[0]!, + { + id: 'kernel-bench', + kind: 'check', + implementation: 'benchmark-gate.v1', + version: 1, + digest: installed['benchmark-gate.v1'], + parameters: { + checkId: 'kernel-bench', + endpointRef: 'gpu-relay', + gateId: 'sm90-decode-gate', + heldOutWorkloadId: 'decode-bs1-4k', + }, + capabilities: ['hardware_execution', 'read_only'], + }, + f.registry.spec.handlers[2]!, + f.registry.spec.handlers[3]!, + ]); + setFixture(f.config, ['spec', 'controls', 'maxAttempts'], 4); + setFixture(f.config, ['spec', 'task', 'spec', 'budgets', 'maxImplementationRepairs'], 3); + setFixture(f.config, ['spec', 'task', 'spec', 'steps'], [ + { id: 'bench-step', kind: 'check', uses: 'kernel-bench', roleId: null, dependsOn: [] }, + ]); + setFixture(f.config, ['spec', 'profiles', 'steps'], [{ stepId: 'bench-step', handlerRef: 'kernel-bench' }]); + setFixture(f.config, ['spec', 'task', 'spec', 'target', 'matrix'], [ + { id: 'cuda-h100-whole', platform: 'linux-x86_64', variant: 'h100', hardware }, + ]); + setFixture(f.config, ['spec', 'task', 'spec', 'acceptance'], { + required: ['kernel-bench'], + checks: [ + { + id: 'kernel-bench', + allowedEvidenceLevels: ['hardware_execution'], + targetCellId: 'cuda-h100-whole', + allowSyntheticHardwareProbe: true, + metricThresholds, + }, + ], + }); + await f.save(); + const loaded = await f.load(); + assert.equal(loaded.ok, true, JSON.stringify(loaded)); + if (!loaded.ok) throw new Error('load failed'); + const compiled = await compilePlan(loaded.value); + assert.equal(compiled.ok, true, JSON.stringify(compiled)); + if (!compiled.ok) throw new Error('compile failed'); + return { loaded: loaded.value, plan: compiled.value }; + }; + + // Start mock relay capturing incoming BenchmarkRequest and returning signed Stage B verdict + const receivedRequests: Record[] = []; + let verdictMode: 'full' | 'legacy' | 'bad_bucket_ulp' | 'invalid_diag' = 'full'; + const server = createServer(async (req: IncomingMessage, res: ServerResponse) => { + const chunks: Buffer[] = []; + for await (const chunk of req) chunks.push(Buffer.from(chunk)); + if (req.method === 'PUT') { + res.writeHead(204); + res.end(); + return; + } + const bodyText = Buffer.concat(chunks).toString('utf8'); + const parsed = JSON.parse(bodyText) as Record; + receivedRequests.push(parsed); + + const baseVerdict: Record = { + version: 1, + kind: 'benchmark_verdict', + storeId: parsed.storeId, + runId: parsed.runId, + lockHash: parsed.lockHash, + operationId: parsed.operationId, + dispatchId: parsed.dispatchId, + dispatchGeneration: parsed.dispatchGeneration, + gateId: parsed.gateId, + checkId: parsed.checkId, + candidateDigest: parsed.candidateDigest, + status: 'approved', + reason: null, + expiresAtMs: String(Date.now() + 300_000), + preemptionCount: 0, + metrics: { latency_us_p50: 45.0, max_ulp: 0.5 }, + hardwareProvenance: sampleProvenance(), + }; + if (verdictMode === 'full') { + baseVerdict.bucketMetrics = sampleBucketMetrics(); + baseVerdict.hardwareDiagnostics = sampleHardwareDiagnostics(); + } else if (verdictMode === 'bad_bucket_ulp') { + baseVerdict.bucketMetrics = sampleBucketMetrics({ secondUlp: 2.5 }); + baseVerdict.hardwareDiagnostics = sampleHardwareDiagnostics(); + } else if (verdictMode === 'invalid_diag') { + baseVerdict.hardwareDiagnostics = { boundPipeline: 'free-text-exfil' }; + } + + const payloadBytes = Buffer.from(canonical(baseVerdict), 'utf8'); + const sig = signPayload(BENCH_SECRET, payloadBytes); + res.writeHead(200, { + 'content-type': 'application/json', + 'x-loopwright-signature': sig, + }); + res.end(payloadBytes); + }); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + const addr = server.address(); + if (!addr || typeof addr === 'string') throw new Error('bind failed'); + const relayUrl = `http://127.0.0.1:${addr.port}/v1/benchmark`; + + try { + const legacyHardware: HardwareTargetSpec = { + accelerator: 'sm_90a', + isolationMode: 'whole_device', + deviceCount: 1, + }; + const auditHardware: HardwareTargetSpec = { + accelerator: 'sm_90a', + isolationMode: 'whole_device', + deviceCount: 1, + forbiddenSymbolPatterns: ['cublas', 'at::native::'], + maxRegisterCount: 128, + maxLocalSpillBytes: 0, + }; + const legacyThresholds: readonly MetricThresholdRule[] = [ + { kind: 'bounds', metric: 'latency_us_p50', max: 100 }, + ]; + const bucketedThresholds: readonly MetricThresholdRule[] = [ + { kind: 'bounds', metric: 'latency_us_p50', max: 100 }, + { kind: 'bounds', metric: 'max_ulp', max: 1.0, bucketScope: 'all_buckets' }, + { kind: 'bounds', metric: 'goodput_rps', min: 1500, bucketScope: { bucketId: 'bs1-isl4k' } }, + ]; + + const legacySetup = await setupBench(cfgLegacy, relayUrl, legacyHardware, legacyThresholds); + const auditSetup = await setupBench(cfgAudit, relayUrl, auditHardware, bucketedThresholds); + + const legacyLockRes = admitTask(legacySetup.plan.task, { admissionId: 'adm-l', runId: 'run-l' }); + const auditLockRes = admitTask(auditSetup.plan.task, { admissionId: 'adm-a', runId: 'run-a' }); + assert.equal(legacyLockRes.ok, true); + assert.equal(auditLockRes.ok, true); + if (!legacyLockRes.ok || !auditLockRes.ok) return; + + const emptyManifest: ArtifactManifest = { + apiVersion: 'loopwright.dev/v1alpha1', + kind: 'ArtifactManifest', + metadata: { id: 'candidate' }, + spec: { entries: [] }, + }; + const legacySubj = bindSubject(legacyLockRes.value, emptyManifest); + const auditSubj = bindSubject(auditLockRes.value, emptyManifest); + assert.equal(legacySubj.ok, true); + assert.equal(auditSubj.ok, true); + if (!legacySubj.ok || !auditSubj.ok) return; + + const legacySlot = legacySetup.plan.verifierSlots.find(s => s.handler.implementation === 'benchmark-gate.v1')!; + const auditSlot = auditSetup.plan.verifierSlots.find(s => s.handler.implementation === 'benchmark-gate.v1')!; + const legacyReq = expectedBenchmarkRequest( + legacySetup.plan, + legacySlot, + legacySetup.loaded.registry.spec.gateEndpoints[0]!, + legacySubj.value, + emptyManifest, + ); + const auditReq = expectedBenchmarkRequest( + auditSetup.plan, + auditSlot, + auditSetup.loaded.registry.spec.gateEndpoints[0]!, + auditSubj.value, + emptyManifest, + ); + + // Legacy request MUST omit Stage A static audit fields and bucketScope completely + const legacyHwObj = legacyReq.targetHardware as Record; + assert.equal(Object.hasOwn(legacyHwObj, 'forbiddenSymbolPatterns'), false); + assert.equal(Object.hasOwn(legacyHwObj, 'maxRegisterCount'), false); + assert.equal(Object.hasOwn(legacyHwObj, 'maxLocalSpillBytes'), false); + assert.equal(Object.hasOwn((legacyReq.metricThresholds as Record[])[0]!, 'bucketScope'), false); + + // Audit request MUST forward all three Stage A static audit fields & bucketScope + const auditHwObj = auditReq.targetHardware as Record; + assert.deepEqual(auditHwObj.forbiddenSymbolPatterns, ['cublas', 'at::native::']); + assert.equal(auditHwObj.maxRegisterCount, 128); + assert.equal(auditHwObj.maxLocalSpillBytes, 0); + assert.equal((auditReq.metricThresholds as Record[])[1]!.bucketScope, 'all_buckets'); + assert.deepEqual((auditReq.metricThresholds as Record[])[2]!.bucketScope, { bucketId: 'bs1-isl4k' }); + + // checkedBenchmarkVerdict accepts valid bucketMetrics + hardwareDiagnostics, omits when absent, rejects invalid + const expectedBinding = { + storeId: 'store.1', + runId: 'run-a', + lockHash: auditLockRes.value.spec.lockHash, + operationId: 'op.1', + dispatchId: 'disp.1', + dispatchGeneration: 1, + gateId: 'sm90-decode-gate', + checkId: 'kernel-bench', + candidateDigest: auditSubj.value.candidateDigest.hex, + slotId: auditSlot.id, + }; + const baseVerdictBody = { + version: 1, + kind: 'benchmark_verdict', + storeId: expectedBinding.storeId, + runId: expectedBinding.runId, + lockHash: expectedBinding.lockHash, + operationId: expectedBinding.operationId, + dispatchId: expectedBinding.dispatchId, + dispatchGeneration: expectedBinding.dispatchGeneration, + gateId: expectedBinding.gateId, + checkId: expectedBinding.checkId, + candidateDigest: expectedBinding.candidateDigest, + status: 'approved', + reason: null, + expiresAtMs: String(Date.now() + 60_000), + preemptionCount: 0, + metrics: { latency_us_p50: 45 }, + hardwareProvenance: sampleProvenance(), + }; + const legacyParsed = checkedBenchmarkVerdict(baseVerdictBody, expectedBinding); + assert.equal(Object.hasOwn(legacyParsed, 'bucketMetrics'), false); + assert.equal(Object.hasOwn(legacyParsed, 'hardwareDiagnostics'), false); + + const fullParsed = checkedBenchmarkVerdict( + { ...baseVerdictBody, bucketMetrics: sampleBucketMetrics(), hardwareDiagnostics: sampleHardwareDiagnostics() }, + expectedBinding, + ); + assert.equal(Object.getPrototypeOf(fullParsed.bucketMetrics?.[0]), null); + assert.equal(Object.getPrototypeOf(fullParsed.hardwareDiagnostics), null); + assert.equal(canonical(fullParsed.bucketMetrics), canonical(sampleBucketMetrics())); + assert.equal(canonical(fullParsed.hardwareDiagnostics), canonical(sampleHardwareDiagnostics())); + + // Invalid hardwareDiagnostics / bucketMetrics rejected fail-closed + assert.throws(() => + checkedBenchmarkVerdict( + { ...baseVerdictBody, hardwareDiagnostics: { boundPipeline: 'not_a_pipeline' } }, + expectedBinding, + ), + ); + assert.throws(() => + checkedBenchmarkVerdict( + { + ...baseVerdictBody, + bucketMetrics: [{ bucketId: 'b1', metrics: { x: Number.NaN } }], + }, + expectedBinding, + ), + ); + assert.throws(() => + checkedBenchmarkVerdict( + { + ...baseVerdictBody, + bucketMetrics: [{ bucketId: 'b1', metrics: { x: 'not-a-number' } }], + }, + expectedBinding, + ), + ); + assert.throws(() => + checkedBenchmarkVerdict( + { + ...baseVerdictBody, + bucketMetrics: [ + { bucketId: 'dup', metrics: { latency_us_p50: 1 } }, + { bucketId: 'dup', metrics: { latency_us_p50: 2 } }, + ], + }, + expectedBinding, + ), + ); + + // computeBenchmarkDisposition enforces bucketScope: 'all_buckets' + const dispBadBucket = computeBenchmarkDisposition({ + verdict: checkedBenchmarkVerdict( + { ...baseVerdictBody, bucketMetrics: sampleBucketMetrics({ secondUlp: 2.5 }) }, + expectedBinding, + ), + timedOut: false, + sawPreemption: false, + wallClockValid: true, + targetHardware: auditHardware, + targetCellId: 'cuda-h100-whole', + allowSyntheticHardwareProbe: true, + metricThresholds: bucketedThresholds, + casOutcome: 'ok', + }); + assert.equal(dispBadBucket.status, 'blocked'); + assert.equal(dispBadBucket.reason, 'METRIC_THRESHOLD_FAILED'); + + // Live BenchmarkGate.run + restore() forwarding Stage A audit fields & Stage B bucketMetrics/hardwareDiagnostics onto Evidence.spec + const repoDir = join(cfgAudit.root, 'repo-bench'); + const rev = await initGitRepo(repoDir, { 'packages/kernel.cu': '// kernel\n' }); + setFixture(cfgAudit.config, ['spec', 'task', 'spec', 'target', 'baseRevision'], rev); + setFixture(cfgAudit.config, ['spec', 'task', 'spec', 'target', 'sourceRevision'], rev); + cfgAudit.input.untrustedRoots = [cfgAudit.taskDirectory, repoDir]; + await cfgAudit.save(); + const loadedRun = await cfgAudit.load(); + assert.equal(loadedRun.ok, true); + if (!loadedRun.ok) return; + const compiledRun = await compilePlan(loadedRun.value); + assert.equal(compiledRun.ok, true); + if (!compiledRun.ok) return; + const runPlan = compiledRun.value; + const runLockRes = admitTask(runPlan.task, { admissionId: 'adm-run', runId: 'run-bench-fwd' }); + assert.equal(runLockRes.ok, true); + if (!runLockRes.ok) return; + const runLock = runLockRes.value; + + const runDir = join(cfgAudit.root, 'runs', 'run-bench-fwd'); + await mkdir(join(runDir, 'artifacts'), { recursive: true, mode: 0o700 }); + const owner = await ControllerOwner.acquire(runDir, 'run-bench-fwd', runPlan.planDigest); + const artifacts = new ArtifactStore(join(runDir, 'artifacts'), owner, approvedState(loadedRun.value).vault); + const store = stateValue( + createLocalRun({ + directory: join(runDir, 'state'), + storeId: 'store.bench-fwd', + lock: runLock, + policy: { version: 1, leaseMs: 60_000, cost: 'observe_only' }, + binding: { + coreApiVersion: 'loopwright.dev/v1alpha1', + hostVersion: 'test', + adapters: [{ id: 'pi', version: '0.0.0' }], + resourceVersion: runPlan.task.spec.trustedContext.revision, + clockEpoch: 'boot.1', + }, + }), + ); + const cur = stateValue(store.inspect()); + const authority = stateValue( + store.claim({ ownerId: 'controller.' + owner.nonce, expectedGeneration: cur.owner.generation, expectedRevision: cur.revision, mode: 'active' }), + ).authority; + + try { + const frozen = await freezeSource(repoDir, runPlan.task, owner, artifacts, []); + const bounds = overlayManifestBounds(runPlan.budgets.overlay); + const manifestRef = await artifacts.json('manifest', frozen.manifest, bounds.manifestMaxBytes); + const inv: ByteInventory = { manifest: frozen.manifest, ref: manifestRef, files: frozen.artifacts }; + const bound = bindSubject(runLock, frozen.manifest, bounds.options); + assert.equal(bound.ok, true); + if (!bound.ok) return; + + const slot = runPlan.verifierSlots.find(s => s.handler.implementation === 'benchmark-gate.v1')!; + const gate = new BenchmarkGate( + store, + authority, + artifacts, + runPlan, + runLock, + ref => approvedState(loadedRun.value).vault.resolveNetworkCredential(ref), + () => bound.value, + ); + + verdictMode = 'full'; + const prep = prepareBenchmarkGate( + runPlan, + runLock, + slot.id, + inv, + 0, + '1'.repeat(32), + loadedRun.value.registry.spec.gateEndpoints, + ); + const ran = await gate.run(prep, new AbortController().signal); + assert.equal(ran.status, 'passed'); + + // Confirm outbound BenchmarkRequest carried Stage A static audit fields + assert.equal(receivedRequests.length, 1); + const sentHw = receivedRequests[0]!.targetHardware as Record; + assert.deepEqual(sentHw.forbiddenSymbolPatterns, ['cublas', 'at::native::']); + assert.equal(sentHw.maxRegisterCount, 128); + assert.equal(sentHw.maxLocalSpillBytes, 0); + + // Confirm recorded Evidence.spec carries bucketMetrics and hardwareDiagnostics verbatim + const obs = authenticatedBenchmarkGate(ran); + assert.equal(canonical(obs.evidence.spec.bucketMetrics), canonical(sampleBucketMetrics())); + assert.equal(canonical(obs.evidence.spec.hardwareDiagnostics), canonical(sampleHardwareDiagnostics())); + + // Confirm restore() reproduces identical Evidence including bucketMetrics + hardwareDiagnostics + const restored = await gate.restore(prep); + assert.equal(canonical(restored), canonical(ran)); + const restoredObs = authenticatedBenchmarkGate(restored); + assert.equal(canonical(restoredObs.evidence.spec.bucketMetrics), canonical(sampleBucketMetrics())); + assert.equal(canonical(restoredObs.evidence.spec.hardwareDiagnostics), canonical(sampleHardwareDiagnostics())); + + // Confirm legacy Stage B verdict (without bucketMetrics/hardwareDiagnostics) keeps Evidence keys omitted + verdictMode = 'legacy'; + const prepLegacy = prepareBenchmarkGate( + runPlan, + runLock, + slot.id, + inv, + 1, + '2'.repeat(32), + loadedRun.value.registry.spec.gateEndpoints, + ); + const ranLegacy = await gate.run(prepLegacy, new AbortController().signal); + assert.equal(ranLegacy.status, 'blocked'); + assert.equal(ranLegacy.reason, 'METRIC_THRESHOLD_FAILED'); // bucketScope: 'all_buckets' fails closed when bucketMetrics omitted + const legacyObs = authenticatedBenchmarkGate(ranLegacy); + assert.equal(Object.hasOwn(legacyObs.evidence.spec, 'bucketMetrics'), false); + assert.equal(Object.hasOwn(legacyObs.evidence.spec, 'hardwareDiagnostics'), false); + + // Confirm Stage B verdict with single-bucket max_ulp breach settles blocked (METRIC_THRESHOLD_FAILED) + verdictMode = 'bad_bucket_ulp'; + const prepBadBucket = prepareBenchmarkGate( + runPlan, + runLock, + slot.id, + inv, + 2, + '3'.repeat(32), + loadedRun.value.registry.spec.gateEndpoints, + ); + const ranBadBucket = await gate.run(prepBadBucket, new AbortController().signal); + assert.equal(ranBadBucket.status, 'blocked'); + assert.equal(ranBadBucket.reason, 'METRIC_THRESHOLD_FAILED'); + + // Confirm reconcileCycle accepts receipt with bucketMetrics + hardwareDiagnostics + assert.equal(typeof signBenchmarkVerdict, 'function'); + assert.equal(typeof reconcileCycle, 'function'); + } finally { + stateValue(store.release(authority)); + stateValue(store.close()); + await owner.release(); + } + } finally { + await new Promise(resolve => server.close(() => resolve())); + } + } finally { + await cfgLegacy.cleanup(); + await cfgAudit.cleanup(); + } +}); diff --git a/packages/core/src/acceptance.ts b/packages/core/src/acceptance.ts index 4a757d3..7b917e3 100644 --- a/packages/core/src/acceptance.ts +++ b/packages/core/src/acceptance.ts @@ -7,7 +7,7 @@ import { } from './contracts.js'; import { DIAGNOSTIC_CODES, attempt, fail, type Diagnostic, type Result } from './diagnostics.js'; import { artifactIssue, manifestSchema, resolveInventory, type ArtifactIssue, type ArtifactManifest, type ResolvedArtifactInput } from './artifacts.js'; -import { claimSchema, evidenceSchema, type Evidence, type SubmittedCheck } from './evidence.js'; +import { claimSchema, evidenceSchema, type BucketMetricEntry, type Evidence, type SubmittedCheck } from './evidence.js'; import { unique } from './graph.js'; import { deriveSubject, lockSchema, matchSubject, subjectSchema, type TaskLock } from './identity.js'; import { LIMITS, type OverlayLimitOptions, type OverlayLimits } from './limits.js'; @@ -40,36 +40,75 @@ function readFiniteMetric(metrics: MetricsMap, key: string): number | undefined return Object.is(raw, -0) ? 0 : raw; } -function evaluateMetricThresholds( +function evaluateSingleMetricRule(rule: MetricThresholdRule, metrics: MetricsMap): boolean { + const value = readFiniteMetric(metrics, rule.metric); + if (value === undefined) return false; + if (rule.kind === 'bounds') { + if (rule.min !== undefined && value < rule.min) return false; + if (rule.max !== undefined && value > rule.max) return false; + return true; + } + // Comparative rules always evaluate both metric and baselineMetric within the same scope + // (aggregate or the same bucket), never falling back across scopes. + const baseline = readFiniteMetric(metrics, rule.baselineMetric); + if (baseline === undefined) return false; + if (rule.operator === 'min_ratio') { + if (!(baseline > 0)) return false; + const ratio = value / baseline; + return !Number.isNaN(ratio) && ratio >= rule.threshold; + } + if (rule.operator === 'max_ratio') { + if (!(baseline > 0)) return false; + const ratio = value / baseline; + return !Number.isNaN(ratio) && ratio <= rule.threshold; + } + const delta = value - baseline; + return !Number.isNaN(delta) && delta <= rule.threshold; +} + +function findMetricThresholdFailurePath( rules: readonly MetricThresholdRule[], metrics: MetricsMap | undefined, -): boolean { - if (rules.length === 0) return true; - if (metrics === undefined) return false; + bucketMetrics: readonly BucketMetricEntry[] | undefined, + evidenceSpecPath: string, +): string | null { + if (rules.length === 0) return null; for (const rule of rules) { - const value = readFiniteMetric(metrics, rule.metric); - if (value === undefined) return false; - if (rule.kind === 'bounds') { - if (rule.min !== undefined && value < rule.min) return false; - if (rule.max !== undefined && value > rule.max) return false; + const scope = rule.bucketScope ?? 'aggregate'; + if (scope === 'aggregate') { + if (metrics === undefined || !evaluateSingleMetricRule(rule, metrics)) { + return `${evidenceSpecPath}/metrics`; + } continue; } - const baseline = readFiniteMetric(metrics, rule.baselineMetric); - if (baseline === undefined) return false; - if (rule.operator === 'min_ratio') { - if (!(baseline > 0)) return false; - const ratio = value / baseline; - if (Number.isNaN(ratio) || ratio < rule.threshold) return false; - } else if (rule.operator === 'max_ratio') { - if (!(baseline > 0)) return false; - const ratio = value / baseline; - if (Number.isNaN(ratio) || ratio > rule.threshold) return false; - } else { - const delta = value - baseline; - if (Number.isNaN(delta) || delta > rule.threshold) return false; + if (bucketMetrics === undefined || bucketMetrics.length === 0) { + return `${evidenceSpecPath}/bucketMetrics`; + } + if (scope === 'all_buckets') { + for (let index = 0; index < bucketMetrics.length; index++) { + if (!evaluateSingleMetricRule(rule, bucketMetrics[index]!.metrics)) { + return `${evidenceSpecPath}/bucketMetrics/${index}/metrics`; + } + } + continue; + } + const bucketIndex = bucketMetrics.findIndex(entry => entry.bucketId === scope.bucketId); + if (bucketIndex === -1) { + return `${evidenceSpecPath}/bucketMetrics`; + } + if (!evaluateSingleMetricRule(rule, bucketMetrics[bucketIndex]!.metrics)) { + return `${evidenceSpecPath}/bucketMetrics/${bucketIndex}/metrics`; } } - return true; + return null; +} + +export function evaluateMetricThresholds( + rules: readonly MetricThresholdRule[], + metrics: MetricsMap | undefined, + bucketMetrics?: readonly BucketMetricEntry[], +): boolean { + return findMetricThresholdFailurePath(rules, metrics, bucketMetrics, '') === null; } export interface EvaluationInput { @@ -335,8 +374,14 @@ export function evaluateValidated( } } if (requirement.metricThresholds !== undefined && requirement.metricThresholds.length > 0) { - if (!evaluateMetricThresholds(requirement.metricThresholds, evidence.spec.metrics)) { - return blocked('METRIC_THRESHOLD_FAILED', 'metric_threshold_failed', `${evidenceSpecPath}/metrics`); + const failedThresholdPath = findMetricThresholdFailurePath( + requirement.metricThresholds, + evidence.spec.metrics, + evidence.spec.bucketMetrics, + evidenceSpecPath, + ); + if (failedThresholdPath !== null) { + return blocked('METRIC_THRESHOLD_FAILED', 'metric_threshold_failed', failedThresholdPath); } } return withMetadata( diff --git a/packages/core/src/contracts.ts b/packages/core/src/contracts.ts index 7424e3f..fc9a961 100644 --- a/packages/core/src/contracts.ts +++ b/packages/core/src/contracts.ts @@ -3,6 +3,7 @@ import { attempt, fail, type Result } from './diagnostics.js'; import { LIMITS, OVERLAY_LIMITS, type OverlayLimits } from './limits.js'; import { graphBounds, unique, validateGraph } from './graph.js'; import { isVerifierNamespacePath, matches, relativeName, scopePattern } from './scope.js'; +import { SecretScrubber } from './scrubber.js'; export type Schema = (value: Json, path: string) => T; export type Infer = S extends Schema ? T : never; @@ -149,11 +150,14 @@ export const mediaType: Schema = (value, path) => { return mime; }; -const FORBIDDEN_PROTOTYPE_KEYS = new Set(['__proto__', 'constructor', 'prototype']); +export const FORBIDDEN_PROTOTYPE_KEYS = new Set(['__proto__', 'constructor', 'prototype']); const FORBIDDEN_METRIC_KEYS = FORBIDDEN_PROTOTYPE_KEYS; const METRIC_KEY_RE = /^[A-Za-z_][A-Za-z0-9._-]*$/; +const BUCKET_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]*$/; +const FORBIDDEN_SYMBOL_GLOB_RE = /[*?[\]]/; const LONE_SURROGATE_RE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(? { return (value, path) => { @@ -173,6 +177,15 @@ export function printableText(min = 1, max: number = LIMITS.string): Schema(schema: Schema, min: number, max: number): Schema { + const base = arrayOf(schema, min, max); + return (value, path) => { + const items = base(value, path); + unique(items, path); + return items; + }; +} + function parseDottedVersion(value: string): readonly number[] | null { if (!value.length || !DOTTED_VERSION_RE.test(value)) return null; const segments: number[] = []; @@ -213,6 +226,12 @@ const driverConstraintSchema: Schema = (value, path) => { return constraint; }; +const forbiddenSymbolPatternSchema: Schema = (value, path) => { + const parsed = printableAscii(1, LIMITS.forbiddenSymbolPattern)(value, path); + if (FORBIDDEN_SYMBOL_GLOB_RE.test(parsed)) fail('PATTERN_UNSUPPORTED', path); + return parsed; +}; + export const hardwareIsolationMode = enumeration('whole_device', 'sliced'); export interface HardwareTargetSpec { readonly accelerator: string; @@ -220,6 +239,9 @@ export interface HardwareTargetSpec { readonly deviceCount?: number; readonly driverConstraint?: string; readonly topology?: string; + readonly forbiddenSymbolPatterns?: readonly string[]; + readonly maxRegisterCount?: number; + readonly maxLocalSpillBytes?: number; } export const hardwareTargetSchema: Schema = record({ accelerator: printableAscii(1, 64), @@ -227,9 +249,12 @@ export const hardwareTargetSchema: Schema = record({ deviceCount: optional(integer(1, 64)), driverConstraint: optional(driverConstraintSchema), topology: optional(printableText(1, 128)), + forbiddenSymbolPatterns: optional(uniqueArrayOf(forbiddenSymbolPatternSchema, 0, LIMITS.forbiddenSymbolPatterns)), + maxRegisterCount: optional(integer(0)), + maxLocalSpillBytes: optional(integer(0)), }); -function isValidMetricKey(key: string): boolean { +export function isValidMetricKey(key: string): boolean { return key.length >= 1 && key.length <= LIMITS.metricKey && !FORBIDDEN_METRIC_KEYS.has(key) && METRIC_KEY_RE.test(key); @@ -241,6 +266,38 @@ const metricKeySchema: Schema = (value, path) => { return value; }; +export function validateBucketId( + value: Json, + path: string, + scrubber: SecretScrubber = DEFAULT_SECRET_SCRUBBER, +): string { + const parsed = text(1, LIMITS.bucketId)(value, path); + if (FORBIDDEN_PROTOTYPE_KEYS.has(parsed) || !BUCKET_ID_RE.test(parsed)) fail('IDENTIFIER_INVALID', path); + if (scrubber.containsSecret(parsed)) fail('VALUE_RANGE', path); + return parsed; +} + +export const bucketIdSchema: Schema = (value, path) => validateBucketId(value, path); + +export type MetricBucketScope = + | 'aggregate' + | 'all_buckets' + | { readonly bucketId: string }; + +const bucketScopeTargetShape = record({ + bucketId: bucketIdSchema, +}); + +export const metricBucketScopeSchema: Schema = (value, path) => { + if (typeof value === 'string') { + return enumeration('aggregate', 'all_buckets')(value, path); + } + if (value !== null && typeof value === 'object' && !Array.isArray(value)) { + return bucketScopeTargetShape(value, path); + } + fail('VALUE_TYPE', path); +}; + const finiteNumber: Schema = (value, path) => { if (typeof value !== 'number') fail('VALUE_TYPE', path); if (!Number.isFinite(value)) fail('VALUE_RANGE', path); @@ -252,6 +309,7 @@ export interface MetricBoundsRule { readonly metric: string; readonly min?: number; readonly max?: number; + readonly bucketScope?: MetricBucketScope; } export interface MetricComparativeRule { readonly kind: 'comparative'; @@ -259,6 +317,7 @@ export interface MetricComparativeRule { readonly baselineMetric: string; readonly operator: 'min_ratio' | 'max_ratio' | 'max_delta'; readonly threshold: number; + readonly bucketScope?: MetricBucketScope; } export type MetricThresholdRule = MetricBoundsRule | MetricComparativeRule; @@ -267,6 +326,7 @@ const metricBoundsShape = record({ metric: metricKeySchema, min: optional(finiteNumber), max: optional(finiteNumber), + bucketScope: optional(metricBucketScopeSchema), }); const metricComparativeShape = record({ kind: enumeration('comparative'), @@ -274,6 +334,7 @@ const metricComparativeShape = record({ baselineMetric: metricKeySchema, operator: enumeration('min_ratio', 'max_ratio', 'max_delta'), threshold: finiteNumber, + bucketScope: optional(metricBucketScopeSchema), }); export const metricThresholdRuleSchema: Schema = (value, path) => { @@ -350,15 +411,6 @@ export const reworkPolicySchema = record({ }); export type ReworkPolicy = Infer; -function uniqueArrayOf(schema: Schema, min: number, max: number): Schema { - const base = arrayOf(schema, min, max); - return (value, path) => { - const items = base(value, path); - unique(items, path); - return items; - }; -} - const handoffHeadingSchema: Schema = (value, path) => { const raw = text(1, LIMITS.handoffHeading)(value, path); if (/[\r\n\0\p{C}]/u.test(raw) || raw.trim().length === 0) fail('VALUE_RANGE', path); diff --git a/packages/core/src/diagnostics.ts b/packages/core/src/diagnostics.ts index e9668c7..e06a21e 100644 --- a/packages/core/src/diagnostics.ts +++ b/packages/core/src/diagnostics.ts @@ -1,3 +1,7 @@ +export const STAGE_A_STATIC_AUDIT_FAILED = 'STAGE_A_STATIC_AUDIT_FAILED' as const; +export const TEAM_ENVELOPE_VIOLATION = 'TEAM_ENVELOPE_VIOLATION' as const; +export const EXPORT_UNVERIFIED_FORBIDDEN = 'EXPORT_UNVERIFIED_FORBIDDEN' as const; + export const DIAGNOSTIC_CODES = Object.freeze([ 'INPUT_TYPE', 'INPUT_UNSUPPORTED', 'INPUT_CYCLE', 'INPUT_ALIAS', 'LIMIT_BYTES', 'LIMIT_DEPTH', 'LIMIT_STRING', 'LIMIT_COLLECTION', 'LIMIT_NODES', @@ -12,6 +16,7 @@ export const DIAGNOSTIC_CODES = Object.freeze([ 'RUN_RECONCILIATION_REQUIRED', 'CHECK_MISSING', 'EVIDENCE_MISSING', 'EVIDENCE_LEVEL_DISALLOWED', 'ARTIFACT_MISSING', 'ARTIFACT_LENGTH_MISMATCH', 'ARTIFACT_DIGEST_MISMATCH', 'HARDWARE_PROVENANCE_MISMATCH', 'METRIC_THRESHOLD_FAILED', + STAGE_A_STATIC_AUDIT_FAILED, TEAM_ENVELOPE_VIOLATION, EXPORT_UNVERIFIED_FORBIDDEN, ] as const); export type DiagnosticCode = typeof DIAGNOSTIC_CODES[number]; diff --git a/packages/core/src/evidence.ts b/packages/core/src/evidence.ts index a24b0f1..7d15755 100644 --- a/packages/core/src/evidence.ts +++ b/packages/core/src/evidence.ts @@ -1,14 +1,20 @@ +import { snapshot, type Json } from './boundary.js'; import { artifactRefSchema, arrayOf, checkStatus, digestSchema, document, driverVersionSchema, enumeration, - evidenceLevel, findingsSchema, hardwareIsolationMode, identifier, integer, metricsSchema, nullable, - optional, printableAscii, printableText, record, text, type Digest, type Infer, type Schema, + evidenceLevel, findingsSchema, FORBIDDEN_PROTOTYPE_KEYS, hardwareIsolationMode, identifier, integer, + isValidMetricKey, metricsSchema, nullable, object, optional, printableAscii, printableText, record, + text, validateBucketId, type Digest, type Infer, type MetricsMap, type MetricValue, type Schema, } from './contracts.js'; -import { fail } from './diagnostics.js'; +import { attempt, fail, type Result } from './diagnostics.js'; import { unique } from './graph.js'; import { subjectSchema } from './identity.js'; import { LIMITS, VERIFIER_ARTIFACT_LIMITS } from './limits.js'; import { isVerifierNamespacePath, parseVerifierArtifactPath } from './scope.js'; -import type { Json } from './boundary.js'; +import { SecretScrubber } from './scrubber.js'; + +const DEFAULT_SECRET_SCRUBBER = new SecretScrubber(); +const BUCKET_DIMENSION_STRING_RE = /^[A-Za-z0-9][A-Za-z0-9._:/+-]*$/; +const STALL_REASON_RE = /^[A-Za-z][A-Za-z0-9._:-]*$/; export interface HardwareProvenance { readonly targetCellId: string; @@ -40,6 +46,175 @@ const hardwareProvenanceSchema: Schema = record({ clockLockMode: enumeration('locked', 'unlocked', 'unknown'), }); +export type BucketDimensionValue = number | string; +export type BucketDimensionsMap = Readonly>; +export interface BucketMetricEntry { + readonly bucketId: string; + readonly dimensions?: BucketDimensionsMap; + readonly metrics: MetricsMap; +} + +function makeBucketDimensionsSchema(scrubber: SecretScrubber): Schema { + return (value, path) => { + const input = object(value, path); + const keys = Object.keys(input).sort(); + if (keys.length > LIMITS.bucketDimensionEntries) fail('VALUE_RANGE', path); + const output: Record = Object.create(null) as Record; + for (const key of keys) { + if (!Object.hasOwn(input, key)) continue; + if (!isValidMetricKey(key)) fail('IDENTIFIER_INVALID', path); + const entryPath = `${path}/${key}`; + if (scrubber.containsSecret(key)) fail('VALUE_RANGE', entryPath); + const raw = input[key]; + if (typeof raw === 'number') { + if (!Number.isFinite(raw) || Object.is(raw, -0)) fail('VALUE_RANGE', entryPath); + output[key] = raw; + } else if (typeof raw === 'string') { + if ( + raw.length < 1 + || raw.length > LIMITS.bucketDimensionStringValue + || !BUCKET_DIMENSION_STRING_RE.test(raw) + || scrubber.containsSecret(raw) + ) { + fail('VALUE_RANGE', entryPath); + } + output[key] = raw; + } else { + fail('VALUE_TYPE', entryPath); + } + } + return output; + }; +} + +function makeBucketNumericMetricsSchema(scrubber: SecretScrubber): Schema { + return (value, path) => { + const input = object(value, path); + const keys = Object.keys(input).sort(); + if (keys.length > LIMITS.bucketMetricEntries) fail('VALUE_RANGE', path); + const output: Record = Object.create(null) as Record; + for (const key of keys) { + if (!Object.hasOwn(input, key)) continue; + if (!isValidMetricKey(key)) fail('IDENTIFIER_INVALID', path); + const entryPath = `${path}/${key}`; + if (scrubber.containsSecret(key)) fail('VALUE_RANGE', entryPath); + const raw = input[key]; + if (typeof raw !== 'number') fail('VALUE_TYPE', entryPath); + if (!Number.isFinite(raw) || Object.is(raw, -0)) fail('VALUE_RANGE', entryPath); + output[key] = raw; + } + return output; + }; +} + +function makeBucketMetricsSchema(scrubber: SecretScrubber): Schema { + const entrySchema: Schema = record({ + bucketId: (value: Json, path: string) => validateBucketId(value, path, scrubber), + dimensions: optional(makeBucketDimensionsSchema(scrubber)), + metrics: makeBucketNumericMetricsSchema(scrubber), + }); + const listSchema = arrayOf(entrySchema, 1, LIMITS.bucketMetrics); + return (value, path) => { + const entries = listSchema(value, path); + unique(entries.map(entry => entry.bucketId), path); + return entries; + }; +} + +export const bucketMetricsSchema: Schema = makeBucketMetricsSchema(DEFAULT_SECRET_SCRUBBER); + +export function validateBucketMetrics( + input: unknown, + scrubber: SecretScrubber = DEFAULT_SECRET_SCRUBBER, +): Result { + return attempt(() => makeBucketMetricsSchema(scrubber)(snapshot(input), '')); +} + +export const HARDWARE_BOUND_PIPELINES = Object.freeze([ + 'hbm', + 'l2', + 'smem_lds_ub', + 'tensor_cube', + 'vector_valu', + 'host_launch', + 'comm', + 'unknown', +] as const); +export type HardwareBoundPipeline = typeof HARDWARE_BOUND_PIPELINES[number]; + +export interface HardwareStallReason { + readonly reason: string; + readonly pct: number; +} + +export interface HardwareDiagnostics { + readonly boundPipeline: HardwareBoundPipeline; + readonly rooflineHeadroom?: number; + readonly achievedSolPct?: number; + readonly arithmeticIntensity?: number; + readonly occupancyPct?: number; + readonly registerCount?: number; + readonly sharedMemBytes?: number; + readonly localSpillBytes?: number; + readonly l2HitPct?: number; + readonly bankConflictPct?: number; + readonly topStallReasons?: readonly HardwareStallReason[]; +} + +const nonNegativeFiniteNumber: Schema = (value, path) => { + if (typeof value !== 'number') fail('VALUE_TYPE', path); + if (!Number.isFinite(value) || Object.is(value, -0) || value < 0) fail('VALUE_RANGE', path); + return value; +}; + +const percentageNumber: Schema = (value, path) => { + if (typeof value !== 'number') fail('VALUE_TYPE', path); + if (!Number.isFinite(value) || Object.is(value, -0) || value < 0 || value > 100) fail('VALUE_RANGE', path); + return value; +}; + +function makeHardwareDiagnosticsSchema(scrubber: SecretScrubber): Schema { + const stallReasonTextSchema: Schema = (value, path) => { + const parsed = text(1, LIMITS.hardwareStallReason)(value, path); + if (FORBIDDEN_PROTOTYPE_KEYS.has(parsed) || !STALL_REASON_RE.test(parsed)) fail('IDENTIFIER_INVALID', path); + if (scrubber.containsSecret(parsed)) fail('VALUE_RANGE', path); + return parsed; + }; + const stallReasonEntrySchema: Schema = record({ + reason: stallReasonTextSchema, + pct: percentageNumber, + }); + const stallReasonsListSchema = arrayOf(stallReasonEntrySchema, 0, LIMITS.hardwareStallReasons); + const uniqueStallReasonsSchema: Schema = (value, path) => { + const items = stallReasonsListSchema(value, path); + unique(items.map(item => item.reason), path); + return items; + }; + + return record({ + boundPipeline: enumeration(...HARDWARE_BOUND_PIPELINES), + rooflineHeadroom: optional(nonNegativeFiniteNumber), + achievedSolPct: optional(percentageNumber), + arithmeticIntensity: optional(nonNegativeFiniteNumber), + occupancyPct: optional(percentageNumber), + registerCount: optional(integer(0)), + sharedMemBytes: optional(integer(0)), + localSpillBytes: optional(integer(0)), + l2HitPct: optional(percentageNumber), + bankConflictPct: optional(percentageNumber), + topStallReasons: optional(uniqueStallReasonsSchema), + }); +} + +export const hardwareDiagnosticsSchema: Schema = makeHardwareDiagnosticsSchema(DEFAULT_SECRET_SCRUBBER); + +export function validateHardwareDiagnostics( + input: unknown, + scrubber: SecretScrubber = DEFAULT_SECRET_SCRUBBER, +): Result { + return attempt(() => makeHardwareDiagnosticsSchema(scrubber)(snapshot(input), '')); +} + const evidenceShape = document('Evidence', record({ checkId: identifier, observedStatus: checkStatus, producerId: identifier, method: identifier, level: evidenceLevel, subject: subjectSchema, @@ -48,6 +223,8 @@ const evidenceShape = document('Evidence', record({ metrics: optional(metricsSchema), findings: optional(findingsSchema), hardwareProvenance: optional(hardwareProvenanceSchema), + bucketMetrics: optional(bucketMetricsSchema), + hardwareDiagnostics: optional(hardwareDiagnosticsSchema), })); export type Evidence = Infer; export function evidenceSchema(value: Json, path = ''): Evidence { diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 1baa511..d14c256 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -3,7 +3,10 @@ export { LIMITS, OVERLAY_LIMITS, HANDOFF_LIMITS, VERIFIER_ARTIFACT_LIMITS, type OverlayLimits, type OverlayLimitsInput, type OverlayLimitOptions, } from './limits.js'; -export { DIAGNOSTIC_CODES, type DiagnosticCode, type Diagnostic, type Result } from './diagnostics.js'; +export { + DIAGNOSTIC_CODES, STAGE_A_STATIC_AUDIT_FAILED, TEAM_ENVELOPE_VIOLATION, EXPORT_UNVERIFIED_FORBIDDEN, + type DiagnosticCode, type Diagnostic, type Result, +} from './diagnostics.js'; export { matchesScopePattern, validateScopePattern, validateRelativePath, isVerifierNamespacePath, parseVerifierArtifactPath, type VerifierArtifactPath, @@ -14,7 +17,8 @@ export { type MetricValue, type MetricsMap, type FindingSeverity, type StructuredFinding, type StepHandoffSource, type StepHandoffSelect, type StepHandoffSelector, type ResourceActivationPhase, type ResourceActivationRule, - type HardwareTargetSpec, type MetricBoundsRule, type MetricComparativeRule, type MetricThresholdRule, + type HardwareTargetSpec, type MetricBucketScope, type MetricBoundsRule, type MetricComparativeRule, + type MetricThresholdRule, } from './contracts.js'; export { admitTask, identifyManifest, bindSubject, type TaskLock, type Subject } from './identity.js'; export { @@ -23,10 +27,15 @@ export { type BaseTreeAnchor, type ResolvedArtifact, type ResolvedArtifactInput, type VerifiedArtifactDescriptor, } from './artifacts.js'; export { - evaluateAcceptance, matchesHardwareTarget, + evaluateAcceptance, evaluateMetricThresholds, matchesHardwareTarget, type VerificationResult, type EvaluatedCheck, } from './acceptance.js'; -export type { Evidence, HardwareProvenance, SubmittedCheck } from './evidence.js'; +export { + HARDWARE_BOUND_PIPELINES, validateBucketMetrics, validateHardwareDiagnostics, + type Evidence, type HardwareProvenance, type SubmittedCheck, + type BucketDimensionValue, type BucketDimensionsMap, type BucketMetricEntry, + type HardwareBoundPipeline, type HardwareStallReason, type HardwareDiagnostics, +} from './evidence.js'; export { aggregateUsage, type RequestUsage, type Quantity, type Aggregate, type UsageSummary } from './usage.js'; export { SecretScrubber } from './scrubber.js'; export { constructRunResult, type RunResult, type RunStatus, type MemoryObservation, type NoChangeVerification } from './results.js'; diff --git a/packages/core/src/limits.ts b/packages/core/src/limits.ts index 923f0f7..0ddb2fc 100644 --- a/packages/core/src/limits.ts +++ b/packages/core/src/limits.ts @@ -49,6 +49,10 @@ export const LIMITS = Object.freeze({ checks: 256, evidence: 256, manifest: 256, overlayEntries: 128, baselineEntries: 65_536, requests: 1_024, resolvedArtifacts: 512, artifactBytes: 67_108_864, resolvedBytes: 134_217_728, metricEntries: 64, metricKey: 64, metricStringValue: 256, metricThresholds: 32, + forbiddenSymbolPatterns: 64, forbiddenSymbolPattern: 128, + bucketMetrics: 64, bucketId: 64, bucketMetricEntries: 16, + bucketDimensionEntries: 8, bucketDimensionStringValue: 64, + hardwareStallReasons: 16, hardwareStallReason: 64, findings: 64, findingTitle: 256, findingEvidence: 2_048, artifactUri: 2_048, mediaType: 128, maxReworks: 8, handoffsPerStep: HANDOFF_LIMITS.maxPerStep, diff --git a/packages/core/test/evolution-contracts.test.ts b/packages/core/test/evolution-contracts.test.ts new file mode 100644 index 0000000..862acdc --- /dev/null +++ b/packages/core/test/evolution-contracts.test.ts @@ -0,0 +1,875 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { + admitTask, + bindSubject, + constructRunResult, + evaluateAcceptance, + evaluateMetricThresholds, + validateBucketMetrics, + validateDocument, + validateHardwareDiagnostics, + DIAGNOSTIC_CODES, + EXPORT_UNVERIFIED_FORBIDDEN, + HARDWARE_BOUND_PIPELINES, + LIMITS, + SecretScrubber, + STAGE_A_STATIC_AUDIT_FAILED, + TEAM_ENVELOPE_VIOLATION, + type BucketMetricEntry, + type Digest, + type HardwareDiagnostics, + type HardwareProvenance, + type HardwareTargetSpec, + type MetricBucketScope, + type MetricThresholdRule, +} from '../src/index.js'; +import { hardwareTargetSchema } from '../src/contracts.js'; +import { bucketMetricsSchema, hardwareDiagnosticsSchema } from '../src/evidence.js'; +import { canonical } from '../src/identity.js'; +import { contract, evaluationFixture, value, code } from './fixtures.js'; + +const ADMISSION = { admissionId: 'admission-1', runId: 'run-1' }; +const WORKLOAD_DIGEST: Digest = { algorithm: 'sha256', hex: 'd'.repeat(64) }; + +function makeProvenance(overrides?: Partial): HardwareProvenance { + return { + targetCellId: 'h100-sm90', + probeKind: 'physical', + vendor: 'NVIDIA', + deviceModel: 'NVIDIA H100 80GB HBM3', + accelerator: 'sm_90a', + isolationMode: 'whole_device', + deviceCount: 1, + driverVersion: '550.54.15', + runtimeVersion: 'cuda-12.4', + topology: 'nvlink-8x', + workloadDigest: { ...WORKLOAD_DIGEST }, + clockLockMode: 'locked', + ...overrides, + }; +} + +function makeHardwareEvaluation(options?: { + readonly hardware?: HardwareTargetSpec; + readonly metricThresholds?: readonly MetricThresholdRule[]; + readonly metrics?: Record; + readonly bucketMetrics?: readonly BucketMetricEntry[]; + readonly hardwareDiagnostics?: HardwareDiagnostics; +}) { + const task = contract(); + const hardware: HardwareTargetSpec = options?.hardware ?? { + accelerator: 'sm_90a', + isolationMode: 'whole_device', + deviceCount: 1, + driverConstraint: '>=550.54.15', + topology: 'nvlink-8x', + }; + Object.assign(task.spec.target, { + matrix: [{ + id: 'h100-sm90', + platform: 'linux', + variant: 'cuda', + hardware, + }], + }); + Object.assign(task.spec.acceptance.checks[0]!, { + allowedEvidenceLevels: ['hardware_execution'], + targetCellId: 'h100-sm90', + ...(options?.metricThresholds !== undefined ? { metricThresholds: options.metricThresholds } : {}), + }); + const fixture = evaluationFixture(task); + Object.assign(fixture.input.trusted.eligibleEvidence[0]!.spec, { + level: 'hardware_execution', + hardwareProvenance: makeProvenance(), + ...(options?.metrics !== undefined ? { metrics: options.metrics } : {}), + ...(options?.bucketMetrics !== undefined ? { bucketMetrics: options.bucketMetrics } : {}), + ...(options?.hardwareDiagnostics !== undefined ? { hardwareDiagnostics: options.hardwareDiagnostics } : {}), + }); + return fixture; +} + +test('evolution diagnostic constants are exported and registered in frozen DIAGNOSTIC_CODES', () => { + assert.equal(STAGE_A_STATIC_AUDIT_FAILED, 'STAGE_A_STATIC_AUDIT_FAILED'); + assert.equal(TEAM_ENVELOPE_VIOLATION, 'TEAM_ENVELOPE_VIOLATION'); + assert.equal(EXPORT_UNVERIFIED_FORBIDDEN, 'EXPORT_UNVERIFIED_FORBIDDEN'); + assert.equal(DIAGNOSTIC_CODES.includes(STAGE_A_STATIC_AUDIT_FAILED), true); + assert.equal(DIAGNOSTIC_CODES.includes(TEAM_ENVELOPE_VIOLATION), true); + assert.equal(DIAGNOSTIC_CODES.includes(EXPORT_UNVERIFIED_FORBIDDEN), true); + assert.equal(Object.isFrozen(DIAGNOSTIC_CODES), true); + + // New diagnostic codes validate cleanly inside VerificationResult.spec.diagnostics + const fixture = evaluationFixture(); + const baseResult = value(evaluateAcceptance(fixture.input, fixture.artifacts)); + const withEvolutionDiagnostics = { + ...baseResult, + spec: { + ...baseResult.spec, + diagnostics: [ + { code: STAGE_A_STATIC_AUDIT_FAILED, path: '/stageA', checkId: 'tests' }, + { code: TEAM_ENVELOPE_VIOLATION, path: '/teamPatch', checkId: null }, + { code: EXPORT_UNVERIFIED_FORBIDDEN, path: '/bundle', checkId: null }, + ], + }, + }; + assert.equal(validateDocument(withEvolutionDiagnostics, 'VerificationResult').ok, true); +}); + +test('HardwareTargetSpec Stage A static audit fields validate bounds and preserve legacy canonical digests when omitted', () => { + const baseTask = contract(); + Object.assign(baseTask.spec.target, { + matrix: [{ + id: 'h100-sm90', + platform: 'linux', + variant: 'cuda', + hardware: { + accelerator: 'sm_90a', + isolationMode: 'whole_device', + deviceCount: 1, + driverConstraint: '>=550.54.15', + topology: 'nvlink-8x', + }, + }], + }); + const baseLock = value(admitTask(baseTask, ADMISSION)); + const baseHw = baseLock.spec.contract.spec.target.matrix![0]!.hardware!; + assert.equal(Object.hasOwn(baseHw, 'forbiddenSymbolPatterns'), false); + assert.equal(Object.hasOwn(baseHw, 'maxRegisterCount'), false); + assert.equal(Object.hasOwn(baseHw, 'maxLocalSpillBytes'), false); + + const manifest = { + apiVersion: 'loopwright.dev/v1alpha1', + kind: 'ArtifactManifest', + metadata: { id: 'candidate' }, + spec: { entries: [] }, + }; + const baseSubject = value(bindSubject(baseLock, manifest)); + + // Valid Stage A static audit fields: empty patterns (0), realistic patterns, 64 patterns, 0 ceilings + const withHardware = (hardware: unknown) => { + const task = contract(); + Object.assign(task.spec.target, { + matrix: [{ id: 'h100-sm90', platform: 'linux', variant: 'cuda', hardware }], + }); + return validateDocument(task, 'TaskContract'); + }; + + const fullHw: HardwareTargetSpec = { + accelerator: 'sm_90a', + isolationMode: 'whole_device', + forbiddenSymbolPatterns: ['cublas', 'cudnn', 'rocblas', 'miopen', 'aclnn', 'at::native::', 'torch_cuda'], + maxRegisterCount: 128, + maxLocalSpillBytes: 0, + }; + const parsedFull = value(withHardware(fullHw)); + const parsedHw = parsedFull.spec.target.matrix![0]!.hardware!; + assert.equal(Object.getPrototypeOf(parsedHw), null); + assert.deepEqual(parsedHw.forbiddenSymbolPatterns, fullHw.forbiddenSymbolPatterns); + assert.equal(parsedHw.maxRegisterCount, 128); + assert.equal(parsedHw.maxLocalSpillBytes, 0); + + // Adding Stage A static audit fields changes targetMatrixDigest, contractHash, and lockHash + const auditTask = contract(); + Object.assign(auditTask.spec.target, { + matrix: [{ + id: 'h100-sm90', + platform: 'linux', + variant: 'cuda', + hardware: { + accelerator: 'sm_90a', + isolationMode: 'whole_device', + deviceCount: 1, + driverConstraint: '>=550.54.15', + topology: 'nvlink-8x', + forbiddenSymbolPatterns: ['cublas'], + maxRegisterCount: 255, + maxLocalSpillBytes: 0, + }, + }], + }); + const auditLock = value(admitTask(auditTask, ADMISSION)); + const auditSubject = value(bindSubject(auditLock, manifest)); + assert.notEqual(auditSubject.targetMatrixDigest?.hex, baseSubject.targetMatrixDigest?.hex); + assert.notEqual(auditLock.spec.contractHash.hex, baseLock.spec.contractHash.hex); + assert.notEqual(auditLock.spec.lockHash.hex, baseLock.spec.lockHash.hex); + + // Boundary counts: 0 patterns, 64 patterns (max length 128), 65 rejected + assert.equal(withHardware({ accelerator: 'sm_90a', isolationMode: 'whole_device', forbiddenSymbolPatterns: [] }).ok, true); + const patterns64 = Array.from({ length: LIMITS.forbiddenSymbolPatterns }, (_, i) => `sym_${String(i).padStart(2, '0')}`); + assert.equal(withHardware({ accelerator: 'sm_90a', isolationMode: 'whole_device', forbiddenSymbolPatterns: patterns64 }).ok, true); + assert.equal( + withHardware({ + accelerator: 'sm_90a', + isolationMode: 'whole_device', + forbiddenSymbolPatterns: ['a'.repeat(LIMITS.forbiddenSymbolPattern)], + }).ok, + true, + ); + assert.equal( + code(withHardware({ accelerator: 'sm_90a', isolationMode: 'whole_device', forbiddenSymbolPatterns: [...patterns64, 'extra'] })), + 'VALUE_RANGE', + ); + + // Invalid forbiddenSymbolPatterns entries + for (const badPattern of ['', ' cublas', 'cublas ', 'cublas\n', 'cublas\t', 'c\u00FCblas', 'a'.repeat(LIMITS.forbiddenSymbolPattern + 1)]) { + assert.equal( + code(withHardware({ accelerator: 'sm_90a', isolationMode: 'whole_device', forbiddenSymbolPatterns: [badPattern] })), + 'VALUE_RANGE', + badPattern, + ); + } + assert.equal( + code(withHardware({ accelerator: 'sm_90a', isolationMode: 'whole_device', forbiddenSymbolPatterns: ['cublas\uD800'] })), + 'INPUT_UNSUPPORTED', + ); + for (const globPattern of ['cublas*', 'cublas?', 'cublas[0]', 'cublas]']) { + assert.equal( + code(withHardware({ accelerator: 'sm_90a', isolationMode: 'whole_device', forbiddenSymbolPatterns: [globPattern] })), + 'PATTERN_UNSUPPORTED', + globPattern, + ); + } + assert.equal( + code(withHardware({ accelerator: 'sm_90a', isolationMode: 'whole_device', forbiddenSymbolPatterns: ['cublas', 'cublas'] })), + 'DUPLICATE_ID', + ); + assert.equal( + code(withHardware({ accelerator: 'sm_90a', isolationMode: 'whole_device', forbiddenSymbolPatterns: [123] })), + 'VALUE_TYPE', + ); + + // maxRegisterCount and maxLocalSpillBytes bounds and type checks + assert.equal(withHardware({ accelerator: 'sm_90a', isolationMode: 'whole_device', maxRegisterCount: 0, maxLocalSpillBytes: 0 }).ok, true); + for (const field of ['maxRegisterCount', 'maxLocalSpillBytes'] as const) { + for (const badNum of [-1, 1.5, NaN, Infinity, -Infinity, Number.MAX_SAFE_INTEGER + 1]) { + assert.equal( + code(withHardware({ accelerator: 'sm_90a', isolationMode: 'whole_device', [field]: badNum })), + 'VALUE_RANGE', + `${field}=${String(badNum)}`, + ); + } + assert.equal( + code(withHardware({ accelerator: 'sm_90a', isolationMode: 'whole_device', [field]: '64' })), + 'VALUE_TYPE', + field, + ); + // Boundary snapshot normalizes -0 -> 0 in validateDocument + const negZeroDoc = value(withHardware({ accelerator: 'sm_90a', isolationMode: 'whole_device', [field]: -0 })); + const parsedVal = negZeroDoc.spec.target.matrix![0]!.hardware![field]; + assert.equal(Object.is(parsedVal, 0), true); + assert.equal(Object.is(parsedVal, -0), false); + // Direct schema rejects raw -0 + assert.throws( + () => hardwareTargetSchema({ accelerator: 'sm_90a', isolationMode: 'whole_device', [field]: -0 }, '/hw'), + (err: unknown) => err instanceof Error && err.message === 'VALUE_RANGE', + ); + } +}); + +test('MetricThresholdRule.bucketScope validates all variants and preserves legacy hashes when omitted', () => { + const legacyTask = contract(); + Object.assign(legacyTask.spec.acceptance.checks[0]!, { + metricThresholds: [ + { kind: 'bounds', metric: 'max_ulp', max: 1 }, + { kind: 'comparative', metric: 'latency_us', baselineMetric: 'base_latency_us', operator: 'max_ratio', threshold: 0.9 }, + ], + }); + const legacyLock = value(admitTask(legacyTask, ADMISSION)); + const rules = legacyLock.spec.contract.spec.acceptance.checks[0]!.metricThresholds!; + assert.equal(Object.hasOwn(rules[0]!, 'bucketScope'), false); + assert.equal(Object.hasOwn(rules[1]!, 'bucketScope'), false); + + const withThresholds = (metricThresholds: unknown) => { + const task = contract(); + Object.assign(task.spec.acceptance.checks[0]!, { metricThresholds }); + return validateDocument(task, 'TaskContract'); + }; + + // Valid scopes on both bounds and comparative rules + const validRules: readonly MetricThresholdRule[] = [ + { kind: 'bounds', metric: 'max_ulp', max: 1, bucketScope: 'aggregate' }, + { kind: 'bounds', metric: 'token_force_max_delta', max: 0.02, bucketScope: 'all_buckets' }, + { kind: 'bounds', metric: 'latency_us_p50', max: 100, bucketScope: { bucketId: 'bs1-isl4k' } }, + { + kind: 'comparative', + metric: 'latency_us_p50', + baselineMetric: 'baseline_latency_us_p50', + operator: 'max_ratio', + threshold: 0.85, + bucketScope: 'all_buckets', + }, + { + kind: 'comparative', + metric: 'goodput_rps', + baselineMetric: 'baseline_goodput_rps', + operator: 'min_ratio', + threshold: 1.15, + bucketScope: { bucketId: 'bs16_isl8k:fp16' }, + }, + ]; + const parsed = value(withThresholds(validRules)); + const parsedScope = parsed.spec.acceptance.checks[0]!.metricThresholds![2]!.bucketScope; + assert.equal(typeof parsedScope, 'object'); + assert.equal(Object.getPrototypeOf(parsedScope), null); + assert.deepEqual({ ...(parsedScope as { readonly bucketId: string }) }, { bucketId: 'bs1-isl4k' }); + + // Invalid bucketScope values + assert.equal(code(withThresholds([{ kind: 'bounds', metric: 'a', max: 1, bucketScope: 'some_buckets' }])), 'VALUE_ENUM'); + for (const badType of [123, true, null, []]) { + assert.equal(code(withThresholds([{ kind: 'bounds', metric: 'a', max: 1, bucketScope: badType }])), 'VALUE_TYPE'); + } + assert.equal(code(withThresholds([{ kind: 'bounds', metric: 'a', max: 1, bucketScope: {} }])), 'FIELD_REQUIRED'); + assert.equal(code(withThresholds([{ kind: 'bounds', metric: 'a', max: 1, bucketScope: { bucketId: 'bs1', extra: true } }])), 'FIELD_UNKNOWN'); + for (const badId of ['', 'a'.repeat(LIMITS.bucketId + 1), 'ghp_123456789012345678901234', 'OPENAI_API_KEY']) { + assert.equal( + code(withThresholds([{ kind: 'bounds', metric: 'a', max: 1, bucketScope: { bucketId: badId } }])), + 'VALUE_RANGE', + badId, + ); + } + for (const badId of ['bad space', '../escape', '-leading', 'constructor', 'prototype', '__proto__', 'bücket']) { + assert.equal( + code(withThresholds([{ kind: 'bounds', metric: 'a', max: 1, bucketScope: { bucketId: badId } }])), + 'IDENTIFIER_INVALID', + badId, + ); + } +}); + +test('Evidence.spec.bucketMetrics validates 1..64 buckets, <=16 numeric metrics, <=8 dimensions, null-proto, and secret guards', () => { + // Legacy Evidence omits bucketMetrics and hardwareDiagnostics cleanly + const baseline = evaluationFixture(); + const baseEv = value(validateDocument(baseline.input.trusted.eligibleEvidence[0], 'Evidence')); + assert.equal(Object.hasOwn(baseEv.spec, 'bucketMetrics'), false); + assert.equal(Object.hasOwn(baseEv.spec, 'hardwareDiagnostics'), false); + + const withBucketMetrics = (bucketMetrics: unknown) => { + const fixture = evaluationFixture(); + Object.assign(fixture.input.trusted.eligibleEvidence[0]!.spec, { bucketMetrics }); + return validateDocument(fixture.input.trusted.eligibleEvidence[0], 'Evidence'); + }; + + // Exact maximum boundaries: 64 buckets, 16 numeric metrics, 8 dimensions + const maxBuckets: BucketMetricEntry[] = Array.from({ length: LIMITS.bucketMetrics }, (_, i) => ({ + bucketId: `bucket_${String(i).padStart(2, '0')}`, + dimensions: Object.fromEntries([ + ['bs', i + 1], + ['isl', 4096], + ['osl', 512], + ['dtype', 'fp16'], + ['layout', 'row-major'], + ['tp', 1], + ['kv_dtype', 'fp8_e4m3'], + ['causal', 'true'], + ]), + metrics: Object.fromEntries(Array.from({ length: LIMITS.bucketMetricEntries }, (_, m) => [`m_${m}`, m + 0.5])), + })); + const parsedMax = value(withBucketMetrics(maxBuckets)); + assert.equal(parsedMax.spec.bucketMetrics?.length, 64); + assert.equal(Object.getPrototypeOf(parsedMax.spec.bucketMetrics![0]), null); + assert.equal(Object.getPrototypeOf(parsedMax.spec.bucketMetrics![0]!.dimensions), null); + assert.equal(Object.getPrototypeOf(parsedMax.spec.bucketMetrics![0]!.metrics), null); + + // Optional dimensions omitted when absent + const noDims = value(withBucketMetrics([{ bucketId: 'bs1-isl4k', metrics: { latency_us_p50: 42.5, max_ulp: 0 } }])); + assert.equal(Object.hasOwn(noDims.spec.bucketMetrics![0]!, 'dimensions'), false); + + // Boundary overruns + assert.equal(code(withBucketMetrics([])), 'VALUE_RANGE'); + assert.equal(code(withBucketMetrics([...maxBuckets, { bucketId: 'bucket_64', metrics: { m_0: 1 } }])), 'VALUE_RANGE'); + assert.equal( + code(withBucketMetrics([{ + bucketId: 'b0', + metrics: Object.fromEntries(Array.from({ length: LIMITS.bucketMetricEntries + 1 }, (_, m) => [`m_${m}`, m])), + }])), + 'VALUE_RANGE', + ); + assert.equal( + code(withBucketMetrics([{ + bucketId: 'b0', + dimensions: Object.fromEntries(Array.from({ length: LIMITS.bucketDimensionEntries + 1 }, (_, d) => [`d_${d}`, d])), + metrics: { m_0: 1 }, + }])), + 'VALUE_RANGE', + ); + + // Duplicate bucketId rejected + assert.equal( + code(withBucketMetrics([ + { bucketId: 'bs1-isl4k', metrics: { latency_us: 10 } }, + { bucketId: 'bs1-isl4k', metrics: { latency_us: 12 } }, + ])), + 'DUPLICATE_ID', + ); + + // Non-numeric bucket metric values rejected (prevents free-text exfiltration) + assert.equal(code(withBucketMetrics([{ bucketId: 'b0', metrics: { note: 'leaked text' } }])), 'VALUE_TYPE'); + assert.equal(code(withBucketMetrics([{ bucketId: 'b0', metrics: { flag: true } }])), 'VALUE_TYPE'); + assert.equal(code(withBucketMetrics([{ bucketId: 'b0', metrics: { bad: null } }])), 'VALUE_TYPE'); + + // Non-finite numbers rejected; -0 normalized via validateDocument and rejected in direct schema + for (const badNum of [NaN, Infinity, -Infinity]) { + assert.equal(code(withBucketMetrics([{ bucketId: 'b0', metrics: { lat: badNum } }])), 'VALUE_RANGE'); + assert.equal(code(withBucketMetrics([{ bucketId: 'b0', dimensions: { bs: badNum }, metrics: { lat: 1 } }])), 'VALUE_RANGE'); + } + const negZeroEv = value(withBucketMetrics([{ bucketId: 'b0', dimensions: { bs: -0 }, metrics: { delta: -0 } }])); + assert.equal(Object.is(negZeroEv.spec.bucketMetrics![0]!.dimensions!.bs, 0), true); + assert.equal(Object.is(negZeroEv.spec.bucketMetrics![0]!.metrics.delta, 0), true); + assert.throws( + () => bucketMetricsSchema([{ bucketId: 'b0', metrics: { delta: -0 } }], '/bucketMetrics'), + (err: unknown) => err instanceof Error && err.message === 'VALUE_RANGE', + ); + assert.throws( + () => bucketMetricsSchema([{ bucketId: 'b0', dimensions: { bs: -0 }, metrics: { delta: 1 } }], '/bucketMetrics'), + (err: unknown) => err instanceof Error && err.message === 'VALUE_RANGE', + ); + + // Free-text, non-ASCII, lone surrogate, prototype pollution, and secret exfiltration rejected + assert.equal(code(withBucketMetrics([{ bucketId: 'free text prompt', metrics: { x: 1 } }])), 'IDENTIFIER_INVALID'); + assert.equal(code(withBucketMetrics([{ bucketId: 'b0', dimensions: { tag: 'secret prompt sentence' }, metrics: { x: 1 } }])), 'VALUE_RANGE'); + assert.equal(code(withBucketMetrics([{ bucketId: 'b0', dimensions: { tag: 'non-ascii-π' }, metrics: { x: 1 } }])), 'VALUE_RANGE'); + assert.equal(code(withBucketMetrics([{ bucketId: 'b0', dimensions: { tag: 'surrogate\uD800' }, metrics: { x: 1 } }])), 'INPUT_UNSUPPORTED'); + assert.equal(code(withBucketMetrics([{ bucketId: 'b0', dimensions: { tag: true }, metrics: { x: 1 } }])), 'VALUE_TYPE'); + assert.equal(code(withBucketMetrics([{ bucketId: 'b0', metrics: { x: 1 }, extra: 1 }])), 'FIELD_UNKNOWN'); + + // Secrets blocked in bucketId, dimension key, dimension value, and metric key + for (const secret of ['ghp_123456789012345678901234', 'ghs_abcdefghijklmnopqrstuvwx', 'OPENAI_API_KEY', 'AWS_SECRET_ACCESS_KEY']) { + assert.equal(code(withBucketMetrics([{ bucketId: secret, metrics: { x: 1 } }])), 'VALUE_RANGE', `bucketId:${secret}`); + assert.equal(code(withBucketMetrics([{ bucketId: 'b0', dimensions: { tag: secret }, metrics: { x: 1 } }])), 'VALUE_RANGE', `dimVal:${secret}`); + assert.equal(code(withBucketMetrics([{ bucketId: 'b0', dimensions: { [secret]: 1 }, metrics: { x: 1 } }])), 'VALUE_RANGE', `dimKey:${secret}`); + assert.equal(code(withBucketMetrics([{ bucketId: 'b0', metrics: { [secret]: 1 } }])), 'VALUE_RANGE', `metricKey:${secret}`); + } + + // Custom registered secret blocked via validateBucketMetrics(input, scrubber) + const customScrubber = new SecretScrubber(); + customScrubber.register('canary-token-9999'); + assert.equal( + code(validateBucketMetrics([{ bucketId: 'b0', dimensions: { tag: 'canary-token-9999' }, metrics: { x: 1 } }], customScrubber)), + 'VALUE_RANGE', + ); + assert.equal( + validateBucketMetrics([{ bucketId: 'b0', dimensions: { tag: 'fp16' }, metrics: { x: 1 } }], customScrubber).ok, + true, + ); + + // Prototype pollution via JSON string rejected + for (const protoKey of ['__proto__', 'constructor', 'prototype']) { + const fixture = evaluationFixture(); + const jsonDim = JSON.stringify(fixture.input.trusted.eligibleEvidence[0]).replace( + '"reason":null', + `"reason":null,"bucketMetrics":[{"bucketId":"b0","dimensions":{"${protoKey}":1},"metrics":{"x":1}}]`, + ); + assert.equal(code(validateDocument(jsonDim, 'Evidence')), 'IDENTIFIER_INVALID', `dim:${protoKey}`); + + const jsonMetric = JSON.stringify(fixture.input.trusted.eligibleEvidence[0]).replace( + '"reason":null', + `"reason":null,"bucketMetrics":[{"bucketId":"b0","metrics":{"${protoKey}":1}}]`, + ); + assert.equal(code(validateDocument(jsonMetric, 'Evidence')), 'IDENTIFIER_INVALID', `metric:${protoKey}`); + + const jsonEntry = JSON.stringify(fixture.input.trusted.eligibleEvidence[0]).replace( + '"reason":null', + `"reason":null,"bucketMetrics":[{"bucketId":"b0","metrics":{"x":1},"${protoKey}":1}]`, + ); + assert.equal(code(validateDocument(jsonEntry, 'Evidence')), 'FIELD_UNKNOWN', `entry:${protoKey}`); + } +}); + +test('Evidence.spec.hardwareDiagnostics validates closed enum, numeric bounds, topStallReasons, and rejects exfiltration', () => { + const withDiagnostics = (hardwareDiagnostics: unknown) => { + const fixture = evaluationFixture(); + Object.assign(fixture.input.trusted.eligibleEvidence[0]!.spec, { hardwareDiagnostics }); + return validateDocument(fixture.input.trusted.eligibleEvidence[0], 'Evidence'); + }; + + // Every closed boundPipeline enum value accepted; optional fields omitted when absent + assert.deepEqual([...HARDWARE_BOUND_PIPELINES], [ + 'hbm', 'l2', 'smem_lds_ub', 'tensor_cube', 'vector_valu', 'host_launch', 'comm', 'unknown', + ]); + for (const pipeline of HARDWARE_BOUND_PIPELINES) { + const parsed = value(withDiagnostics({ boundPipeline: pipeline })); + const diag = parsed.spec.hardwareDiagnostics!; + assert.equal(diag.boundPipeline, pipeline); + assert.equal(Object.getPrototypeOf(diag), null); + assert.equal(Object.hasOwn(diag, 'rooflineHeadroom'), false); + assert.equal(Object.hasOwn(diag, 'topStallReasons'), false); + } + + // Full payload with exact 16 stall reasons and boundary values + const fullDiag: HardwareDiagnostics = { + boundPipeline: 'tensor_cube', + rooflineHeadroom: 1.08, + achievedSolPct: 92.5, + arithmeticIntensity: 256.4, + occupancyPct: 75, + registerCount: 96, + sharedMemBytes: 49_152, + localSpillBytes: 0, + l2HitPct: 88.2, + bankConflictPct: 0.5, + topStallReasons: Array.from({ length: LIMITS.hardwareStallReasons }, (_, i) => ({ + reason: `stall_reason_${i}`, + pct: i === 0 ? 0 : i === 15 ? 100 : 5.25, + })), + }; + const parsedFull = value(withDiagnostics(fullDiag)); + assert.equal(parsedFull.spec.hardwareDiagnostics?.registerCount, 96); + assert.equal(parsedFull.spec.hardwareDiagnostics?.topStallReasons?.length, 16); + assert.equal(Object.getPrototypeOf(parsedFull.spec.hardwareDiagnostics?.topStallReasons?.[0]), null); + + // Invalid boundPipeline, missing required field, unknown keys, prototype keys + assert.equal(code(withDiagnostics({})), 'FIELD_REQUIRED'); + assert.equal(code(withDiagnostics({ boundPipeline: 'dram' })), 'VALUE_ENUM'); + assert.equal(code(withDiagnostics({ boundPipeline: 42 })), 'VALUE_TYPE'); + assert.equal(code(withDiagnostics({ boundPipeline: 'hbm', freeTextNote: 'leaked' })), 'FIELD_UNKNOWN'); + + for (const protoKey of ['__proto__', 'constructor', 'prototype']) { + const fixture = evaluationFixture(); + const jsonWithProto = JSON.stringify(fixture.input.trusted.eligibleEvidence[0]).replace( + '"reason":null', + `"reason":null,"hardwareDiagnostics":{"boundPipeline":"hbm","${protoKey}":1}`, + ); + assert.equal(code(validateDocument(jsonWithProto, 'Evidence')), 'FIELD_UNKNOWN', protoKey); + } + + // Percentage fields must be in [0, 100] + for (const pctField of ['achievedSolPct', 'occupancyPct', 'l2HitPct', 'bankConflictPct'] as const) { + for (const badVal of [-0.01, 100.01, NaN, Infinity, -Infinity]) { + assert.equal(code(withDiagnostics({ boundPipeline: 'hbm', [pctField]: badVal })), 'VALUE_RANGE', `${pctField}:${badVal}`); + } + assert.equal(code(withDiagnostics({ boundPipeline: 'hbm', [pctField]: '50' })), 'VALUE_TYPE', pctField); + assert.throws( + () => hardwareDiagnosticsSchema({ boundPipeline: 'hbm', [pctField]: -0 }, '/diag'), + (err: unknown) => err instanceof Error && err.message === 'VALUE_RANGE', + ); + } + + // Non-negative float fields + for (const floatField of ['rooflineHeadroom', 'arithmeticIntensity'] as const) { + for (const badVal of [-0.001, NaN, Infinity, -Infinity]) { + assert.equal(code(withDiagnostics({ boundPipeline: 'hbm', [floatField]: badVal })), 'VALUE_RANGE', `${floatField}:${badVal}`); + } + assert.throws( + () => hardwareDiagnosticsSchema({ boundPipeline: 'hbm', [floatField]: -0 }, '/diag'), + (err: unknown) => err instanceof Error && err.message === 'VALUE_RANGE', + ); + } + + // Non-negative integer fields + for (const intField of ['registerCount', 'sharedMemBytes', 'localSpillBytes'] as const) { + for (const badVal of [-1, 1.5, NaN, Infinity, Number.MAX_SAFE_INTEGER + 1]) { + assert.equal(code(withDiagnostics({ boundPipeline: 'hbm', [intField]: badVal })), 'VALUE_RANGE', `${intField}:${badVal}`); + } + assert.throws( + () => hardwareDiagnosticsSchema({ boundPipeline: 'hbm', [intField]: -0 }, '/diag'), + (err: unknown) => err instanceof Error && err.message === 'VALUE_RANGE', + ); + } + + // topStallReasons bounds, duplicates, free-text, non-ASCII, lone surrogate, secrets + assert.equal( + code(withDiagnostics({ + boundPipeline: 'hbm', + topStallReasons: Array.from({ length: LIMITS.hardwareStallReasons + 1 }, (_, i) => ({ reason: `r_${i}`, pct: 1 })), + })), + 'VALUE_RANGE', + ); + assert.equal( + code(withDiagnostics({ + boundPipeline: 'hbm', + topStallReasons: [ + { reason: 'long_scoreboard', pct: 30 }, + { reason: 'long_scoreboard', pct: 20 }, + ], + })), + 'DUPLICATE_ID', + ); + for (const badReason of ['free text workload leak', 'stall\nwait', 'stáll', '9leading_digit', 'constructor', '__proto__', 'prototype']) { + assert.equal( + code(withDiagnostics({ boundPipeline: 'hbm', topStallReasons: [{ reason: badReason, pct: 10 }] })), + 'IDENTIFIER_INVALID', + badReason, + ); + } + for (const secretReason of ['', 'a'.repeat(LIMITS.hardwareStallReason + 1), 'ghp_123456789012345678901234', 'OPENAI_API_KEY']) { + assert.equal( + code(withDiagnostics({ boundPipeline: 'hbm', topStallReasons: [{ reason: secretReason, pct: 10 }] })), + 'VALUE_RANGE', + secretReason, + ); + } + assert.equal( + code(withDiagnostics({ boundPipeline: 'hbm', topStallReasons: [{ reason: 'stall_\uD800', pct: 10 }] })), + 'INPUT_UNSUPPORTED', + ); + assert.equal( + code(withDiagnostics({ boundPipeline: 'hbm', topStallReasons: [{ reason: 'long_scoreboard', pct: 101 }] })), + 'VALUE_RANGE', + ); + assert.equal( + code(withDiagnostics({ boundPipeline: 'hbm', topStallReasons: [{ reason: 'long_scoreboard', pct: -1 }] })), + 'VALUE_RANGE', + ); + assert.equal( + code(withDiagnostics({ boundPipeline: 'hbm', topStallReasons: [{ reason: 'long_scoreboard', pct: 10, extra: true }] })), + 'FIELD_UNKNOWN', + ); + + // Custom scrubber secret rejected in validateHardwareDiagnostics + const customScrubber = new SecretScrubber(); + customScrubber.register('secret_stall_canary'); + assert.equal( + code(validateHardwareDiagnostics({ + boundPipeline: 'hbm', + topStallReasons: [{ reason: 'secret_stall_canary', pct: 10 }], + }, customScrubber)), + 'VALUE_RANGE', + ); + assert.equal( + validateHardwareDiagnostics({ + boundPipeline: 'hbm', + topStallReasons: [{ reason: 'long_scoreboard', pct: 42.5 }], + }, customScrubber).ok, + true, + ); + + // Legacy canonical digest parity when optional Evidence fields are absent + const ev1 = evaluationFixture().input.trusted.eligibleEvidence[0]!; + const parsedEv1 = value(validateDocument(ev1, 'Evidence')); + assert.equal(canonical(parsedEv1), canonical(ev1)); +}); + +test('evaluateAcceptance and evaluateMetricThresholds enforce bucketScope across aggregate, all_buckets, and targeted bucketId', () => { + const buckets: readonly BucketMetricEntry[] = [ + { + bucketId: 'bs1-isl4k', + dimensions: { bs: 1, isl: 4096 }, + metrics: { + max_ulp: 0.5, + token_force_max_delta: 0.01, + latency_us_p50: 40, + baseline_latency_us_p50: 50, + goodput_rps: 120, + baseline_goodput_rps: 100, + }, + }, + { + bucketId: 'bs16-isl8k', + dimensions: { bs: 16, isl: 8192 }, + metrics: { + max_ulp: 1, + token_force_max_delta: 0.02, + latency_us_p50: 320, + baseline_latency_us_p50: 400, + goodput_rps: 900, + baseline_goodput_rps: 800, + }, + }, + ]; + + // 1. Mixed aggregate + all_buckets + targeted { bucketId } (bounds and comparative) passes cleanly + const passingRules: readonly MetricThresholdRule[] = [ + { kind: 'bounds', metric: 'tflops', min: 400 }, + { kind: 'bounds', metric: 'tflops', min: 400, bucketScope: 'aggregate' }, + { kind: 'bounds', metric: 'max_ulp', min: 0, max: 1, bucketScope: 'all_buckets' }, + { kind: 'bounds', metric: 'token_force_max_delta', max: 0.02, bucketScope: 'all_buckets' }, + { + kind: 'comparative', + metric: 'latency_us_p50', + baselineMetric: 'baseline_latency_us_p50', + operator: 'max_ratio', + threshold: 0.85, + bucketScope: 'all_buckets', + }, + { + kind: 'comparative', + metric: 'goodput_rps', + baselineMetric: 'baseline_goodput_rps', + operator: 'min_ratio', + threshold: 1.1, + bucketScope: 'all_buckets', + }, + { + kind: 'comparative', + metric: 'latency_us_p50', + baselineMetric: 'baseline_latency_us_p50', + operator: 'max_delta', + threshold: -10, + bucketScope: { bucketId: 'bs1-isl4k' }, + }, + { kind: 'bounds', metric: 'latency_us_p50', max: 350, bucketScope: { bucketId: 'bs16-isl8k' } }, + ]; + const passing = makeHardwareEvaluation({ + metricThresholds: passingRules, + metrics: { tflops: 420 }, + bucketMetrics: buckets, + hardwareDiagnostics: { boundPipeline: 'hbm', rooflineHeadroom: 1.12, occupancyPct: 68 }, + }); + const evalPass = value(evaluateAcceptance(passing.input, passing.artifacts)); + assert.equal(evalPass.spec.satisfied, true); + assert.equal(evalPass.spec.required[0]!.status, 'passed'); + const runPass = value(constructRunResult({ + trusted: { ...passing.input.trusted, usage: [], externalEffects: 'none', noChange: null }, + candidate: { status: 'completed', checks: passing.input.claims, memory: { status: 'not_requested', reason: null } }, + }, passing.artifacts)); + assert.equal(runPass.spec.status, 'completed'); + + // 2. Bucket-scoped rules ONLY pass even when aggregate Evidence.spec.metrics is omitted + const bucketOnlyPass = makeHardwareEvaluation({ + metricThresholds: [ + { kind: 'bounds', metric: 'max_ulp', max: 1, bucketScope: 'all_buckets' }, + { kind: 'bounds', metric: 'latency_us_p50', max: 50, bucketScope: { bucketId: 'bs1-isl4k' } }, + ], + bucketMetrics: buckets, + }); + assert.equal(value(evaluateAcceptance(bucketOnlyPass.input, bucketOnlyPass.artifacts)).spec.satisfied, true); + + // 3. Targeted { bucketId } passes even when a DIFFERENT bucket would violate the rule + const targetedPass = makeHardwareEvaluation({ + metricThresholds: [ + { kind: 'bounds', metric: 'latency_us_p50', max: 50, bucketScope: { bucketId: 'bs1-isl4k' } }, + ], + bucketMetrics: buckets, // bs16-isl8k has latency_us_p50 = 320 > 50, but scope is bs1-isl4k + }); + assert.equal(value(evaluateAcceptance(targetedPass.input, targetedPass.artifacts)).spec.satisfied, true); + + // 4. All fail-closed bucketScope rejection scenarios + const failingCases: { + readonly label: string; + readonly rules: readonly MetricThresholdRule[]; + readonly metrics?: Record; + readonly bucketMetrics?: readonly BucketMetricEntry[]; + }[] = [ + { + label: 'all_buckets missing bucketMetrics', + rules: [{ kind: 'bounds', metric: 'max_ulp', max: 1, bucketScope: 'all_buckets' }], + metrics: { max_ulp: 0 }, + }, + { + label: 'all_buckets single bucket violates bounds', + rules: [{ kind: 'bounds', metric: 'max_ulp', max: 1, bucketScope: 'all_buckets' }], + bucketMetrics: [ + { bucketId: 'bs1-isl4k', metrics: { max_ulp: 0.5 } }, + { bucketId: 'bs16-isl8k', metrics: { max_ulp: 1.5 } }, + ], + }, + { + label: 'all_buckets single bucket missing metric', + rules: [{ kind: 'bounds', metric: 'max_ulp', max: 1, bucketScope: 'all_buckets' }], + metrics: { max_ulp: 0 }, + bucketMetrics: [ + { bucketId: 'bs1-isl4k', metrics: { max_ulp: 0.5 } }, + { bucketId: 'bs16-isl8k', metrics: { latency_us_p50: 100 } }, + ], + }, + { + label: 'all_buckets comparative fails on second bucket', + rules: [{ + kind: 'comparative', + metric: 'latency_us_p50', + baselineMetric: 'baseline_latency_us_p50', + operator: 'max_ratio', + threshold: 0.85, + bucketScope: 'all_buckets', + }], + bucketMetrics: [ + { bucketId: 'bs1-isl4k', metrics: { latency_us_p50: 40, baseline_latency_us_p50: 50 } }, + { bucketId: 'bs16-isl8k', metrics: { latency_us_p50: 360, baseline_latency_us_p50: 400 } }, + ], + }, + { + label: 'all_buckets comparative missing baselineMetric in bucket does NOT fall back to aggregate', + rules: [{ + kind: 'comparative', + metric: 'latency_us_p50', + baselineMetric: 'baseline_latency_us_p50', + operator: 'max_delta', + threshold: 0, + bucketScope: 'all_buckets', + }], + metrics: { latency_us_p50: 40, baseline_latency_us_p50: 500 }, + bucketMetrics: [ + { bucketId: 'bs1-isl4k', metrics: { latency_us_p50: 40 } }, + ], + }, + { + label: 'all_buckets comparative non-positive baseline fails ratio check', + rules: [{ + kind: 'comparative', + metric: 'goodput_rps', + baselineMetric: 'baseline_goodput_rps', + operator: 'min_ratio', + threshold: 1.0, + bucketScope: 'all_buckets', + }], + bucketMetrics: [ + { bucketId: 'bs1-isl4k', metrics: { goodput_rps: 100, baseline_goodput_rps: 0 } }, + ], + }, + { + label: 'targeted bucketId missing bucketMetrics', + rules: [{ kind: 'bounds', metric: 'max_ulp', max: 1, bucketScope: { bucketId: 'bs1-isl4k' } }], + metrics: { max_ulp: 0 }, + }, + { + label: 'targeted bucketId not found in bucketMetrics', + rules: [{ kind: 'bounds', metric: 'max_ulp', max: 1, bucketScope: { bucketId: 'bs32-isl16k' } }], + bucketMetrics: buckets, + }, + { + label: 'targeted bucketId fails bounds', + rules: [{ kind: 'bounds', metric: 'latency_us_p50', max: 30, bucketScope: { bucketId: 'bs1-isl4k' } }], + bucketMetrics: buckets, + }, + { + label: 'targeted bucketId comparative fails max_delta', + rules: [{ + kind: 'comparative', + metric: 'latency_us_p50', + baselineMetric: 'baseline_latency_us_p50', + operator: 'max_delta', + threshold: -15, + bucketScope: { bucketId: 'bs1-isl4k' }, + }], + bucketMetrics: buckets, // 40 - 50 = -10 > -15 -> fail + }, + { + label: 'explicit aggregate fails when aggregate metrics missing even if bucketMetrics has key', + rules: [{ kind: 'bounds', metric: 'max_ulp', max: 1, bucketScope: 'aggregate' }], + bucketMetrics: buckets, + }, + ]; + + for (const tc of failingCases) { + const f = makeHardwareEvaluation({ + metricThresholds: tc.rules, + ...(tc.metrics !== undefined ? { metrics: tc.metrics } : {}), + ...(tc.bucketMetrics !== undefined ? { bucketMetrics: tc.bucketMetrics } : {}), + }); + const res = value(evaluateAcceptance(f.input, f.artifacts)); + assert.equal(res.spec.satisfied, false, tc.label); + assert.equal(res.spec.required[0]!.status, 'blocked', tc.label); + assert.equal(res.spec.required[0]!.reason, 'metric_threshold_failed', tc.label); + assert.equal(res.spec.diagnostics[0]!.code, 'METRIC_THRESHOLD_FAILED', tc.label); + assert.equal(validateDocument(res, 'VerificationResult').ok, true, tc.label); + assert.equal(code(constructRunResult({ + trusted: { ...f.input.trusted, usage: [], externalEffects: 'none', noChange: null }, + candidate: { status: 'completed', checks: f.input.claims, memory: { status: 'not_requested', reason: null } }, + }, f.artifacts)), 'RUN_ACCEPTANCE_REQUIRED', tc.label); + } + + // Direct evaluateMetricThresholds helper checks (including empty bucketMetrics array fail-closed) + const allBucketsRule: MetricThresholdRule = { + kind: 'bounds', + metric: 'max_ulp', + max: 1, + bucketScope: 'all_buckets' as MetricBucketScope, + }; + assert.equal(evaluateMetricThresholds([allBucketsRule], { max_ulp: 0 }, []), false); + assert.equal(evaluateMetricThresholds([allBucketsRule], undefined, buckets), true); + assert.equal( + evaluateMetricThresholds([{ kind: 'bounds', metric: 'max_ulp', max: 1, bucketScope: { bucketId: 'bs1-isl4k' } }], undefined, []), + false, + ); + assert.equal(evaluateMetricThresholds([], undefined, undefined), true); +}); diff --git a/packages/decisions/src/index.ts b/packages/decisions/src/index.ts index dd426d7..c1112f4 100644 --- a/packages/decisions/src/index.ts +++ b/packages/decisions/src/index.ts @@ -3,7 +3,10 @@ export { DecisionError, DEFAULT_DECISION_POLICY, DECISION_ENDPOINT, DECISION_POL DECISION_MAX_QUESTIONS, DECISION_MAX_OPTIONS, DECISION_MIN_CRITERIA, DECISION_MAX_CRITERIA, DECISION_MAX_STATE_DEPTH, DECISION_MAX_STATE_BYTES, DECISION_MAX_PUBLIC_METADATA_CHARS, DECISION_INPUT_COST_PER_MTOK_USD, DECISION_OUTPUT_COST_PER_MTOK_USD, DECISION_MAX_IMAGE_BASE64_CHARS, DECISION_MAX_IMAGES, DECISION_IMAGE_MEDIA_TYPES, - DECISION_FORBIDDEN_AUTHORITY_INTENTS, DECISION_ALLOWED_AUTHORITY_INTENTS, getProviderDialect } from './types.js'; + DECISION_FORBIDDEN_AUTHORITY_INTENTS, DECISION_ALLOWED_AUTHORITY_INTENTS, + DECISION_NOVELTY_DEFAULT_THRESHOLD, DECISION_NOVELTY_DEFAULT_SHINGLE_SIZE, DECISION_NOVELTY_MAX_SLICE_BYTES, + DECISION_NOVELTY_MAX_HISTORY_SLICES, DECISION_NOVELTY_MAX_SHINGLES, DECISION_EVOLUTION_MAX_TRACKS, + DECISION_EVOLUTION_MAX_METRICS, DECISION_CASCADE_DEFAULT_REGRESSION_TOLERANCE, getProviderDialect } from './types.js'; export type { DecisionErrorCode, DecisionDisclosurePolicy, DecisionFallbackUnavailableAction, DecisionProviderKind, DecisionWireDialect, DecisionStartluxOptions, DecisionPolicyConfig, DecisionChoiceQuestion, DecisionScoreQuestion, @@ -18,6 +21,10 @@ export type { DecisionDiffTriageResult, DecisionImageAsset, DecisionBenchmarkArm, DecisionBenchmarkCaseKind, DecisionBenchmarkFixture, DecisionBenchmarkCase, DecisionBenchmarkArmSummary, DecisionBenchmarkReport, DecisionClientOptions, DecisionSdkRequest, DecisionSdkAdapter, + DecisionMutationNoveltyAction, DecisionMutationNoveltyHistoryEntry, DecisionMutationNoveltyInput, + DecisionMutationNoveltyResult, DecisionBoundPipeline, DecisionEvolutionMutationKind, DecisionHardwareDiagnostics, + DecisionEvolutionStrategyInput, DecisionEvolutionStrategyResult, DecisionCascadeAction, + DecisionCascadeEscalationInput, DecisionCascadeEscalationResult, } from './types.js'; export { isPlainObject, loadDecisionPolicyFile, parseDecisionPolicyDocument, @@ -35,10 +42,13 @@ export type { DecisionFanOutResult, } from './router.js'; export { assertDecisionAuthorityBoundary, routeTaskCapability, heuristicCapabilityTier, evaluateCyclePrechecks, - evaluateCycleAlignment, evaluateSoftCompactionAdvisory, triageCandidateDiff, DECISION_CAPABILITY_JEV_SKILL_CHECKS } from './nodes.js'; + evaluateCycleAlignment, evaluateSoftCompactionAdvisory, triageCandidateDiff, DECISION_CAPABILITY_JEV_SKILL_CHECKS, + normalizeEvolveBlockSource, computeTokenShingleJaccard, evaluateMutationNovelty, heuristicEvolutionStrategy, + routeEvolutionStrategy, heuristicCascadeEscalation, evaluateCascadeEscalation } from './nodes.js'; export type { DecisionRouteCapabilityRequest, DecisionCycleAlignmentRequest, DecisionSoftCompactionRequest, DecisionDiffTriageRequest, + DecisionMutationNoveltyRequest, DecisionRouteEvolutionStrategyRequest, DecisionCascadeEscalationRequest, } from './nodes.js'; export { DEFAULT_DECISION_BENCHMARK_CORPUS, runControlledDecisionBenchmark } from './benchmark.js'; export type { DecisionBenchmarkOptions } from './benchmark.js'; diff --git a/packages/decisions/src/nodes.ts b/packages/decisions/src/nodes.ts index 4f4807d..cac8e55 100644 --- a/packages/decisions/src/nodes.ts +++ b/packages/decisions/src/nodes.ts @@ -1,10 +1,27 @@ import { evaluateDecision, type DecisionRequestBase } from './router.js'; -import { DecisionError, DECISION_ALLOWED_AUTHORITY_INTENTS, DECISION_FORBIDDEN_AUTHORITY_INTENTS } from './types.js'; +import { isPlainObject } from './schema.js'; +import { + DECISION_ALLOWED_AUTHORITY_INTENTS, + DECISION_CASCADE_DEFAULT_REGRESSION_TOLERANCE, + DECISION_EVOLUTION_MAX_METRICS, + DECISION_EVOLUTION_MAX_TRACKS, + DECISION_FORBIDDEN_AUTHORITY_INTENTS, + DECISION_NOVELTY_DEFAULT_SHINGLE_SIZE, + DECISION_NOVELTY_DEFAULT_THRESHOLD, + DECISION_NOVELTY_MAX_HISTORY_SLICES, + DECISION_NOVELTY_MAX_SHINGLES, + DECISION_NOVELTY_MAX_SLICE_BYTES, + DECISION_NOVELTY_STATE_SLICE_CHARS, + DecisionError, +} from './types.js'; import type { - DecisionCapabilityResult, DecisionCapabilityTier, DecisionCycleAlignmentResult, DecisionCyclePrecheckInput, - DecisionCycleRoute, DecisionDiffSummary, DecisionDiffTriageEscalation, DecisionDiffTriageResult, - DecisionDiffTriageRule, DecisionQuestion, DecisionSoftCompactionAdvisoryResult, DecisionSource, - DecisionTaskMetadata, + DecisionBoundPipeline, DecisionCapabilityResult, DecisionCapabilityTier, DecisionCascadeAction, + DecisionCascadeEscalationInput, DecisionCascadeEscalationResult, DecisionCycleAlignmentResult, + DecisionCyclePrecheckInput, DecisionCycleRoute, DecisionDiffSummary, DecisionDiffTriageEscalation, + DecisionDiffTriageResult, DecisionDiffTriageRule, DecisionEvolutionMutationKind, DecisionEvolutionStrategyInput, + DecisionEvolutionStrategyResult, DecisionHardwareDiagnostics, DecisionMutationNoveltyHistoryEntry, + DecisionMutationNoveltyInput, DecisionMutationNoveltyResult, DecisionQuestion, + DecisionSoftCompactionAdvisoryResult, DecisionSource, DecisionTaskMetadata, } from './types.js'; /** @@ -301,3 +318,756 @@ export async function triageCandidateDiff(request: DecisionDiffTriageRequest): P transportCalls: evaluation.transportCalls, }; } + +// --------------------------------------------------------------------------- +// Evolutionary Inner-Loop Advisory Nodes (T3) +// --------------------------------------------------------------------------- + +const FORBIDDEN_RECORD_KEYS: ReadonlySet = new Set(['__proto__', 'constructor', 'prototype']); + +const BOUND_PIPELINES: ReadonlySet = new Set([ + 'hbm', 'l2', 'smem_lds_ub', 'tensor_cube', 'vector_valu', 'host_launch', 'comm', 'unknown', +]); + +const MUTATION_KINDS: ReadonlySet = new Set([ + 'diff_tune', 'full_rewrite', 'crossover', +]); + +const CASCADE_ACTIONS: ReadonlySet = new Set([ + 'prune', 'confirm', 'escalate', +]); + +function failSchema(detail: string): never { + throw new DecisionError('DECISION_SCHEMA_INVALID', detail); +} + +function assertSafePlainObject(value: unknown, label: string): Record { + if (!isPlainObject(value)) failSchema(`${label} must be a plain object`); + for (const key of Object.keys(value)) { + if (FORBIDDEN_RECORD_KEYS.has(key)) failSchema(`${label} contains forbidden key "${key}"`); + } + return value; +} + +function hasLoneSurrogate(value: string): boolean { + for (let i = 0; i < value.length; i += 1) { + const code = value.charCodeAt(i); + if (code >= 0xd800 && code <= 0xdbff) { + const next = i + 1 < value.length ? value.charCodeAt(i + 1) : 0; + if (next < 0xdc00 || next > 0xdfff) return true; + i += 1; + } else if (code >= 0xdc00 && code <= 0xdfff) { + return true; + } + } + return false; +} + +function assertNonEmptyString(value: unknown, label: string, maxChars: number): string { + if (typeof value !== 'string' || hasLoneSurrogate(value) || value.trim().length === 0 || value.length > maxChars) { + failSchema(`${label} must be a non-empty well-formed string of at most ${maxChars} characters`); + } + return value; +} + +function assertFiniteNonNegZero(value: unknown, label: string): number { + if (typeof value !== 'number' || !Number.isFinite(value) || Object.is(value, -0)) { + failSchema(`${label} must be a finite number`); + } + return value; +} + +function mergeDecisionState(baseState: unknown, key: string, payload: Record): unknown { + if (!isPlainObject(baseState)) return baseState; + const merged = Object.create(null) as Record; + for (const existingKey of Object.keys(baseState)) { + Object.defineProperty(merged, existingKey, { + value: baseState[existingKey], + enumerable: true, + writable: true, + configurable: true, + }); + } + Object.defineProperty(merged, key, { + value: payload, + enumerable: true, + writable: true, + configurable: true, + }); + return merged; +} + +const DECISION_NOVELTY_STATE_SLICE_MAX_BYTES = 16_384; + +function truncateUtf8CodePointSafe(text: string, maxBytes: number, maxChars: number): string { + if (maxBytes <= 0 || maxChars <= 0 || text.length === 0) return ''; + let byteCount = 0; + let charEnd = 0; + while (charEnd < text.length && charEnd < maxChars) { + const cp = text.codePointAt(charEnd)!; + const stepChars = cp > 0xffff ? 2 : 1; + if (charEnd + stepChars > maxChars) break; + const stepBytes = cp <= 0x7f ? 1 : cp <= 0x7ff ? 2 : cp <= 0xffff ? 3 : 4; + if (byteCount + stepBytes > maxBytes) break; + byteCount += stepBytes; + charEnd += stepChars; + } + return text.slice(0, charEnd); +} + +/** + * Normalize an `EVOLVE-BLOCK` source slice by stripping `//`, `/* ... *\/`, and `#` comments + * (preserving string literals) and collapsing all whitespace to single spaces. + */ +export function normalizeEvolveBlockSource(source: string): string { + let out = ''; + let i = 0; + const len = source.length; + while (i < len) { + const ch = source.charAt(i); + const next = i + 1 < len ? source.charAt(i + 1) : ''; + if (ch === '"' || ch === '\'' || ch === '`') { + const quote = ch; + out += ch; + i += 1; + while (i < len) { + const cur = source.charAt(i); + out += cur; + i += 1; + if (cur === '\\' && i < len) { + out += source.charAt(i); + i += 1; + } else if (cur === quote) { + break; + } + } + continue; + } + if (ch === '/' && next === '/') { + i += 2; + while (i < len && source.charAt(i) !== '\n') i += 1; + out += ' '; + continue; + } + if (ch === '/' && next === '*') { + i += 2; + while (i < len && !(source.charAt(i) === '*' && i + 1 < len && source.charAt(i + 1) === '/')) i += 1; + i += 2; + out += ' '; + continue; + } + if (ch === '#') { + const prevNonSpaceIdx = i - 1; + const atLineStartOrAfterSpace = + prevNonSpaceIdx < 0 + || source.charAt(prevNonSpaceIdx) === '\n' + || source.charAt(prevNonSpaceIdx) === '\r' + || source.charAt(prevNonSpaceIdx) === ' ' + || source.charAt(prevNonSpaceIdx) === '\t'; + const restOfLine = source.slice(i + 1); + const isPreprocessorDirective = /^\s*(?:include|define|undef|if|ifdef|ifndef|elif|else|endif|pragma|error|line|warning)\b/.test(restOfLine); + if (atLineStartOrAfterSpace && !isPreprocessorDirective) { + i += 1; + while (i < len && source.charAt(i) !== '\n') i += 1; + out += ' '; + continue; + } + } + out += ch; + i += 1; + } + return out.replace(/\s+/g, ' ').trim(); +} + +function tokenizeNormalizedSource(normalized: string): readonly string[] { + const matched = normalized.match(/[A-Za-z0-9_]+|[^\sA-Za-z0-9_]/g); + return matched === null ? [] : matched; +} + +function buildTokenShingles(normalized: string, shingleSize: number): ReadonlySet { + const tokenList = tokenizeNormalizedSource(normalized); + const shingles = new Set(); + if (tokenList.length === 0) return shingles; + if (tokenList.length <= shingleSize) { + shingles.add(tokenList.join('\u001f')); + return shingles; + } + const limit = tokenList.length - shingleSize + 1; + for (let i = 0; i < limit && shingles.size < DECISION_NOVELTY_MAX_SHINGLES; i += 1) { + shingles.add(tokenList.slice(i, i + shingleSize).join('\u001f')); + } + return shingles; +} + +function jaccardSimilarity(a: ReadonlySet, b: ReadonlySet): number { + if (a.size === 0 && b.size === 0) return 1; + if (a.size === 0 || b.size === 0) return 0; + let intersection = 0; + const [smaller, larger] = a.size <= b.size ? [a, b] : [b, a]; + for (const item of smaller) { + if (larger.has(item)) intersection += 1; + } + const union = a.size + b.size - intersection; + return union === 0 ? 1 : intersection / union; +} + +/** Deterministic whitespace/comment-normalized token-shingle Jaccard similarity in `[0, 1]`. */ +export function computeTokenShingleJaccard( + sourceA: string, + sourceB: string, + shingleSize: number = DECISION_NOVELTY_DEFAULT_SHINGLE_SIZE, +): number { + if (!Number.isInteger(shingleSize) || shingleSize < 1 || shingleSize > 8) { + failSchema('shingleSize must be an integer in [1, 8]'); + } + const normA = normalizeEvolveBlockSource(sourceA); + const normB = normalizeEvolveBlockSource(sourceB); + return jaccardSimilarity(buildTokenShingles(normA, shingleSize), buildTokenShingles(normB, shingleSize)); +} + +function validateMutationNoveltyInput(raw: unknown): { + readonly candidateId: string; + readonly candidateSlice: string; + readonly historySlices: readonly DecisionMutationNoveltyHistoryEntry[]; + readonly noveltyThreshold: number; + readonly shingleSize: number; +} { + const obj = assertSafePlainObject(raw, 'novelty'); + const candidateId = assertNonEmptyString(obj['candidateId'], 'novelty.candidateId', 128); + const candidateSlice = obj['candidateSlice']; + if (typeof candidateSlice !== 'string' || hasLoneSurrogate(candidateSlice) + || Buffer.byteLength(candidateSlice, 'utf8') > DECISION_NOVELTY_MAX_SLICE_BYTES) { + failSchema(`novelty.candidateSlice must be a well-formed string of at most ${DECISION_NOVELTY_MAX_SLICE_BYTES} UTF-8 bytes`); + } + const rawHistory = obj['historySlices']; + if (!Array.isArray(rawHistory) || rawHistory.length > DECISION_NOVELTY_MAX_HISTORY_SLICES) { + failSchema(`novelty.historySlices must be an array of at most ${DECISION_NOVELTY_MAX_HISTORY_SLICES} entries`); + } + const historySlices: DecisionMutationNoveltyHistoryEntry[] = rawHistory.map((entry, idx) => { + const entryObj = assertSafePlainObject(entry, `novelty.historySlices[${idx}]`); + const id = assertNonEmptyString(entryObj['id'], `novelty.historySlices[${idx}].id`, 128); + const sourceSlice = entryObj['sourceSlice']; + if (typeof sourceSlice !== 'string' || hasLoneSurrogate(sourceSlice) + || Buffer.byteLength(sourceSlice, 'utf8') > DECISION_NOVELTY_MAX_SLICE_BYTES) { + failSchema(`novelty.historySlices[${idx}].sourceSlice must be a well-formed string of at most ${DECISION_NOVELTY_MAX_SLICE_BYTES} UTF-8 bytes`); + } + return { id, sourceSlice }; + }); + const rawThreshold = obj['noveltyThreshold'] ?? DECISION_NOVELTY_DEFAULT_THRESHOLD; + const noveltyThreshold = assertFiniteNonNegZero(rawThreshold, 'novelty.noveltyThreshold'); + if (noveltyThreshold <= 0 || noveltyThreshold > 1) { + failSchema('novelty.noveltyThreshold must be a finite number in (0, 1]'); + } + const rawShingleSize = obj['shingleSize'] ?? DECISION_NOVELTY_DEFAULT_SHINGLE_SIZE; + const shingleSize = assertFiniteNonNegZero(rawShingleSize, 'novelty.shingleSize'); + if (!Number.isInteger(shingleSize) || shingleSize < 1 || shingleSize > 8) { + failSchema('novelty.shingleSize must be an integer in [1, 8]'); + } + return { candidateId, candidateSlice, historySlices, noveltyThreshold, shingleSize }; +} + +export interface DecisionMutationNoveltyRequest extends DecisionRequestBase { + readonly novelty: DecisionMutationNoveltyInput; +} + +/** + * Advisory inner-loop mutation novelty filter: + * 1. Normalizes `EVOLVE-BLOCK` slices and computes bounded token-shingle Jaccard similarity. + * 2. Rejects exact normalized clones (`maxSimilarity === 1`) immediately with 0 transport calls. + * 3. Accepts clearly novel candidates (`maxSimilarity < noveltyThreshold`) with 0 transport calls. + * 4. Queries System-One (`noul`) in `[noveltyThreshold, 1)` under `disclosurePolicy` to catch cosmetic + * variable renames or constant-folding clones, falling back deterministically to `accept`. + */ +export async function evaluateMutationNovelty( + request: DecisionMutationNoveltyRequest, +): Promise { + assertDecisionAuthorityBoundary('advise_mutation_novelty'); + const validated = validateMutationNoveltyInput(request.novelty); + const normalizedCandidate = normalizeEvolveBlockSource(validated.candidateSlice); + const candidateShingles = buildTokenShingles(normalizedCandidate, validated.shingleSize); + + let maxSimilarity = 0; + let matchedHistoryId: string | null = null; + let matchedNormalized = ''; + for (const entry of validated.historySlices) { + const normalizedHistory = normalizeEvolveBlockSource(entry.sourceSlice); + const similarity = jaccardSimilarity(candidateShingles, buildTokenShingles(normalizedHistory, validated.shingleSize)); + if (matchedHistoryId === null || similarity > maxSimilarity) { + maxSimilarity = similarity; + matchedHistoryId = entry.id; + matchedNormalized = normalizedHistory; + } + if (maxSimilarity === 1) break; + } + + const noveltyScore = Math.max(0, Math.min(1, 1 - maxSimilarity)); + + if (maxSimilarity === 1) { + return { + action: 'reject_resample', + noveltyScore: 0, + maxSimilarity: 1, + matchedHistoryId, + advisoryOnly: true, + verificationCertified: false, + source: 'deterministic_heuristic', + zone: null, + fallbackReason: null, + transportCalls: 0, + }; + } + + if (maxSimilarity < validated.noveltyThreshold) { + return { + action: 'accept', + noveltyScore, + maxSimilarity, + matchedHistoryId, + advisoryOnly: true, + verificationCertified: false, + source: 'deterministic_heuristic', + zone: null, + fallbackReason: null, + transportCalls: 0, + }; + } + + const questions: readonly DecisionQuestion[] = [ + { + type: 'noul', + id: 'mutation-cosmetic-clone', + prompt: `Is candidate ${validated.candidateId} a cosmetic variable rename or constant-folding clone of ${matchedHistoryId ?? 'prior history'} (Jaccard ${maxSimilarity.toFixed(4)}) with no structural algorithmic change?`, + }, + ]; + const state = mergeDecisionState(request.state, 'mutationNovelty', { + candidateId: validated.candidateId, + matchedHistoryId, + maxSimilarity, + normalizedCandidateSlice: truncateUtf8CodePointSafe( + normalizedCandidate, + DECISION_NOVELTY_STATE_SLICE_MAX_BYTES, + DECISION_NOVELTY_STATE_SLICE_CHARS, + ), + normalizedMatchedSlice: truncateUtf8CodePointSafe( + matchedNormalized, + DECISION_NOVELTY_STATE_SLICE_MAX_BYTES, + DECISION_NOVELTY_STATE_SLICE_CHARS, + ), + }); + const evaluation = await evaluateDecision({ ...request, state, questions, fallback: () => null }); + const outcome = evaluation.outcomes.find(entry => entry.output.id === 'mutation-cosmetic-clone'); + if (evaluation.mode === 'jev' && outcome !== undefined && outcome.output.type === 'noul') { + return { + action: outcome.output.affirmative ? 'reject_resample' : 'accept', + noveltyScore, + maxSimilarity, + matchedHistoryId, + advisoryOnly: true, + verificationCertified: false, + source: 'jev', + zone: evaluation.aggregateZone, + fallbackReason: null, + transportCalls: evaluation.transportCalls, + }; + } + + return { + action: 'accept', + noveltyScore, + maxSimilarity, + matchedHistoryId, + advisoryOnly: true, + verificationCertified: false, + source: evaluation.fallbackReason === null && evaluation.mode !== 'jev' + ? 'deterministic_heuristic' + : 'deterministic_fallback', + zone: evaluation.aggregateZone, + fallbackReason: evaluation.fallbackReason ?? (evaluation.mode === 'jev' ? 'invalid_response' : null), + transportCalls: evaluation.transportCalls, + }; +} + +function validateHardwareDiagnostics(raw: unknown): DecisionHardwareDiagnostics { + const obj = assertSafePlainObject(raw, 'strategy.hardwareDiagnostics'); + const boundPipeline = obj['boundPipeline']; + if (typeof boundPipeline !== 'string' || !BOUND_PIPELINES.has(boundPipeline as DecisionBoundPipeline)) { + failSchema('strategy.hardwareDiagnostics.boundPipeline must be a valid boundPipeline enum value'); + } + const optionalNonNeg = ['rooflineHeadroom', 'arithmeticIntensity', 'registerCount', 'sharedMemBytes', 'localSpillBytes'] as const; + const optionalPct = ['achievedSolPct', 'occupancyPct', 'l2HitPct', 'bankConflictPct'] as const; + const result: Record = { boundPipeline }; + for (const key of optionalNonNeg) { + if (Object.hasOwn(obj, key) && obj[key] !== undefined) { + const value = assertFiniteNonNegZero(obj[key], `strategy.hardwareDiagnostics.${key}`); + if (value < 0) failSchema(`strategy.hardwareDiagnostics.${key} must be non-negative`); + result[key] = value; + } + } + for (const key of optionalPct) { + if (Object.hasOwn(obj, key) && obj[key] !== undefined) { + const value = assertFiniteNonNegZero(obj[key], `strategy.hardwareDiagnostics.${key}`); + if (value < 0 || value > 100) failSchema(`strategy.hardwareDiagnostics.${key} must be in [0, 100]`); + result[key] = value; + } + } + return result as unknown as DecisionHardwareDiagnostics; +} + +function validateEvolutionStrategyInput(raw: unknown): DecisionEvolutionStrategyInput { + const obj = assertSafePlainObject(raw, 'strategy'); + const operatorKind = assertNonEmptyString(obj['operatorKind'], 'strategy.operatorKind', 128); + const tensorRank = assertFiniteNonNegZero(obj['tensorRank'], 'strategy.tensorRank'); + if (!Number.isInteger(tensorRank) || tensorRank < 0 || tensorRank > 16) { + failSchema('strategy.tensorRank must be an integer in [0, 16]'); + } + const dtype = assertNonEmptyString(obj['dtype'], 'strategy.dtype', 64); + if (obj['isReduction'] !== undefined && typeof obj['isReduction'] !== 'boolean') { + failSchema('strategy.isReduction must be a boolean'); + } + if (obj['isCausal'] !== undefined && typeof obj['isCausal'] !== 'boolean') { + failSchema('strategy.isCausal must be a boolean'); + } + const rawTracks = obj['declaredTracks']; + if (!Array.isArray(rawTracks) || rawTracks.length < 1 || rawTracks.length > DECISION_EVOLUTION_MAX_TRACKS) { + failSchema(`strategy.declaredTracks must declare between 1 and ${DECISION_EVOLUTION_MAX_TRACKS} tracks`); + } + const seenTracks = new Set(); + const declaredTracks: string[] = rawTracks.map((entry, idx) => { + const track = assertNonEmptyString(entry, `strategy.declaredTracks[${idx}]`, 128); + if (seenTracks.has(track)) failSchema(`duplicate track "${track}" in strategy.declaredTracks`); + seenTracks.add(track); + return track; + }); + const rawKinds = obj['allowedMutationKinds']; + if (!Array.isArray(rawKinds) || rawKinds.length < 1 || rawKinds.length > 3) { + failSchema('strategy.allowedMutationKinds must declare between 1 and 3 mutation kinds'); + } + const seenKinds = new Set(); + const allowedMutationKinds: DecisionEvolutionMutationKind[] = rawKinds.map((entry, idx) => { + if (typeof entry !== 'string' || !MUTATION_KINDS.has(entry as DecisionEvolutionMutationKind)) { + failSchema(`strategy.allowedMutationKinds[${idx}] must be diff_tune, full_rewrite, or crossover`); + } + if (seenKinds.has(entry)) failSchema(`duplicate mutation kind "${entry}" in strategy.allowedMutationKinds`); + seenKinds.add(entry); + return entry as DecisionEvolutionMutationKind; + }); + let stalledGenerations: number | undefined; + if (obj['stalledGenerations'] !== undefined) { + const val = assertFiniteNonNegZero(obj['stalledGenerations'], 'strategy.stalledGenerations'); + if (!Number.isInteger(val) || val < 0 || val > 10_000) { + failSchema('strategy.stalledGenerations must be an integer in [0, 10000]'); + } + stalledGenerations = val; + } + const hardwareDiagnostics = obj['hardwareDiagnostics'] === undefined + ? undefined + : validateHardwareDiagnostics(obj['hardwareDiagnostics']); + return { + operatorKind, + tensorRank, + dtype, + ...(obj['isReduction'] !== undefined ? { isReduction: obj['isReduction'] as boolean } : {}), + ...(obj['isCausal'] !== undefined ? { isCausal: obj['isCausal'] as boolean } : {}), + declaredTracks, + allowedMutationKinds, + ...(stalledGenerations !== undefined ? { stalledGenerations } : {}), + ...(hardwareDiagnostics !== undefined ? { hardwareDiagnostics } : {}), + }; +} + +function pickDeclaredTrack(declaredTracks: readonly string[], preferredSubstrings: readonly string[]): string { + for (const hint of preferredSubstrings) { + const match = declaredTracks.find(track => track.toLowerCase().includes(hint)); + if (match !== undefined) return match; + } + return declaredTracks[0] as string; +} + +function pickAllowedMutation( + allowed: readonly DecisionEvolutionMutationKind[], + preferred: readonly DecisionEvolutionMutationKind[], +): DecisionEvolutionMutationKind { + for (const kind of preferred) { + if (allowed.includes(kind)) return kind; + } + return allowed[0] as DecisionEvolutionMutationKind; +} + +/** Deterministic Roofline fallback for `routeEvolutionStrategy`, always selecting from declared tracks and mutation kinds. */ +export function heuristicEvolutionStrategy( + strategy: DecisionEvolutionStrategyInput, +): { readonly trackId: string; readonly mutationKind: DecisionEvolutionMutationKind } { + const diag = strategy.hardwareDiagnostics; + const bound = diag?.boundPipeline ?? 'unknown'; + const highSpills = (diag?.localSpillBytes ?? 0) > 0; + const lowOccupancy = diag?.occupancyPct !== undefined && diag.occupancyPct < 35; + const highHeadroom = diag?.rooflineHeadroom !== undefined && diag.rooflineHeadroom > 1.5; + const stalled = (strategy.stalledGenerations ?? 0) >= 3; + + let mutationKind: DecisionEvolutionMutationKind; + if (highSpills) { + mutationKind = pickAllowedMutation(strategy.allowedMutationKinds, ['diff_tune', 'full_rewrite', 'crossover']); + } else if (stalled) { + mutationKind = pickAllowedMutation(strategy.allowedMutationKinds, ['full_rewrite', 'crossover', 'diff_tune']); + } else if (bound === 'smem_lds_ub' || bound === 'hbm') { + mutationKind = lowOccupancy || highHeadroom + ? pickAllowedMutation(strategy.allowedMutationKinds, ['full_rewrite', 'crossover', 'diff_tune']) + : pickAllowedMutation(strategy.allowedMutationKinds, ['diff_tune', 'full_rewrite', 'crossover']); + } else if (bound === 'tensor_cube' || bound === 'vector_valu') { + const tightHeadroom = diag?.rooflineHeadroom !== undefined && diag.rooflineHeadroom <= 1.15; + mutationKind = tightHeadroom + ? pickAllowedMutation(strategy.allowedMutationKinds, ['diff_tune', 'crossover', 'full_rewrite']) + : pickAllowedMutation(strategy.allowedMutationKinds, ['crossover', 'diff_tune', 'full_rewrite']); + } else { + mutationKind = pickAllowedMutation(strategy.allowedMutationKinds, ['diff_tune', 'crossover', 'full_rewrite']); + } + + let trackId: string; + if (highSpills || bound === 'smem_lds_ub' || bound === 'hbm' || lowOccupancy) { + trackId = pickDeclaredTrack(strategy.declaredTracks, ['cute', 'cuda_raw', 'ascend_tile', 'ascend_regbase', 'triton', 'ascend_simt']); + } else if (bound === 'tensor_cube') { + trackId = pickDeclaredTrack(strategy.declaredTracks, ['cute', 'ascend_tile', 'triton', 'cuda_raw', 'ascend_regbase']); + } else if (bound === 'vector_valu' || strategy.isReduction === true) { + trackId = pickDeclaredTrack(strategy.declaredTracks, ['triton', 'ascend_simt', 'ascend_regbase', 'cuda_raw', 'cute']); + } else { + trackId = strategy.declaredTracks[0] as string; + } + + return { trackId, mutationKind }; +} + +export interface DecisionRouteEvolutionStrategyRequest extends DecisionRequestBase { + readonly strategy: DecisionEvolutionStrategyInput; +} + +/** + * Advisory strategy track router: chooses `{ trackId, mutationKind }` strictly from the campaign's + * declared track and mutation sets, falling back to deterministic Roofline rules when System-One is + * disabled, offline, disclosure-blocked, low-confidence, or returns an undeclared option. + */ +export async function routeEvolutionStrategy( + request: DecisionRouteEvolutionStrategyRequest, +): Promise { + assertDecisionAuthorityBoundary('route_evolution_strategy'); + const validated = validateEvolutionStrategyInput(request.strategy); + const trackOptions: Record = {}; + for (const track of validated.declaredTracks) trackOptions[track] = `Use declared evolution track ${track}`; + const mutationOptions: Record = {}; + for (const kind of validated.allowedMutationKinds) mutationOptions[kind] = `Apply ${kind} mutation`; + + const questions: readonly DecisionQuestion[] = [ + { + type: 'choice', + id: 'evolution-track', + prompt: `Select the best declared evolution track for ${validated.operatorKind} (rank ${validated.tensorRank}, ${validated.dtype}).`, + options: trackOptions, + }, + { + type: 'choice', + id: 'evolution-mutation-kind', + prompt: `Select the best allowed mutation kind for ${validated.operatorKind} given current hardware diagnostics.`, + options: mutationOptions, + }, + ]; + const state = mergeDecisionState(request.state, 'evolutionStrategy', { + operatorKind: validated.operatorKind, + tensorRank: validated.tensorRank, + dtype: validated.dtype, + isReduction: validated.isReduction ?? false, + isCausal: validated.isCausal ?? false, + declaredTracks: validated.declaredTracks, + allowedMutationKinds: validated.allowedMutationKinds, + ...(validated.stalledGenerations !== undefined ? { stalledGenerations: validated.stalledGenerations } : {}), + ...(validated.hardwareDiagnostics !== undefined ? { hardwareDiagnostics: validated.hardwareDiagnostics } : {}), + }); + + const evaluation = await evaluateDecision({ ...request, state, questions, fallback: () => null }); + const trackAnswer = evaluation.outcomes.find(entry => entry.output.id === 'evolution-track')?.output; + const mutationAnswer = evaluation.outcomes.find(entry => entry.output.id === 'evolution-mutation-kind')?.output; + + const validJevTrack = trackAnswer !== undefined + && trackAnswer.type === 'choice' + && trackAnswer.choice !== null + && validated.declaredTracks.includes(trackAnswer.choice); + const validJevMutation = mutationAnswer !== undefined + && mutationAnswer.type === 'choice' + && mutationAnswer.choice !== null + && validated.allowedMutationKinds.includes(mutationAnswer.choice as DecisionEvolutionMutationKind); + + if (evaluation.mode === 'jev' && validJevTrack && validJevMutation) { + return { + trackId: trackAnswer.choice as string, + mutationKind: mutationAnswer.choice as DecisionEvolutionMutationKind, + advisoryOnly: true, + verificationCertified: false, + source: 'jev', + zone: evaluation.aggregateZone, + fallbackReason: null, + transportCalls: evaluation.transportCalls, + }; + } + + const fallback = heuristicEvolutionStrategy(validated); + return { + trackId: fallback.trackId, + mutationKind: fallback.mutationKind, + advisoryOnly: true, + verificationCertified: false, + source: evaluation.fallbackReason === null && evaluation.mode !== 'jev' ? 'deterministic_heuristic' : 'deterministic_fallback', + zone: evaluation.aggregateZone, + fallbackReason: evaluation.fallbackReason ?? (evaluation.mode === 'jev' ? 'invalid_response' : null), + transportCalls: evaluation.transportCalls, + }; +} + +function validateMetricsMap(raw: unknown, label: string, minKeys: number): Readonly> { + const obj = assertSafePlainObject(raw, label); + const keys = Object.keys(obj); + if (keys.length < minKeys || keys.length > DECISION_EVOLUTION_MAX_METRICS) { + failSchema(`${label} must have between ${minKeys} and ${DECISION_EVOLUTION_MAX_METRICS} numeric entries`); + } + const normalized: Record = Object.create(null) as Record; + for (const key of keys) { + assertNonEmptyString(key, `${label} key`, 128); + normalized[key] = assertFiniteNonNegZero(obj[key], `${label}.${key}`); + } + return normalized; +} + +function validateCascadeEscalationInput(raw: unknown): DecisionCascadeEscalationInput { + const obj = assertSafePlainObject(raw, 'cascade'); + const candidateId = assertNonEmptyString(obj['candidateId'], 'cascade.candidateId', 128); + if (typeof obj['smokeCorrectnessPassed'] !== 'boolean') { + failSchema('cascade.smokeCorrectnessPassed must be a boolean'); + } + const smokeMetrics = validateMetricsMap(obj['smokeMetrics'], 'cascade.smokeMetrics', 1); + const referenceMetrics = validateMetricsMap(obj['referenceMetrics'], 'cascade.referenceMetrics', 0); + const primaryMetric = assertNonEmptyString(obj['primaryMetric'], 'cascade.primaryMetric', 128); + if (!Object.hasOwn(smokeMetrics, primaryMetric)) { + failSchema(`cascade.primaryMetric "${primaryMetric}" must exist in cascade.smokeMetrics`); + } + const direction = obj['direction']; + if (direction !== 'minimize' && direction !== 'maximize') { + failSchema('cascade.direction must be minimize or maximize'); + } + const remainingBudgetRatio = assertFiniteNonNegZero(obj['remainingBudgetRatio'], 'cascade.remainingBudgetRatio'); + if (remainingBudgetRatio < 0 || remainingBudgetRatio > 1) { + failSchema('cascade.remainingBudgetRatio must be in [0, 1]'); + } + let regressionToleranceRatio: number | undefined; + if (obj['regressionToleranceRatio'] !== undefined) { + const tol = assertFiniteNonNegZero(obj['regressionToleranceRatio'], 'cascade.regressionToleranceRatio'); + if (tol < 0 || tol > 1) failSchema('cascade.regressionToleranceRatio must be in [0, 1]'); + regressionToleranceRatio = tol; + } + return { + candidateId, + smokeCorrectnessPassed: obj['smokeCorrectnessPassed'] as boolean, + smokeMetrics, + referenceMetrics, + primaryMetric, + direction, + remainingBudgetRatio, + ...(regressionToleranceRatio !== undefined ? { regressionToleranceRatio } : {}), + }; +} + +/** Deterministic fallback for `evaluateCascadeEscalation`. */ +export function heuristicCascadeEscalation(cascade: DecisionCascadeEscalationInput): DecisionCascadeAction { + if (!cascade.smokeCorrectnessPassed) return 'prune'; + const smokeVal = cascade.smokeMetrics[cascade.primaryMetric]; + const refVal = cascade.referenceMetrics[cascade.primaryMetric]; + if (smokeVal === undefined) return 'prune'; + if (refVal === undefined || refVal === 0) { + return cascade.remainingBudgetRatio > 0.2 ? 'escalate' : 'confirm'; + } + const gain = cascade.direction === 'minimize' + ? (refVal - smokeVal) / Math.abs(refVal) + : (smokeVal - refVal) / Math.abs(refVal); + if (gain > 0) return 'escalate'; + const tolerance = cascade.regressionToleranceRatio ?? DECISION_CASCADE_DEFAULT_REGRESSION_TOLERANCE; + if (gain >= -tolerance && cascade.remainingBudgetRatio >= 0.25) return 'confirm'; + return 'prune'; +} + +export interface DecisionCascadeEscalationRequest extends DecisionRequestBase { + readonly cascade: DecisionCascadeEscalationInput; +} + +/** + * Advisory cascade escalation filter: if smoke correctness failed, deterministically returns `'prune'` + * with 0 transport calls. Otherwise queries System-One for `'prune' | 'confirm' | 'escalate'` to the + * full multi-bucket benchmark gate, never certifying verification (`verificationCertified: false`). + */ +export async function evaluateCascadeEscalation( + request: DecisionCascadeEscalationRequest, +): Promise { + assertDecisionAuthorityBoundary('advise_cascade_escalation'); + const validated = validateCascadeEscalationInput(request.cascade); + if (!validated.smokeCorrectnessPassed) { + return { + action: 'prune', + smokeCorrectnessPassed: false, + advisoryOnly: true, + verificationCertified: false, + source: 'deterministic_heuristic', + zone: null, + fallbackReason: null, + transportCalls: 0, + }; + } + + const questions: readonly DecisionQuestion[] = [ + { + type: 'choice', + id: 'cascade-escalation', + prompt: `Smoke correctness passed for ${validated.candidateId} (primary metric ${validated.primaryMetric}, ${validated.direction}). Should this candidate prune, confirm, or escalate to full benchmark verification?`, + options: { + prune: 'Prune candidate before full benchmark gate', + confirm: 'Run a confirmation check before full escalation', + escalate: 'Escalate candidate to full multi-bucket benchmark gate', + }, + }, + ]; + const state = mergeDecisionState(request.state, 'cascadeEscalation', { + candidateId: validated.candidateId, + smokeCorrectnessPassed: true, + smokeMetrics: { ...validated.smokeMetrics }, + referenceMetrics: { ...validated.referenceMetrics }, + primaryMetric: validated.primaryMetric, + direction: validated.direction, + remainingBudgetRatio: validated.remainingBudgetRatio, + }); + + const evaluation = await evaluateDecision({ ...request, state, questions, fallback: () => null }); + const answer = evaluation.outcomes.find(entry => entry.output.id === 'cascade-escalation')?.output; + if ( + evaluation.mode === 'jev' + && answer !== undefined + && answer.type === 'choice' + && answer.choice !== null + && CASCADE_ACTIONS.has(answer.choice as DecisionCascadeAction) + ) { + return { + action: answer.choice as DecisionCascadeAction, + smokeCorrectnessPassed: true, + advisoryOnly: true, + verificationCertified: false, + source: 'jev', + zone: evaluation.aggregateZone, + fallbackReason: null, + transportCalls: evaluation.transportCalls, + }; + } + + return { + action: heuristicCascadeEscalation(validated), + smokeCorrectnessPassed: true, + advisoryOnly: true, + verificationCertified: false, + source: evaluation.fallbackReason === null && evaluation.mode !== 'jev' ? 'deterministic_heuristic' : 'deterministic_fallback', + zone: evaluation.aggregateZone, + fallbackReason: evaluation.fallbackReason ?? (evaluation.mode === 'jev' ? 'invalid_response' : null), + transportCalls: evaluation.transportCalls, + }; +} diff --git a/packages/decisions/src/types.ts b/packages/decisions/src/types.ts index 3955522..896d94e 100644 --- a/packages/decisions/src/types.ts +++ b/packages/decisions/src/types.ts @@ -359,8 +359,121 @@ export const DECISION_ALLOWED_AUTHORITY_INTENTS: readonly string[] = Object.free 'evaluate_cycle_alignment', 'advise_soft_compaction', 'triage_candidate_diff', + 'advise_mutation_novelty', + 'route_evolution_strategy', + 'advise_cascade_escalation', ]); +export const DECISION_NOVELTY_DEFAULT_THRESHOLD = 0.85; +export const DECISION_NOVELTY_DEFAULT_SHINGLE_SIZE = 3; +export const DECISION_NOVELTY_MAX_SLICE_BYTES = 32_768; +export const DECISION_NOVELTY_MAX_HISTORY_SLICES = 64; +export const DECISION_NOVELTY_MAX_SHINGLES = 4_096; +export const DECISION_NOVELTY_STATE_SLICE_CHARS = 24_576; +export const DECISION_EVOLUTION_MAX_TRACKS = 32; +export const DECISION_EVOLUTION_MAX_METRICS = 32; +export const DECISION_CASCADE_DEFAULT_REGRESSION_TOLERANCE = 0.05; + +export type DecisionMutationNoveltyAction = 'accept' | 'reject_resample'; + +export interface DecisionMutationNoveltyHistoryEntry { + readonly id: string; + readonly sourceSlice: string; +} + +export interface DecisionMutationNoveltyInput { + readonly candidateId: string; + readonly candidateSlice: string; + readonly historySlices: readonly DecisionMutationNoveltyHistoryEntry[]; + readonly noveltyThreshold?: number; + readonly shingleSize?: number; +} + +export interface DecisionMutationNoveltyResult { + readonly action: DecisionMutationNoveltyAction; + readonly noveltyScore: number; + readonly maxSimilarity: number; + readonly matchedHistoryId: string | null; + readonly advisoryOnly: true; + readonly verificationCertified: false; + readonly source: DecisionSource; + readonly zone: DecisionConfidenceZone | null; + readonly fallbackReason: DecisionFallbackReason; + readonly transportCalls: number; +} + +export type DecisionBoundPipeline = + | 'hbm' + | 'l2' + | 'smem_lds_ub' + | 'tensor_cube' + | 'vector_valu' + | 'host_launch' + | 'comm' + | 'unknown'; + +export type DecisionEvolutionMutationKind = 'diff_tune' | 'full_rewrite' | 'crossover'; + +export interface DecisionHardwareDiagnostics { + readonly boundPipeline: DecisionBoundPipeline; + readonly rooflineHeadroom?: number; + readonly achievedSolPct?: number; + readonly arithmeticIntensity?: number; + readonly occupancyPct?: number; + readonly registerCount?: number; + readonly sharedMemBytes?: number; + readonly localSpillBytes?: number; + readonly l2HitPct?: number; + readonly bankConflictPct?: number; +} + +export interface DecisionEvolutionStrategyInput { + readonly operatorKind: string; + readonly tensorRank: number; + readonly dtype: string; + readonly isReduction?: boolean; + readonly isCausal?: boolean; + readonly declaredTracks: readonly string[]; + readonly allowedMutationKinds: readonly DecisionEvolutionMutationKind[]; + readonly stalledGenerations?: number; + readonly hardwareDiagnostics?: DecisionHardwareDiagnostics; +} + +export interface DecisionEvolutionStrategyResult { + readonly trackId: string; + readonly mutationKind: DecisionEvolutionMutationKind; + readonly advisoryOnly: true; + readonly verificationCertified: false; + readonly source: DecisionSource; + readonly zone: DecisionConfidenceZone | null; + readonly fallbackReason: DecisionFallbackReason; + readonly transportCalls: number; +} + +export type DecisionCascadeAction = 'prune' | 'confirm' | 'escalate'; + +export interface DecisionCascadeEscalationInput { + readonly candidateId: string; + readonly smokeCorrectnessPassed: boolean; + readonly smokeMetrics: Readonly>; + readonly referenceMetrics: Readonly>; + readonly primaryMetric: string; + readonly direction: 'minimize' | 'maximize'; + readonly remainingBudgetRatio: number; + readonly regressionToleranceRatio?: number; +} + +export interface DecisionCascadeEscalationResult { + readonly action: DecisionCascadeAction; + readonly smokeCorrectnessPassed: boolean; + readonly advisoryOnly: true; + readonly verificationCertified: false; + readonly source: DecisionSource; + readonly zone: DecisionConfidenceZone | null; + readonly fallbackReason: DecisionFallbackReason; + readonly transportCalls: number; +} + export type DecisionCapabilityTier = 'fast' | 'balanced' | 'strongest'; export interface DecisionTaskMetadata { diff --git a/packages/decisions/test/evolution-nodes.test.ts b/packages/decisions/test/evolution-nodes.test.ts new file mode 100644 index 0000000..6c0a9ae --- /dev/null +++ b/packages/decisions/test/evolution-nodes.test.ts @@ -0,0 +1,568 @@ +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; +import { DecisionBudgetTracker } from '../src/client.js'; +import { + assertDecisionAuthorityBoundary, + computeTokenShingleJaccard, + evaluateCascadeEscalation, + evaluateMutationNovelty, + heuristicCascadeEscalation, + heuristicEvolutionStrategy, + normalizeEvolveBlockSource, + routeEvolutionStrategy, +} from '../src/nodes.js'; +import type { DecisionRequestBase } from '../src/router.js'; +import { validateDecisionPolicy } from '../src/schema.js'; +import { + DECISION_ALLOWED_AUTHORITY_INTENTS, + DECISION_FORBIDDEN_AUTHORITY_INTENTS, + DecisionError, +} from '../src/types.js'; +import type { + DecisionCascadeEscalationInput, + DecisionEvolutionStrategyInput, + DecisionMutationNoveltyInput, + DecisionPolicyConfig, + DecisionTransport, +} from '../src/types.js'; + +function policy(overrides: Partial> = {}): DecisionPolicyConfig { + return validateDecisionPolicy({ + enabled: true, + disclosurePolicy: 'repo-approved-redacted-evidence', + ...overrides, + }); +} + +function transportFor( + payload: (body: Record) => Record, +): DecisionTransport & { calls: () => number; lastBody: () => Record | null } { + let calls = 0; + let last: Record | null = null; + return { + calls: () => calls, + lastBody: () => last, + async send(req) { + calls += 1; + last = JSON.parse(req.body) as Record; + return { status: 200, body: JSON.stringify(payload(last)) }; + }, + }; +} + +function base(overrides: Partial = {}): DecisionRequestBase { + return { + policy: policy(), + state: {}, + budget: new DecisionBudgetTracker(), + apiKey: 'fixture-decision-key', + ...overrides, + }; +} + +describe('evolution authority boundaries', () => { + it('registers the three evolution advisory intents in DECISION_ALLOWED_AUTHORITY_INTENTS', () => { + for (const intent of [ + 'advise_mutation_novelty', + 'route_evolution_strategy', + 'advise_cascade_escalation', + ]) { + assert.ok(DECISION_ALLOWED_AUTHORITY_INTENTS.includes(intent), `missing allowed intent ${intent}`); + assert.doesNotThrow(() => assertDecisionAuthorityBoundary(intent)); + } + }); + + it('strictly refuses all forbidden authority intents with DECISION_AUTHORITY_VIOLATION and authorityViolation: true', () => { + const forbiddenIntents = [ + ...DECISION_FORBIDDEN_AUTHORITY_INTENTS, + 'approve_gate', + 'mint_evidence', + 'bypass_sandbox', + 'override_scope', + 'publish_unverified', + 'mutate_protected_workflow', + ]; + for (const intent of forbiddenIntents) { + assert.throws( + () => assertDecisionAuthorityBoundary(intent), + (error: unknown) => + error instanceof DecisionError + && error.code === 'DECISION_AUTHORITY_VIOLATION' + && error.authorityViolation === true, + ); + } + }); +}); + +describe('evaluateMutationNovelty', () => { + const baselineKernel = ` + // Compute tiled dot product + __device__ void gemm_tile(float* a, float* b, float* c, int n) { + /* Accumulate across K */ + float acc = 0.0f; + for (int k = 0; k < n; ++k) { + acc += a[k] * b[k]; + } + c[0] = acc; + } + `; + + it('normalizes comments (//, /* */, #) and whitespace while preserving string/template literals, preprocessor directives, and private fields', () => { + const withComments = ` + # python-style comment + #pragma unroll 4 + const char* tag = "keep // # /* inside */"; // trailing + const tpl = \`keep // # /* inside template */\`; + /* multi-line + comment */ + int x = obj.#secretVal + 2; + `; + const normalized = normalizeEvolveBlockSource(withComments); + assert.equal( + normalized, + '#pragma unroll 4 const char* tag = "keep // # /* inside */"; const tpl = `keep // # /* inside template */`; int x = obj.#secretVal + 2;', + ); + }); + + it('bounds multi-byte UTF-8 and emoji novelty slices under DECISION_MAX_STATE_BYTES without splitting surrogate pairs', async () => { + const emojiBlock = 'const char* s = "' + '\u{1F680}'.repeat(7_000) + '";'; + const candidateBlock = `${emojiBlock}\nint v = 2;`; + const historyBlock = `${emojiBlock}\nint v = 1;`; + const transport = transportFor(() => ({ + answers: { 'mutation-cosmetic-clone': { noul: 0.1 } }, + })); + const result = await evaluateMutationNovelty({ + ...base({ transport }), + novelty: { + candidateId: 'cand-utf8-emoji', + candidateSlice: candidateBlock, + historySlices: [{ id: 'hist-emoji', sourceSlice: historyBlock }], + noveltyThreshold: 0.5, + }, + }); + assert.equal(result.action, 'accept'); + assert.equal(result.source, 'jev'); + }); + + it('rejects exact whitespace/comment-only clones (Jaccard === 1.0) with 0 transport calls', async () => { + const transport = transportFor(() => { + throw new Error('must not be called for exact normalized clone'); + }); + const whitespaceOnlyEdit = ` + # different comment style + __device__ void gemm_tile(float* a, float* b, float* c, int n) { + float acc = 0.0f; + for (int k = 0; k < n; ++k) { acc += a[k] * b[k]; } + c[0] = acc; + } + `; + const input: DecisionMutationNoveltyInput = { + candidateId: 'cand-clone', + candidateSlice: whitespaceOnlyEdit, + historySlices: [{ id: 'hist-1', sourceSlice: baselineKernel }], + }; + const result = await evaluateMutationNovelty({ ...base({ transport }), novelty: input }); + assert.equal(result.action, 'reject_resample'); + assert.equal(result.noveltyScore, 0); + assert.equal(result.maxSimilarity, 1); + assert.equal(result.matchedHistoryId, 'hist-1'); + assert.equal(result.source, 'deterministic_heuristic'); + assert.equal(result.transportCalls, 0); + assert.equal(result.advisoryOnly, true); + assert.equal(result.verificationCertified, false); + assert.equal(transport.calls(), 0); + }); + + it('accepts structurally distinct candidates below noveltyThreshold with 0 transport calls', async () => { + const transport = transportFor(() => { + throw new Error('must not be called below noveltyThreshold'); + }); + const novelKernel = ` + __device__ void warp_reduce_softmax(half* logits, int stride) { + float m = -INFINITY; + for (int lane = threadIdx.x; lane < stride; lane += 32) { + m = fmaxf(m, __half2float(logits[lane])); + } + m = fmaxf(m, __shfl_xor_sync(0xffffffff, m, 16)); + } + `; + const result = await evaluateMutationNovelty({ + ...base({ transport }), + novelty: { + candidateId: 'cand-novel', + candidateSlice: novelKernel, + historySlices: [{ id: 'hist-1', sourceSlice: baselineKernel }], + noveltyThreshold: 0.85, + }, + }); + assert.equal(result.action, 'accept'); + assert.ok(result.maxSimilarity < 0.85); + assert.ok(result.noveltyScore > 0.15); + assert.equal(result.source, 'deterministic_heuristic'); + assert.equal(result.transportCalls, 0); + assert.equal(result.advisoryOnly, true); + assert.equal(result.verificationCertified, false); + assert.equal(transport.calls(), 0); + }); + + it('queries System-One noul in the soft high-similarity band [noveltyThreshold, 1.0) and rejects cosmetic clones', async () => { + const renamedKernel = ` + __device__ void gemm_tile(float* a, float* b, float* c, int n) { + float sum = 0.0f; + for (int k = 0; k < n; ++k) { + sum += a[k] * b[k]; + } + c[0] = sum; + } + `; + const sim = computeTokenShingleJaccard(baselineKernel, renamedKernel); + assert.ok(sim >= 0.5 && sim < 1.0, `expected soft-band similarity, got ${sim}`); + + const transport = transportFor(() => ({ + answers: { 'mutation-cosmetic-clone': { noul: 0.96 } }, + usage: { input_tokens: 45, output_tokens: 5 }, + })); + const result = await evaluateMutationNovelty({ + ...base({ transport }), + novelty: { + candidateId: 'cand-rename', + candidateSlice: renamedKernel, + historySlices: [{ id: 'hist-1', sourceSlice: baselineKernel }], + noveltyThreshold: 0.5, + }, + }); + assert.equal(result.action, 'reject_resample'); + assert.equal(result.source, 'jev'); + assert.equal(result.zone, 'high'); + assert.equal(result.fallbackReason, null); + assert.equal(result.transportCalls, 1); + assert.equal(result.advisoryOnly, true); + assert.equal(result.verificationCertified, false); + }); + + it('accepts soft-band candidates when System-One noul says not a cosmetic clone, or falls back deterministically when disabled/low-confidence/disclosure-blocked', async () => { + const tunedKernel = ` + __device__ void gemm_tile(float* a, float* b, float* c, int n) { + float acc = 0.0f; + for (int k = 0; k < n; k += 2) { + acc += a[k] * b[k]; + } + c[0] = acc; + } + `; + const novelty: DecisionMutationNoveltyInput = { + candidateId: 'cand-tune', + candidateSlice: tunedKernel, + historySlices: [{ id: 'hist-1', sourceSlice: baselineKernel }], + noveltyThreshold: 0.5, + }; + + // System-One says NOT a cosmetic clone (noul = 0.05 -> confidence 0.90, affirmative = false) + const acceptTransport = transportFor(() => ({ + answers: { 'mutation-cosmetic-clone': { noul: 0.05 } }, + })); + const accepted = await evaluateMutationNovelty({ ...base({ transport: acceptTransport }), novelty }); + assert.equal(accepted.action, 'accept'); + assert.equal(accepted.source, 'jev'); + assert.equal(accepted.transportCalls, 1); + assert.equal(accepted.advisoryOnly, true); + assert.equal(accepted.verificationCertified, false); + + // Disabled policy -> deterministic fallback, 0 transport calls + const disabled = await evaluateMutationNovelty({ + ...base({ policy: policy({ enabled: false }) }), + novelty, + }); + assert.equal(disabled.action, 'accept'); + assert.equal(disabled.source, 'deterministic_fallback'); + assert.equal(disabled.fallbackReason, 'policy_disabled'); + assert.equal(disabled.transportCalls, 0); + assert.equal(disabled.advisoryOnly, true); + assert.equal(disabled.verificationCertified, false); + + // Low confidence -> deterministic fallback + const lowConfTransport = transportFor(() => ({ + answers: { 'mutation-cosmetic-clone': { noul: 0.52 } }, + })); + const lowConf = await evaluateMutationNovelty({ ...base({ transport: lowConfTransport }), novelty }); + assert.equal(lowConf.action, 'accept'); + assert.equal(lowConf.source, 'deterministic_fallback'); + assert.equal(lowConf.fallbackReason, 'low_confidence'); + assert.equal(lowConf.transportCalls, 1); + + // Secret in slice -> disclosure_violation fallback with 0 transport calls + const secretTransport = transportFor(() => { + throw new Error('must not be called when slice contains secret'); + }); + const secretSlice = `${tunedKernel}\nconst char* key = "ghp_1234567890abcdefghij123456";`; + const secretResult = await evaluateMutationNovelty({ + ...base({ transport: secretTransport }), + novelty: { ...novelty, candidateSlice: secretSlice, noveltyThreshold: 0.4 }, + }); + assert.equal(secretResult.source, 'deterministic_fallback'); + assert.equal(secretResult.fallbackReason, 'disclosure_violation'); + assert.equal(secretResult.transportCalls, 0); + assert.equal(secretTransport.calls(), 0); + }); + + it('validates untrusted novelty inputs including null-prototype objects and threshold bounds', async () => { + const nullProtoInput = Object.assign(Object.create(null), { + candidateId: 'cand-np', + candidateSlice: 'int x = 1;', + historySlices: [Object.assign(Object.create(null), { id: 'h1', sourceSlice: 'int x = 1;' })], + }) as DecisionMutationNoveltyInput; + const res = await evaluateMutationNovelty({ ...base(), novelty: nullProtoInput }); + assert.equal(res.action, 'reject_resample'); + + await assert.rejects( + () => evaluateMutationNovelty({ + ...base(), + novelty: { candidateId: 'c', candidateSlice: 'a', historySlices: [], noveltyThreshold: 0 }, + }), + (err: unknown) => err instanceof DecisionError && err.code === 'DECISION_SCHEMA_INVALID', + ); + await assert.rejects( + () => evaluateMutationNovelty({ + ...base(), + novelty: { candidateId: 'c', candidateSlice: 'a', historySlices: [], noveltyThreshold: 1.1 }, + }), + (err: unknown) => err instanceof DecisionError && err.code === 'DECISION_SCHEMA_INVALID', + ); + }); +}); + +describe('routeEvolutionStrategy', () => { + const baseStrategy: DecisionEvolutionStrategyInput = { + operatorKind: 'flash_decode', + tensorRank: 4, + dtype: 'bf16', + isReduction: true, + isCausal: true, + declaredTracks: ['triton', 'cute', 'cuda_raw'], + allowedMutationKinds: ['diff_tune', 'full_rewrite', 'crossover'], + hardwareDiagnostics: { + boundPipeline: 'smem_lds_ub', + rooflineHeadroom: 1.6, + occupancyPct: 28, + localSpillBytes: 0, + }, + }; + + it('selects declared trackId and mutationKind via System-One when high-confidence', async () => { + const transport = transportFor(() => ({ + answers: { + 'evolution-track': { + choice: 'cute', + confidence: 0.91, + probabilities: { triton: 0.04, cute: 0.91, cuda_raw: 0.05 }, + }, + 'evolution-mutation-kind': { + choice: 'full_rewrite', + confidence: 0.89, + probabilities: { diff_tune: 0.06, full_rewrite: 0.89, crossover: 0.05 }, + }, + }, + usage: { input_tokens: 70, output_tokens: 10 }, + })); + + const result = await routeEvolutionStrategy({ ...base({ transport }), strategy: baseStrategy }); + assert.equal(result.trackId, 'cute'); + assert.equal(result.mutationKind, 'full_rewrite'); + assert.equal(result.source, 'jev'); + assert.equal(result.transportCalls, 1); + assert.equal(result.advisoryOnly, true); + assert.equal(result.verificationCertified, false); + }); + + it('fails closed to deterministic Roofline fallback if provider returns an undeclared track', async () => { + const transport = transportFor(() => ({ + answers: { + 'evolution-track': { + choice: 'undeclared_custom_dsl', + confidence: 0.95, + probabilities: { triton: 0.02, cute: 0.95, cuda_raw: 0.03 }, + }, + 'evolution-mutation-kind': { + choice: 'diff_tune', + confidence: 0.95, + probabilities: { diff_tune: 0.95, full_rewrite: 0.03, crossover: 0.02 }, + }, + }, + })); + + const result = await routeEvolutionStrategy({ ...base({ transport }), strategy: baseStrategy }); + assert.ok(baseStrategy.declaredTracks.includes(result.trackId)); + assert.ok(baseStrategy.allowedMutationKinds.includes(result.mutationKind)); + assert.equal(result.source, 'deterministic_fallback'); + assert.equal(result.fallbackReason, 'invalid_response'); + assert.equal(result.advisoryOnly, true); + assert.equal(result.verificationCertified, false); + }); + + it('applies deterministic Roofline fallback rules for spills, smem/hbm low occupancy, and tensor_cube', async () => { + // High register spills -> diff_tune + low-level track + const spillStrategy: DecisionEvolutionStrategyInput = { + ...baseStrategy, + hardwareDiagnostics: { + boundPipeline: 'vector_valu', + rooflineHeadroom: 1.3, + occupancyPct: 50, + localSpillBytes: 128, + }, + }; + const spillResult = await routeEvolutionStrategy({ + ...base({ policy: policy({ enabled: false }) }), + strategy: spillStrategy, + }); + assert.equal(spillResult.mutationKind, 'diff_tune'); + assert.equal(spillResult.trackId, 'cute'); + assert.equal(spillResult.source, 'deterministic_fallback'); + assert.equal(spillResult.fallbackReason, 'policy_disabled'); + assert.equal(spillResult.transportCalls, 0); + assert.equal(spillResult.advisoryOnly, true); + assert.equal(spillResult.verificationCertified, false); + + // smem_lds_ub + low occupancy -> full_rewrite + layout track + const smemHeuristic = heuristicEvolutionStrategy(baseStrategy); + assert.equal(smemHeuristic.mutationKind, 'full_rewrite'); + assert.equal(smemHeuristic.trackId, 'cute'); + + // Ascend tracks only -> strictly picks from declared Ascend tracks + const ascendHeuristic = heuristicEvolutionStrategy({ + ...baseStrategy, + declaredTracks: ['ascend_tile', 'ascend_regbase', 'ascend_simt'], + hardwareDiagnostics: { boundPipeline: 'tensor_cube', rooflineHeadroom: 1.4, occupancyPct: 70 }, + }); + assert.equal(ascendHeuristic.trackId, 'ascend_tile'); + assert.equal(ascendHeuristic.mutationKind, 'crossover'); + }); + + it('rejects empty declaredTracks or invalid diagnostics with DECISION_SCHEMA_INVALID', async () => { + await assert.rejects( + () => routeEvolutionStrategy({ + ...base(), + strategy: { ...baseStrategy, declaredTracks: [] }, + }), + (err: unknown) => err instanceof DecisionError && err.code === 'DECISION_SCHEMA_INVALID', + ); + }); +}); + +describe('evaluateCascadeEscalation', () => { + const baseCascade: DecisionCascadeEscalationInput = { + candidateId: 'cand-42', + smokeCorrectnessPassed: true, + smokeMetrics: { latency_us_p50: 85, peak_mem_bytes: 1024 }, + referenceMetrics: { latency_us_p50: 100, peak_mem_bytes: 1024 }, + primaryMetric: 'latency_us_p50', + direction: 'minimize', + remainingBudgetRatio: 0.6, + }; + + it('deterministically prunes with 0 transport calls when smoke correctness failed', async () => { + const transport = transportFor(() => { + throw new Error('must not be called when smoke correctness failed'); + }); + const result = await evaluateCascadeEscalation({ + ...base({ transport }), + cascade: { ...baseCascade, smokeCorrectnessPassed: false }, + }); + assert.equal(result.action, 'prune'); + assert.equal(result.smokeCorrectnessPassed, false); + assert.equal(result.source, 'deterministic_heuristic'); + assert.equal(result.transportCalls, 0); + assert.equal(result.advisoryOnly, true); + assert.equal(result.verificationCertified, false); + assert.equal(transport.calls(), 0); + }); + + it('accepts high-confidence System-One prune | confirm | escalate decisions while never certifying verification', async () => { + for (const action of ['prune', 'confirm', 'escalate'] as const) { + const transport = transportFor(() => ({ + answers: { + 'cascade-escalation': { + choice: action, + confidence: 0.92, + probabilities: { + prune: action === 'prune' ? 0.92 : 0.04, + confirm: action === 'confirm' ? 0.92 : 0.04, + escalate: action === 'escalate' ? 0.92 : 0.04, + }, + }, + }, + usage: { input_tokens: 40, output_tokens: 5 }, + })); + const result = await evaluateCascadeEscalation({ ...base({ transport }), cascade: baseCascade }); + assert.equal(result.action, action); + assert.equal(result.smokeCorrectnessPassed, true); + assert.equal(result.source, 'jev'); + assert.equal(result.transportCalls, 1); + assert.equal(result.advisoryOnly, true); + assert.equal(result.verificationCertified, false); + } + }); + + it('falls back deterministically to escalate, confirm, or prune when System-One is disabled or low-confidence', async () => { + // Improving smoke latency -> escalate + const escalated = await evaluateCascadeEscalation({ + ...base({ policy: policy({ enabled: false }) }), + cascade: baseCascade, + }); + assert.equal(escalated.action, 'escalate'); + assert.equal(escalated.source, 'deterministic_fallback'); + assert.equal(escalated.fallbackReason, 'policy_disabled'); + assert.equal(escalated.transportCalls, 0); + assert.equal(escalated.advisoryOnly, true); + assert.equal(escalated.verificationCertified, false); + + // Slight regression within 5% tolerance and healthy budget -> confirm + assert.equal( + heuristicCascadeEscalation({ + ...baseCascade, + smokeMetrics: { latency_us_p50: 103 }, + remainingBudgetRatio: 0.5, + }), + 'confirm', + ); + + // Large regression -> prune even with low-confidence Jev response + const lowConfTransport = transportFor(() => ({ + answers: { + 'cascade-escalation': { + choice: 'escalate', + confidence: 0.35, + probabilities: { prune: 0.35, confirm: 0.30, escalate: 0.35 }, + }, + }, + })); + const pruned = await evaluateCascadeEscalation({ + ...base({ transport: lowConfTransport }), + cascade: { + ...baseCascade, + smokeMetrics: { latency_us_p50: 140 }, + }, + }); + assert.equal(pruned.action, 'prune'); + assert.equal(pruned.source, 'deterministic_fallback'); + assert.equal(pruned.fallbackReason, 'low_confidence'); + assert.equal(pruned.advisoryOnly, true); + assert.equal(pruned.verificationCertified, false); + }); + + it('validates primaryMetric presence and remainingBudgetRatio bounds', async () => { + await assert.rejects( + () => evaluateCascadeEscalation({ + ...base(), + cascade: { ...baseCascade, primaryMetric: 'missing_metric' }, + }), + (err: unknown) => err instanceof DecisionError && err.code === 'DECISION_SCHEMA_INVALID', + ); + await assert.rejects( + () => evaluateCascadeEscalation({ + ...base(), + cascade: { ...baseCascade, remainingBudgetRatio: 1.5 }, + }), + (err: unknown) => err instanceof DecisionError && err.code === 'DECISION_SCHEMA_INVALID', + ); + }); +}); diff --git a/packages/evolution/package.json b/packages/evolution/package.json new file mode 100644 index 0000000..1dbae1b --- /dev/null +++ b/packages/evolution/package.json @@ -0,0 +1,31 @@ +{ + "name": "@loopwright/evolution", + "version": "0.0.0", + "private": true, + "type": "module", + "engines": { + "node": "26.x" + }, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.js" + } + }, + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "files": [ + "dist" + ], + "scripts": { + "pretest": "node ../../scripts/build.mjs --ensure && tsc -p ../../tsconfig.test.json", + "test": "node --test --test-concurrency=1 ../../.test-build/packages/evolution/test/*.test.js" + }, + "dependencies": { + "@loopwright/controller": "0.0.0", + "@loopwright/core": "0.0.0", + "@loopwright/decisions": "0.0.0", + "@loopwright/hardware-runner": "0.0.0", + "@loopwright/taskpack": "0.0.0" + } +} diff --git a/packages/evolution/src/bundle.ts b/packages/evolution/src/bundle.ts new file mode 100644 index 0000000..3125fa6 --- /dev/null +++ b/packages/evolution/src/bundle.ts @@ -0,0 +1,2524 @@ +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 { computeNsga2Ranking } from './pareto.js'; +import { + canonicalizeJson, + parseBucketMetricsJson, + parseDispatchManifestV1, + parseHardwareDiagnosticsJson, + parseHardwareProvenanceJson, + parseNullProtoJson, + type NullProtoJson, +} from './schema.js'; +import type { EvolutionCampaignStore } from './store.js'; +import { + DISPATCH_MANIFEST_MAX_BYTES, + DISPATCH_MANIFEST_MAX_RULES, + EvolutionError, + type BundleCompatibilityTuple, + type BundleLineageProvenance, + type BundleMemberDigest, + type BundleParetoEntry, + type CampaignRecord, + type DispatchDimensionRange, + type DispatchManifestV1, + type DispatchRuleV1, + type EvolutionBundleManifestV1, + type EvolutionExportFormat, + type IndividualRecord, +} from './types.js'; + +export const EVOLUTION_BUNDLE_KIND = 'EvolutionBundle' as const; +export const EVOLUTION_BUNDLE_VERSION = 1 as const; +export const OCI_IMAGE_LAYOUT_VERSION = '1.0.0' as const; +export const OCI_IMAGE_INDEX_MEDIA_TYPE = 'application/vnd.oci.image.index.v1+json' as const; +export const OCI_IMAGE_MANIFEST_MEDIA_TYPE = 'application/vnd.oci.image.manifest.v1+json' as const; +export const OCI_EMPTY_CONFIG_MEDIA_TYPE = 'application/vnd.oci.empty.v1+json' as const; +export const EVOLUTION_BUNDLE_ARTIFACT_TYPE = 'application/vnd.loopwright.evolution-bundle.v1+json' as const; +export const EVOLUTION_MANIFEST_MEDIA_TYPE = 'application/vnd.loopwright.evolution-bundle.manifest.v1+json' as const; +export const EVOLUTION_DISPATCH_MANIFEST_MEDIA_TYPE = 'application/vnd.loopwright.evolution-bundle.dispatch.v1+json' as const; +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', + '.so', + '.o', + '.ptx', + '.sass', + '.hsaco', + '.om', + '.bin', +]); + +const TEXT_ARTIFACT_EXTENSIONS: readonly string[] = Object.freeze([ + '.json', + '.yaml', + '.yml', + '.txt', + '.md', + '.toml', + '.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', + 'compatibility', + 'paretoSummary', + 'lineage', + 'members', +]); +const COMPATIBILITY_KEYS: ReadonlySet = new Set([ + 'accelerator', + 'isolationMode', + 'deviceCount', + 'driverVersion', + 'driverConstraint', + 'runtimeVersion', + 'topology', + 'workloadDigest', + 'modelDigest', + 'parallelismTags', +]); +const LINEAGE_KEYS: ReadonlySet = new Set([ + 'campaignId', + 'individualIds', + 'baseRevision', + 'lockHash', +]); +const MEMBER_KEYS: ReadonlySet = new Set(['path', 'digest', 'byteLength', 'mediaType']); +const PARETO_ENTRY_KEYS: ReadonlySet = new Set([ + 'individualId', + 'paretoRank', + 'nicheKey', + 'metrics', + 'bucketMetrics', + '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 allowUnverifiedSignature?: boolean; + readonly individualIds?: readonly string[]; + readonly dispatchManifest?: DispatchManifestV1 | string | Uint8Array; + readonly defaultEntrypoint?: string; + readonly receiptSigningSecret?: string; + readonly verifyReceiptSignature?: ReceiptSignatureVerifier; + readonly expectedPortfolioWorkloadDigest?: Digest; + readonly driverConstraint?: string; + readonly modelDigest?: Digest; + readonly parallelismTags?: readonly string[]; + readonly scrubber?: SecretScrubber; + readonly maxBlobBytes?: number; + readonly overwrite?: boolean; +} + +export interface ExportEvolutionBundleResult { + readonly format: EvolutionExportFormat; + readonly outputDir: string; + readonly manifestDigest: Digest; + readonly dispatchManifestDigest: Digest; + readonly ociIndexDigest?: Digest; + readonly exportedIndividualIds: readonly string[]; + readonly blobCount: number; +} + +export interface VerifyEvolutionBundleOptions { + readonly bundleDir: string; + readonly allowSyntheticProbe?: boolean; + readonly allowUnverifiedSignature?: boolean; + readonly receiptSigningSecret?: string; + readonly verifyReceiptSignature?: ReceiptSignatureVerifier; + readonly scrubber?: SecretScrubber; + readonly maxBlobBytes?: number; +} + +export interface VerifyEvolutionBundleResult { + readonly format: EvolutionExportFormat; + readonly bundleDir: string; + readonly manifest: EvolutionBundleManifestV1; + readonly dispatchManifest: DispatchManifestV1; + readonly manifestDigest: Digest; + readonly dispatchManifestDigest: Digest; + readonly ociIndexDigest?: Digest; + readonly receiptCount: number; + 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; + readonly mediaType: string; + readonly artifactNames: readonly string[]; + 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))) { + 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' + && declaredMediaType.length >= 1 + && declaredMediaType.length <= LIMITS.mediaType + && PRINTABLE_ASCII_RE.test(declaredMediaType) + ) { + return declaredMediaType; + } + const lower = name.toLowerCase(); + if (lower.endsWith('.json')) return 'application/json'; + if (lower.endsWith('.yaml') || lower.endsWith('.yml')) return 'application/yaml'; + if (lower.endsWith('.cubin')) return 'application/x-nvidia-cubin'; + if (lower.endsWith('.ptx')) return 'text/x-ptx'; + if (lower.endsWith('.so')) return 'application/x-sharedlib'; + if (lower.endsWith('.o')) return 'application/x-object'; + 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, + requireSameWorkloadDigest: boolean, + individualId: string, +): void { + if ( + base.accelerator !== other.accelerator + || base.isolationMode !== other.isolationMode + || base.deviceCount !== other.deviceCount + || base.driverVersion !== other.driverVersion + || base.runtimeVersion !== other.runtimeVersion + || (base.topology ?? null) !== (other.topology ?? null) + ) { + throw new EvolutionError( + 'ARTIFACT_INVALID', + `selected individual "${individualId}" has incompatible hardwareProvenance compared to bundle compatibility tuple`, + ); + } + if (requireSameWorkloadDigest && base.workloadDigest.hex !== other.workloadDigest.hex) { + throw new EvolutionError( + 'ARTIFACT_INVALID', + `selected individual "${individualId}" has mismatched workloadDigest in single-target export`, + ); + } +} + +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; + if (rankA !== rankB) return rankA - rankB; + const fitA = a.scalarFitness ?? Number.NEGATIVE_INFINITY; + const fitB = b.scalarFitness ?? Number.NEGATIVE_INFINITY; + if (fitA !== fitB) return fitB - fitA; + return compareUtf16(a.individualId, b.individualId); +} + +function isPortfolioCandidate(ind: IndividualRecord, portfolioHeldOutWorkloadId: string): boolean { + return ind.mutationKind === 'portfolio' || ind.bucketId === portfolioHeldOutWorkloadId; +} + +function selectPrimaryArtifactForRule( + artifacts: readonly BenchmarkOutputArtifact[], +): BenchmarkOutputArtifact | null { + if (artifacts.length === 0) return null; + const sorted = [...artifacts].sort((a, b) => { + const aBin = BINARY_ARTIFACT_EXTENSIONS.some(ext => a.name.toLowerCase().endsWith(ext)) ? 0 : 1; + const bBin = BINARY_ARTIFACT_EXTENSIONS.some(ext => b.name.toLowerCase().endsWith(ext)) ? 0 : 1; + if (aBin !== bBin) return aBin - bBin; + const nameCmp = compareUtf16(a.name, b.name); + if (nameCmp !== 0) return nameCmp; + return compareUtf16(a.digest.hex, b.digest.hex); + }); + return sorted[0]!; +} + +function deriveRulePredicatesFromBucketEntry( + entry: BucketMetricEntry, +): { + readonly dimensionBounds?: Readonly>; + readonly dtypes?: readonly string[]; +} { + if (entry.dimensions === undefined) return {}; + const bounds = createNullRecord>(); + let hasBound = false; + let dtypes: string[] | undefined; + + for (const key of Object.keys(entry.dimensions).sort(compareUtf16)) { + if (!Object.hasOwn(entry.dimensions, key)) continue; + const val = entry.dimensions[key]; + if (typeof val === 'number' && Number.isFinite(val) && !Object.is(val, -0)) { + const range = createNullRecord<{ min: number; max: number }>(); + range.min = val; + range.max = val; + bounds[key] = range; + hasBound = true; + } else if (key === 'dtype' && typeof val === 'string' && DTYPE_TOKEN_RE.test(val)) { + dtypes = [val]; + } + } + + return { + ...(hasBound ? { dimensionBounds: bounds } : {}), + ...(dtypes !== undefined ? { dtypes } : {}), + }; +} + +function synthesizeDispatchManifest( + campaign: CampaignRecord, + selectedIndividuals: readonly IndividualRecord[], + receiptsByIndividualId: ReadonlyMap, + defaultEntrypoint: string, + scrubber: SecretScrubber, +): DispatchManifestV1 { + const dispatchCandidates = campaign.manifest.spec.stages.mode === 'specialist-then-portfolio' + ? (() => { + const portfolioWorkloadId = campaign.manifest.spec.stages.portfolioHeldOutWorkloadId; + const specialists = selectedIndividuals.filter(ind => !isPortfolioCandidate(ind, portfolioWorkloadId)); + return specialists.length > 0 ? specialists : selectedIndividuals; + })() + : selectedIndividuals; + + const orderedIndividuals = [...dispatchCandidates].sort((a, b) => { + const aHasBucket = a.bucketId !== null ? 0 : 1; + const bHasBucket = b.bucketId !== null ? 0 : 1; + if (aHasBucket !== bHasBucket) return aHasBucket - bHasBucket; + const bucketCmp = compareUtf16(a.bucketId ?? '', b.bucketId ?? ''); + if (bucketCmp !== 0) return bucketCmp; + const rankA = a.paretoRank ?? Number.MAX_SAFE_INTEGER; + const rankB = b.paretoRank ?? Number.MAX_SAFE_INTEGER; + if (rankA !== rankB) return rankA - rankB; + return compareUtf16(a.individualId, b.individualId); + }); + + const rules: DispatchRuleV1[] = []; + const seenRuleKey = new Set(); + + for (const ind of orderedIndividuals) { + const receiptBundle = receiptsByIndividualId.get(ind.individualId); + if (!receiptBundle) continue; + const primaryArt = selectPrimaryArtifactForRule(receiptBundle.outputArtifacts); + if (!primaryArt) continue; + + const buckets = ind.bucketMetrics ?? receiptBundle.bucketMetrics; + if (ind.bucketId !== null) { + const matchingBucket = buckets?.find(b => b.bucketId === ind.bucketId); + const predicates = matchingBucket ? deriveRulePredicatesFromBucketEntry(matchingBucket) : {}; + const key = `${ind.bucketId}:${primaryArt.digest.hex}`; + if (!seenRuleKey.has(key)) { + seenRuleKey.add(key); + const rule = createNullRecord<{ + bucketId: string; + dimensionBounds?: Readonly>; + dtypes?: readonly string[]; + blobDigest: Digest; + blobPath: string; + entrypoint: string; + }>(); + rule.bucketId = ind.bucketId; + if (predicates.dimensionBounds !== undefined) rule.dimensionBounds = predicates.dimensionBounds; + if (predicates.dtypes !== undefined) rule.dtypes = predicates.dtypes; + rule.blobDigest = primaryArt.digest; + rule.blobPath = `blobs/sha256/${primaryArt.digest.hex}`; + rule.entrypoint = defaultEntrypoint; + rules.push(rule as DispatchRuleV1); + } + } else if (buckets !== undefined && buckets.length > 0) { + const sortedBuckets = [...buckets].sort((a, b) => compareUtf16(a.bucketId, b.bucketId)); + for (const bEntry of sortedBuckets) { + const key = `${bEntry.bucketId}:${primaryArt.digest.hex}`; + if (seenRuleKey.has(key)) continue; + seenRuleKey.add(key); + const predicates = deriveRulePredicatesFromBucketEntry(bEntry); + const rule = createNullRecord<{ + bucketId: string; + dimensionBounds?: Readonly>; + dtypes?: readonly string[]; + blobDigest: Digest; + blobPath: string; + entrypoint: string; + }>(); + rule.bucketId = bEntry.bucketId; + if (predicates.dimensionBounds !== undefined) rule.dimensionBounds = predicates.dimensionBounds; + if (predicates.dtypes !== undefined) rule.dtypes = predicates.dtypes; + rule.blobDigest = primaryArt.digest; + rule.blobPath = `blobs/sha256/${primaryArt.digest.hex}`; + rule.entrypoint = defaultEntrypoint; + rules.push(rule as DispatchRuleV1); + } + } else { + const fallbackBucket = campaign.manifest.spec.targetCellId; + const key = `${fallbackBucket}:${primaryArt.digest.hex}`; + if (!seenRuleKey.has(key)) { + seenRuleKey.add(key); + const rule = createNullRecord<{ + bucketId: string; + blobDigest: Digest; + blobPath: string; + entrypoint: string; + }>(); + rule.bucketId = fallbackBucket; + rule.blobDigest = primaryArt.digest; + rule.blobPath = `blobs/sha256/${primaryArt.digest.hex}`; + rule.entrypoint = defaultEntrypoint; + rules.push(rule as DispatchRuleV1); + } + } + } + + if (rules.length === 0) { + throw new EvolutionError( + 'ARTIFACT_MISSING', + 'no verified Stage A output artifacts available to synthesize dispatch-manifest.json', + ); + } + if (rules.length > DISPATCH_MANIFEST_MAX_RULES) { + throw new EvolutionError( + 'EVOLUTION_SCHEMA_INVALID', + `synthesized dispatch-manifest.json exceeds ${DISPATCH_MANIFEST_MAX_RULES} rules`, + ); + } + + const rawManifest = createNullRecord<{ + version: 1; + fallback: 'baseline'; + rules: readonly DispatchRuleV1[]; + }>(); + rawManifest.version = 1; + rawManifest.fallback = 'baseline'; + rawManifest.rules = rules; + return parseDispatchManifestV1(rawManifest, { scrubber }); +} + +function normalizeAndVerifyDispatchManifest( + input: DispatchManifestV1 | string | Uint8Array, + verifiedBlobsByHex: ReadonlyMap, + scrubber: SecretScrubber, +): DispatchManifestV1 { + const parsed = parseDispatchManifestV1(input, { scrubber }); + const normalizedRules: DispatchRuleV1[] = []; + + for (let i = 0; i < parsed.rules.length; i++) { + const rule = parsed.rules[i]!; + if (!verifiedBlobsByHex.has(rule.blobDigest.hex)) { + throw new EvolutionError( + 'ARTIFACT_INVALID', + `dispatch rule ${i} references unverified blob digest ${rule.blobDigest.hex}`, + `/dispatchManifest/rules/${i}/blobDigest`, + ); + } + const normalized = createNullRecord<{ + bucketId: string; + dimensionBounds?: Readonly>; + dtypes?: readonly string[]; + alignmentBytes?: number; + blobDigest: Digest; + blobPath: string; + entrypoint: string; + }>(); + normalized.bucketId = rule.bucketId; + if (rule.dimensionBounds !== undefined) normalized.dimensionBounds = rule.dimensionBounds; + if (rule.dtypes !== undefined) normalized.dtypes = rule.dtypes; + if (rule.alignmentBytes !== undefined) normalized.alignmentBytes = rule.alignmentBytes; + normalized.blobDigest = rule.blobDigest; + normalized.blobPath = `blobs/sha256/${rule.blobDigest.hex}`; + normalized.entrypoint = rule.entrypoint; + normalizedRules.push(normalized as DispatchRuleV1); + } + + const out = createNullRecord<{ + version: 1; + fallback: 'baseline'; + rules: readonly DispatchRuleV1[]; + }>(); + out.version = 1; + out.fallback = 'baseline'; + out.rules = normalizedRules; + return parseDispatchManifestV1(out, { scrubber }); +} + +function buildCompatibilityTuple( + anchorProvenance: HardwareProvenance, + options: ExportEvolutionBundleOptions, + campaignDriverConstraint: string | null | undefined, + scrubber: SecretScrubber, +): BundleCompatibilityTuple { + const compat = createNullRecord<{ + accelerator: string; + isolationMode: 'whole_device' | 'sliced'; + deviceCount: number; + driverVersion: string; + driverConstraint?: string; + runtimeVersion: string; + topology?: string; + workloadDigest: Digest; + modelDigest?: Digest; + parallelismTags?: readonly string[]; + }>(); + + compat.accelerator = anchorProvenance.accelerator; + compat.isolationMode = anchorProvenance.isolationMode; + compat.deviceCount = anchorProvenance.deviceCount; + compat.driverVersion = anchorProvenance.driverVersion; + + const effectiveDriverConstraint = options.driverConstraint ?? campaignDriverConstraint ?? undefined; + if (effectiveDriverConstraint !== undefined) { + if ( + typeof effectiveDriverConstraint !== 'string' + || effectiveDriverConstraint.length < 1 + || effectiveDriverConstraint.length > 128 + || !PRINTABLE_ASCII_RE.test(effectiveDriverConstraint) + ) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'invalid driverConstraint', '/driverConstraint'); + } + assertCleanSecretText(effectiveDriverConstraint, scrubber, '/driverConstraint'); + compat.driverConstraint = effectiveDriverConstraint; + } + + compat.runtimeVersion = anchorProvenance.runtimeVersion; + if (anchorProvenance.topology !== undefined) { + compat.topology = anchorProvenance.topology; + } + compat.workloadDigest = makeDigest(anchorProvenance.workloadDigest.hex); + + if (options.modelDigest !== undefined) { + if (options.modelDigest.algorithm !== 'sha256' || !SHA256_HEX_RE.test(options.modelDigest.hex)) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'invalid modelDigest', '/modelDigest'); + } + compat.modelDigest = makeDigest(options.modelDigest.hex); + } + + if (options.parallelismTags !== undefined) { + if (options.parallelismTags.length > 16) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'parallelismTags cannot exceed 16 entries', '/parallelismTags'); + } + const deduped = new Set(); + for (let i = 0; i < options.parallelismTags.length; i++) { + const tag = options.parallelismTags[i]!; + if (typeof tag !== 'string' || tag.length < 1 || tag.length > 64 || !PRINTABLE_ASCII_RE.test(tag)) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', `invalid parallelism tag "${String(tag)}"`, `/parallelismTags/${i}`); + } + assertCleanSecretText(tag, scrubber, `/parallelismTags/${i}`); + deduped.add(tag); + } + compat.parallelismTags = [...deduped].sort(compareUtf16); + } + + return compat as BundleCompatibilityTuple; +} + +function buildParetoSummary( + campaign: CampaignRecord, + selectedIndividuals: readonly IndividualRecord[], + receiptsByIndividualId: ReadonlyMap, +): readonly BundleParetoEntry[] { + const rankByIndividualId = new Map(); + const needsRanking = selectedIndividuals.some(ind => ind.paretoRank === null); + + if (needsRanking) { + const rankable = selectedIndividuals.filter(ind => + campaign.manifest.spec.objectives.every(obj => Object.hasOwn(ind.metrics, obj.metric)), + ); + if (rankable.length > 0) { + const ranked = computeNsga2Ranking( + rankable.map(ind => ({ individualId: ind.individualId, metrics: ind.metrics })), + campaign.manifest.spec.objectives, + ); + for (const r of ranked) { + rankByIndividualId.set(r.individualId, r.paretoRank); + } + } + } + + const summary: BundleParetoEntry[] = selectedIndividuals.map(ind => { + const receiptBundle = receiptsByIndividualId.get(ind.individualId); + const rawBuckets = ind.bucketMetrics ?? receiptBundle?.bucketMetrics; + const sortedBuckets = rawBuckets !== undefined + ? [...rawBuckets].sort((a, b) => compareUtf16(a.bucketId, b.bucketId)) + : undefined; + const diagnostics = ind.hardwareDiagnostics ?? receiptBundle?.hardwareDiagnostics; + + const entry = createNullRecord<{ + individualId: string; + paretoRank: number; + nicheKey: string | null; + metrics: Readonly>; + bucketMetrics?: readonly BucketMetricEntry[]; + hardwareDiagnostics?: HardwareDiagnostics; + }>(); + entry.individualId = ind.individualId; + entry.paretoRank = ind.paretoRank ?? rankByIndividualId.get(ind.individualId) ?? 1; + entry.nicheKey = ind.nicheKey; + entry.metrics = ind.metrics; + if (sortedBuckets !== undefined) entry.bucketMetrics = sortedBuckets; + if (diagnostics !== undefined) entry.hardwareDiagnostics = diagnostics; + return entry as BundleParetoEntry; + }); + + summary.sort((a, b) => { + if (a.paretoRank !== b.paretoRank) return a.paretoRank - b.paretoRank; + return compareUtf16(a.individualId, b.individualId); + }); + + return summary; +} + +interface OciDescriptor { + readonly mediaType: string; + readonly digest: string; + readonly size: number; + readonly artifactType?: string; + readonly annotations?: Readonly>; +} + +interface OciLayoutArtifacts { + readonly ociLayoutBytes: Buffer; + readonly ociIndexBytes: Buffer; + readonly ociIndexDigest: Digest; + readonly extraBlobsByHex: ReadonlyMap; +} + +function buildOciLayoutArtifacts(params: { + readonly campaign: CampaignRecord; + readonly compatibility: BundleCompatibilityTuple; + readonly manifestBytes: Buffer; + readonly manifestDigest: Digest; + readonly dispatchBytes: Buffer; + readonly dispatchDigest: Digest; + readonly receipts: readonly { readonly relPath: string; readonly bytes: Buffer; readonly digest: Digest }[]; + readonly stageABlobs: readonly { readonly relPath: string; readonly byteLength: number; readonly digest: Digest; readonly mediaType: string }[]; +}): OciLayoutArtifacts { + const extraBlobsByHex = new Map(); + + const emptyConfigBytes = Buffer.from('{}', 'utf8'); + const emptyConfigHex = sha256Hex(emptyConfigBytes); + extraBlobsByHex.set(emptyConfigHex, emptyConfigBytes); + + extraBlobsByHex.set(params.manifestDigest.hex, params.manifestBytes); + extraBlobsByHex.set(params.dispatchDigest.hex, params.dispatchBytes); + for (const rec of params.receipts) { + extraBlobsByHex.set(rec.digest.hex, rec.bytes); + } + + const layers: OciDescriptor[] = []; + + const makeLayer = ( + mediaType: string, + digestHex: string, + size: number, + title: string, + ): OciDescriptor => { + const ann = createNullRecord>(); + ann['org.opencontainers.image.title'] = title; + const desc = createNullRecord<{ + mediaType: string; + digest: string; + size: number; + annotations: Readonly>; + }>(); + desc.mediaType = mediaType; + desc.digest = `sha256:${digestHex}`; + desc.size = size; + desc.annotations = ann; + return desc; + }; + + layers.push( + makeLayer( + EVOLUTION_MANIFEST_MEDIA_TYPE, + params.manifestDigest.hex, + params.manifestBytes.byteLength, + 'manifest.json', + ), + ); + layers.push( + makeLayer( + EVOLUTION_DISPATCH_MANIFEST_MEDIA_TYPE, + params.dispatchDigest.hex, + params.dispatchBytes.byteLength, + 'dispatch-manifest.json', + ), + ); + for (const rec of params.receipts) { + layers.push( + makeLayer( + EVOLUTION_RECEIPT_MEDIA_TYPE, + rec.digest.hex, + rec.bytes.byteLength, + rec.relPath, + ), + ); + } + for (const blob of params.stageABlobs) { + layers.push( + makeLayer( + blob.mediaType, + blob.digest.hex, + blob.byteLength, + blob.relPath, + ), + ); + } + + const configDesc = createNullRecord<{ mediaType: string; digest: string; size: number }>(); + configDesc.mediaType = OCI_EMPTY_CONFIG_MEDIA_TYPE; + configDesc.digest = `sha256:${emptyConfigHex}`; + configDesc.size = emptyConfigBytes.byteLength; + + const ociManifestAnnotations = createNullRecord>(); + ociManifestAnnotations['dev.loopwright.accelerator'] = params.compatibility.accelerator; + ociManifestAnnotations['dev.loopwright.campaign.id'] = params.campaign.campaignId; + ociManifestAnnotations['dev.loopwright.lock.hash'] = `sha256:${params.campaign.lockHash.hex}`; + + const ociManifestObj = createNullRecord<{ + schemaVersion: 2; + mediaType: typeof OCI_IMAGE_MANIFEST_MEDIA_TYPE; + artifactType: typeof EVOLUTION_BUNDLE_ARTIFACT_TYPE; + config: OciDescriptor; + layers: readonly OciDescriptor[]; + annotations: Readonly>; + }>(); + ociManifestObj.schemaVersion = 2; + ociManifestObj.mediaType = OCI_IMAGE_MANIFEST_MEDIA_TYPE; + ociManifestObj.artifactType = EVOLUTION_BUNDLE_ARTIFACT_TYPE; + ociManifestObj.config = configDesc; + ociManifestObj.layers = layers; + ociManifestObj.annotations = ociManifestAnnotations; + + const ociManifestBytes = Buffer.from(canonicalizeJson(ociManifestObj), 'utf8'); + const ociManifestHex = sha256Hex(ociManifestBytes); + extraBlobsByHex.set(ociManifestHex, ociManifestBytes); + + const indexManifestAnnotations = createNullRecord>(); + indexManifestAnnotations['dev.loopwright.campaign.id'] = params.campaign.campaignId; + indexManifestAnnotations['org.opencontainers.image.ref.name'] = params.campaign.name; + + const indexManifestDesc = createNullRecord<{ + mediaType: typeof OCI_IMAGE_MANIFEST_MEDIA_TYPE; + artifactType: typeof EVOLUTION_BUNDLE_ARTIFACT_TYPE; + digest: string; + size: number; + annotations: Readonly>; + }>(); + indexManifestDesc.mediaType = OCI_IMAGE_MANIFEST_MEDIA_TYPE; + indexManifestDesc.artifactType = EVOLUTION_BUNDLE_ARTIFACT_TYPE; + indexManifestDesc.digest = `sha256:${ociManifestHex}`; + indexManifestDesc.size = ociManifestBytes.byteLength; + indexManifestDesc.annotations = indexManifestAnnotations; + + const ociIndexObj = createNullRecord<{ + schemaVersion: 2; + mediaType: typeof OCI_IMAGE_INDEX_MEDIA_TYPE; + manifests: readonly OciDescriptor[]; + }>(); + ociIndexObj.schemaVersion = 2; + ociIndexObj.mediaType = OCI_IMAGE_INDEX_MEDIA_TYPE; + ociIndexObj.manifests = [indexManifestDesc]; + + const ociIndexBytes = Buffer.from(canonicalizeJson(ociIndexObj), 'utf8'); + const ociIndexDigest = makeDigest(sha256Hex(ociIndexBytes)); + + const ociLayoutObj = createNullRecord<{ imageLayoutVersion: typeof OCI_IMAGE_LAYOUT_VERSION }>(); + ociLayoutObj.imageLayoutVersion = OCI_IMAGE_LAYOUT_VERSION; + const ociLayoutBytes = Buffer.from(canonicalizeJson(ociLayoutObj), 'utf8'); + + return { + ociLayoutBytes, + ociIndexBytes, + ociIndexDigest, + extraBlobsByHex, + }; +} + +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, + * portfolio holdout, CAS `O_NOFOLLOW`/`nlink === 1`/SHA-256, and `SecretScrubber` gates. + */ +export async function exportEvolutionBundle( + options: ExportEvolutionBundleOptions, +): Promise { + if (!options || typeof options !== 'object') { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'exportEvolutionBundle options must be an object'); + } + const scrubber = options.scrubber ?? DEFAULT_SECRET_SCRUBBER; + const allowSyntheticProbe = options.allowSyntheticProbe === true; + const maxBlobBytes = options.maxBlobBytes ?? DEFAULT_MAX_BLOB_BYTES; + const overwrite = options.overwrite !== false; + const defaultEntrypoint = options.defaultEntrypoint ?? DEFAULT_ENTRYPOINT_SYMBOL; + + if (!Number.isSafeInteger(maxBlobBytes) || maxBlobBytes < 1) { + 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 campaign = await options.store.getCampaign(options.campaignId); + if (!campaign) { + throw new EvolutionError('EVOLUTION_NOT_FOUND', `campaign "${options.campaignId}" not found`, '/campaignId'); + } + + const hasReceiptVerifier = + (typeof options.receiptSigningSecret === 'string' && options.receiptSigningSecret.length > 0) + || typeof options.verifyReceiptSignature === 'function'; + if (!hasReceiptVerifier && options.allowUnverifiedSignature !== true) { + throw new EvolutionError( + 'EXPORT_UNVERIFIED_FORBIDDEN', + 'receiptSigningSecret or verifyReceiptSignature is required to verify HMAC verdict receipts', + ); + } + + const format: EvolutionExportFormat = options.format ?? campaign.manifest.spec.export?.format ?? 'dir'; + if (format !== 'dir' && format !== 'oci-layout') { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', `unsupported export format "${String(format)}"`, '/format'); + } + + const allIndividuals = await options.store.listIndividuals(options.campaignId); + const individualsById = new Map(); + for (const ind of allIndividuals) { + individualsById.set(ind.individualId, ind); + } + + const receiptCache = new Map(); + const loadAndVerifyReceipt = async (ind: IndividualRecord): Promise => { + const cached = receiptCache.get(ind.individualId); + if (cached) return cached; + + if (ind.status !== 'passed') { + throw new EvolutionError( + 'EXPORT_UNVERIFIED_FORBIDDEN', + `individual "${ind.individualId}" has status "${ind.status}" (expected "passed")`, + ); + } + if (ind.verdictReceiptCasDigest === null) { + throw new EvolutionError( + 'EXPORT_UNVERIFIED_FORBIDDEN', + `individual "${ind.individualId}" lacks a hardware_execution verdict receipt`, + ); + } + + const rawBytes = await readVerifiedCasBlob(options.store.campaignRoot, ind.verdictReceiptCasDigest.hex, { + maxBytes: MAX_RECEIPT_FILE_BYTES, + }); + const parsed = await parseAndVerifyReceiptBytes(rawBytes, { + individualId: ind.individualId, + expectedTargetCellId: campaign.manifest.spec.targetCellId, + allowSyntheticProbe, + ...(options.receiptSigningSecret !== undefined ? { receiptSigningSecret: options.receiptSigningSecret } : {}), + ...(options.verifyReceiptSignature !== undefined ? { verifyReceiptSignature: options.verifyReceiptSignature } : {}), + scrubber, + 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; + }; + + // Gate: under specialist-then-portfolio mode, verify portfolioHeldOutWorkloadId passed! + let verifiedPortfolioAnchor: { readonly individual: IndividualRecord; readonly receipt: ParsedReceiptBundle } | null = null; + if (campaign.manifest.spec.stages.mode === 'specialist-then-portfolio') { + const portfolioWorkloadId = campaign.manifest.spec.stages.portfolioHeldOutWorkloadId; + const passingPortfolioCandidates = allIndividuals + .filter(ind => isPortfolioCandidate(ind, portfolioWorkloadId) && ind.status === 'passed') + .sort(comparePortfolioCandidateBetter); + + if (passingPortfolioCandidates.length === 0) { + throw new EvolutionError( + 'EXPORT_UNVERIFIED_FORBIDDEN', + `specialist-then-portfolio campaign "${campaign.campaignId}" has no passing portfolio evaluation on "${portfolioWorkloadId}"`, + ); + } + + let lastFailure: unknown = null; + for (const candidate of passingPortfolioCandidates) { + if ( + candidate.bucketId !== null + && candidate.bucketId !== 'portfolio' + && candidate.bucketId !== portfolioWorkloadId + ) { + continue; + } + try { + const receipt = await loadAndVerifyReceipt(candidate); + if (receipt.heldOutWorkloadId !== undefined && receipt.heldOutWorkloadId !== portfolioWorkloadId) { + lastFailure = new EvolutionError( + 'EXPORT_UNVERIFIED_FORBIDDEN', + `portfolio receipt heldOutWorkloadId "${receipt.heldOutWorkloadId}" does not match "${portfolioWorkloadId}"`, + ); + continue; + } + if ( + options.expectedPortfolioWorkloadDigest !== undefined + && receipt.provenance.workloadDigest.hex !== options.expectedPortfolioWorkloadDigest.hex + ) { + lastFailure = new EvolutionError( + 'EXPORT_UNVERIFIED_FORBIDDEN', + `portfolio receipt workloadDigest does not match expectedPortfolioWorkloadDigest`, + ); + continue; + } + verifiedPortfolioAnchor = { individual: candidate, receipt }; + break; + } catch (err: unknown) { + lastFailure = err; + } + } + + if (verifiedPortfolioAnchor === null) { + if (lastFailure instanceof EvolutionError) throw lastFailure; + throw new EvolutionError( + 'EXPORT_UNVERIFIED_FORBIDDEN', + `specialist-then-portfolio campaign "${campaign.campaignId}" failed portfolio verification on "${portfolioWorkloadId}"`, + ); + } + } + + // Select individuals deterministically + let selectedIndividuals: IndividualRecord[]; + if (options.individualIds !== undefined) { + if (options.individualIds.length === 0 || options.individualIds.length > DISPATCH_MANIFEST_MAX_RULES) { + throw new EvolutionError( + 'EVOLUTION_SCHEMA_INVALID', + `individualIds must contain 1..${DISPATCH_MANIFEST_MAX_RULES} entries`, + '/individualIds', + ); + } + const seen = new Set(); + selectedIndividuals = []; + for (const id of options.individualIds) { + if (typeof id !== 'string' || !SAFE_FILENAME_ID_RE.test(id)) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', `invalid individualId "${String(id)}"`, '/individualIds'); + } + if (seen.has(id)) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', `duplicate individualId "${id}"`, '/individualIds'); + } + seen.add(id); + const found = individualsById.get(id); + if (!found) { + throw new EvolutionError('EVOLUTION_NOT_FOUND', `individual "${id}" not found in campaign "${campaign.campaignId}"`); + } + selectedIndividuals.push(found); + } + } else if (campaign.manifest.spec.stages.mode === 'specialist-then-portfolio') { + const portfolioWorkloadId = campaign.manifest.spec.stages.portfolioHeldOutWorkloadId; + const passingPortfolio = allIndividuals + .filter(ind => isPortfolioCandidate(ind, portfolioWorkloadId) && ind.status === 'passed') + .sort(comparePortfolioCandidateBetter); + const rank1Portfolio = passingPortfolio.filter(ind => ind.paretoRank === 1); + const chosenPortfolio = rank1Portfolio.length > 0 ? rank1Portfolio : [verifiedPortfolioAnchor!.individual]; + + const selectedMap = new Map(); + for (const p of chosenPortfolio) { + selectedMap.set(p.individualId, p); + } + + const portfolioEdges = await options.store.listLineageEdges(campaign.campaignId, { role: 'portfolio_member' }); + let addedPortfolioMember = false; + for (const edge of portfolioEdges) { + if (!selectedMap.has(edge.childIndividualId)) continue; + const member = individualsById.get(edge.parentIndividualId); + if (member) { + selectedMap.set(member.individualId, member); + addedPortfolioMember = true; + } + } + + if (!addedPortfolioMember) { + for (const specBucket of campaign.manifest.spec.stages.specialistBuckets) { + const passingSpec = allIndividuals + .filter(ind => ind.bucketId === specBucket.id && ind.status === 'passed') + .sort(comparePortfolioCandidateBetter); + if (passingSpec.length > 0) { + selectedMap.set(passingSpec[0]!.individualId, passingSpec[0]!); + } + } + } + selectedIndividuals = [...selectedMap.values()]; + } else { + const passing = allIndividuals.filter(ind => ind.status === 'passed'); + if (passing.length === 0) { + throw new EvolutionError( + 'EXPORT_UNVERIFIED_FORBIDDEN', + `campaign "${campaign.campaignId}" has no passing individuals eligible for export`, + ); + } + const rank1 = passing.filter(ind => ind.paretoRank === 1); + if (rank1.length > 0) { + selectedIndividuals = rank1; + } else { + const rankable = passing.filter(ind => + campaign.manifest.spec.objectives.every(obj => Object.hasOwn(ind.metrics, obj.metric)), + ); + if (rankable.length > 0) { + const ranked = computeNsga2Ranking( + rankable.map(ind => ({ individualId: ind.individualId, metrics: ind.metrics })), + campaign.manifest.spec.objectives, + ); + const rank1Ids = new Set(ranked.filter(r => r.paretoRank === 1).map(r => r.individualId)); + selectedIndividuals = passing.filter(ind => rank1Ids.has(ind.individualId)); + } else { + selectedIndividuals = passing; + } + } + } + + selectedIndividuals.sort((a, b) => compareUtf16(a.individualId, b.individualId)); + for (const ind of selectedIndividuals) { + if (!SAFE_FILENAME_ID_RE.test(ind.individualId) || ind.individualId === '.' || ind.individualId === '..') { + throw new EvolutionError('ARTIFACT_INVALID', `unsafe individualId for receipt filename: "${ind.individualId}"`); + } + } + + // Verify every selected individual's receipt, hardware compatibility, and CAS Stage A output blobs + const verifiedBlobsByHex = new Map(); + const anchorProvenance = verifiedPortfolioAnchor?.receipt.provenance ?? null; + let resolvedAnchorProvenance: HardwareProvenance | null = anchorProvenance; + const isSingleTarget = campaign.manifest.spec.stages.mode === 'single-target'; + const expectedSingleTargetWorkloadId = isSingleTarget + ? (campaign.manifest.spec.stages.heldOutWorkloadId ?? campaign.manifest.spec.heldOutWorkloadId) + : undefined; + + for (const ind of selectedIndividuals) { + const receiptBundle = await loadAndVerifyReceipt(ind); + + if ( + expectedSingleTargetWorkloadId !== undefined + && receiptBundle.heldOutWorkloadId !== undefined + && receiptBundle.heldOutWorkloadId !== expectedSingleTargetWorkloadId + ) { + throw new EvolutionError( + 'EXPORT_UNVERIFIED_FORBIDDEN', + `receipt for individual "${ind.individualId}" has heldOutWorkloadId "${receiptBundle.heldOutWorkloadId}" (expected "${expectedSingleTargetWorkloadId}")`, + ); + } + + if (resolvedAnchorProvenance === null) { + resolvedAnchorProvenance = receiptBundle.provenance; + } else { + assertCompatibleHardwareProvenance( + resolvedAnchorProvenance, + receiptBundle.provenance, + isSingleTarget, + ind.individualId, + ); + } + + 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); + }); + + for (const art of sortedReceiptArtifacts) { + const isTextual = isTextualArtifact(art.name, art.mediaType); + const existing = verifiedBlobsByHex.get(art.digest.hex); + if (existing !== undefined) { + if (existing.byteLength !== art.byteLength) { + throw new EvolutionError( + 'ARTIFACT_INVALID', + `conflicting byteLength for blob ${art.digest.hex}`, + ); + } + if (isTextual && !existing.textChecked) { + const blobBytes = await readVerifiedCasBlob(options.store.campaignRoot, art.digest.hex, { + expectedByteLength: art.byteLength, + maxBytes: maxBlobBytes, + }); + const text = decodeUtf8Strict(blobBytes, `/blobs/sha256/${art.digest.hex}`); + assertCleanSecretText(text, scrubber, `/blobs/sha256/${art.digest.hex}`); + existing.textChecked = true; + } + continue; + } + + const blobBytes = await readVerifiedCasBlob(options.store.campaignRoot, art.digest.hex, { + expectedByteLength: art.byteLength, + maxBytes: maxBlobBytes, + }); + + if (isTextual) { + const text = decodeUtf8Strict(blobBytes, `/blobs/sha256/${art.digest.hex}`); + assertCleanSecretText(text, scrubber, `/blobs/sha256/${art.digest.hex}`); + } + + verifiedBlobsByHex.set(art.digest.hex, { + digest: art.digest, + byteLength: art.byteLength, + mediaType: inferBlobMediaType(art.name, art.mediaType), + artifactNames: [art.name], + textChecked: isTextual, + }); + } + } + + if (resolvedAnchorProvenance === null) { + throw new EvolutionError('EXPORT_UNVERIFIED_FORBIDDEN', 'no verified hardware provenance available for bundle export'); + } + + // Build & validate dispatch-manifest.json + const dispatchManifest = options.dispatchManifest !== undefined + ? normalizeAndVerifyDispatchManifest(options.dispatchManifest, verifiedBlobsByHex, scrubber) + : synthesizeDispatchManifest(campaign, selectedIndividuals, receiptCache, defaultEntrypoint, scrubber); + + const dispatchCanonical = canonicalizeJson(dispatchManifest); + assertCleanSecretText(dispatchCanonical, scrubber, '/dispatch-manifest.json'); + const dispatchBytes = Buffer.from(dispatchCanonical, 'utf8'); + const dispatchManifestDigest = makeDigest(sha256Hex(dispatchBytes)); + + // Prepare deterministic sorted receipts and Stage A blobs + const sortedReceipts = selectedIndividuals.map(ind => { + const rec = receiptCache.get(ind.individualId)!; + return { + individualId: ind.individualId, + relPath: `receipts/${ind.individualId}.verdict.json`, + bytes: rec.rawBytes, + digest: rec.rawDigest, + }; + }).sort((a, b) => compareUtf16(a.relPath, b.relPath)); + + const sortedStageABlobs = [...verifiedBlobsByHex.values()] + .map(blob => ({ + relPath: `blobs/sha256/${blob.digest.hex}`, + byteLength: blob.byteLength, + digest: blob.digest, + mediaType: blob.mediaType, + })) + .sort((a, b) => compareUtf16(a.relPath, b.relPath)); + + // Build members list (sorted lexicographically by path) + const members: BundleMemberDigest[] = []; + const pushMember = (path: string, digest: Digest, byteLength: number, mediaType: string): void => { + const m = createNullRecord<{ + path: string; + digest: Digest; + byteLength: number; + mediaType: string; + }>(); + m.path = path; + m.digest = makeDigest(digest.hex); + m.byteLength = byteLength; + m.mediaType = mediaType; + members.push(m); + }; + + pushMember( + 'dispatch-manifest.json', + dispatchManifestDigest, + dispatchBytes.byteLength, + EVOLUTION_DISPATCH_MANIFEST_MEDIA_TYPE, + ); + for (const rec of sortedReceipts) { + pushMember(rec.relPath, rec.digest, rec.bytes.byteLength, EVOLUTION_RECEIPT_MEDIA_TYPE); + } + for (const blob of sortedStageABlobs) { + pushMember(blob.relPath, blob.digest, blob.byteLength, blob.mediaType); + } + members.sort((a, b) => compareUtf16(a.path, b.path)); + + // Build compatibility, paretoSummary, lineage, and manifest.json + const compatibility = buildCompatibilityTuple( + resolvedAnchorProvenance, + options, + campaign.driverConstraint, + scrubber, + ); + const paretoSummary = buildParetoSummary(campaign, selectedIndividuals, receiptCache); + const exportedIndividualIds = selectedIndividuals.map(ind => ind.individualId).sort(compareUtf16); + + const lineage = createNullRecord<{ + campaignId: string; + individualIds: readonly string[]; + baseRevision: string; + lockHash: Digest; + }>(); + lineage.campaignId = campaign.campaignId; + lineage.individualIds = exportedIndividualIds; + lineage.baseRevision = campaign.baseRevision; + lineage.lockHash = makeDigest(campaign.lockHash.hex); + + const bundleManifest = createNullRecord<{ + kind: typeof EVOLUTION_BUNDLE_KIND; + version: typeof EVOLUTION_BUNDLE_VERSION; + compatibility: BundleCompatibilityTuple; + paretoSummary: readonly BundleParetoEntry[]; + lineage: BundleLineageProvenance; + members: readonly BundleMemberDigest[]; + }>(); + bundleManifest.kind = EVOLUTION_BUNDLE_KIND; + bundleManifest.version = EVOLUTION_BUNDLE_VERSION; + bundleManifest.compatibility = compatibility; + bundleManifest.paretoSummary = paretoSummary; + bundleManifest.lineage = lineage; + bundleManifest.members = members; + + const manifestCanonical = canonicalizeJson(bundleManifest); + assertCleanSecretText(manifestCanonical, scrubber, '/manifest.json'); + const manifestBytes = Buffer.from(manifestCanonical, 'utf8'); + const manifestDigest = makeDigest(sha256Hex(manifestBytes)); + + const ociArtifacts = format === 'oci-layout' + ? buildOciLayoutArtifacts({ + campaign, + compatibility, + manifestBytes, + manifestDigest, + dispatchBytes, + dispatchDigest: dispatchManifestDigest, + receipts: sortedReceipts, + stageABlobs: sortedStageABlobs, + }) + : null; + + // Atomically stage into sibling temp directory and rename into resolvedOutputDir + const parentDir = dirname(resolvedOutputDir); + await ensureDirectoryChainNoSymlink(parentDir, 0o755); + + const stagingDir = join(parentDir, `.evolution-bundle-stage-${randomBytes(8).toString('hex')}`); + let published = false; + try { + await mkdir(stagingDir, { mode: 0o755, recursive: false }); + await mkdir(join(stagingDir, 'receipts'), { mode: 0o755, recursive: false }); + await mkdir(join(stagingDir, 'blobs'), { mode: 0o755, recursive: false }); + await mkdir(join(stagingDir, 'blobs', 'sha256'), { mode: 0o755, recursive: false }); + + await writeNewFileNoFollow(join(stagingDir, 'manifest.json'), manifestBytes, 0o644); + await writeNewFileNoFollow(join(stagingDir, 'dispatch-manifest.json'), dispatchBytes, 0o644); + + for (const rec of sortedReceipts) { + await writeNewFileNoFollow(join(stagingDir, rec.relPath), rec.bytes, 0o644); + } + + const writtenBlobHexes = new Set(); + for (const blob of sortedStageABlobs) { + if (writtenBlobHexes.has(blob.digest.hex)) continue; + writtenBlobHexes.add(blob.digest.hex); + // Re-read one verified CAS blob at a time so export peak memory stays O(1) blob. + const blobBytes = await readVerifiedCasBlob(options.store.campaignRoot, blob.digest.hex, { + expectedByteLength: blob.byteLength, + maxBytes: maxBlobBytes, + }); + await writeNewFileNoFollow(join(stagingDir, blob.relPath), blobBytes, 0o644); + } + + if (ociArtifacts !== null) { + const sortedExtraHexes = [...ociArtifacts.extraBlobsByHex.keys()].sort(compareUtf16); + for (const hex of sortedExtraHexes) { + if (writtenBlobHexes.has(hex)) continue; + writtenBlobHexes.add(hex); + const bytes = ociArtifacts.extraBlobsByHex.get(hex)!; + await writeNewFileNoFollow(join(stagingDir, 'blobs', 'sha256', hex), bytes, 0o644); + } + await writeNewFileNoFollow(join(stagingDir, 'oci-layout'), ociArtifacts.ociLayoutBytes, 0o644); + await writeNewFileNoFollow(join(stagingDir, 'index.json'), ociArtifacts.ociIndexBytes, 0o644); + } + + await publishStagingDirectoryAtomically(stagingDir, resolvedOutputDir, overwrite); + published = true; + } finally { + if (!published) { + await rm(stagingDir, { recursive: true, force: true }).catch(() => undefined); + } + } + + return Object.freeze({ + format, + outputDir: resolvedOutputDir, + manifestDigest, + dispatchManifestDigest, + ...(ociArtifacts !== null ? { ociIndexDigest: ociArtifacts.ociIndexDigest } : {}), + exportedIndividualIds: Object.freeze(exportedIndividualIds), + blobCount: sortedStageABlobs.length, + }); +} + +function parseBundleManifestJson( + manifestBytes: Buffer, + scrubber: SecretScrubber, +): EvolutionBundleManifestV1 { + const text = decodeUtf8Strict(manifestBytes, '/manifest.json'); + assertCleanSecretText(text, scrubber, '/manifest.json'); + + let parsedRaw: NullProtoJson; + try { + parsedRaw = parseNullProtoJson(text, MAX_BUNDLE_MANIFEST_BYTES, '/manifest.json'); + } catch (err: unknown) { + throw new EvolutionError( + 'ARTIFACT_INVALID', + `invalid manifest.json: ${err instanceof Error ? err.message : String(err)}`, + '/manifest.json', + ); + } + + const root = expectRecord( + parsedRaw, + BUNDLE_MANIFEST_KEYS, + ['kind', 'version', 'compatibility', 'paretoSummary', 'lineage', 'members'], + 'ARTIFACT_INVALID', + '/manifest.json', + ); + if (root['kind'] !== EVOLUTION_BUNDLE_KIND || root['version'] !== EVOLUTION_BUNDLE_VERSION) { + throw new EvolutionError('ARTIFACT_INVALID', 'manifest.json must have kind: "EvolutionBundle" and version: 1', '/manifest.json'); + } + + const compatObj = expectRecord( + root['compatibility'], + COMPATIBILITY_KEYS, + ['accelerator', 'isolationMode', 'deviceCount', 'driverVersion', 'runtimeVersion', 'workloadDigest'], + 'ARTIFACT_INVALID', + '/manifest.json/compatibility', + ); + if (compatObj['isolationMode'] !== 'whole_device' && compatObj['isolationMode'] !== 'sliced') { + throw new EvolutionError('ARTIFACT_INVALID', 'invalid compatibility.isolationMode', '/manifest.json/compatibility/isolationMode'); + } + if ( + typeof compatObj['deviceCount'] !== 'number' + || !Number.isSafeInteger(compatObj['deviceCount']) + || compatObj['deviceCount'] < 1 + || compatObj['deviceCount'] > 64 + ) { + throw new EvolutionError('ARTIFACT_INVALID', 'invalid compatibility.deviceCount', '/manifest.json/compatibility/deviceCount'); + } + parseDigestValue(compatObj['workloadDigest'], 'ARTIFACT_INVALID', '/manifest.json/compatibility/workloadDigest'); + if (Object.hasOwn(compatObj, 'driverConstraint') && compatObj['driverConstraint'] !== undefined) { + if ( + typeof compatObj['driverConstraint'] !== 'string' + || compatObj['driverConstraint'].length < 1 + || compatObj['driverConstraint'].length > 128 + || !PRINTABLE_ASCII_RE.test(compatObj['driverConstraint']) + ) { + throw new EvolutionError('ARTIFACT_INVALID', 'invalid compatibility.driverConstraint', '/manifest.json/compatibility/driverConstraint'); + } + } + if (Object.hasOwn(compatObj, 'modelDigest') && compatObj['modelDigest'] !== undefined) { + parseDigestValue(compatObj['modelDigest'], 'ARTIFACT_INVALID', '/manifest.json/compatibility/modelDigest'); + } + + const lineageObj = expectRecord( + root['lineage'], + LINEAGE_KEYS, + ['campaignId', 'individualIds', 'baseRevision', 'lockHash'], + 'ARTIFACT_INVALID', + '/manifest.json/lineage', + ); + if (typeof lineageObj['campaignId'] !== 'string' || !SAFE_ID_RE.test(lineageObj['campaignId'])) { + throw new EvolutionError('ARTIFACT_INVALID', 'invalid lineage.campaignId', '/manifest.json/lineage/campaignId'); + } + if (!Array.isArray(lineageObj['individualIds']) || lineageObj['individualIds'].length === 0) { + throw new EvolutionError('ARTIFACT_INVALID', 'lineage.individualIds must be non-empty', '/manifest.json/lineage/individualIds'); + } + parseDigestValue(lineageObj['lockHash'], 'ARTIFACT_INVALID', '/manifest.json/lineage/lockHash'); + + const rawPareto = root['paretoSummary']; + if (!Array.isArray(rawPareto) || rawPareto.length === 0) { + throw new EvolutionError('ARTIFACT_INVALID', 'paretoSummary must be a non-empty array', '/manifest.json/paretoSummary'); + } + for (let i = 0; i < rawPareto.length; i++) { + expectRecord( + rawPareto[i], + PARETO_ENTRY_KEYS, + ['individualId', 'paretoRank', 'nicheKey', 'metrics'], + 'ARTIFACT_INVALID', + `/manifest.json/paretoSummary/${i}`, + ); + } + + const rawMembers = root['members']; + if (!Array.isArray(rawMembers) || rawMembers.length === 0) { + throw new EvolutionError('ARTIFACT_INVALID', 'members must be a non-empty array', '/manifest.json/members'); + } + const seenPaths = new Set(); + for (let i = 0; i < rawMembers.length; i++) { + const mPath = `/manifest.json/members/${i}`; + const mObj = expectRecord(rawMembers[i], MEMBER_KEYS, ['path', 'digest', 'byteLength'], 'ARTIFACT_INVALID', mPath); + const relPath = mObj['path']; + if (typeof relPath !== 'string' || !validateRelativePath(relPath).ok) { + throw new EvolutionError('ARTIFACT_INVALID', 'invalid member path', `${mPath}/path`); + } + if (seenPaths.has(relPath)) { + throw new EvolutionError('ARTIFACT_INVALID', `duplicate member path "${relPath}"`, `${mPath}/path`); + } + seenPaths.add(relPath); + parseDigestValue(mObj['digest'], 'ARTIFACT_INVALID', `${mPath}/digest`); + const byteLength = mObj['byteLength']; + if (typeof byteLength !== 'number' || !Number.isSafeInteger(byteLength) || byteLength < 0) { + throw new EvolutionError('ARTIFACT_INVALID', 'invalid member byteLength', `${mPath}/byteLength`); + } + } + + return root as unknown as EvolutionBundleManifestV1; +} + +function parseOciDigestString(raw: unknown, diagPath: string): string { + if (typeof raw !== 'string' || !raw.startsWith('sha256:')) { + throw new EvolutionError('ARTIFACT_INVALID', 'OCI digest must start with "sha256:"', diagPath); + } + const hex = raw.slice(7); + if (!SHA256_HEX_RE.test(hex)) { + throw new EvolutionError('ARTIFACT_INVALID', 'OCI digest must contain 64 lowercase hex characters', diagPath); + } + return hex; +} + +/** + * Verify an exported `evolution-bundle.v1` directory (`dir` or `oci-layout`) on disk, + * enforcing `O_NOFOLLOW`, `nlink === 1`, exact SHA-256 + `byteLength` member digests, + * `dispatch-manifest.json` rules, signed `receipts/*.verdict.json` proofs, and OCI layout integrity. + */ +export async function verifyEvolutionBundle( + options: VerifyEvolutionBundleOptions, +): Promise { + const scrubber = options.scrubber ?? DEFAULT_SECRET_SCRUBBER; + const allowSyntheticProbe = options.allowSyntheticProbe === true; + const maxBlobBytes = options.maxBlobBytes ?? DEFAULT_MAX_BLOB_BYTES; + + const hasReceiptVerifier = + (typeof options.receiptSigningSecret === 'string' && options.receiptSigningSecret.length > 0) + || typeof options.verifyReceiptSignature === 'function'; + if (!hasReceiptVerifier && options.allowUnverifiedSignature !== true) { + throw new EvolutionError( + 'EXPORT_UNVERIFIED_FORBIDDEN', + 'receiptSigningSecret or verifyReceiptSignature is required to verify HMAC verdict receipts', + ); + } + + const resolvedBundleDir = validateAbsoluteFilesystemPath(options.bundleDir, 'bundleDir'); + await assertNoSymlinkPath(resolvedBundleDir, { checkLeaf: true, diagPath: resolvedBundleDir }); + await verifyNonSymlinkDirectoryFd(resolvedBundleDir); + + const manifestBytes = await readVerifiedRegularFileNoFollow(join(resolvedBundleDir, 'manifest.json'), { + maxBytes: MAX_BUNDLE_MANIFEST_BYTES, + missingCode: 'ARTIFACT_MISSING', + }); + const manifestDigest = makeDigest(sha256Hex(manifestBytes)); + const manifest = parseBundleManifestJson(manifestBytes, scrubber); + + // Verify every member listed in manifest.json + const verifiedMemberBytes = new Map(); + const verifiedBlobHexes = new Set(); + let receiptCount = 0; + + for (const member of manifest.members) { + const absMemberPath = join(resolvedBundleDir, member.path); + await assertNoSymlinkPath(absMemberPath, { checkLeaf: true, diagPath: absMemberPath }); + const bytes = await readVerifiedRegularFileNoFollow(absMemberPath, { + expectedSha256Hex: member.digest.hex, + expectedByteLength: member.byteLength, + maxBytes: maxBlobBytes, + missingCode: 'ARTIFACT_MISSING', + }); + if (member.path.startsWith('blobs/sha256/')) { + 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}`); + } + verifiedBlobHexes.add(member.digest.hex); + // Do not retain large verified Stage A blob buffers in memory after digest verification + } else { + verifiedMemberBytes.set(member.path, bytes); + } + } + + // Verify dispatch-manifest.json + const dispatchBytes = verifiedMemberBytes.get('dispatch-manifest.json'); + if (!dispatchBytes) { + throw new EvolutionError('ARTIFACT_MISSING', 'manifest.json does not list dispatch-manifest.json'); + } + const dispatchManifest = parseDispatchManifestV1(dispatchBytes, { scrubber }); + if (dispatchBytes.byteLength > DISPATCH_MANIFEST_MAX_BYTES) { + throw new EvolutionError('ARTIFACT_INVALID', 'dispatch-manifest.json exceeds max byte size'); + } + for (let i = 0; i < dispatchManifest.rules.length; i++) { + const rule = dispatchManifest.rules[i]!; + if (!verifiedBlobHexes.has(rule.blobDigest.hex)) { + throw new EvolutionError( + 'ARTIFACT_INVALID', + `dispatch-manifest.json rule ${i} references missing blob ${rule.blobDigest.hex}`, + ); + } + } + const dispatchManifestDigest = makeDigest(sha256Hex(dispatchBytes)); + + // Verify every receipt listed in manifest.lineage.individualIds + const verifiedReceiptDigests = new Map(); + for (const individualId of manifest.lineage.individualIds) { + const relPath = `receipts/${individualId}.verdict.json`; + const receiptBytes = verifiedMemberBytes.get(relPath); + if (!receiptBytes) { + throw new EvolutionError('EXPORT_UNVERIFIED_FORBIDDEN', `missing receipt member "${relPath}"`); + } + const parsedReceipt = await parseAndVerifyReceiptBytes(receiptBytes, { + individualId, + allowSyntheticProbe, + ...(options.receiptSigningSecret !== undefined ? { receiptSigningSecret: options.receiptSigningSecret } : {}), + ...(options.verifyReceiptSignature !== undefined ? { verifyReceiptSignature: options.verifyReceiptSignature } : {}), + scrubber, + maxBlobBytes, + }); + if ( + parsedReceipt.provenance.accelerator !== manifest.compatibility.accelerator + || parsedReceipt.provenance.isolationMode !== manifest.compatibility.isolationMode + || parsedReceipt.provenance.deviceCount !== manifest.compatibility.deviceCount + || parsedReceipt.provenance.driverVersion !== manifest.compatibility.driverVersion + || parsedReceipt.provenance.runtimeVersion !== manifest.compatibility.runtimeVersion + || (parsedReceipt.provenance.topology ?? null) !== (manifest.compatibility.topology ?? null) + ) { + throw new EvolutionError( + 'ARTIFACT_INVALID', + `receipt "${individualId}" hardwareProvenance does not match manifest.json compatibility tuple`, + ); + } + for (const art of parsedReceipt.outputArtifacts) { + if (!verifiedBlobHexes.has(art.digest.hex)) { + throw new EvolutionError( + 'ARTIFACT_INVALID', + `receipt "${individualId}" references blob ${art.digest.hex} missing from bundle members`, + ); + } + } + verifiedReceiptDigests.set(relPath, parsedReceipt.rawDigest.hex); + receiptCount++; + } + + // Detect and verify optional OCI Image Layout + const ociLayoutPath = join(resolvedBundleDir, 'oci-layout'); + const ociLayoutStat = await lstat(ociLayoutPath).catch((err: NodeJS.ErrnoException) => { + if (err.code === 'ENOENT') return null; + if (err.code === 'ELOOP') { + throw new EvolutionError('ARTIFACT_INVALID', 'oci-layout cannot be a symlink', ociLayoutPath); + } + throw err; + }); + + let format: EvolutionExportFormat = 'dir'; + let ociIndexDigest: Digest | undefined; + + if (ociLayoutStat !== null) { + format = 'oci-layout'; + const ociLayoutBytes = await readVerifiedRegularFileNoFollow(ociLayoutPath, { + maxBytes: 1_024, + missingCode: 'ARTIFACT_MISSING', + }); + const layoutObj = expectRecord( + parseNullProtoJson(decodeUtf8Strict(ociLayoutBytes, '/oci-layout'), 1_024, '/oci-layout'), + new Set(['imageLayoutVersion']), + ['imageLayoutVersion'], + 'ARTIFACT_INVALID', + '/oci-layout', + ); + if (layoutObj['imageLayoutVersion'] !== OCI_IMAGE_LAYOUT_VERSION) { + throw new EvolutionError('ARTIFACT_INVALID', `unsupported oci-layout version "${String(layoutObj['imageLayoutVersion'])}"`); + } + + const indexBytes = await readVerifiedRegularFileNoFollow(join(resolvedBundleDir, 'index.json'), { + maxBytes: MAX_OCI_DOC_BYTES, + missingCode: 'ARTIFACT_MISSING', + }); + ociIndexDigest = makeDigest(sha256Hex(indexBytes)); + const indexObj = expectRecord( + parseNullProtoJson(decodeUtf8Strict(indexBytes, '/index.json'), MAX_OCI_DOC_BYTES, '/index.json'), + new Set(['schemaVersion', 'mediaType', 'manifests', 'annotations']), + ['schemaVersion', 'mediaType', 'manifests'], + 'ARTIFACT_INVALID', + '/index.json', + ); + if (indexObj['schemaVersion'] !== 2 || indexObj['mediaType'] !== OCI_IMAGE_INDEX_MEDIA_TYPE) { + throw new EvolutionError('ARTIFACT_INVALID', 'invalid OCI index.json schemaVersion or mediaType', '/index.json'); + } + const manifestsArr = indexObj['manifests']; + if (!Array.isArray(manifestsArr) || manifestsArr.length === 0) { + throw new EvolutionError('ARTIFACT_INVALID', 'OCI index.json manifests[] must be non-empty', '/index.json/manifests'); + } + + const descKeys = new Set(['mediaType', 'artifactType', 'digest', 'size', 'annotations']); + for (let i = 0; i < manifestsArr.length; i++) { + const mDesc = expectRecord( + manifestsArr[i], + descKeys, + ['mediaType', 'digest', 'size'], + 'ARTIFACT_INVALID', + `/index.json/manifests/${i}`, + ); + if (mDesc['mediaType'] !== OCI_IMAGE_MANIFEST_MEDIA_TYPE) { + throw new EvolutionError('ARTIFACT_INVALID', 'unexpected OCI manifest mediaType', `/index.json/manifests/${i}/mediaType`); + } + const ociManifestHex = parseOciDigestString(mDesc['digest'], `/index.json/manifests/${i}/digest`); + const ociManifestSize = mDesc['size']; + if (typeof ociManifestSize !== 'number' || !Number.isSafeInteger(ociManifestSize) || ociManifestSize < 2) { + throw new EvolutionError('ARTIFACT_INVALID', 'invalid OCI manifest size', `/index.json/manifests/${i}/size`); + } + + const ociManifestBytes = await readVerifiedRegularFileNoFollow( + join(resolvedBundleDir, 'blobs', 'sha256', ociManifestHex), + { + expectedSha256Hex: ociManifestHex, + expectedByteLength: ociManifestSize, + maxBytes: MAX_OCI_DOC_BYTES, + missingCode: 'ARTIFACT_MISSING', + }, + ); + const ociManifestObj = expectRecord( + parseNullProtoJson(decodeUtf8Strict(ociManifestBytes, '/oci-manifest'), MAX_OCI_DOC_BYTES, '/oci-manifest'), + new Set(['schemaVersion', 'mediaType', 'artifactType', 'config', 'layers', 'annotations']), + ['schemaVersion', 'mediaType', 'config', 'layers'], + 'ARTIFACT_INVALID', + '/oci-manifest', + ); + if (ociManifestObj['schemaVersion'] !== 2 || ociManifestObj['mediaType'] !== OCI_IMAGE_MANIFEST_MEDIA_TYPE) { + throw new EvolutionError('ARTIFACT_INVALID', 'invalid OCI manifest schemaVersion or mediaType', '/oci-manifest'); + } + + const configDesc = expectRecord( + ociManifestObj['config'], + descKeys, + ['mediaType', 'digest', 'size'], + 'ARTIFACT_INVALID', + '/oci-manifest/config', + ); + const configHex = parseOciDigestString(configDesc['digest'], '/oci-manifest/config/digest'); + const configSize = configDesc['size']; + if (typeof configSize !== 'number' || !Number.isSafeInteger(configSize) || configSize < 0) { + throw new EvolutionError('ARTIFACT_INVALID', 'invalid OCI config size', '/oci-manifest/config/size'); + } + await readVerifiedRegularFileNoFollow(join(resolvedBundleDir, 'blobs', 'sha256', configHex), { + expectedSha256Hex: configHex, + expectedByteLength: configSize, + maxBytes: MAX_OCI_DOC_BYTES, + missingCode: 'ARTIFACT_MISSING', + }); + + const layersArr = ociManifestObj['layers']; + if (!Array.isArray(layersArr) || layersArr.length === 0) { + throw new EvolutionError('ARTIFACT_INVALID', 'OCI manifest layers[] must be non-empty', '/oci-manifest/layers'); + } + const ociLayerHexes = new Set(); + for (let j = 0; j < layersArr.length; j++) { + const lDesc = expectRecord( + layersArr[j], + descKeys, + ['mediaType', 'digest', 'size'], + 'ARTIFACT_INVALID', + `/oci-manifest/layers/${j}`, + ); + const layerHex = parseOciDigestString(lDesc['digest'], `/oci-manifest/layers/${j}/digest`); + const layerSize = lDesc['size']; + if (typeof layerSize !== 'number' || !Number.isSafeInteger(layerSize) || layerSize < 0) { + throw new EvolutionError('ARTIFACT_INVALID', 'invalid OCI layer size', `/oci-manifest/layers/${j}/size`); + } + await readVerifiedRegularFileNoFollow(join(resolvedBundleDir, 'blobs', 'sha256', layerHex), { + expectedSha256Hex: layerHex, + expectedByteLength: layerSize, + maxBytes: maxBlobBytes, + missingCode: 'ARTIFACT_MISSING', + }); + ociLayerHexes.add(layerHex); + } + if (!ociLayerHexes.has(manifestDigest.hex) || !ociLayerHexes.has(dispatchManifestDigest.hex)) { + throw new EvolutionError( + 'ARTIFACT_INVALID', + 'OCI manifest layers do not cover root manifest.json and dispatch-manifest.json', + '/oci-manifest/layers', + ); + } + for (const receiptHex of verifiedReceiptDigests.values()) { + if (!ociLayerHexes.has(receiptHex)) { + throw new EvolutionError( + 'ARTIFACT_INVALID', + `OCI manifest layers omit receipt blob ${receiptHex}`, + '/oci-manifest/layers', + ); + } + } + for (const blobHex of verifiedBlobHexes) { + if (!ociLayerHexes.has(blobHex)) { + throw new EvolutionError( + 'ARTIFACT_INVALID', + `OCI manifest layers omit Stage A blob ${blobHex}`, + '/oci-manifest/layers', + ); + } + } + } + } + + return Object.freeze({ + format, + bundleDir: resolvedBundleDir, + manifest, + dispatchManifest, + manifestDigest, + dispatchManifestDigest, + ...(ociIndexDigest !== undefined ? { ociIndexDigest } : {}), + receiptCount, + blobCount: verifiedBlobHexes.size, + }); +} diff --git a/packages/evolution/src/campaign.ts b/packages/evolution/src/campaign.ts new file mode 100644 index 0000000..84890ac --- /dev/null +++ b/packages/evolution/src/campaign.ts @@ -0,0 +1,3592 @@ +import { execFile } from 'node:child_process'; +import { createHash, randomBytes } from 'node:crypto'; +import { constants } from 'node:fs'; +import { + chmod, + lstat, + mkdir, + mkdtemp, + open, + readdir, + readFile, + realpath, + rename, + rm, + unlink, + writeFile, +} from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { dirname, isAbsolute, join, resolve, sep } from 'node:path'; +import { promisify } from 'node:util'; +import { + admitTask, + LIMITS, + SecretScrubber, + type ArtifactRef, + type BucketMetricEntry, + type Digest, + type HardwareDiagnostics, + type HardwareProvenance, + type StructuredFinding, + type TaskContract, +} from '@loopwright/core'; +import { + inspectRun, + loadTrustedConfiguration, + resolveCanonicalCasBlobPath, + stepCancel, + stepNext, + stepSubmit, + type ControllerPolicyProfile, + type RunEvalReport, + type StepVerdict, +} from '@loopwright/controller'; +import { + DECISION_NOVELTY_MAX_HISTORY_SLICES, + DECISION_NOVELTY_MAX_SLICE_BYTES, + DECISION_PROVIDER_API_KEY_ENV, + DECISION_PROVIDER_DEFAULTS, + DecisionBudgetTracker, + DEFAULT_DECISION_POLICY, + evaluateCascadeEscalation, + evaluateMutationNovelty, + HttpDecisionTransport, + routeEvolutionStrategy, + type DecisionCascadeEscalationResult, + type DecisionEvolutionMutationKind, + type DecisionEvolutionStrategyResult, + type DecisionHardwareDiagnostics, + type DecisionMutationNoveltyHistoryEntry, + type DecisionMutationNoveltyResult, + type DecisionPolicyConfig, + type DecisionTransport, +} from '@loopwright/decisions'; +import { MAX_RECEIPT_FILE_BYTES } from '@loopwright/hardware-runner'; +import { + compileDeclarativeTaskpack, + loadDeclarativeTaskpack, + stageCompiledInstructionResources, + type ExecutionHostPolicy, + type HostCredentialEnvMap, + type HostGateEndpointPlan, + type TaskpackManifest, + type TaskpackRoleDeclaration, + type TaskpackStepDeclaration, + type TaskpackToolName, +} from '@loopwright/taskpack'; +import { + exportEvolutionBundle, + type ExportEvolutionBundleResult, + type ReceiptSignatureVerifier, +} from './bundle.js'; +import { + computeHypervolume, + computeHypervolumeDelta, + computeNicheKey, + computeNsga2Ranking, + computeObjectiveReferenceStats, + scalarizeFitness, +} from './pareto.js'; +import { + computeTruncatedImprovementReward, + createSeededPrng, + sampleParents, + selectModelCandidate, + selectRingMigrationElites, + stageMultiParentContextFiles, + stagePortfolioSpecialistContextFiles, + type ParentContextInput, + type PortfolioSpecialistContextInput, + type SampledParentEntry, + type StagedParentContextFile, +} from './sampler.js'; +import { + canonicalizeJson, + loadEvolutionCampaignFile, + parseArtifactRefsJson, + parseBucketMetricsJson, + parseEvolutionCampaignDocument, + parseHardwareDiagnosticsJson, + parseHardwareProvenanceJson, + parseMetricsRecordJson, + parseNullProtoJson, + parseStructuredFindingsJson, + type NullProtoJson, +} from './schema.js'; +import { synthesizeCampaignScratchpad } from './scratchpad.js'; +import { EvolutionCampaignStore } from './store.js'; +import { + hasRunEvalLoopPathology, + recordTeamTrialOutcome, + runPlateauSupervisorTurn, + validateAndCompileTeamPatch, + type IslandTrajectoryEntry, + type SupervisorRunnerPort, +} from './team-supervisor.js'; +import { + EvolutionError, + type CampaignClockSource, + type CampaignLease, + type CampaignRecord, + type CampaignStagePhase, + type DispatchManifestV1, + type EvolutionCampaignManifest, + type IndividualMutationKind, + type IndividualRecord, + type IndividualStatus, + type IslandRecord, + type LineageEdgeRecord, + type ModelBanditArmRecord, + type ObjectiveDirectionSpec, + type ScratchpadSnapshotRecord, + type TeamConfigRecord, + type TeamPatchV1, +} from './types.js'; + +const execFileAsync = promisify(execFile); +const DEFAULT_CAMPAIGN_SCRUBBER = new SecretScrubber(); +const AVAILABLE_EVOLUTION_TRACKS: readonly string[] = Object.freeze([ + 'cuda_raw', + 'cute', + 'triton', + 'tilelang', + 'ascend_tile', + 'policy_json', +]); + +const DEFAULT_CHILD_TASK_BUDGETS: TaskContract['spec']['budgets'] = Object.freeze({ + wallTimeMs: 600_000, + totalTokens: 250_000, + perCallOutputTokens: 16_384, + maxModelCalls: 16, + maxConcurrency: 1, + maxFormatRepairs: 0, + maxImplementationRepairs: 0, + maxTransportRetries: 1, + enforcement: Object.freeze({ + wallTime: 'hard_admission' as const, + tokens: 'soft_accounting' as const, + modelCalls: 'hard_admission' as const, + concurrency: 'hard_admission' as const, + formatRepairs: 'hard_admission' as const, + implementationRepairs: 'hard_admission' as const, + transportRetries: 'hard_admission' as const, + }), +}); + +export type EvolutionaryAdvisoryDecision = + | DecisionMutationNoveltyResult + | DecisionEvolutionStrategyResult + | DecisionCascadeEscalationResult; + +export interface CheckEvolutionCampaignOptions { + readonly manifestPath?: string | undefined; + readonly manifest?: EvolutionCampaignManifest | string | Uint8Array | undefined; + readonly format?: 'yaml' | 'json' | undefined; + readonly repositoryRoot?: string | undefined; + readonly taskpack?: TaskpackManifest | undefined; + readonly hostPolicy?: ExecutionHostPolicy | undefined; + readonly allowLoopbackHttp?: boolean | undefined; + readonly scrubber?: SecretScrubber | undefined; +} + +export interface CheckEvolutionCampaignResult { + readonly valid: true; + readonly manifest: EvolutionCampaignManifest; + readonly manifestDigest: Digest; + readonly taskpack: TaskpackManifest; + readonly targetCellId: string; + readonly modelIds: readonly string[]; + readonly stageMode: 'single-target' | 'specialist-then-portfolio'; + readonly specialistBucketIds: readonly string[]; + readonly portfolioHeldOutWorkloadId: string | null; +} + +export interface CandidateProposalContext { + readonly campaignId: string; + readonly individualId: string; + readonly islandId: number; + readonly generation: number; + readonly stagePhase: CampaignStagePhase; + readonly bucketId: string | null; + readonly heldOutWorkloadId: string; + readonly modelId: string; + readonly trackId: string; + readonly mutationKind: IndividualMutationKind; + readonly teamConfigId: string; + readonly parents: readonly SampledParentEntry[]; + readonly stagedParentFiles: readonly StagedParentContextFile[]; + readonly stagedScratchpadPath?: string | undefined; + readonly portfolioSpecialists?: readonly IndividualRecord[] | undefined; +} + +export interface ScreenCandidateNoveltyOptions { + readonly candidateId: string; + readonly candidateSlice: string; + readonly historySlices: readonly DecisionMutationNoveltyHistoryEntry[]; + readonly policy?: DecisionPolicyConfig | undefined; + readonly budget?: DecisionBudgetTracker | undefined; + readonly transport?: DecisionTransport | undefined; + readonly apiKey?: string | undefined; + readonly noveltyThreshold?: number | undefined; + readonly shingleSize?: number | undefined; + readonly scrubber?: SecretScrubber | undefined; +} + +export interface ScreenCandidateNoveltyOutcome { + readonly rejected: boolean; + readonly failureReason: 'NOVELTY_CLONE_REJECTED' | null; + readonly decision: DecisionMutationNoveltyResult; +} + +export interface BuildStageScopedTaskpackOptions { + readonly taskpack: TaskpackManifest; + readonly heldOutWorkloadId: string; + readonly targetCellId: string; + readonly teamPatch?: TeamPatchV1 | undefined; +} + +export interface CollectedChildBenchmarkArtifacts { + readonly hasBenchmarkProof: boolean; + readonly rawVerdictReceiptBytes?: Uint8Array | undefined; + readonly metrics: Readonly>; + readonly bucketMetrics?: readonly BucketMetricEntry[] | undefined; + readonly hardwareDiagnostics?: HardwareDiagnostics | undefined; + readonly hardwareProvenance?: HardwareProvenance | undefined; + readonly findings?: readonly StructuredFinding[] | undefined; + readonly outputArtifacts: readonly ArtifactRef[]; + readonly stageABlobs: readonly StageABlobPayload[]; + readonly dispositionReason: string | null; + readonly retryablePreemption: boolean; +} + +export interface CandidateEvaluationProposal extends CandidateProposalContext { + readonly campaignRoot: string; + readonly childRunDir: string; + readonly baseRevision: string; + readonly manifest: EvolutionCampaignManifest; + readonly taskpack: TaskpackManifest; + readonly teamPatch?: TeamPatchV1 | undefined; + readonly proposedCodeSlice?: string | undefined; + readonly islandHistorySlices?: readonly DecisionMutationNoveltyHistoryEntry[] | undefined; + readonly noveltyGate?: ((candidateSlice: string) => Promise) | undefined; + readonly signal?: AbortSignal | undefined; +} + +export interface StageABlobPayload { + readonly name: string; + readonly bytes: Uint8Array; + readonly digest: Digest; + readonly byteLength: number; + readonly mediaType?: string | null | undefined; +} + +export interface CandidateEvaluationResult { + readonly status: IndividualStatus; + readonly failureReason?: string | null | undefined; + readonly codeSlice: string; + readonly metrics: Readonly>; + readonly smokeMetrics?: Readonly> | undefined; + readonly bucketMetrics?: readonly BucketMetricEntry[] | undefined; + readonly hardwareDiagnostics?: HardwareDiagnostics | undefined; + readonly hardwareProvenance?: HardwareProvenance | undefined; + readonly findings?: readonly StructuredFinding[] | undefined; + readonly outputArtifacts?: readonly ArtifactRef[] | undefined; + readonly stageABlobs?: readonly StageABlobPayload[] | undefined; + readonly rawVerdictReceiptBytes?: Uint8Array | undefined; + readonly evidenceDigest?: Digest | null | undefined; + readonly childRunRelPath?: string | undefined; + readonly runEvalReport?: RunEvalReport | undefined; + readonly noveltyDecision?: DecisionMutationNoveltyResult | undefined; +} + +export type CandidateEvaluator = ( + proposal: CandidateEvaluationProposal, +) => Promise; + +export interface CandidateAgentStepContext { + readonly campaignId: string; + readonly individualId: string; + readonly islandId: number; + readonly generation: number; + readonly stagePhase: CampaignStagePhase; + readonly bucketId: string | null; + readonly roleId: string; + readonly stepId: string; + readonly workspacePath: string; + readonly childRunDir: string; + readonly prompt: string; + readonly contextFiles: readonly string[]; + readonly modelId: string; + readonly trackId: string; + readonly mutationKind: IndividualMutationKind; + readonly parents: readonly SampledParentEntry[]; + readonly signal?: AbortSignal | undefined; +} + +export interface CandidateAgentStepResult { + readonly submissionFile?: string | undefined; + readonly verdict?: StepVerdict | undefined; + readonly status?: 'completed' | 'no_change' | 'failed' | 'blocked' | undefined; + readonly reason?: string | undefined; +} + +export interface ControllerChildRunEvaluatorOptions { + readonly repositoryRoot: string; + readonly gateEndpoints?: readonly HostGateEndpointPlan[] | undefined; + readonly credentialEnvMap?: HostCredentialEnvMap | undefined; + readonly environment?: ((name: string) => string | undefined) | undefined; + readonly allowLoopbackHttp?: boolean | undefined; + readonly policyProfile?: ControllerPolicyProfile | undefined; + readonly decisionPolicy?: DecisionPolicyConfig | undefined; + readonly decisionBudget?: DecisionBudgetTracker | undefined; + readonly decisionTransport?: DecisionTransport | undefined; + readonly decisionApiKey?: string | undefined; + readonly agentDriver: (context: CandidateAgentStepContext) => Promise; + readonly onAfterChildEvaluation?: ((proposal: CandidateEvaluationProposal, result: CandidateEvaluationResult) => Promise | void) | undefined; + readonly scrubber?: SecretScrubber | undefined; +} + +export interface RunEvolutionCampaignOptions { + readonly campaignRoot: string; + readonly campaignId?: string | undefined; + readonly manifestPath?: string | undefined; + readonly manifest?: EvolutionCampaignManifest | string | Uint8Array | undefined; + readonly format?: 'yaml' | 'json' | undefined; + readonly repositoryRoot?: string | undefined; + readonly baseRevision?: string | undefined; + readonly taskpack?: TaskpackManifest | undefined; + readonly evaluator?: CandidateEvaluator | undefined; + readonly controllerEvaluatorOptions?: ControllerChildRunEvaluatorOptions | undefined; + readonly proposeCandidateSlice?: ((context: CandidateProposalContext) => Promise) | undefined; + readonly supervisorRunner?: SupervisorRunnerPort | undefined; + readonly decisionPolicy?: DecisionPolicyConfig | undefined; + readonly decisionTransport?: DecisionTransport | undefined; + readonly decisionApiKey?: string | undefined; + readonly environment?: ((name: string) => string | undefined) | undefined; + readonly clock?: CampaignClockSource | undefined; + readonly signal?: AbortSignal | undefined; + readonly autoExport?: boolean | undefined; + readonly exportFormat?: 'dir' | 'oci-layout' | undefined; + readonly allowSyntheticProbe?: boolean | undefined; + readonly receiptSigningSecret?: string | undefined; + readonly verifyReceiptSignature?: ReceiptSignatureVerifier | undefined; + readonly dispatchManifest?: DispatchManifestV1 | undefined; + readonly scrubber?: SecretScrubber | undefined; +} + +export interface ResumeEvolutionCampaignOptions { + readonly campaignRoot: string; + readonly campaignId?: string | undefined; + readonly repositoryRoot?: string | undefined; + readonly taskpack?: TaskpackManifest | undefined; + readonly evaluator?: CandidateEvaluator | undefined; + readonly controllerEvaluatorOptions?: ControllerChildRunEvaluatorOptions | undefined; + readonly proposeCandidateSlice?: ((context: CandidateProposalContext) => Promise) | undefined; + readonly supervisorRunner?: SupervisorRunnerPort | undefined; + readonly decisionPolicy?: DecisionPolicyConfig | undefined; + readonly decisionTransport?: DecisionTransport | undefined; + readonly decisionApiKey?: string | undefined; + readonly environment?: ((name: string) => string | undefined) | undefined; + readonly clock?: CampaignClockSource | undefined; + readonly signal?: AbortSignal | undefined; + readonly autoExport?: boolean | undefined; + readonly exportFormat?: 'dir' | 'oci-layout' | undefined; + readonly allowSyntheticProbe?: boolean | undefined; + readonly receiptSigningSecret?: string | undefined; + readonly verifyReceiptSignature?: ReceiptSignatureVerifier | undefined; + readonly dispatchManifest?: DispatchManifestV1 | undefined; + readonly scrubber?: SecretScrubber | undefined; +} + +export interface RunEvolutionCampaignResult { + readonly store: EvolutionCampaignStore; + readonly campaign: CampaignRecord; + readonly islands: readonly IslandRecord[]; + readonly paretoFrontier: readonly IndividualRecord[]; + readonly noveltyRejectionsCount: number; + readonly cascadeSoftStopsCount: number; + readonly advisoryDecisions: readonly EvolutionaryAdvisoryDecision[]; + readonly earlyStoppedByRoofline: boolean; + readonly exportedBundle?: ExportEvolutionBundleResult | undefined; +} + +export interface GetEvolutionCampaignStatusOptions { + readonly campaignRoot: string; + readonly campaignId?: string | undefined; + readonly store?: EvolutionCampaignStore | undefined; + readonly clock?: CampaignClockSource | undefined; +} + +export interface EvolutionCampaignStatus { + readonly campaign: CampaignRecord; + readonly islands: readonly IslandRecord[]; + readonly paretoFrontier: readonly IndividualRecord[]; + readonly countsByStatus: { + readonly passed: number; + readonly soft_passed: number; + readonly failed: number; + readonly preempted: number; + readonly noveltyRejected: number; + }; + readonly activeTeams: readonly TeamConfigRecord[]; + readonly latestScratchpad: ScratchpadSnapshotRecord | null; +} + +export interface IslandNicheArchiveView { + readonly islandId: number; + readonly bucketId: string | null; + readonly elites: readonly IndividualRecord[]; +} + +export interface InspectEvolutionCampaignOptions { + readonly campaignRoot: string; + readonly campaignId?: string | undefined; + readonly store?: EvolutionCampaignStore | undefined; + readonly clock?: CampaignClockSource | undefined; +} + +export interface EvolutionCampaignInspection { + readonly campaign: CampaignRecord; + readonly islands: readonly IslandRecord[]; + readonly paretoFrontier: readonly IndividualRecord[]; + readonly nicheArchives: readonly IslandNicheArchiveView[]; + readonly teamConfigs: readonly TeamConfigRecord[]; + readonly individuals: readonly IndividualRecord[]; + readonly lineageEdges: readonly LineageEdgeRecord[]; + readonly modelBanditArms: readonly ModelBanditArmRecord[]; + readonly scratchpadSnapshots: readonly ScratchpadSnapshotRecord[]; +} + +const CONTROLLER_RUN_ID_RE = /^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/; +const FORBIDDEN_RUN_IDS: ReadonlySet = new Set(['__proto__', 'constructor', 'prototype']); +const DEFAULT_MAX_CHILD_BLOB_BYTES = 67_108_864; + +/** Compute a frozen `{ algorithm: 'sha256', hex }` digest over UTF-8 string or raw bytes. */ +export function sha256Digest(bytes: Uint8Array | string): Digest { + return Object.freeze({ + algorithm: 'sha256' as const, + hex: createHash('sha256').update(bytes).digest('hex'), + }); +} + +function truncateUtf8ByBytes(text: string, maxBytes: number): string { + if (Buffer.byteLength(text, 'utf8') <= maxBytes) return text; + const buf = Buffer.from(text, 'utf8'); + let end = maxBytes; + while (end > 0 && (buf[end]! & 0xc0) === 0x80) { + end -= 1; + } + return buf.subarray(0, end).toString('utf8'); +} + +/** + * Sanitize an arbitrary string into a strict controller-valid lowercase identifier + * matching `/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/` (`<= 64` chars), preserving any + * trailing hexadecimal nonce segment whenever truncation occurs. + */ +export function sanitizeRunId(raw: string): string { + let cleaned = raw + .toLowerCase() + .replace(/[^a-z0-9._-]+/g, '-') + .replace(/[._-]{2,}/g, '-') + .replace(/^[^a-z0-9]+|[^a-z0-9]+$/g, ''); + + if (cleaned.length === 0) { + return `ind-${randomBytes(4).toString('hex')}`; + } + if (!/^[a-z]/.test(cleaned)) { + cleaned = `r-${cleaned}`; + } + if (FORBIDDEN_RUN_IDS.has(cleaned)) { + cleaned = `id-${cleaned}`; + } + + if (cleaned.length > LIMITS.identifier) { + const trailingNonceMatch = /[._-]([0-9a-f]{4,16})$/.exec(cleaned); + const suffix = trailingNonceMatch !== null + ? trailingNonceMatch[1]! + : createHash('sha256').update(raw, 'utf8').digest('hex').slice(0, 8); + const maxPrefixLen = Math.max(1, LIMITS.identifier - 1 - suffix.length); + let prefix = cleaned + .slice(0, maxPrefixLen) + .replace(/[^a-z0-9]+$/g, ''); + if (prefix.length === 0 || !/^[a-z]/.test(prefix)) { + prefix = 'r'; + } + cleaned = `${prefix}-${suffix}`; + } + + if (!CONTROLLER_RUN_ID_RE.test(cleaned) || cleaned.length > LIMITS.identifier) { + return `ind-${randomBytes(4).toString('hex')}`; + } + return cleaned; +} + +async function resolveGitHeadRevision(repositoryRoot: string | undefined): Promise { + if (repositoryRoot !== undefined && repositoryRoot.trim().length > 0) { + try { + const { stdout } = await execFileAsync('git', ['rev-parse', 'HEAD'], { + cwd: resolve(repositoryRoot), + encoding: 'utf8', + maxBuffer: 1024 * 64, + }); + const out = stdout.trim(); + if (/^[0-9a-f]{40}$/i.test(out)) { + return out.toLowerCase(); + } + } catch { + // Fall through to deterministic synthetic 40-hex revision + } + } + return '0'.repeat(40); +} + +async function resolveCanonicalPathAllowMissingLeaf(rawPath: string, label: string): Promise { + if (typeof rawPath !== 'string' || rawPath.trim().length === 0 || rawPath.includes('\0')) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', `${label} must be a non-empty path`, `/${label}`); + } + const absPath = resolve(rawPath); + const missingSegments: string[] = []; + let cursor = absPath; + + for (;;) { + 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 loop along ${absPath}`, `/${label}`); + } + throw err; + }); + if (st !== null) { + const realExisting = await realpath(cursor).catch((err: NodeJS.ErrnoException) => { + if (err.code === 'ELOOP') { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `symlink loop along ${absPath}`, `/${label}`); + } + throw err; + }); + return missingSegments.length > 0 + ? join(realExisting, ...missingSegments.reverse()) + : realExisting; + } + const parent = dirname(cursor); + if (parent === cursor) { + return absPath; + } + missingSegments.push(cursor.slice(parent.length + (parent.endsWith(sep) ? 0 : 1))); + cursor = parent; + } +} + +async function assertDisjointCampaignAndRepositoryRoots( + campaignRoot: string, + repositoryRoot: string | undefined, +): Promise { + if (repositoryRoot === undefined || repositoryRoot.trim().length === 0) { + return; + } + const canonicalCampaign = await resolveCanonicalPathAllowMissingLeaf(campaignRoot, 'campaignRoot'); + const canonicalRepo = await resolveCanonicalPathAllowMissingLeaf(repositoryRoot, 'repositoryRoot'); + const campaignPrefix = canonicalCampaign.endsWith(sep) ? canonicalCampaign : `${canonicalCampaign}${sep}`; + const repoPrefix = canonicalRepo.endsWith(sep) ? canonicalRepo : `${canonicalRepo}${sep}`; + + if ( + canonicalCampaign === canonicalRepo + || canonicalCampaign.startsWith(repoPrefix) + || canonicalRepo.startsWith(campaignPrefix) + ) { + throw new EvolutionError( + 'EVOLUTION_SCHEMA_INVALID', + 'campaignRoot must live outside repositoryRoot', + '/campaignRoot', + ); + } +} + +async function copyRegularFileNoFollow(srcFile: string, dstFile: string, preserveExec: boolean): Promise { + const noFollow = 'O_NOFOLLOW' in constants ? constants.O_NOFOLLOW : 0; + const st = await lstat(srcFile); + if (st.isSymbolicLink()) { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `symlink forbidden inside repository tree: "${srcFile}"`, srcFile); + } + if (!st.isFile()) return; + + const srcFh = await open(srcFile, constants.O_RDONLY | noFollow).catch((err: NodeJS.ErrnoException) => { + if (err.code === 'ELOOP' || err.code === 'EFTYPE') { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `symlink forbidden inside repository tree: "${srcFile}"`, srcFile); + } + throw err; + }); + let bytes: Buffer; + try { + const fdStat = await srcFh.stat(); + if (!fdStat.isFile()) return; + bytes = await srcFh.readFile(); + } finally { + await srcFh.close(); + } + + await mkdir(dirname(dstFile), { recursive: true, mode: 0o700 }); + const execBit = preserveExec && (st.mode & 0o111) !== 0; + const mode = execBit ? 0o755 : 0o644; + const dstFh = await open(dstFile, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | noFollow, mode); + try { + await dstFh.writeFile(bytes); + if (execBit) await dstFh.chmod(0o755); + } finally { + await dstFh.close(); + } +} + +async function copyGitMetadataDirNoFollow(srcGitDir: string, dstGitDir: string): Promise { + const st = await lstat(srcGitDir); + if (st.isSymbolicLink() || !st.isDirectory()) { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `git directory must not be a symlink: "${srcGitDir}"`, srcGitDir); + } + await mkdir(dstGitDir, { recursive: true, mode: 0o700 }); + const entries = await readdir(srcGitDir, { withFileTypes: true }); + for (const entry of entries) { + if (entry.name === 'hooks') continue; + const srcChild = join(srcGitDir, entry.name); + const dstChild = join(dstGitDir, entry.name); + const childStat = await lstat(srcChild); + if (childStat.isSymbolicLink()) { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `symlink forbidden inside .git metadata: "${srcChild}"`, srcChild); + } + if (childStat.isDirectory()) { + await copyGitMetadataDirNoFollow(srcChild, dstChild); + } else if (childStat.isFile()) { + await copyRegularFileNoFollow(srcChild, dstChild, false); + } + } +} + +async function copyUntrackedFallbackTreeNoFollow(srcDir: string, dstDir: string): Promise { + const srcStat = await lstat(srcDir); + if (srcStat.isSymbolicLink() || !srcStat.isDirectory()) { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `source directory must be a non-symlink directory: "${srcDir}"`, srcDir); + } + await mkdir(dstDir, { recursive: true, mode: 0o700 }); + const entries = await readdir(srcDir, { withFileTypes: true }); + for (const entry of entries) { + if (entry.name === 'node_modules' || entry.name === '.git') continue; + const srcChild = join(srcDir, entry.name); + const dstChild = join(dstDir, entry.name); + const st = await lstat(srcChild); + if (st.isSymbolicLink()) { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `symlink forbidden inside repository tree: "${srcChild}"`, srcChild); + } + if (st.isDirectory()) { + await copyUntrackedFallbackTreeNoFollow(srcChild, dstChild); + } else if (st.isFile()) { + await copyRegularFileNoFollow(srcChild, dstChild, true); + } + } +} + +/** + * Materialize an isolated child Git checkout into `dstRepoDir` by copying tracked Git tree files + * (`git ls-files -z` with `O_NOFOLLOW` regular-file copy + preserving executable `0o755` mode, + * refusing any tracked symlink, and copying `.git` metadata without hardlinks or hooks) so + * untracked directories such as `node_modules/.bin/*` symlinks never cause crashes or recursion. + */ +export async function materializeGitCheckoutNoFollow(srcRepoDir: string, dstRepoDir: string): Promise { + const srcStat = await lstat(srcRepoDir); + if (srcStat.isSymbolicLink() || !srcStat.isDirectory()) { + throw new EvolutionError( + 'EVOLUTION_SYMLINK_FORBIDDEN', + `source directory must be a non-symlink directory: "${srcRepoDir}"`, + srcRepoDir, + ); + } + + const dotGitPath = join(srcRepoDir, '.git'); + const dotGitStat = await lstat(dotGitPath).catch((err: NodeJS.ErrnoException) => { + if (err.code === 'ENOENT') return null; + throw err; + }); + + if (dotGitStat === null) { + await copyUntrackedFallbackTreeNoFollow(srcRepoDir, dstRepoDir); + return; + } + if (dotGitStat.isSymbolicLink()) { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `.git cannot be a symlink: "${dotGitPath}"`, dotGitPath); + } + + await mkdir(dstRepoDir, { recursive: true, mode: 0o700 }); + + if (dotGitStat.isDirectory()) { + await copyGitMetadataDirNoFollow(dotGitPath, join(dstRepoDir, '.git')); + } else if (dotGitStat.isFile()) { + await execFileAsync('git', ['clone', '--no-hardlinks', '--quiet', '--no-checkout', srcRepoDir, dstRepoDir], { + maxBuffer: 1024 * 1024, + }); + await rm(join(dstRepoDir, '.git', 'hooks'), { recursive: true, force: true }).catch(() => undefined); + } + + const { stdout: rawTracked } = await execFileAsync('git', ['ls-files', '-z'], { + cwd: srcRepoDir, + encoding: 'buffer', + maxBuffer: 64 * 1024 * 1024, + }); + + const checkedParentDirs = new Set(); + let start = 0; + for (let i = 0; i <= rawTracked.byteLength; i += 1) { + if (i < rawTracked.byteLength && rawTracked[i] !== 0) continue; + if (i > start) { + const relPath = rawTracked.subarray(start, i).toString('utf8'); + const parts = relPath.split('/'); + if ( + relPath.startsWith('/') + || parts.some(seg => seg.length === 0 || seg === '.' || seg === '..') + ) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', `invalid tracked Git path "${relPath}"`, relPath); + } + + let cursorDir = srcRepoDir; + for (let p = 0; p < parts.length - 1; p += 1) { + cursorDir = join(cursorDir, parts[p]!); + if (!checkedParentDirs.has(cursorDir)) { + const dirSt = await lstat(cursorDir).catch((err: NodeJS.ErrnoException) => { + if (err.code === 'ENOENT') return null; + throw err; + }); + if (dirSt !== null && dirSt.isSymbolicLink()) { + throw new EvolutionError( + 'EVOLUTION_SYMLINK_FORBIDDEN', + `symlink directory forbidden inside tracked repository path: "${cursorDir}"`, + cursorDir, + ); + } + checkedParentDirs.add(cursorDir); + } + } + + const srcFile = join(srcRepoDir, ...parts); + const fileSt = await lstat(srcFile).catch((err: NodeJS.ErrnoException) => { + if (err.code === 'ENOENT') return null; + throw err; + }); + if (fileSt !== null) { + if (fileSt.isSymbolicLink()) { + throw new EvolutionError( + 'EVOLUTION_SYMLINK_FORBIDDEN', + `tracked symlink forbidden inside repository tree: "${srcFile}"`, + srcFile, + ); + } + if (fileSt.isFile()) { + const dstFile = join(dstRepoDir, ...parts); + await copyRegularFileNoFollow(srcFile, dstFile, true); + } + } + } + start = i + 1; + } +} + +async function writeReadOnlyScratchpadFile( + dirPath: string, + markdown: string, + scrubber: SecretScrubber, +): Promise<{ readonly filePath: string; readonly digest: Digest; readonly byteLength: number }> { + const scrubbed = scrubber.scrub(markdown); + if (scrubbed !== markdown) { + throw new EvolutionError('SECRET_LEAK_DETECTED', 'secret detected in campaign scratchpad markdown', '/scratchpad'); + } + await mkdir(dirPath, { recursive: true, mode: 0o700 }); + const targetPath = join(dirPath, 'scratchpad.md'); + const existing = await lstat(targetPath).catch((err: NodeJS.ErrnoException) => { + if (err.code === 'ENOENT') return null; + throw err; + }); + if (existing !== null) { + if (existing.isSymbolicLink()) { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `symlink scratchpad path forbidden: "${targetPath}"`); + } + await chmod(targetPath, 0o600).catch(() => undefined); + await unlink(targetPath); + } + const bytes = Buffer.from(markdown, 'utf8'); + const tmpPath = `${targetPath}.${randomBytes(6).toString('hex')}.tmp`; + const fh = await open(tmpPath, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o400); + try { + await fh.writeFile(bytes); + await fh.chmod(0o400); + await fh.sync(); + } finally { + await fh.close(); + } + await rename(tmpPath, targetPath); + return Object.freeze({ + filePath: targetPath, + digest: sha256Digest(bytes), + byteLength: bytes.byteLength, + }); +} + +/** Extract `EVOLVE-BLOCK-START:` .. `EVOLVE-BLOCK-END:` slices from source text, falling back to full text when absent. */ +export function extractEvolveBlocksFromSource(text: string): string { + const lines = text.split('\n'); + const blocks: string[] = []; + let inBlock = false; + let current: string[] = []; + for (const line of lines) { + if (line.includes('EVOLVE-BLOCK-START:')) { + inBlock = true; + current = [line]; + continue; + } + if (inBlock) { + current.push(line); + if (line.includes('EVOLVE-BLOCK-END:')) { + blocks.push(current.join('\n')); + inBlock = false; + current = []; + } + } + } + return blocks.length > 0 ? `${blocks.join('\n')}\n` : text; +} + +/** + * Screen a candidate's `EVOLVE-BLOCK` source slice against island history (`<= 64` newest slices) + * BEFORE dispatching `benchmark-gate.v1` Stage A/B, rejecting exact normalized clones (`Jaccard === 1.0`) + * with `0` network calls and Jev soft-band clones with `NOVELTY_CLONE_REJECTED`. + */ +export async function screenCandidateNoveltyBeforeDispatch( + options: ScreenCandidateNoveltyOptions, +): Promise { + const boundedHistory = options.historySlices + .slice(-DECISION_NOVELTY_MAX_HISTORY_SLICES) + .map(entry => ({ + id: entry.id.slice(0, 128), + sourceSlice: truncateUtf8ByBytes(entry.sourceSlice, DECISION_NOVELTY_MAX_SLICE_BYTES), + })); + const boundedCandidateSlice = truncateUtf8ByBytes(options.candidateSlice, DECISION_NOVELTY_MAX_SLICE_BYTES); + const safeCandidateId = options.candidateId.trim().slice(0, 128) || 'candidate'; + const decision = await evaluateMutationNovelty({ + policy: options.policy ?? DEFAULT_DECISION_POLICY, + state: {}, + budget: options.budget ?? new DecisionBudgetTracker(), + ...(options.transport !== undefined ? { transport: options.transport } : {}), + ...(options.apiKey !== undefined ? { apiKey: options.apiKey } : {}), + ...(options.scrubber !== undefined ? { scrubber: options.scrubber } : {}), + novelty: { + candidateId: safeCandidateId, + candidateSlice: boundedCandidateSlice, + historySlices: boundedHistory, + ...(options.noveltyThreshold !== undefined ? { noveltyThreshold: options.noveltyThreshold } : {}), + ...(options.shingleSize !== undefined ? { shingleSize: options.shingleSize } : {}), + }, + }); + const rejected = decision.action === 'reject_resample'; + return Object.freeze({ + rejected, + failureReason: rejected ? ('NOVELTY_CLONE_REJECTED' as const) : null, + decision, + }); +} + +/** + * Validate an `EvolutionCampaign` manifest and its linked `Taskpack` fail-closed. + */ +export async function checkEvolutionCampaign( + options: CheckEvolutionCampaignOptions, +): Promise { + const scrubber = options.scrubber ?? DEFAULT_CAMPAIGN_SCRUBBER; + + let manifest: EvolutionCampaignManifest; + let manifestDigest: Digest; + let inferredRepoRoot = options.repositoryRoot !== undefined ? resolve(options.repositoryRoot) : undefined; + + if (options.manifestPath !== undefined) { + const absManifestPath = isAbsolute(options.manifestPath) + ? resolve(options.manifestPath) + : resolve(inferredRepoRoot ?? process.cwd(), options.manifestPath); + manifest = await loadEvolutionCampaignFile(absManifestPath, { scrubber }); + manifestDigest = sha256Digest(canonicalizeJson(manifest)); + if (inferredRepoRoot === undefined) { + inferredRepoRoot = dirname(absManifestPath); + } + } else if (options.manifest !== undefined) { + if (typeof options.manifest === 'string' || options.manifest instanceof Uint8Array) { + manifest = parseEvolutionCampaignDocument(options.manifest, { scrubber }); + } else { + manifest = parseEvolutionCampaignDocument(canonicalizeJson(options.manifest), { scrubber }); + } + manifestDigest = sha256Digest(canonicalizeJson(manifest)); + } else { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'either manifestPath or manifest is required'); + } + + let taskpack: TaskpackManifest; + if (options.taskpack !== undefined) { + taskpack = options.taskpack; + } else { + try { + taskpack = await loadDeclarativeTaskpack({ + manifestPath: manifest.spec.taskpack, + ...(inferredRepoRoot !== undefined ? { repositoryRoot: inferredRepoRoot } : {}), + executionMode: 'delegated', + allowLoopbackHttp: options.allowLoopbackHttp ?? true, + ...(options.hostPolicy !== undefined ? { hostPolicy: options.hostPolicy } : {}), + }); + } catch (err: unknown) { + throw new EvolutionError( + 'EVOLUTION_SCHEMA_INVALID', + `linked taskpack "${manifest.spec.taskpack}" failed validation: ${err instanceof Error ? err.message : String(err)}`, + '/spec/taskpack', + ); + } + } + + const targetMatrix = taskpack.spec.target?.matrix ?? null; + const targetCell = targetMatrix?.find(cell => cell.id === manifest.spec.targetCellId); + if (targetCell === undefined || targetCell.hardware === undefined) { + throw new EvolutionError( + 'EVOLUTION_SCHEMA_INVALID', + `targetCellId "${manifest.spec.targetCellId}" must match a hardware target.matrix cell in taskpack "${taskpack.metadata.name}"`, + '/spec/targetCellId', + ); + } + + const matchingBenchGates = taskpack.spec.verification.externalGates.filter( + g => g.implementation === 'benchmark-gate.v1' && g.targetCellId === manifest.spec.targetCellId, + ); + if (matchingBenchGates.length === 0) { + throw new EvolutionError( + 'EVOLUTION_SCHEMA_INVALID', + `taskpack "${taskpack.metadata.name}" must declare a benchmark-gate.v1 externalGate for targetCellId "${manifest.spec.targetCellId}"`, + '/spec/targetCellId', + ); + } + + let specialistBucketIds: readonly string[] = Object.freeze([]); + let portfolioHeldOutWorkloadId: string | null = null; + if (manifest.spec.stages.mode === 'specialist-then-portfolio') { + portfolioHeldOutWorkloadId = manifest.spec.stages.portfolioHeldOutWorkloadId; + const specIds: string[] = []; + for (const bucket of manifest.spec.stages.specialistBuckets) { + if (bucket.heldOutWorkloadId === portfolioHeldOutWorkloadId) { + throw new EvolutionError( + 'EVOLUTION_SCHEMA_INVALID', + `portfolioHeldOutWorkloadId "${portfolioHeldOutWorkloadId}" must not collide with specialist bucket "${bucket.id}" heldOutWorkloadId`, + '/spec/stages/portfolioHeldOutWorkloadId', + ); + } + specIds.push(bucket.id); + } + specialistBucketIds = Object.freeze(specIds); + } + + if (manifest.spec.teamEvolution?.enabled === true) { + const teamSpec = manifest.spec.teamEvolution; + const declaredRoleIds = new Set( + taskpack.spec.roles !== undefined && taskpack.spec.roles.length > 0 + ? taskpack.spec.roles.map(r => r.id) + : ['author'], + ); + for (const archId of teamSpec.allowedArchetypeRoles) { + if (!declaredRoleIds.has(archId)) { + throw new EvolutionError( + 'TEAM_ENVELOPE_VIOLATION', + `teamEvolution.allowedArchetypeRoles entry "${archId}" is not declared in taskpack "${taskpack.metadata.name}"`, + '/spec/teamEvolution/allowedArchetypeRoles', + ); + } + } + const supervisorInTaskpack = taskpack.spec.roles?.find(r => r.id === teamSpec.supervisorRoleId); + if ( + supervisorInTaskpack?.tools !== undefined + && supervisorInTaskpack.tools.some(t => t === 'write' || t === 'edit' || t === 'delete' || t === 'bash') + ) { + throw new EvolutionError( + 'TEAM_ENVELOPE_VIOLATION', + `supervisorRoleId "${teamSpec.supervisorRoleId}" must not declare mutating or exec tools`, + '/spec/teamEvolution/supervisorRoleId', + ); + } + } + + const rawModels = taskpack.spec.models?.map(m => m.id) ?? []; + const modelIds = Object.freeze(rawModels.length > 0 ? Array.from(new Set(rawModels)) : ['default']); + + return Object.freeze({ + valid: true, + manifest, + manifestDigest, + taskpack, + targetCellId: manifest.spec.targetCellId, + modelIds, + stageMode: manifest.spec.stages.mode, + specialistBucketIds, + portfolioHeldOutWorkloadId, + }); +} + +/** + * Build a stage-scoped `TaskpackManifest` rewriting `heldOutWorkloadId` ONLY on `benchmark-gate.v1` + * gates matching `targetCellId`, and applying validated `teamPatch` roles, `thinking`, `timeoutSeconds`, + * and `onRework` step policies when present. + */ +export function buildStageScopedTaskpack(options: BuildStageScopedTaskpackOptions): TaskpackManifest; +export function buildStageScopedTaskpack( + baseTaskpack: TaskpackManifest, + heldOutWorkloadId: string, + teamPatch: TeamPatchV1 | undefined, + targetCellId: string, +): TaskpackManifest; +export function buildStageScopedTaskpack( + first: BuildStageScopedTaskpackOptions | TaskpackManifest, + heldOutWorkloadIdArg?: string, + teamPatchArg?: TeamPatchV1 | undefined, + targetCellIdArg?: string, +): TaskpackManifest { + const isOptions = !('apiVersion' in first); + const baseTaskpack = isOptions ? first.taskpack : first; + const heldOutWorkloadId = isOptions ? first.heldOutWorkloadId : heldOutWorkloadIdArg!; + const targetCellId = isOptions ? first.targetCellId : targetCellIdArg!; + const teamPatch = isOptions ? first.teamPatch : teamPatchArg; + + const updatedGates = baseTaskpack.spec.verification.externalGates.map(gate => { + if (gate.implementation !== 'benchmark-gate.v1' || gate.targetCellId !== targetCellId) { + return gate; + } + return { + ...gate, + heldOutWorkloadId, + }; + }); + + let roles = baseTaskpack.spec.roles; + let steps = baseTaskpack.spec.steps; + let limits = baseTaskpack.spec.limits; + + if (teamPatch !== undefined) { + const baseRoleById = new Map((baseTaskpack.spec.roles ?? []).map(r => [r.id, r] as const)); + const declaredModelsByKey = new Map(); + for (const m of baseTaskpack.spec.models ?? []) { + const entry = { + provider: m.provider, + model: m.id, + ...(m.thinking !== undefined ? { thinking: m.thinking } : {}), + }; + declaredModelsByKey.set(m.id, entry); + declaredModelsByKey.set(`${m.provider}/${m.id}`, entry); + } + for (const r of baseTaskpack.spec.roles ?? []) { + if (r.model !== undefined && r.provider !== undefined) { + const entry = { + provider: r.provider, + model: r.model, + ...(r.thinking !== undefined ? { thinking: r.thinking } : {}), + }; + if (!declaredModelsByKey.has(r.model)) { + declaredModelsByKey.set(r.model, entry); + } + if (!declaredModelsByKey.has(`${r.provider}/${r.model}`)) { + declaredModelsByKey.set(`${r.provider}/${r.model}`, entry); + } + } + } + const firstModel = baseTaskpack.spec.models?.[0]; + const mappedRoles: TaskpackRoleDeclaration[] = teamPatch.roles.map(pr => { + const arch = baseRoleById.get(pr.archetypeRoleId); + const resolvedModel = pr.model !== undefined ? declaredModelsByKey.get(pr.model) : undefined; + return { + id: pr.id, + provider: resolvedModel?.provider ?? arch?.provider ?? firstModel?.provider ?? 'delegated', + model: resolvedModel?.model ?? pr.model ?? arch?.model ?? firstModel?.id ?? 'default', + thinking: pr.thinking ?? arch?.thinking ?? resolvedModel?.thinking ?? firstModel?.thinking ?? 'medium', + purpose: pr.purpose, + prompt: pr.prompt, + tools: [...pr.tools] as TaskpackToolName[], + ...(arch?.instructions !== undefined ? { instructions: arch.instructions } : {}), + ...(arch?.skills !== undefined ? { skills: arch.skills } : {}), + ...(arch?.mcpServers !== undefined ? { mcpServers: arch.mcpServers } : {}), + }; + }); + + const roleTimeouts = teamPatch.roles + .map(r => r.timeoutSeconds) + .filter((v): v is number => v !== undefined); + if (roleTimeouts.length > 0) { + const maxPatchTimeout = Math.max(...roleTimeouts); + const baseTimeout = baseTaskpack.spec.limits?.toolTimeoutSeconds; + const narrowedTimeout = baseTimeout !== undefined ? Math.min(baseTimeout, maxPatchTimeout) : maxPatchTimeout; + limits = { + ...baseTaskpack.spec.limits, + toolTimeoutSeconds: narrowedTimeout, + }; + } + + const mappedAgentSteps: TaskpackStepDeclaration[] = teamPatch.steps.map(ps => ({ + id: ps.id, + kind: 'agent', + role: ps.roleId, + dependsOn: [...ps.dependsOn], + ...(ps.onRework !== undefined + ? { onRework: { rejectTo: ps.onRework.rejectTo, maxReworks: ps.onRework.maxReworks } } + : {}), + ...(ps.handoffs !== undefined + ? { + handoffs: ps.handoffs.map(h => ({ + ...(h.id !== undefined ? { id: h.id } : {}), + fromStep: h.fromStep, + source: (h.source as { readonly kind: string }).kind === 'assistant_final' + ? { kind: 'submission' as const } + : h.source, + select: h.select, + ...(h.maxBytes !== undefined ? { maxBytes: h.maxBytes } : {}), + ...(h.required !== undefined ? { required: h.required } : {}), + })), + } + : {}), + })); + + const childrenCount = new Map(teamPatch.steps.map(s => [s.id, 0] as const)); + for (const s of teamPatch.steps) { + for (const dep of s.dependsOn) { + childrenCount.set(dep, (childrenCount.get(dep) ?? 0) + 1); + } + } + const sinkIds = teamPatch.steps.filter(s => (childrenCount.get(s.id) ?? 0) === 0).map(s => s.id); + const checkIds = [ + ...baseTaskpack.spec.verification.localChecks.map(c => c.id), + ...updatedGates.map(g => g.id), + ]; + const mappedCheckSteps: TaskpackStepDeclaration[] = checkIds.map((chkId, idx) => ({ + id: `check-${chkId}`.slice(0, LIMITS.identifier), + kind: 'check', + check: chkId, + dependsOn: idx === 0 ? sinkIds : [`check-${checkIds[idx - 1]!}`.slice(0, LIMITS.identifier)], + })); + + roles = mappedRoles; + steps = [...mappedAgentSteps, ...mappedCheckSteps]; + } else if (baseTaskpack.spec.roles !== undefined && baseTaskpack.spec.roles.length > 1 && baseTaskpack.spec.steps === undefined) { + const mutatingTaskRoles = baseTaskpack.spec.roles.filter( + r => (r.purpose ?? 'task') === 'task' && (r.tools === undefined || r.tools.some(t => t === 'write' || t === 'edit')), + ); + if (mutatingTaskRoles.length >= 1) { + const chosen = mutatingTaskRoles[0]!; + roles = [ + { + ...chosen, + dependsOn: [], + }, + ]; + } + } + + return { + ...baseTaskpack, + spec: { + ...baseTaskpack.spec, + ...(limits !== undefined ? { limits } : {}), + ...(roles !== undefined ? { roles } : {}), + ...(steps !== undefined ? { steps } : {}), + verification: { + ...baseTaskpack.spec.verification, + externalGates: updatedGates, + }, + }, + }; +} + +async function readBoundedRegularBytesNoFollow( + filePath: string, + maxBytes: number, + pointer: string, +): Promise { + const noFollow = 'O_NOFOLLOW' in constants ? constants.O_NOFOLLOW : 0; + const preStat = await lstat(filePath).catch((err: NodeJS.ErrnoException) => { + if (err.code === 'ELOOP') { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `symlink loop forbidden at "${filePath}"`, pointer); + } + throw err; + }); + if (preStat.isSymbolicLink()) { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `symlink artifact forbidden at "${filePath}"`, pointer); + } + if (!preStat.isFile()) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', `expected regular file at "${filePath}"`, pointer); + } + if (preStat.nlink > 1) { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `hardlinked artifact (nlink=${preStat.nlink}) forbidden at "${filePath}"`, pointer); + } + if (preStat.size > maxBytes) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', `artifact at "${filePath}" exceeds ${maxBytes} bytes`, pointer); + } + + const fh = await open(filePath, constants.O_RDONLY | noFollow).catch((err: NodeJS.ErrnoException) => { + if (err.code === 'ELOOP' || err.code === 'EFTYPE') { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `symlink artifact forbidden at "${filePath}"`, pointer); + } + throw err; + }); + try { + const fdStat = await fh.stat(); + if (!fdStat.isFile()) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', `expected regular file at "${filePath}"`, pointer); + } + if (fdStat.nlink > 1) { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `hardlinked artifact (nlink=${fdStat.nlink}) forbidden at "${filePath}"`, pointer); + } + if (fdStat.size > maxBytes) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', `artifact at "${filePath}" exceeds ${maxBytes} bytes`, pointer); + } + const bytes = await fh.readFile(); + if (bytes.byteLength > maxBytes) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', `artifact at "${filePath}" exceeds ${maxBytes} bytes`, pointer); + } + return bytes; + } finally { + await fh.close(); + } +} + +async function readBoundedNullProtoJsonNoFollow( + filePath: string, + maxBytes: number, + pointer: string, +): Promise>> { + const bytes = await readBoundedRegularBytesNoFollow(filePath, maxBytes, pointer); + const parsed = parseNullProtoJson(bytes.toString('utf8'), maxBytes, pointer); + if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', `expected JSON object at ${pointer}`, pointer); + } + return parsed as Readonly>; +} + +/** + * Safely collect and validate benchmark proof JSON, signed `responseBytes`, hardware telemetry, + * and Stage A CAS blobs from a child controller run's `artifacts/` directory (`O_NOFOLLOW`, `nlink === 1`, + * `MAX_RECEIPT_FILE_BYTES`, null-prototype JSON parsing). + */ +export async function collectChildBenchmarkArtifacts( + artifactsDir: string, + runSucceeded: boolean, + scrubber: SecretScrubber = DEFAULT_CAMPAIGN_SCRUBBER, +): Promise { + const dirStat = await lstat(artifactsDir).catch((err: NodeJS.ErrnoException) => { + if (err.code === 'ENOENT') return null; + if (err.code === 'ELOOP') { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `symlink artifacts directory forbidden: "${artifactsDir}"`, '/artifacts'); + } + throw err; + }); + if (dirStat === null) { + return Object.freeze({ + hasBenchmarkProof: false, + metrics: Object.freeze({}), + outputArtifacts: Object.freeze([]), + stageABlobs: Object.freeze([]), + dispositionReason: null, + retryablePreemption: false, + }); + } + if (dirStat.isSymbolicLink() || !dirStat.isDirectory()) { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `artifacts path must be a non-symlink directory: "${artifactsDir}"`, '/artifacts'); + } + + const artifactNames = await readdir(artifactsDir); + const benchProofFiles = artifactNames + .filter(n => n.startsWith('benchmark-producer-') && n.endsWith('.proof.json')) + .sort(); + + if (benchProofFiles.length === 0) { + return Object.freeze({ + hasBenchmarkProof: false, + metrics: Object.freeze({}), + outputArtifacts: Object.freeze([]), + stageABlobs: Object.freeze([]), + dispositionReason: null, + retryablePreemption: false, + }); + } + + const latestProofFile = join(artifactsDir, benchProofFiles[benchProofFiles.length - 1]!); + const proofJson = await readBoundedNullProtoJsonNoFollow(latestProofFile, MAX_RECEIPT_FILE_BYTES, '/proof'); + const outputRaw = proofJson['output']; + let benchJson: Readonly> = Object.freeze(Object.create(null) as Record); + + if (outputRaw !== undefined && outputRaw !== null) { + if (typeof outputRaw !== 'object' || Array.isArray(outputRaw)) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'proof.output must be an object', '/proof/output'); + } + const outputName = (outputRaw as Readonly>)['name']; + if ( + typeof outputName !== 'string' + || outputName.length === 0 + || outputName.includes('/') + || outputName.includes('\\') + || outputName === '.' + || outputName === '..' + || outputName.includes('..') + || outputName.includes('\0') + ) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'proof.output.name must be a safe single-segment filename', '/proof/output/name'); + } + benchJson = await readBoundedNullProtoJsonNoFollow( + join(artifactsDir, outputName), + MAX_RECEIPT_FILE_BYTES, + '/benchmarkOutput', + ); + } + + let rawVerdictReceiptBytes: Uint8Array | undefined; + let metrics: Readonly> = Object.freeze({}); + let bucketMetrics: readonly BucketMetricEntry[] | undefined; + let hardwareDiagnostics: HardwareDiagnostics | undefined; + let hardwareProvenance: HardwareProvenance | undefined; + let findings: readonly StructuredFinding[] | undefined; + let outputArtifacts: readonly ArtifactRef[] = Object.freeze([]); + const stageABlobs: StageABlobPayload[] = []; + let dispositionReason: string | null = null; + let retryablePreemption = false; + + const responseB64 = benchJson['responseBytes']; + const responseSigRaw = benchJson['responseSignature']; + if (responseB64 !== undefined && responseB64 !== null) { + if (typeof responseB64 !== 'string' || Buffer.byteLength(responseB64, 'utf8') > MAX_RECEIPT_FILE_BYTES * 2) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'responseBytes must be a bounded base64 string', '/benchmarkOutput/responseBytes'); + } + if (responseB64.length > 0) { + const decodedBytes = Buffer.from(responseB64, 'base64'); + if (decodedBytes.byteLength > MAX_RECEIPT_FILE_BYTES) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', `decoded responseBytes exceeds ${MAX_RECEIPT_FILE_BYTES} bytes`, '/benchmarkOutput/responseBytes'); + } + if (typeof responseSigRaw === 'string' && responseSigRaw.length > 0) { + const sigHex = responseSigRaw.startsWith('sha256=') ? responseSigRaw.slice(7) : responseSigRaw; + const parsedResp = parseNullProtoJson(decodedBytes.toString('utf8'), MAX_RECEIPT_FILE_BYTES, '/benchmarkOutput/responseBytes'); + if (typeof parsedResp !== 'object' || parsedResp === null || Array.isArray(parsedResp)) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'decoded responseBytes must be a JSON object', '/benchmarkOutput/responseBytes'); + } + const signedObj = Object.assign( + Object.create(null) as Record, + parsedResp as Record, + { signature: sigHex }, + ); + rawVerdictReceiptBytes = Buffer.from(`${canonicalizeJson(signedObj)}\n`, 'utf8'); + } else { + rawVerdictReceiptBytes = decodedBytes; + } + } + } + + const dispRaw = benchJson['disposition']; + if (dispRaw !== undefined && dispRaw !== null) { + if (typeof dispRaw !== 'object' || Array.isArray(dispRaw)) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'disposition must be an object', '/benchmarkOutput/disposition'); + } + const dispObj = dispRaw as Readonly>; + if (typeof dispObj['reason'] === 'string') { + dispositionReason = dispObj['reason']; + } + if (dispObj['retryablePreemption'] === true || dispositionReason === 'BENCHMARK_PREEMPTED') { + retryablePreemption = true; + } + } + + const verdictRaw = benchJson['verdict']; + if (verdictRaw !== undefined && verdictRaw !== null) { + if (typeof verdictRaw !== 'object' || Array.isArray(verdictRaw)) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'verdict must be an object or null', '/benchmarkOutput/verdict'); + } + const verdictObj = verdictRaw as Readonly>; + if (verdictObj['metrics'] !== undefined && verdictObj['metrics'] !== null) { + metrics = parseMetricsRecordJson(verdictObj['metrics'] as unknown as Readonly>); + } + if (verdictObj['bucketMetrics'] !== undefined && verdictObj['bucketMetrics'] !== null) { + bucketMetrics = parseBucketMetricsJson(verdictObj['bucketMetrics'] as unknown as readonly BucketMetricEntry[], scrubber); + } + if (verdictObj['hardwareDiagnostics'] !== undefined && verdictObj['hardwareDiagnostics'] !== null) { + hardwareDiagnostics = parseHardwareDiagnosticsJson(verdictObj['hardwareDiagnostics'] as unknown as HardwareDiagnostics, scrubber); + } + if (verdictObj['hardwareProvenance'] !== undefined && verdictObj['hardwareProvenance'] !== null) { + hardwareProvenance = parseHardwareProvenanceJson(verdictObj['hardwareProvenance'] as unknown as HardwareProvenance); + } + if (verdictObj['findings'] !== undefined && verdictObj['findings'] !== null) { + findings = parseStructuredFindingsJson(verdictObj['findings'] as unknown as readonly StructuredFinding[], '/verdict/findings'); + } + if (dispositionReason === null && typeof verdictObj['reason'] === 'string') { + dispositionReason = verdictObj['reason']; + } + if (verdictObj['outputArtifacts'] !== undefined && verdictObj['outputArtifacts'] !== null && runSucceeded) { + const validatedRefs = parseArtifactRefsJson(verdictObj['outputArtifacts'] as unknown as readonly ArtifactRef[], '/verdict/outputArtifacts'); + for (const artRef of validatedRefs) { + const casPath = await resolveCanonicalCasBlobPath(artifactsDir, artRef.digest.hex); + const blobBytes = await readBoundedRegularBytesNoFollow( + casPath, + DEFAULT_MAX_CHILD_BLOB_BYTES, + `/verdict/outputArtifacts/${artRef.name}`, + ); + if (blobBytes.byteLength !== artRef.byteLength) { + throw new EvolutionError( + 'ARTIFACT_INVALID', + `Stage A CAS blob "${artRef.name}" byteLength mismatch (expected ${artRef.byteLength}, got ${blobBytes.byteLength})`, + `/verdict/outputArtifacts/${artRef.name}`, + ); + } + const actualDigest = sha256Digest(blobBytes); + if (actualDigest.hex !== artRef.digest.hex) { + throw new EvolutionError( + 'ARTIFACT_INVALID', + `Stage A CAS blob "${artRef.name}" SHA-256 mismatch`, + `/verdict/outputArtifacts/${artRef.name}`, + ); + } + stageABlobs.push({ + name: artRef.name, + bytes: blobBytes, + digest: artRef.digest, + byteLength: artRef.byteLength, + ...(artRef.mediaType !== undefined ? { mediaType: artRef.mediaType } : {}), + }); + } + outputArtifacts = validatedRefs; + } + } + + return Object.freeze({ + hasBenchmarkProof: true, + ...(rawVerdictReceiptBytes !== undefined ? { rawVerdictReceiptBytes } : {}), + metrics, + ...(bucketMetrics !== undefined ? { bucketMetrics } : {}), + ...(hardwareDiagnostics !== undefined ? { hardwareDiagnostics } : {}), + ...(hardwareProvenance !== undefined ? { hardwareProvenance } : {}), + ...(findings !== undefined ? { findings } : {}), + outputArtifacts, + stageABlobs: Object.freeze(stageABlobs), + dispositionReason, + retryablePreemption, + }); +} + +/** + * Create a real child `LocalRunStore` evaluator backed by `@loopwright/controller` (`stepNext` / `stepSubmit`), + * `evolve-block-guard.v1`, and `benchmark-gate.v1` (`RelayServer` + `runHardwareWorker`). + */ +export function createControllerChildRunEvaluator( + options: ControllerChildRunEvaluatorOptions, +): CandidateEvaluator { + const scrubber = options.scrubber ?? DEFAULT_CAMPAIGN_SCRUBBER; + const resolvedBaseRepo = resolve(options.repositoryRoot); + const envLookup = options.environment ?? ((name: string) => process.env[name]); + + return async (proposal: CandidateEvaluationProposal): Promise => { + await mkdir(proposal.childRunDir, { recursive: true, mode: 0o700 }); + const childRunDir = await realpath(proposal.childRunDir); + const realBaseRepo = await realpath(resolvedBaseRepo); + const childRepoDir = join(childRunDir, 'repo'); + const childConfigDir = join(childRunDir, 'config'); + const childDiagRegistryDir = join(childRunDir, 'registry'); + const controllerRunRoot = join(childRunDir, 'controller'); + const runId = sanitizeRunId(proposal.individualId); + + await mkdir(childConfigDir, { recursive: true, mode: 0o700 }); + await mkdir(childDiagRegistryDir, { recursive: true, mode: 0o700 }); + await materializeGitCheckoutNoFollow(realBaseRepo, childRepoDir); + + const realTmpRoot = await realpath(tmpdir()); + const trustedTempDir = await mkdtemp(join(realTmpRoot, 'lw-evo-trusted-reg-')); + await chmod(trustedTempDir, 0o700); + + try { + const scopedTaskpack = buildStageScopedTaskpack({ + taskpack: proposal.taskpack, + heldOutWorkloadId: proposal.heldOutWorkloadId, + targetCellId: proposal.manifest.spec.targetCellId, + ...(proposal.teamPatch !== undefined ? { teamPatch: proposal.teamPatch } : {}), + }); + + const normalizedGateEndpoints = options.gateEndpoints?.map(ep => ({ + ...ep, + url: new URL(ep.url).href, + })); + + const compiled = await compileDeclarativeTaskpack(scopedTaskpack, { + mode: 'candidate', + executionMode: 'delegated', + repository: 'local/evolution', + hostPolicy: { + policyProfile: options.policyProfile ?? 'local', + allowWorkflowWrites: false, + }, + repositoryRoot: childRepoDir, + baseRevision: proposal.baseRevision, + sourceRevision: proposal.baseRevision, + taskpackPath: proposal.manifest.spec.taskpack, + ...(normalizedGateEndpoints !== undefined ? { gateEndpoints: normalizedGateEndpoints } : {}), + ...(options.credentialEnvMap !== undefined ? { credentialEnvMap: options.credentialEnvMap } : {}), + budgets: DEFAULT_CHILD_TASK_BUDGETS, + scrubber, + }); + + await stageCompiledInstructionResources(trustedTempDir, compiled.instructionResources); + + const extraRegistryResources: Array<{ + readonly id: string; + readonly kind: 'document'; + readonly path: string; + readonly digest: Digest; + }> = []; + + if (proposal.stagedParentFiles.length > 0) { + const parentResDir = join(trustedTempDir, '.loopwright-evo', 'parents'); + await mkdir(parentResDir, { recursive: true, mode: 0o700 }); + for (let i = 0; i < proposal.stagedParentFiles.length; i += 1) { + const pf = proposal.stagedParentFiles[i]!; + const relPath = `.loopwright-evo/parents/parent-${i}.json`; + const dstPath = join(trustedTempDir, relPath); + const bytes = await readFile(pf.filePath); + await writeFile(dstPath, bytes, { mode: 0o400 }); + await chmod(dstPath, 0o400); + extraRegistryResources.push({ + id: `evo-parent-${i}`, + kind: 'document', + path: relPath, + digest: pf.digest, + }); + } + } + + if (proposal.stagedScratchpadPath !== undefined) { + const scDir = join(trustedTempDir, '.loopwright-evo', 'scratchpad'); + await mkdir(scDir, { recursive: true, mode: 0o700 }); + const scBytes = await readFile(proposal.stagedScratchpadPath); + const relPath = '.loopwright-evo/scratchpad/latest.md'; + const dstPath = join(trustedTempDir, relPath); + await writeFile(dstPath, scBytes, { mode: 0o400 }); + await chmod(dstPath, 0o400); + extraRegistryResources.push({ + id: 'evo-scratchpad', + kind: 'document', + path: relPath, + digest: sha256Digest(scBytes), + }); + } + + const patchRoleById = new Map( + (proposal.teamPatch?.roles ?? []).map(r => [r.id, r] as const), + ); + const updatedRoleProfiles = compiled.registry.spec.roleProfiles.map(prof => { + for (const [rId, pr] of patchRoleById.entries()) { + if ((prof.id === rId || prof.id === `taskpack.profile.${rId}`) && pr.timeoutSeconds !== undefined) { + const requestedWallMs = pr.timeoutSeconds * 1000; + const currentWallMs = prof.limits?.toolWallMs; + const narrowedWallMs = currentWallMs !== undefined ? Math.min(currentWallMs, requestedWallMs) : requestedWallMs; + return { + ...prof, + limits: { + ...prof.limits, + toolWallMs: narrowedWallMs, + }, + }; + } + } + return prof; + }); + + const finalRegistryObj = { + ...compiled.registry, + spec: { + ...compiled.registry.spec, + resources: extraRegistryResources.length > 0 + ? [...compiled.registry.spec.resources, ...extraRegistryResources] + : compiled.registry.spec.resources, + roleProfiles: updatedRoleProfiles, + }, + }; + + const registryBytes = Buffer.from(`${JSON.stringify(finalRegistryObj, null, 2)}\n`, 'utf8'); + const registrySha256 = createHash('sha256').update(registryBytes).digest('hex'); + const registryPath = join(trustedTempDir, 'registry.json'); + await writeFile(registryPath, registryBytes, { mode: 0o600 }); + await chmod(registryPath, 0o600); + + const extraResourceIds = extraRegistryResources.map(r => r.id); + const updatedTaskRoles = compiled.config.spec.task.spec.roles.map(role => { + const pr = patchRoleById.get(role.id); + const baseResIds = pr?.resourceIds !== undefined ? [...pr.resourceIds] : role.resourceIds; + if (baseResIds === undefined) { + return role; + } + const mergedResIds = extraResourceIds.length > 0 + ? Array.from(new Set([...baseResIds, ...extraResourceIds])) + : Array.from(new Set(baseResIds)); + return { + ...role, + resourceIds: mergedResIds, + }; + }); + + const finalTaskObj = { + ...compiled.config.spec.task, + spec: { + ...compiled.config.spec.task.spec, + roles: updatedTaskRoles, + trustedContext: extraRegistryResources.length > 0 + ? { + ...compiled.config.spec.task.spec.trustedContext, + resources: [...compiled.config.spec.task.spec.trustedContext.resources, ...extraRegistryResources], + } + : compiled.config.spec.task.spec.trustedContext, + }, + }; + + const finalConfigObj = { + ...compiled.config, + spec: { + ...compiled.config.spec, + registry: { + name: finalRegistryObj.metadata.name, + digest: { algorithm: 'sha256' as const, hex: registrySha256 }, + }, + task: finalTaskObj, + }, + }; + + const configBytes = Buffer.from(`${JSON.stringify(finalConfigObj, null, 2)}\n`, 'utf8'); + const configPath = join(childConfigDir, 'config.json'); + await writeFile(configPath, configBytes, { mode: 0o600 }); + await chmod(configPath, 0o600); + + await writeFile(join(childDiagRegistryDir, 'registry.json'), registryBytes, { mode: 0o600 }); + await writeFile(join(childDiagRegistryDir, 'config.json'), configBytes, { mode: 0o600 }); + + const loadedRes = await loadTrustedConfiguration({ + configPath, + registryPath, + registrySha256, + untrustedRoots: [childRepoDir], + environment: envLookup, + }); + if (!loadedRes.ok) { + throw new EvolutionError( + 'EVOLUTION_STORE_ERROR', + `child run loadTrustedConfiguration failed: ${loadedRes.error.code} (${loadedRes.error.path})`, + ); + } + + const evolveGuardDecl = scopedTaskpack.spec.verification.localChecks.find( + c => c.implementation === 'evolve-block-guard.v1', + ); + const guardedFiles = Array.isArray(evolveGuardDecl?.parameters?.['files']) + ? (evolveGuardDecl.parameters['files'] as readonly string[]) + : []; + const extractWorkspaceSlice = async (workspaceDir: string): Promise => { + let slice = proposal.proposedCodeSlice ?? ''; + if (guardedFiles.length > 0) { + const slices: string[] = []; + for (const rel of guardedFiles) { + const candidatePath = join(workspaceDir, rel); + const fallbackPath = join(childRepoDir, rel); + const content = await readFile(candidatePath, 'utf8').catch(() => readFile(fallbackPath, 'utf8').catch(() => '')); + if (content.length > 0) { + slices.push(extractEvolveBlocksFromSource(content)); + } + } + if (slices.length > 0) { + slice = slices.join('\n'); + } + } + if (slice.length === 0) { + slice = `// individual:${proposal.individualId}\n`; + } + return slice; + }; + + const allAgentStepIds = finalTaskObj.spec.steps + .filter(s => s.kind === 'agent') + .map(s => s.id); + const stepById = new Map(finalTaskObj.spec.steps.map(s => [s.id, s] as const)); + const completedAgentStepIds = new Set(); + const childRunRelPath = `runs/${proposal.individualId}/controller/${runId}`; + let noveltyDecisionOut: DecisionMutationNoveltyResult | undefined; + let latestExtractedSlice: string | undefined; + + let latestWorkspacePath = childRepoDir; + const tickRes = await stepNext({ + configuration: loadedRes.value, + repository: childRepoDir, + runRoot: controllerRunRoot, + runId, + mode: 'candidate', + policyProfile: options.policyProfile ?? 'local', + allowWorkflowWrites: false, + environment: envLookup, + ...(proposal.signal !== undefined ? { signal: proposal.signal } : {}), + }); + if (!tickRes.ok) { + throw new EvolutionError('EVOLUTION_STORE_ERROR', `child stepNext failed: ${tickRes.error.code}`); + } + + let tick = tickRes.value; + while (tick.kind === 'step') { + latestWorkspacePath = tick.candidateDir; + const stepOut = await options.agentDriver({ + campaignId: proposal.campaignId, + individualId: proposal.individualId, + islandId: proposal.islandId, + generation: proposal.generation, + stagePhase: proposal.stagePhase, + bucketId: proposal.bucketId, + roleId: tick.roleId, + stepId: tick.stepId, + workspacePath: tick.candidateDir, + childRunDir, + prompt: tick.prompt, + contextFiles: tick.contextFiles, + modelId: proposal.modelId, + trackId: proposal.trackId, + mutationKind: proposal.mutationKind, + parents: proposal.parents, + ...(proposal.signal !== undefined ? { signal: proposal.signal } : {}), + }); + + const effectiveStepStatus = stepOut?.status ?? 'completed'; + const stepDecl = stepById.get(tick.stepId); + if (stepOut?.verdict?.verdict === 'rework' && stepDecl?.onRework !== undefined) { + const resetQueue = [stepDecl.onRework.rejectTo]; + const visited = new Set(); + while (resetQueue.length > 0) { + const cur = resetQueue.shift()!; + if (visited.has(cur)) continue; + visited.add(cur); + completedAgentStepIds.delete(cur); + for (const s of finalTaskObj.spec.steps) { + if (s.dependsOn.includes(cur)) { + resetQueue.push(s.id); + } + } + } + } else if (effectiveStepStatus === 'completed') { + completedAgentStepIds.add(tick.stepId); + } + + const allAgentsFinished = allAgentStepIds.length > 0 + && allAgentStepIds.every(id => completedAgentStepIds.has(id)) + && effectiveStepStatus === 'completed' + && stepOut?.verdict?.verdict !== 'rework'; + + // Capture candidate EVOLVE-BLOCK slice BEFORE stepSubmit cleans up tick.candidateDir! + latestExtractedSlice = await extractWorkspaceSlice(tick.candidateDir); + + if ( + allAgentsFinished + && proposal.stagePhase !== 'portfolio' + && proposal.proposedCodeSlice === undefined + && ( + proposal.noveltyGate !== undefined + || (proposal.islandHistorySlices !== undefined && proposal.islandHistorySlices.length > 0) + || options.decisionPolicy !== undefined + || options.decisionTransport !== undefined + ) + ) { + const preGateSlice = latestExtractedSlice; + const noveltyOutcome = proposal.noveltyGate !== undefined + ? await proposal.noveltyGate(preGateSlice) + : await screenCandidateNoveltyBeforeDispatch({ + candidateId: proposal.individualId, + candidateSlice: preGateSlice, + historySlices: proposal.islandHistorySlices ?? [], + ...(options.decisionPolicy !== undefined ? { policy: options.decisionPolicy } : {}), + ...(options.decisionBudget !== undefined ? { budget: options.decisionBudget } : {}), + ...(options.decisionTransport !== undefined + ? { transport: options.decisionTransport } + : (options.decisionPolicy?.enabled === true ? { transport: new HttpDecisionTransport() } : {})), + ...(options.decisionApiKey !== undefined ? { apiKey: options.decisionApiKey } : {}), + scrubber, + }); + noveltyDecisionOut = noveltyOutcome.decision; + if (noveltyOutcome.rejected) { + await stepCancel({ runRoot: controllerRunRoot, runId, environment: envLookup }).catch(() => undefined); + const rejectedResult: CandidateEvaluationResult = Object.freeze({ + status: 'failed', + failureReason: 'NOVELTY_CLONE_REJECTED', + codeSlice: preGateSlice, + metrics: Object.freeze({}), + outputArtifacts: Object.freeze([]), + evidenceDigest: null, + childRunRelPath, + noveltyDecision: noveltyOutcome.decision, + }); + if (options.onAfterChildEvaluation !== undefined) { + await options.onAfterChildEvaluation(proposal, rejectedResult); + } + return rejectedResult; + } + } + + const submitRes = await stepSubmit({ + runRoot: controllerRunRoot, + runId, + leaseToken: tick.leaseToken, + ...(stepOut?.submissionFile !== undefined ? { submissionFile: stepOut.submissionFile } : {}), + ...(stepOut?.verdict !== undefined ? { verdict: stepOut.verdict } : {}), + status: effectiveStepStatus, + ...(stepOut?.reason !== undefined ? { reason: stepOut.reason } : {}), + environment: envLookup, + ...(proposal.signal !== undefined ? { signal: proposal.signal } : {}), + }); + if (!submitRes.ok) { + await stepCancel({ runRoot: controllerRunRoot, runId, environment: envLookup }).catch(() => undefined); + throw new EvolutionError('EVOLUTION_STORE_ERROR', `child stepSubmit failed: ${submitRes.error.code}`); + } + tick = submitRes.value; + } + + const extractedCodeSlice = latestExtractedSlice ?? await extractWorkspaceSlice(latestWorkspacePath); + + let runEvalReport: RunEvalReport | undefined; + const inspectedRes = await inspectRun({ + runRoot: controllerRunRoot, + runId, + }).catch(() => null); + if (inspectedRes !== null && inspectedRes.ok && inspectedRes.value.runEval !== null) { + runEvalReport = inspectedRes.value.runEval; + } + + const runSucceeded = tick.kind === 'result' && tick.result.spec.status === 'completed'; + const terminalStatusLabel = tick.kind === 'result' ? tick.result.spec.status : 'incident'; + + const artifactsDir = join(controllerRunRoot, runId, 'artifacts'); + const collected = await collectChildBenchmarkArtifacts(artifactsDir, runSucceeded, scrubber); + + let finalStatus: IndividualStatus; + let failureReason: string | null = null; + + if (collected.retryablePreemption) { + finalStatus = 'preempted'; + failureReason = 'BENCHMARK_PREEMPTED'; + } else if (runSucceeded) { + finalStatus = 'passed'; + failureReason = null; + } else { + finalStatus = 'failed'; + failureReason = collected.dispositionReason + ?? (!collected.hasBenchmarkProof ? 'LOCAL_VERIFICATION_FAILED' : `RUN_${terminalStatusLabel.toUpperCase()}`); + } + + const evidenceDigest = collected.rawVerdictReceiptBytes !== undefined + ? sha256Digest(collected.rawVerdictReceiptBytes) + : ( + runSucceeded + ? sha256Digest( + JSON.stringify({ + metrics: collected.metrics, + bucketMetrics: collected.bucketMetrics ?? null, + outputArtifacts: collected.outputArtifacts, + codeSlice: extractedCodeSlice, + }), + ) + : null + ); + + const evalResult: CandidateEvaluationResult = Object.freeze({ + status: finalStatus, + failureReason, + codeSlice: extractedCodeSlice, + metrics: collected.metrics, + ...(collected.bucketMetrics !== undefined ? { bucketMetrics: collected.bucketMetrics } : {}), + ...(collected.hardwareDiagnostics !== undefined ? { hardwareDiagnostics: collected.hardwareDiagnostics } : {}), + ...(collected.hardwareProvenance !== undefined ? { hardwareProvenance: collected.hardwareProvenance } : {}), + ...(collected.findings !== undefined ? { findings: collected.findings } : {}), + outputArtifacts: collected.outputArtifacts, + ...(collected.stageABlobs.length > 0 ? { stageABlobs: collected.stageABlobs } : {}), + ...(collected.rawVerdictReceiptBytes !== undefined ? { rawVerdictReceiptBytes: collected.rawVerdictReceiptBytes } : {}), + evidenceDigest, + childRunRelPath, + ...(runEvalReport !== undefined ? { runEvalReport } : {}), + ...(noveltyDecisionOut !== undefined ? { noveltyDecision: noveltyDecisionOut } : {}), + }); + + if (options.onAfterChildEvaluation !== undefined) { + await options.onAfterChildEvaluation(proposal, evalResult); + } + + return evalResult; + } finally { + await rm(trustedTempDir, { recursive: true, force: true }).catch(() => undefined); + } + }; +} + +function selectMutationKindDeterministically( + rng: () => number, + weights: EvolutionCampaignManifest['spec']['sampling']['mutationWeights'], + availableParentsCount: number, +): IndividualMutationKind { + const total = weights.diff_tune + weights.full_rewrite + weights.crossover; + if (total <= 0) { + return availableParentsCount >= 2 ? 'crossover' : 'diff_tune'; + } + const draw = rng() * total; + let kind: IndividualMutationKind; + if (draw < weights.diff_tune) { + kind = 'diff_tune'; + } else if (draw < weights.diff_tune + weights.full_rewrite) { + kind = 'full_rewrite'; + } else { + kind = 'crossover'; + } + if (kind === 'crossover' && availableParentsCount < 2) { + return availableParentsCount === 1 ? 'diff_tune' : 'full_rewrite'; + } + return kind; +} + +function deriveHypervolumeReferencePoint( + points: readonly Readonly>[], + objectives: readonly ObjectiveDirectionSpec[], +): Readonly> { + const ref: Record = Object.create(null) as Record; + for (const obj of objectives) { + const vals = points + .map(p => p[obj.metric]) + .filter((v): v is number => typeof v === 'number' && Number.isFinite(v)); + if (vals.length === 0) { + ref[obj.metric] = obj.direction === 'minimize' ? 1_000_000 : -1_000_000; + continue; + } + if (obj.direction === 'minimize') { + const worst = Math.max(...vals); + ref[obj.metric] = worst + Math.max(1, Math.abs(worst) * 0.5); + } else { + const worst = Math.min(...vals); + ref[obj.metric] = Math.min(0, worst - Math.max(1, Math.abs(worst) * 0.5)); + } + } + return ref; +} + +async function computeBaselineCampaignLockHash( + taskpack: TaskpackManifest, + campaignId: string, + baseRevision: string, + repositoryRoot: string | undefined, +): Promise<{ readonly lockHash: Digest; readonly baseTaskContract: TaskContract }> { + const compiled = await compileDeclarativeTaskpack(taskpack, { + mode: 'candidate', + executionMode: 'delegated', + repository: 'local/evolution', + hostPolicy: { policyProfile: 'local', allowWorkflowWrites: false }, + ...(repositoryRoot !== undefined ? { repositoryRoot } : {}), + baseRevision, + sourceRevision: baseRevision, + gateEndpoints: taskpack.spec.verification.externalGates.map(g => ({ + id: g.endpointId, + url: g.url ?? 'http://127.0.0.1:9/unused', + signingCredentialRef: g.signingCredentialRef ?? 'bench-sign', + ...(g.implementation === 'benchmark-gate.v1' ? { implementation: 'benchmark-gate.v1' as const } : {}), + })), + credentialEnvMap: { + gate: 'LOOPWRIGHT_GATE_SIGNING_SECRET', + byCredentialRef: { 'bench-sign': 'LOOPWRIGHT_GATE_SIGNING_SECRET' }, + }, + budgets: DEFAULT_CHILD_TASK_BUDGETS, + }); + const admitted = admitTask(compiled.config.spec.task, { + admissionId: `admission.${sanitizeRunId(campaignId)}`.slice(0, LIMITS.identifier), + runId: sanitizeRunId(campaignId), + }); + if (!admitted.ok) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'unable to derive baseline TaskLock for campaign'); + } + return { + lockHash: admitted.value.spec.lockHash, + baseTaskContract: compiled.config.spec.task, + }; +} + +async function runWithConcurrencyLimit( + tasks: readonly (() => Promise)[], + concurrency: number, +): Promise { + const results = new Array(tasks.length); + let nextIdx = 0; + let hasError = false; + let firstError: unknown; + const workerCount = Math.max(1, Math.min(concurrency, tasks.length)); + const workers = Array.from({ length: workerCount }, async () => { + for (;;) { + if (hasError) return; + const idx = nextIdx; + nextIdx += 1; + if (idx >= tasks.length) return; + try { + results[idx] = await tasks[idx]!(); + } catch (err: unknown) { + if (!hasError) { + hasError = true; + firstError = err; + } + return; + } + } + }); + await Promise.all(workers); + if (hasError) { + throw firstError; + } + return results; +} + +function resolveEffectiveDecisionPolicy( + explicitPolicy: DecisionPolicyConfig | undefined, + taskpack: TaskpackManifest, +): DecisionPolicyConfig { + if (explicitPolicy !== undefined) { + return explicitPolicy; + } + const tpDec = taskpack.spec.decisions; + if (tpDec === undefined) { + return DEFAULT_DECISION_POLICY; + } + const provider = tpDec.provider ?? DEFAULT_DECISION_POLICY.provider; + const provDefaults = DECISION_PROVIDER_DEFAULTS[provider]; + return Object.freeze({ + enabled: tpDec.enabled, + disclosurePolicy: tpDec.disclosurePolicy ?? (tpDec.enabled ? 'repo-approved-redacted-evidence' : 'disabled'), + minConfidence: tpDec.minConfidence ?? DEFAULT_DECISION_POLICY.minConfidence, + confirmThreshold: tpDec.confirmThreshold ?? DEFAULT_DECISION_POLICY.confirmThreshold, + hardDeadlineMs: tpDec.hardDeadlineMs ?? DEFAULT_DECISION_POLICY.hardDeadlineMs, + maxAttempts: tpDec.maxAttempts ?? DEFAULT_DECISION_POLICY.maxAttempts, + fallbackRole: 'deterministic', + onFallbackUnavailable: 'deterministic_default', + provider, + endpoint: provDefaults.endpoint, + model: provDefaults.model, + startluxOptions: null, + allowImages: tpDec.allowImages ?? false, + }); +} + +function resolveDecisionApiKey( + explicitApiKey: string | undefined, + policy: DecisionPolicyConfig, + envLookup: ((name: string) => string | undefined) | undefined, + scrubber: SecretScrubber, +): string | undefined { + let key = explicitApiKey; + if (key === undefined && envLookup !== undefined) { + for (const envName of DECISION_PROVIDER_API_KEY_ENV[policy.provider] ?? []) { + const val = envLookup(envName); + if (val !== undefined && val.length > 0) { + key = val; + break; + } + } + } + if (key !== undefined && key.length > 0) { + scrubber.register(key); + } + return key; +} + +function resolveTargetDriverConstraint( + taskpack: TaskpackManifest, + targetCellId: string, +): string | null { + const cell = taskpack.spec.target?.matrix?.find(item => item.id === targetCellId); + return cell?.hardware?.driverConstraint ?? null; +} + +interface InternalDriverOptions { + readonly store: EvolutionCampaignStore; + readonly lease: CampaignLease; + readonly campaignId: string; + readonly manifest: EvolutionCampaignManifest; + readonly taskpack: TaskpackManifest; + readonly baseTaskContract: TaskContract; + readonly modelIds: readonly string[]; + readonly driverConstraint: string | null; + readonly repositoryRoot?: string | undefined; + readonly evaluator: CandidateEvaluator; + readonly proposeCandidateSlice?: ((context: CandidateProposalContext) => Promise) | undefined; + readonly supervisorRunner?: SupervisorRunnerPort | undefined; + readonly decisionPolicy?: DecisionPolicyConfig | undefined; + readonly decisionTransport?: DecisionTransport | undefined; + readonly decisionApiKey?: string | undefined; + readonly environment?: ((name: string) => string | undefined) | undefined; + readonly signal?: AbortSignal | undefined; + readonly autoExport: boolean; + readonly exportFormat?: 'dir' | 'oci-layout' | undefined; + readonly allowSyntheticProbe: boolean; + readonly receiptSigningSecret?: string | undefined; + readonly verifyReceiptSignature?: ReceiptSignatureVerifier | undefined; + readonly dispatchManifest?: DispatchManifestV1 | undefined; + readonly scrubber: SecretScrubber; +} + +async function refreshStageParetoArchive( + store: EvolutionCampaignStore, + lease: CampaignLease, + campaignId: string, + bucketId: string | null, + objectives: readonly ObjectiveDirectionSpec[], +): Promise { + const allStageEligible = ( + await store.listIndividuals(campaignId, { status: ['passed', 'soft_passed'], bucketId }) + ).filter(ind => + objectives.every(obj => typeof ind.metrics[obj.metric] === 'number' && Number.isFinite(ind.metrics[obj.metric])), + ); + if (allStageEligible.length === 0) return []; + + const stats = computeObjectiveReferenceStats( + allStageEligible.map(ind => ind.metrics), + objectives, + ); + const passedInds = allStageEligible.filter(ind => ind.status === 'passed'); + const softPassedInds = allStageEligible.filter(ind => ind.status === 'soft_passed'); + + const rankedPassed = passedInds.length > 0 + ? computeNsga2Ranking( + passedInds.map(ind => ({ individualId: ind.individualId, metrics: ind.metrics })), + objectives, + ) + : []; + const maxPassedRank = rankedPassed.reduce((acc, r) => Math.max(acc, r.paretoRank), 1); + + const rankedSoft = softPassedInds.length > 0 + ? computeNsga2Ranking( + softPassedInds.map(ind => ({ individualId: ind.individualId, metrics: ind.metrics })), + objectives, + ) + : []; + + const rankMap = new Map(); + for (const r of rankedPassed) { + rankMap.set(r.individualId, r); + } + for (const r of rankedSoft) { + rankMap.set(r.individualId, { + paretoRank: maxPassedRank + r.paretoRank, + crowdingDistance: r.crowdingDistance, + }); + } + + await store.updateParetoRanks( + lease, + campaignId, + allStageEligible.map(ind => { + const r = rankMap.get(ind.individualId)!; + const sf = scalarizeFitness(ind.metrics, objectives, stats); + return { + individualId: ind.individualId, + paretoRank: r.paretoRank, + crowdingDistance: r.crowdingDistance, + scalarFitness: sf, + }; + }), + ); + + return store.listIndividuals(campaignId, { status: ['passed', 'soft_passed'], bucketId }); +} + +async function driveCampaignExecution(opts: InternalDriverOptions): Promise { + const { store, lease, campaignId, manifest, taskpack, baseTaskContract, modelIds, evaluator, scrubber } = opts; + const budgets = manifest.spec.budgets; + const population = manifest.spec.population; + const sampling = manifest.spec.sampling; + const objectives = manifest.spec.objectives; + const declaredTracks = manifest.spec.tracks ?? AVAILABLE_EVOLUTION_TRACKS; + const effectiveDecisionPolicy = resolveEffectiveDecisionPolicy(opts.decisionPolicy, taskpack); + const effectiveDecisionTransport: DecisionTransport | undefined = opts.decisionTransport + ?? (effectiveDecisionPolicy.enabled ? new HttpDecisionTransport() : undefined); + const resolvedDecisionApiKey = resolveDecisionApiKey( + opts.decisionApiKey, + effectiveDecisionPolicy, + opts.environment ?? ((name: string) => process.env[name]), + scrubber, + ); + + let noveltyRejectionsCount = 0; + let cascadeSoftStopsCount = 0; + const advisoryDecisions: EvolutionaryAdvisoryDecision[] = []; + const decisionBudget = new DecisionBudgetTracker(); + let earlyStoppedByRoofline = false; + let sequenceCounter = (await store.listIndividuals(campaignId)).length; + + const islandRunEvals = new Map(); + const islandTrajectories = new Map(); + + const defaultBenchGate = taskpack.spec.verification.externalGates.find( + g => g.implementation === 'benchmark-gate.v1' && g.targetCellId === manifest.spec.targetCellId, + )!; + const defaultHeldOutWorkloadId = defaultBenchGate.heldOutWorkloadId!; + + const loadValidatedActiveTeamPatch = async (teamConfigId: string): Promise => { + const activeTeamRec = await store.getTeamConfig(teamConfigId); + if (activeTeamRec?.patchCasDigest === null || activeTeamRec?.patchCasDigest === undefined) { + return undefined; + } + if (manifest.spec.teamEvolution?.enabled !== true) { + throw new EvolutionError( + 'TEAM_ENVELOPE_VIOLATION', + `team patch "${teamConfigId}" cannot execute when manifest.spec.teamEvolution.enabled is not true`, + '/spec/teamEvolution/enabled', + ); + } + const rawPatchBytes = await store.readCasBlob(activeTeamRec.patchCasDigest.hex); + const compiledPatch = validateAndCompileTeamPatch({ + rawPatch: rawPatchBytes, + teamEvolution: manifest.spec.teamEvolution, + baseTaskContract, + taskpack, + scrubber, + }); + return compiledPatch.patch; + }; + + const runStageGenerations = async (params: { + readonly stagePhase: CampaignStagePhase; + readonly bucketId: string | null; + readonly heldOutWorkloadId: string; + readonly startGen: number; + readonly maxGenInclusive: number; + readonly maxEvalsCeiling: number; + }): Promise<'completed_stage' | 'paused' | 'budget_reached'> => { + for (let gen = params.startGen; gen <= params.maxGenInclusive; gen += 1) { + if (opts.signal?.aborted) { + await store.updateCampaignProgress(lease, { campaignId, status: 'paused' }); + return 'paused'; + } + + const currentCamp = (await store.getCampaign(campaignId))!; + if (currentCamp.evaluationsUsed >= params.maxEvalsCeiling || currentCamp.evaluationsUsed >= budgets.maxEvaluations) { + return 'budget_reached'; + } + + if (budgets.targetRooflineHeadroom !== undefined) { + const stagePassed = await store.listIndividuals(campaignId, { status: ['passed'], bucketId: params.bucketId }); + if ( + stagePassed.some( + ind => + ind.hardwareDiagnostics?.rooflineHeadroom !== undefined + && ind.hardwareDiagnostics.rooflineHeadroom <= budgets.targetRooflineHeadroom!, + ) + ) { + earlyStoppedByRoofline = true; + return 'completed_stage'; + } + } + + await store.updateCampaignProgress(lease, { + campaignId, + status: 'active', + stagePhase: params.stagePhase, + activeBucketId: params.bucketId, + }); + + const stagePassingBefore = await store.listIndividuals(campaignId, { + status: ['passed', 'soft_passed'], + bucketId: params.bucketId, + }); + + const migrations = selectRingMigrationElites({ + generation: gen, + islands: population.islands, + migrationIntervalGenerations: population.migrationIntervalGenerations, + maxMigrationElites: population.maxMigrationElites, + individuals: stagePassingBefore, + }); + const inspirationByIsland = new Map(); + for (const mig of migrations) { + const arr = inspirationByIsland.get(mig.targetIslandId) ?? []; + arr.push(mig.individual); + inspirationByIsland.set(mig.targetIslandId, arr); + } + + const allPriorStageInds = await store.listIndividuals(campaignId, { bucketId: params.bucketId }); + const completedIslandsInGen = new Set( + allPriorStageInds + .filter(prior => prior.generation === gen && prior.status !== 'preempted') + .map(prior => prior.islandId), + ); + + const historySlicesByIsland = new Map(); + for (let isl = 0; isl < population.islands; isl += 1) { + const candidates = allPriorStageInds + .filter( + prior => + prior.islandId === isl + && (prior.status === 'passed' || prior.status === 'soft_passed') + && prior.codeSliceCasDigest !== null, + ) + .slice(-DECISION_NOVELTY_MAX_HISTORY_SLICES); + const slices: DecisionMutationNoveltyHistoryEntry[] = []; + for (const prior of candidates) { + const rawSlice = await store.readCasBlob(prior.codeSliceCasDigest!.hex).catch(() => null); + if (rawSlice !== null) { + slices.push({ + id: prior.individualId.slice(0, 128), + sourceSlice: truncateUtf8ByBytes(rawSlice.toString('utf8'), DECISION_NOVELTY_MAX_SLICE_BYTES), + }); + } + } + historySlicesByIsland.set(isl, slices); + } + + const latestScratchpadRec = await store.getLatestScratchpadSnapshot(campaignId); + const latestScratchpadMd = latestScratchpadRec !== null + ? (await store.readCasBlob(latestScratchpadRec.casDigest.hex)).toString('utf8') + : undefined; + + const remainingEvals = Math.min( + budgets.maxEvaluations - currentCamp.evaluationsUsed, + params.maxEvalsCeiling - currentCamp.evaluationsUsed, + ); + const islandsList = await store.listIslands(campaignId); + + const preGenNichesByIsland = new Map>(); + for (let isl = 0; isl < population.islands; isl += 1) { + preGenNichesByIsland.set(isl, await store.getIslandNicheElites(campaignId, isl, params.bucketId)); + } + + interface IslandSlotOutcome { + readonly islandId: number; + readonly teamConfigId: string; + readonly individual: IndividualRecord; + readonly primaryParent: IndividualRecord | null; + readonly runEvalReport?: RunEvalReport | undefined; + } + + const slotTasks: Array<() => Promise> = []; + let scheduledSlotsInGen = 0; + + for (let isl = 0; isl < population.islands; isl += 1) { + if (completedIslandsInGen.has(isl)) continue; + if (scheduledSlotsInGen >= remainingEvals) break; + scheduledSlotsInGen += 1; + + const islandRec = islandsList.find(item => item.islandId === isl)!; + const seqIdx = sequenceCounter; + sequenceCounter += 1; + + slotTasks.push(async (): Promise => { + if (opts.signal?.aborted) return null; + + const nonce = randomBytes(3).toString('hex'); + const individualId = sanitizeRunId( + `ind-g${gen}-i${isl}-${params.bucketId ?? 'main'}-${nonce}`, + ); + const childRunDir = join(store.campaignRoot, 'runs', individualId); + await mkdir(childRunDir, { recursive: true, mode: 0o700 }); + + const localNicheMap = preGenNichesByIsland.get(isl) ?? new Map(); + const localElites = [...localNicheMap.values()]; + const migratedInspirations = inspirationByIsland.get(isl) ?? []; + const totalParentPool = localElites.length + migratedInspirations.length; + const crossoverFeasible = totalParentPool >= 2 && sampling.maxCrossoversPerPrompt > 0; + + const rng = createSeededPrng(`${campaignId}:gen-${gen}:isl-${isl}:seq-${seqIdx}`); + const sampledMutationKind: DecisionEvolutionMutationKind = localElites.length === 0 + ? 'full_rewrite' + : (selectMutationKindDeterministically( + rng, + crossoverFeasible + ? sampling.mutationWeights + : { ...sampling.mutationWeights, crossover: 0 }, + totalParentPool, + ) as DecisionEvolutionMutationKind); + + let preliminarySelection: ReturnType | null = null; + if (localElites.length > 0) { + preliminarySelection = sampleParents({ + islandId: isl, + localCandidates: localElites, + inspirationCandidates: migratedInspirations, + maxCrossoversPerPrompt: sampling.maxCrossoversPerPrompt, + noveltyDecayLambda: sampling.noveltyDecayLambda, + seed: `${campaignId}:parents:g${gen}:i${isl}`, + }); + } + + const preliminaryPrimary = preliminarySelection?.primary.individual ?? null; + const parentDiag = preliminaryPrimary?.hardwareDiagnostics; + const decisionDiag: DecisionHardwareDiagnostics | undefined = parentDiag?.boundPipeline !== undefined + ? { + boundPipeline: parentDiag.boundPipeline as DecisionHardwareDiagnostics['boundPipeline'], + ...(parentDiag.rooflineHeadroom !== undefined ? { rooflineHeadroom: parentDiag.rooflineHeadroom } : {}), + ...(parentDiag.occupancyPct !== undefined ? { occupancyPct: parentDiag.occupancyPct } : {}), + ...(parentDiag.localSpillBytes !== undefined ? { localSpillBytes: parentDiag.localSpillBytes } : {}), + } + : undefined; + + const configuredAllowedKinds: DecisionEvolutionMutationKind[] = []; + if (localElites.length === 0) { + configuredAllowedKinds.push('full_rewrite'); + } else if (effectiveDecisionPolicy.enabled) { + if (sampling.mutationWeights.diff_tune > 0) configuredAllowedKinds.push('diff_tune'); + if (sampling.mutationWeights.full_rewrite > 0) configuredAllowedKinds.push('full_rewrite'); + if (sampling.mutationWeights.crossover > 0 && crossoverFeasible) configuredAllowedKinds.push('crossover'); + if (configuredAllowedKinds.length === 0) configuredAllowedKinds.push(sampledMutationKind); + } else { + configuredAllowedKinds.push(sampledMutationKind); + } + + const strategyDecision = await routeEvolutionStrategy({ + policy: effectiveDecisionPolicy, + state: {}, + budget: decisionBudget, + ...(effectiveDecisionTransport !== undefined ? { transport: effectiveDecisionTransport } : {}), + ...(resolvedDecisionApiKey !== undefined ? { apiKey: resolvedDecisionApiKey } : {}), + scrubber, + strategy: { + operatorKind: taskpack.metadata.name, + tensorRank: 4, + dtype: 'fp16', + declaredTracks, + allowedMutationKinds: configuredAllowedKinds, + stalledGenerations: islandRec.consecutiveNoGainGenerations, + ...(decisionDiag !== undefined ? { hardwareDiagnostics: decisionDiag } : {}), + }, + }); + advisoryDecisions.push(strategyDecision); + const trackId = strategyDecision.trackId; + const mutationKind: IndividualMutationKind = localElites.length === 0 + ? 'full_rewrite' + : (strategyDecision.mutationKind === 'crossover' && !crossoverFeasible + ? (totalParentPool === 1 ? 'diff_tune' : 'full_rewrite') + : strategyDecision.mutationKind); + + let sampledParents: readonly SampledParentEntry[] = []; + let primaryParent: IndividualRecord | null = null; + let stagedParentFiles: readonly StagedParentContextFile[] = []; + + if (preliminarySelection !== null) { + primaryParent = preliminarySelection.primary.individual; + sampledParents = mutationKind === 'crossover' + ? [preliminarySelection.primary, ...preliminarySelection.secondary] + : [preliminarySelection.primary]; + + const parentInputs: ParentContextInput[] = []; + for (const sp of sampledParents) { + const codeBytes = sp.individual.codeSliceCasDigest !== null + ? await store.readCasBlob(sp.individual.codeSliceCasDigest.hex) + : Buffer.from('// baseline\n', 'utf8'); + parentInputs.push({ + individual: sp.individual, + role: sp.role as ParentContextInput['role'], + codeSlice: codeBytes.toString('utf8'), + }); + await store.incrementOffspringCount(lease, sp.individual.individualId, 1); + } + + const staged = await stageMultiParentContextFiles({ + stagingDir: join(childRunDir, 'parent-context'), + parents: parentInputs, + maxCrossoversPerPrompt: mutationKind === 'crossover' ? sampling.maxCrossoversPerPrompt : 0, + scrubber, + }); + stagedParentFiles = staged.files; + } + + const arms = await store.listModelBanditArms(campaignId); + const modelPick = selectModelCandidate({ + strategy: sampling.modelBandit, + modelIds, + arms, + sequenceIndex: seqIdx, + }); + const modelId = modelPick.modelId; + + let stagedScratchpadPath: string | undefined; + if (latestScratchpadMd !== undefined) { + const stagedSc = await writeReadOnlyScratchpadFile( + join(childRunDir, 'scratchpad-context'), + latestScratchpadMd, + scrubber, + ); + stagedScratchpadPath = stagedSc.filePath; + } + + const activeTeamPatch = await loadValidatedActiveTeamPatch(islandRec.activeTeamConfigId); + const islandHistorySlices = historySlicesByIsland.get(isl) ?? []; + + const proposalCtx: CandidateProposalContext = { + campaignId, + individualId, + islandId: isl, + generation: gen, + stagePhase: params.stagePhase, + bucketId: params.bucketId, + heldOutWorkloadId: params.heldOutWorkloadId, + modelId, + trackId, + mutationKind, + teamConfigId: islandRec.activeTeamConfigId, + parents: sampledParents, + stagedParentFiles, + ...(stagedScratchpadPath !== undefined ? { stagedScratchpadPath } : {}), + }; + + let proposedCodeSlice: string | undefined; + if (opts.proposeCandidateSlice !== undefined) { + proposedCodeSlice = await opts.proposeCandidateSlice(proposalCtx); + const noveltyOutcome = await screenCandidateNoveltyBeforeDispatch({ + candidateId: individualId, + candidateSlice: proposedCodeSlice, + historySlices: islandHistorySlices, + policy: effectiveDecisionPolicy, + budget: decisionBudget, + ...(effectiveDecisionTransport !== undefined ? { transport: effectiveDecisionTransport } : {}), + ...(resolvedDecisionApiKey !== undefined ? { apiKey: resolvedDecisionApiKey } : {}), + scrubber, + }); + advisoryDecisions.push(noveltyOutcome.decision); + + if (noveltyOutcome.rejected) { + noveltyRejectionsCount += 1; + const sliceCas = await store.writeCasBlob(Buffer.from(proposedCodeSlice, 'utf8')); + const rejectedInd = await store.recordIndividual(lease, { + individualId, + campaignId, + islandId: isl, + generation: gen, + bucketId: params.bucketId, + teamConfigId: islandRec.activeTeamConfigId, + modelId, + trackId, + mutationKind, + status: 'failed', + failureReason: 'NOVELTY_CLONE_REJECTED', + nicheKey: null, + paretoRank: null, + crowdingDistance: null, + scalarFitness: null, + countEvaluation: false, + codeSliceCasDigest: sliceCas.digest, + evidenceDigest: null, + verdictReceiptCasDigest: null, + outputArtifacts: [], + metrics: {}, + }); + return { + islandId: isl, + teamConfigId: islandRec.activeTeamConfigId, + individual: rejectedInd, + primaryParent, + }; + } + } + + const currentCampaignRow = (await store.getCampaign(campaignId))!; + const evalOutcome = await evaluator({ + ...proposalCtx, + campaignRoot: store.campaignRoot, + childRunDir, + baseRevision: currentCampaignRow.baseRevision, + manifest, + taskpack, + ...(activeTeamPatch !== undefined ? { teamPatch: activeTeamPatch } : {}), + ...(proposedCodeSlice !== undefined ? { proposedCodeSlice } : {}), + islandHistorySlices, + ...(opts.proposeCandidateSlice === undefined && params.stagePhase !== 'portfolio' + ? { + noveltyGate: async (candidateSlice: string) => screenCandidateNoveltyBeforeDispatch({ + candidateId: individualId, + candidateSlice, + historySlices: islandHistorySlices, + policy: effectiveDecisionPolicy, + budget: decisionBudget, + ...(effectiveDecisionTransport !== undefined ? { transport: effectiveDecisionTransport } : {}), + ...(resolvedDecisionApiKey !== undefined ? { apiKey: resolvedDecisionApiKey } : {}), + scrubber, + }), + } + : {}), + ...(opts.signal !== undefined ? { signal: opts.signal } : {}), + }); + + if (evalOutcome.noveltyDecision !== undefined) { + advisoryDecisions.push(evalOutcome.noveltyDecision); + } + + let finalStatus = evalOutcome.status; + let finalFailureReason = evalOutcome.failureReason ?? null; + const isNoveltyRejected = finalFailureReason === 'NOVELTY_CLONE_REJECTED'; + if (isNoveltyRejected) { + noveltyRejectionsCount += 1; + } + + if (finalStatus === 'passed' && evalOutcome.smokeMetrics !== undefined) { + const primaryMetric = objectives[0]?.metric ?? 'latency_us_p50'; + if (Object.hasOwn(evalOutcome.smokeMetrics, primaryMetric)) { + const remainingRatio = Math.max( + 0, + Math.min(1, (budgets.maxEvaluations - currentCampaignRow.evaluationsUsed) / budgets.maxEvaluations), + ); + const cascadeDecision = await evaluateCascadeEscalation({ + policy: effectiveDecisionPolicy, + state: {}, + budget: decisionBudget, + ...(effectiveDecisionTransport !== undefined ? { transport: effectiveDecisionTransport } : {}), + ...(resolvedDecisionApiKey !== undefined ? { apiKey: resolvedDecisionApiKey } : {}), + scrubber, + cascade: { + candidateId: individualId, + smokeCorrectnessPassed: true, + smokeMetrics: evalOutcome.smokeMetrics, + referenceMetrics: primaryParent?.metrics ?? {}, + primaryMetric, + direction: objectives[0]?.direction ?? 'minimize', + remainingBudgetRatio: remainingRatio, + }, + }); + advisoryDecisions.push(cascadeDecision); + if (cascadeDecision.action === 'prune') { + finalStatus = 'soft_passed'; + finalFailureReason = 'CASCADE_NOT_ESCALATED'; + cascadeSoftStopsCount += 1; + } + } + } + + const codeCas = await store.writeCasBlob( + Buffer.from(evalOutcome.codeSlice.length > 0 ? evalOutcome.codeSlice : '// empty\n', 'utf8'), + ); + + let verdictReceiptCasDigest: Digest | null = null; + if (evalOutcome.rawVerdictReceiptBytes !== undefined) { + const vrCas = await store.writeCasBlob(evalOutcome.rawVerdictReceiptBytes); + verdictReceiptCasDigest = vrCas.digest; + } + + const storedArtifacts: ArtifactRef[] = []; + if (evalOutcome.stageABlobs !== undefined && evalOutcome.stageABlobs.length > 0) { + for (const blob of evalOutcome.stageABlobs) { + const writtenBlob = await store.writeCasBlob(blob.bytes); + storedArtifacts.push({ + name: blob.name, + digest: writtenBlob.digest, + byteLength: writtenBlob.byteLength, + ...(blob.mediaType !== undefined && blob.mediaType !== null ? { mediaType: blob.mediaType } : {}), + }); + } + } else if (evalOutcome.outputArtifacts !== undefined) { + storedArtifacts.push(...evalOutcome.outputArtifacts); + } + + const retainsInArchive = finalStatus === 'passed' || finalStatus === 'soft_passed'; + const nicheKey = retainsInArchive + ? computeNicheKey(population.nicheAxes, evalOutcome.metrics, evalOutcome.hardwareDiagnostics) + : null; + + const lineageEdges = sampledParents.map(sp => ({ + campaignId, + childIndividualId: individualId, + parentIndividualId: sp.individual.individualId, + role: sp.role, + sourceIslandId: sp.sourceIslandId, + createdGeneration: gen, + })); + + const recorded = await store.recordIndividual(lease, { + individualId, + campaignId, + islandId: isl, + generation: gen, + bucketId: params.bucketId, + teamConfigId: islandRec.activeTeamConfigId, + modelId, + trackId, + mutationKind, + status: finalStatus, + failureReason: finalFailureReason, + nicheKey, + paretoRank: finalStatus === 'passed' ? 1 : (finalStatus === 'soft_passed' ? 2 : null), + crowdingDistance: retainsInArchive ? 0 : null, + scalarFitness: retainsInArchive ? 0.5 : null, + countEvaluation: !isNoveltyRejected, + codeSliceCasDigest: codeCas.digest, + evidenceDigest: evalOutcome.evidenceDigest ?? null, + verdictReceiptCasDigest, + outputArtifacts: storedArtifacts, + metrics: evalOutcome.metrics, + ...(evalOutcome.bucketMetrics !== undefined ? { bucketMetrics: evalOutcome.bucketMetrics } : {}), + ...(evalOutcome.hardwareDiagnostics !== undefined ? { hardwareDiagnostics: evalOutcome.hardwareDiagnostics } : {}), + ...(evalOutcome.hardwareProvenance !== undefined ? { hardwareProvenance: evalOutcome.hardwareProvenance } : {}), + ...(evalOutcome.findings !== undefined ? { findings: evalOutcome.findings } : {}), + lineageEdges, + }); + + return { + islandId: isl, + teamConfigId: islandRec.activeTeamConfigId, + individual: recorded, + primaryParent, + ...(evalOutcome.runEvalReport !== undefined ? { runEvalReport: evalOutcome.runEvalReport } : {}), + }; + }); + } + + const rawSlotOutcomes = await runWithConcurrencyLimit(slotTasks, budgets.maxConcurrentEvaluations); + const slotOutcomes = rawSlotOutcomes.filter((x): x is IslandSlotOutcome => x !== null); + + const updatedStagePassed = await refreshStageParetoArchive( + store, + lease, + campaignId, + params.bucketId, + objectives, + ); + const passedById = new Map(updatedStagePassed.map(ind => [ind.individualId, ind] as const)); + + for (const slot of slotOutcomes) { + if (slot.individual.status === 'preempted' || slot.individual.failureReason === 'NOVELTY_CLONE_REJECTED') { + continue; + } + const refreshedChild = passedById.get(slot.individual.individualId); + const refreshedParent = slot.primaryParent !== null ? passedById.get(slot.primaryParent.individualId) : undefined; + let reward = 0; + if (refreshedChild?.scalarFitness !== null && refreshedChild?.scalarFitness !== undefined) { + const parentFit = refreshedParent?.scalarFitness ?? 0.5; + reward = slot.primaryParent === null + ? Math.max(0, refreshedChild.scalarFitness * 0.1) + : computeTruncatedImprovementReward(refreshedChild.scalarFitness, parentFit); + } + await store.recordModelBanditReward(lease, { + campaignId, + modelId: slot.individual.modelId, + reward, + generation: gen, + }); + } + + const minHvDelta = manifest.spec.teamEvolution?.minHypervolumeDelta ?? 0.001; + for (const slot of slotOutcomes) { + const isl = slot.islandId; + const currentIsland = (await store.getIsland(campaignId, isl))!; + + if (slot.runEvalReport !== undefined) { + const hist = islandRunEvals.get(isl) ?? []; + hist.push(slot.runEvalReport); + islandRunEvals.set(isl, hist); + } + + const beforeMap = preGenNichesByIsland.get(isl) ?? new Map(); + const afterMap = await store.getIslandNicheElites(campaignId, isl, params.bucketId); + + let newNichesOpened = 0; + let upgradedNiche = false; + for (const [nKey, elite] of afterMap.entries()) { + const prevElite = beforeMap.get(nKey); + if (prevElite === undefined) { + newNichesOpened += 1; + } else if (prevElite.individualId !== elite.individualId) { + upgradedNiche = true; + } + } + + const beforePoints = [...beforeMap.values()].map(e => e.metrics); + const afterPoints = [...afterMap.values()].map(e => e.metrics); + const refPoint = deriveHypervolumeReferencePoint([...beforePoints, ...afterPoints], objectives); + const hvDelta = computeHypervolumeDelta(beforePoints, afterPoints, objectives, refPoint); + const nextHv = computeHypervolume(afterPoints, objectives, refPoint); + + const isPreempted = slot.individual.status === 'preempted'; + const advancedPareto = hvDelta >= minHvDelta; + const discoveredNiche = newNichesOpened > 0 || upgradedNiche; + + const usedTeam = await store.getTeamConfig(slot.teamConfigId); + if (usedTeam?.status === 'trial') { + await recordTeamTrialOutcome(store, lease, { + campaignId, + islandId: isl, + teamConfigId: slot.teamConfigId, + advancedPareto, + discoveredNiche, + preempted: isPreempted, + }); + } + + if (!isPreempted) { + const nextNoGain = (advancedPareto || newNichesOpened > 0) + ? 0 + : currentIsland.consecutiveNoGainGenerations + 1; + const nextPathology = slot.runEvalReport !== undefined && hasRunEvalLoopPathology(slot.runEvalReport) + ? currentIsland.consecutivePathologyRuns + 1 + : 0; + const candidateHeadroom = slot.individual.status === 'passed' + ? slot.individual.hardwareDiagnostics?.rooflineHeadroom + : undefined; + const nextBestHeadroom = candidateHeadroom !== undefined + ? (currentIsland.bestRooflineHeadroom === null + ? candidateHeadroom + : Math.min(currentIsland.bestRooflineHeadroom, candidateHeadroom)) + : currentIsland.bestRooflineHeadroom; + + const updatedIsl = await store.updateIslandProgress(lease, { + campaignId, + islandId: isl, + currentGeneration: gen, + consecutiveNoGainGenerations: nextNoGain, + consecutivePathologyRuns: nextPathology, + lastHypervolume: nextHv, + bestRooflineHeadroom: nextBestHeadroom, + }); + + const bestSf = afterMap.size > 0 + ? Math.max(...[...afterMap.values()].map(e => e.scalarFitness ?? 0)) + : null; + const traj = islandTrajectories.get(isl) ?? []; + traj.push({ + generation: gen, + hypervolume: nextHv, + bestScalarFitness: bestSf, + nichesOpen: afterMap.size, + }); + islandTrajectories.set(isl, traj); + + if (manifest.spec.teamEvolution?.enabled === true && opts.supervisorRunner !== undefined && !opts.signal?.aborted) { + const freshCamp = (await store.getCampaign(campaignId))!; + const islandInds = await store.listIndividuals(campaignId, { islandId: isl, bucketId: params.bucketId }); + const evalsForIsl = islandRunEvals.get(isl); + await runPlateauSupervisorTurn({ + store, + lease, + campaignId, + island: updatedIsl, + teamEvolution: manifest.spec.teamEvolution, + budgets, + evaluationsUsed: freshCamp.evaluationsUsed, + currentGeneration: gen, + baseTaskContract, + taskpack, + trajectory: traj, + ...(evalsForIsl !== undefined ? { recentRunEvals: evalsForIsl } : {}), + recentIndividuals: islandInds.slice(-16), + ...(latestScratchpadMd !== undefined ? { latestScratchpadMarkdown: latestScratchpadMd } : {}), + stagingDir: join(store.campaignRoot, 'supervisor', `isl-${isl}-gen-${gen}`), + supervisorRunner: opts.supervisorRunner, + scrubber, + }); + } + } + } + + if (opts.signal?.aborted) { + await store.updateCampaignProgress(lease, { campaignId, status: 'paused' }); + return 'paused'; + } + + const anyPreemptedOnly = slotOutcomes.length > 0 && slotOutcomes.every(s => s.individual.status === 'preempted'); + if (!anyPreemptedOnly) { + await store.updateCampaignProgress(lease, { + campaignId, + status: 'active', + stagePhase: params.stagePhase, + activeBucketId: params.bucketId, + currentGeneration: gen, + }); + } + + // Periodic campaign scratchpad synthesis + if (gen > 0 && gen % budgets.scratchpadIntervalGenerations === 0) { + const allEvaluated = await store.listIndividuals(campaignId); + if (allEvaluated.length > 0) { + await synthesizeCampaignScratchpad({ + store, + lease, + campaignId, + generation: gen, + scrubber, + }); + } + } + } + + return 'completed_stage'; + }; + + const currentCampaign = (await store.getCampaign(campaignId))!; + if (manifest.spec.stages.mode === 'single-target') { + const singleTargetWorkloadId = + manifest.spec.stages.heldOutWorkloadId + ?? manifest.spec.heldOutWorkloadId + ?? defaultHeldOutWorkloadId; + const startGen = Math.max(1, currentCampaign.currentGeneration + 1); + const outcome = await runStageGenerations({ + stagePhase: 'single-target', + bucketId: null, + heldOutWorkloadId: singleTargetWorkloadId, + startGen, + maxGenInclusive: budgets.maxGenerations, + maxEvalsCeiling: budgets.maxEvaluations, + }); + if (outcome !== 'paused') { + await store.updateCampaignProgress(lease, { campaignId, status: 'completed' }); + } + } else { + const specBuckets = manifest.spec.stages.specialistBuckets; + const portfolioWorkloadId = manifest.spec.stages.portfolioHeldOutWorkloadId; + const gensForSpecialists = Math.max(specBuckets.length, budgets.maxGenerations - 1); + const gensPerBucket = Math.max(1, Math.floor(gensForSpecialists / specBuckets.length)); + + let maxSpecialistGenUsed = currentCampaign.currentGeneration; + + if (currentCampaign.stagePhase !== 'portfolio') { + const startBucketIdx = currentCampaign.activeBucketId !== null + ? Math.max(0, specBuckets.findIndex(b => b.id === currentCampaign.activeBucketId)) + : 0; + + for (let bIdx = startBucketIdx; bIdx < specBuckets.length; bIdx += 1) { + const bucket = specBuckets[bIdx]!; + const freshCamp = (await store.getCampaign(campaignId))!; + + if (freshCamp.activeBucketId !== bucket.id) { + const allIslands = await store.listIslands(campaignId); + for (const islRec of allIslands) { + await store.updateIslandProgress(lease, { + campaignId, + islandId: islRec.islandId, + consecutiveNoGainGenerations: 0, + consecutivePathologyRuns: 0, + lastHypervolume: 0, + bestRooflineHeadroom: null, + }); + } + islandRunEvals.clear(); + islandTrajectories.clear(); + await store.updateCampaignProgress(lease, { + campaignId, + status: 'active', + stagePhase: 'specialist', + activeBucketId: bucket.id, + }); + } + + const bucketWindowStart = bIdx * gensPerBucket + 1; + const bucketWindowEnd = bIdx === specBuckets.length - 1 + ? Math.max(bucketWindowStart, budgets.maxGenerations - 1) + : bucketWindowStart + gensPerBucket - 1; + const startGenForBucket = freshCamp.activeBucketId === bucket.id + ? Math.max(bucketWindowStart, freshCamp.currentGeneration + 1) + : bucketWindowStart; + + const remainingBucketsAfter = specBuckets.length - 1 - bIdx; + const maxEvalsForThisBucket = Math.max( + freshCamp.evaluationsUsed + 1, + budgets.maxEvaluations - remainingBucketsAfter - 1, + ); + + const stageRes = await runStageGenerations({ + stagePhase: 'specialist', + bucketId: bucket.id, + heldOutWorkloadId: bucket.heldOutWorkloadId, + startGen: startGenForBucket, + maxGenInclusive: bucketWindowEnd, + maxEvalsCeiling: maxEvalsForThisBucket, + }); + maxSpecialistGenUsed = Math.max(maxSpecialistGenUsed, bucketWindowEnd); + if (stageRes === 'paused') { + break; + } + } + } + + const afterSpecCamp = (await store.getCampaign(campaignId))!; + if (afterSpecCamp.status !== 'paused' && !opts.signal?.aborted) { + const winningSpecialists: Array<{ readonly bucketId: string; readonly individual: IndividualRecord }> = []; + let missingBucketWinner = false; + for (const bucket of specBuckets) { + const passedInBucket = await store.listIndividuals(campaignId, { + status: ['passed'], + bucketId: bucket.id, + }); + if (passedInBucket.length === 0) { + missingBucketWinner = true; + break; + } + const sorted = [...passedInBucket].sort((a, b) => { + const ra = a.paretoRank ?? Number.MAX_SAFE_INTEGER; + const rb = b.paretoRank ?? Number.MAX_SAFE_INTEGER; + if (ra !== rb) return ra - rb; + return (b.scalarFitness ?? 0) - (a.scalarFitness ?? 0); + }); + winningSpecialists.push({ bucketId: bucket.id, individual: sorted[0]! }); + } + + if (missingBucketWinner || afterSpecCamp.evaluationsUsed >= budgets.maxEvaluations) { + await store.updateCampaignProgress(lease, { campaignId, status: 'failed' }); + } else { + const portfolioGen = Math.max(maxSpecialistGenUsed + 1, afterSpecCamp.currentGeneration + 1); + await store.updateCampaignProgress(lease, { + campaignId, + status: 'active', + stagePhase: 'portfolio', + activeBucketId: portfolioWorkloadId, + }); + + const islandsList = await store.listIslands(campaignId); + const isl0 = islandsList[0]!; + const portfolioTeamPatch = await loadValidatedActiveTeamPatch(isl0.activeTeamConfigId); + const portfolioId = sanitizeRunId(`ind-portfolio-g${portfolioGen}-${randomBytes(3).toString('hex')}`); + const childRunDir = join(store.campaignRoot, 'runs', portfolioId); + await mkdir(childRunDir, { recursive: true, mode: 0o700 }); + + const specialistInputs: PortfolioSpecialistContextInput[] = []; + const sampledPortfolioMembers: SampledParentEntry[] = []; + for (const entry of winningSpecialists) { + const specWinner = entry.individual; + const codeBytes = specWinner.codeSliceCasDigest !== null + ? await store.readCasBlob(specWinner.codeSliceCasDigest.hex) + : Buffer.from('// specialist\n', 'utf8'); + specialistInputs.push({ + bucketId: entry.bucketId, + individual: specWinner, + codeSlice: codeBytes.toString('utf8'), + }); + sampledPortfolioMembers.push({ + individual: specWinner, + role: 'portfolio_member', + sourceIslandId: specWinner.islandId, + weight: 1, + }); + } + + const stagedPortfolioCtx = await stagePortfolioSpecialistContextFiles({ + stagingDir: join(childRunDir, 'portfolio-specialists'), + specialists: specialistInputs, + scrubber, + }); + + const arms = await store.listModelBanditArms(campaignId); + const modelPick = selectModelCandidate({ + strategy: sampling.modelBandit, + modelIds, + arms, + sequenceIndex: sequenceCounter, + }); + + const portfolioTrackId = winningSpecialists[0]?.individual.trackId ?? declaredTracks[0] ?? 'cuda_raw'; + const portfolioOutcome = await evaluator({ + campaignId, + individualId: portfolioId, + islandId: isl0.islandId, + generation: portfolioGen, + stagePhase: 'portfolio', + bucketId: portfolioWorkloadId, + heldOutWorkloadId: portfolioWorkloadId, + modelId: modelPick.modelId, + trackId: portfolioTrackId, + mutationKind: 'portfolio', + teamConfigId: isl0.activeTeamConfigId, + parents: sampledPortfolioMembers, + stagedParentFiles: stagedPortfolioCtx.files, + portfolioSpecialists: winningSpecialists.map(w => w.individual), + campaignRoot: store.campaignRoot, + childRunDir, + baseRevision: afterSpecCamp.baseRevision, + manifest, + taskpack, + ...(portfolioTeamPatch !== undefined ? { teamPatch: portfolioTeamPatch } : {}), + ...(opts.signal !== undefined ? { signal: opts.signal } : {}), + }); + + const codeCas = await store.writeCasBlob( + Buffer.from(portfolioOutcome.codeSlice.length > 0 ? portfolioOutcome.codeSlice : '// portfolio\n', 'utf8'), + ); + let vrDigest: Digest | null = null; + if (portfolioOutcome.rawVerdictReceiptBytes !== undefined) { + vrDigest = (await store.writeCasBlob(portfolioOutcome.rawVerdictReceiptBytes)).digest; + } + const storedPortfolioArts: ArtifactRef[] = []; + if (portfolioOutcome.stageABlobs !== undefined && portfolioOutcome.stageABlobs.length > 0) { + for (const blob of portfolioOutcome.stageABlobs) { + const wb = await store.writeCasBlob(blob.bytes); + storedPortfolioArts.push({ + name: blob.name, + digest: wb.digest, + byteLength: wb.byteLength, + ...(blob.mediaType !== undefined && blob.mediaType !== null ? { mediaType: blob.mediaType } : {}), + }); + } + } else if (portfolioOutcome.outputArtifacts !== undefined) { + storedPortfolioArts.push(...portfolioOutcome.outputArtifacts); + } + + const portfolioNiche = portfolioOutcome.status === 'passed' + ? computeNicheKey(population.nicheAxes, portfolioOutcome.metrics, portfolioOutcome.hardwareDiagnostics) + : null; + + await store.recordIndividual(lease, { + individualId: portfolioId, + campaignId, + islandId: isl0.islandId, + generation: portfolioGen, + bucketId: portfolioWorkloadId, + teamConfigId: isl0.activeTeamConfigId, + modelId: modelPick.modelId, + trackId: portfolioTrackId, + mutationKind: 'portfolio', + status: portfolioOutcome.status, + failureReason: portfolioOutcome.failureReason ?? null, + nicheKey: portfolioNiche, + paretoRank: portfolioOutcome.status === 'passed' ? 1 : null, + crowdingDistance: portfolioOutcome.status === 'passed' ? Number.POSITIVE_INFINITY : null, + scalarFitness: portfolioOutcome.status === 'passed' ? 1.0 : null, + codeSliceCasDigest: codeCas.digest, + evidenceDigest: portfolioOutcome.evidenceDigest ?? null, + verdictReceiptCasDigest: vrDigest, + outputArtifacts: storedPortfolioArts, + metrics: portfolioOutcome.metrics, + ...(portfolioOutcome.bucketMetrics !== undefined ? { bucketMetrics: portfolioOutcome.bucketMetrics } : {}), + ...(portfolioOutcome.hardwareDiagnostics !== undefined ? { hardwareDiagnostics: portfolioOutcome.hardwareDiagnostics } : {}), + ...(portfolioOutcome.hardwareProvenance !== undefined ? { hardwareProvenance: portfolioOutcome.hardwareProvenance } : {}), + ...(portfolioOutcome.findings !== undefined ? { findings: portfolioOutcome.findings } : {}), + lineageEdges: winningSpecialists.map(sw => ({ + campaignId, + childIndividualId: portfolioId, + parentIndividualId: sw.individual.individualId, + role: 'portfolio_member' as const, + sourceIslandId: sw.individual.islandId, + createdGeneration: portfolioGen, + })), + }); + + await refreshStageParetoArchive(store, lease, campaignId, portfolioWorkloadId, objectives); + await store.updateCampaignProgress(lease, { + campaignId, + status: portfolioOutcome.status === 'passed' ? 'completed' : 'failed', + stagePhase: 'portfolio', + activeBucketId: portfolioWorkloadId, + currentGeneration: portfolioGen, + }); + } + } + } + + const finalCampaign = (await store.getCampaign(campaignId))!; + const finalIslands = await store.listIslands(campaignId); + const allPassed = await store.listIndividuals(campaignId, { status: ['passed'] }); + const paretoFrontier = allPassed.filter(ind => ind.paretoRank === 1); + + let exportedBundle: ExportEvolutionBundleResult | undefined; + if (finalCampaign.status === 'completed' && manifest.spec.export !== undefined && opts.autoExport) { + const rawOutDir = manifest.spec.export.outputDir; + const resolvedOutDir = isAbsolute(rawOutDir) + ? rawOutDir + : resolve(opts.repositoryRoot ?? store.campaignRoot, rawOutDir); + const effectiveDriverConstraint = opts.driverConstraint ?? finalCampaign.driverConstraint ?? undefined; + exportedBundle = await exportEvolutionBundle({ + store, + campaignId, + outputDir: resolvedOutDir, + format: opts.exportFormat ?? manifest.spec.export.format, + allowSyntheticProbe: opts.allowSyntheticProbe, + ...(effectiveDriverConstraint !== undefined ? { driverConstraint: effectiveDriverConstraint } : {}), + ...(opts.receiptSigningSecret !== undefined ? { receiptSigningSecret: opts.receiptSigningSecret } : {}), + ...(opts.verifyReceiptSignature !== undefined ? { verifyReceiptSignature: opts.verifyReceiptSignature } : {}), + ...(opts.dispatchManifest !== undefined ? { dispatchManifest: opts.dispatchManifest } : {}), + scrubber, + }); + } + + return Object.freeze({ + store, + campaign: finalCampaign, + islands: Object.freeze(finalIslands), + paretoFrontier: Object.freeze(paretoFrontier), + noveltyRejectionsCount, + cascadeSoftStopsCount, + advisoryDecisions: Object.freeze(advisoryDecisions), + earlyStoppedByRoofline, + ...(exportedBundle !== undefined ? { exportedBundle } : {}), + }); +} + +function resolveCampaignEvaluator( + evaluator: CandidateEvaluator | undefined, + controllerOptions: ControllerChildRunEvaluatorOptions | undefined, +): CandidateEvaluator { + if (evaluator !== undefined) return evaluator; + if (controllerOptions !== undefined) { + return createControllerChildRunEvaluator(controllerOptions); + } + throw new EvolutionError( + 'EVOLUTION_SCHEMA_INVALID', + 'either evaluator or controllerEvaluatorOptions must be provided to execute candidate runs', + ); +} + +/** + * Create and run an evolutionary optimization campaign inside `/campaign.sqlite`. + */ +export async function runEvolutionCampaign( + options: RunEvolutionCampaignOptions, +): Promise { + const scrubber = options.scrubber ?? DEFAULT_CAMPAIGN_SCRUBBER; + const effectiveRepoRoot = options.repositoryRoot ?? options.controllerEvaluatorOptions?.repositoryRoot; + await assertDisjointCampaignAndRepositoryRoots(options.campaignRoot, effectiveRepoRoot); + + const checked = await checkEvolutionCampaign({ + ...(options.manifestPath !== undefined ? { manifestPath: options.manifestPath } : {}), + ...(options.manifest !== undefined ? { manifest: options.manifest } : {}), + ...(options.format !== undefined ? { format: options.format } : {}), + ...(effectiveRepoRoot !== undefined ? { repositoryRoot: effectiveRepoRoot } : {}), + ...(options.taskpack !== undefined ? { taskpack: options.taskpack } : {}), + scrubber, + }); + + if (options.manifestPath !== undefined && effectiveRepoRoot === undefined) { + await assertDisjointCampaignAndRepositoryRoots(options.campaignRoot, dirname(resolve(options.manifestPath))); + } + + const evaluator = resolveCampaignEvaluator(options.evaluator, options.controllerEvaluatorOptions); + const campaignId = options.campaignId ?? `camp-${checked.manifest.metadata.name}-${randomBytes(4).toString('hex')}`; + const baseRevision = options.baseRevision ?? await resolveGitHeadRevision(effectiveRepoRoot); + const { lockHash, baseTaskContract } = await computeBaselineCampaignLockHash( + checked.taskpack, + campaignId, + baseRevision, + effectiveRepoRoot, + ); + const driverConstraint = resolveTargetDriverConstraint(checked.taskpack, checked.targetCellId); + + const store = await EvolutionCampaignStore.open({ + campaignRoot: options.campaignRoot, + ...(options.clock !== undefined ? { clock: options.clock } : {}), + createIfMissing: true, + }); + + try { + const lease = await store.acquireLease(`coordinator-${randomBytes(6).toString('hex')}`); + const initialStagePhase: CampaignStagePhase = checked.manifest.spec.stages.mode === 'specialist-then-portfolio' + ? 'specialist' + : 'single-target'; + const initialBucketId = checked.manifest.spec.stages.mode === 'specialist-then-portfolio' + ? checked.manifest.spec.stages.specialistBuckets[0]!.id + : null; + + await store.createCampaign(lease, { + campaignId, + manifest: checked.manifest, + manifestDigest: checked.manifestDigest, + baseRevision, + lockHash, + driverConstraint, + stagePhase: initialStagePhase, + activeBucketId: initialBucketId, + modelIds: checked.modelIds, + }); + + await store.ensureModelBanditArms(lease, campaignId, checked.modelIds); + + return await driveCampaignExecution({ + store, + lease, + campaignId, + manifest: checked.manifest, + taskpack: checked.taskpack, + baseTaskContract, + modelIds: checked.modelIds, + driverConstraint, + ...(effectiveRepoRoot !== undefined ? { repositoryRoot: effectiveRepoRoot } : {}), + evaluator, + ...(options.proposeCandidateSlice !== undefined ? { proposeCandidateSlice: options.proposeCandidateSlice } : {}), + ...(options.supervisorRunner !== undefined ? { supervisorRunner: options.supervisorRunner } : {}), + ...(options.decisionPolicy !== undefined + ? { decisionPolicy: options.decisionPolicy } + : (options.controllerEvaluatorOptions?.decisionPolicy !== undefined + ? { decisionPolicy: options.controllerEvaluatorOptions.decisionPolicy } + : {})), + ...(options.decisionTransport !== undefined + ? { decisionTransport: options.decisionTransport } + : (options.controllerEvaluatorOptions?.decisionTransport !== undefined + ? { decisionTransport: options.controllerEvaluatorOptions.decisionTransport } + : {})), + ...(options.decisionApiKey !== undefined + ? { decisionApiKey: options.decisionApiKey } + : (options.controllerEvaluatorOptions?.decisionApiKey !== undefined + ? { decisionApiKey: options.controllerEvaluatorOptions.decisionApiKey } + : {})), + ...(options.environment !== undefined + ? { environment: options.environment } + : (options.controllerEvaluatorOptions?.environment !== undefined + ? { environment: options.controllerEvaluatorOptions.environment } + : {})), + ...(options.signal !== undefined ? { signal: options.signal } : {}), + autoExport: options.autoExport ?? true, + ...(options.exportFormat !== undefined ? { exportFormat: options.exportFormat } : {}), + allowSyntheticProbe: options.allowSyntheticProbe === true, + ...(options.receiptSigningSecret !== undefined ? { receiptSigningSecret: options.receiptSigningSecret } : {}), + ...(options.verifyReceiptSignature !== undefined ? { verifyReceiptSignature: options.verifyReceiptSignature } : {}), + ...(options.dispatchManifest !== undefined ? { dispatchManifest: options.dispatchManifest } : {}), + scrubber, + }); + } catch (err: unknown) { + await store.close().catch(() => undefined); + throw err; + } +} + +/** + * Resume an existing paused or interrupted campaign from `/campaign.sqlite` + * under a newly fenced coordinator lease without double-counting `maxEvaluations` or `trial_used_generations`. + */ +export async function resumeEvolutionCampaign( + options: ResumeEvolutionCampaignOptions, +): Promise { + const scrubber = options.scrubber ?? DEFAULT_CAMPAIGN_SCRUBBER; + const effectiveRepoRoot = options.repositoryRoot ?? options.controllerEvaluatorOptions?.repositoryRoot; + await assertDisjointCampaignAndRepositoryRoots(options.campaignRoot, effectiveRepoRoot); + + const evaluator = resolveCampaignEvaluator(options.evaluator, options.controllerEvaluatorOptions); + + const store = await EvolutionCampaignStore.open({ + campaignRoot: options.campaignRoot, + ...(options.clock !== undefined ? { clock: options.clock } : {}), + createIfMissing: false, + }); + + try { + const lease = await store.acquireLease(`resume-coordinator-${randomBytes(6).toString('hex')}`); + + let existingCampaign: CampaignRecord | null; + if (options.campaignId !== undefined) { + existingCampaign = await store.getCampaign(options.campaignId); + } else { + const all = await store.listCampaigns(); + existingCampaign = all[0] ?? null; + } + if (existingCampaign === null) { + throw new EvolutionError('EVOLUTION_NOT_FOUND', 'no campaign found to resume in campaign.sqlite'); + } + + if (existingCampaign.status === 'completed') { + const islands = await store.listIslands(existingCampaign.campaignId); + const allPassed = await store.listIndividuals(existingCampaign.campaignId, { status: ['passed'] }); + return Object.freeze({ + store, + campaign: existingCampaign, + islands: Object.freeze(islands), + paretoFrontier: Object.freeze(allPassed.filter(i => i.paretoRank === 1)), + noveltyRejectionsCount: 0, + cascadeSoftStopsCount: 0, + advisoryDecisions: Object.freeze([]), + earlyStoppedByRoofline: false, + }); + } + + const checked = await checkEvolutionCampaign({ + manifest: existingCampaign.manifest, + ...(effectiveRepoRoot !== undefined ? { repositoryRoot: effectiveRepoRoot } : {}), + ...(options.taskpack !== undefined ? { taskpack: options.taskpack } : {}), + scrubber, + }); + + const { baseTaskContract } = await computeBaselineCampaignLockHash( + checked.taskpack, + existingCampaign.campaignId, + existingCampaign.baseRevision, + effectiveRepoRoot, + ); + const driverConstraint = resolveTargetDriverConstraint(checked.taskpack, checked.targetCellId) + ?? existingCampaign.driverConstraint; + + await store.ensureModelBanditArms(lease, existingCampaign.campaignId, checked.modelIds); + await store.updateCampaignProgress(lease, { + campaignId: existingCampaign.campaignId, + status: 'active', + ...(driverConstraint !== null ? { driverConstraint } : {}), + }); + + return await driveCampaignExecution({ + store, + lease, + campaignId: existingCampaign.campaignId, + manifest: existingCampaign.manifest, + taskpack: checked.taskpack, + baseTaskContract, + modelIds: checked.modelIds, + driverConstraint, + ...(effectiveRepoRoot !== undefined ? { repositoryRoot: effectiveRepoRoot } : {}), + evaluator, + ...(options.proposeCandidateSlice !== undefined ? { proposeCandidateSlice: options.proposeCandidateSlice } : {}), + ...(options.supervisorRunner !== undefined ? { supervisorRunner: options.supervisorRunner } : {}), + ...(options.decisionPolicy !== undefined + ? { decisionPolicy: options.decisionPolicy } + : (options.controllerEvaluatorOptions?.decisionPolicy !== undefined + ? { decisionPolicy: options.controllerEvaluatorOptions.decisionPolicy } + : {})), + ...(options.decisionTransport !== undefined + ? { decisionTransport: options.decisionTransport } + : (options.controllerEvaluatorOptions?.decisionTransport !== undefined + ? { decisionTransport: options.controllerEvaluatorOptions.decisionTransport } + : {})), + ...(options.decisionApiKey !== undefined + ? { decisionApiKey: options.decisionApiKey } + : (options.controllerEvaluatorOptions?.decisionApiKey !== undefined + ? { decisionApiKey: options.controllerEvaluatorOptions.decisionApiKey } + : {})), + ...(options.environment !== undefined + ? { environment: options.environment } + : (options.controllerEvaluatorOptions?.environment !== undefined + ? { environment: options.controllerEvaluatorOptions.environment } + : {})), + ...(options.signal !== undefined ? { signal: options.signal } : {}), + autoExport: options.autoExport ?? true, + ...(options.exportFormat !== undefined ? { exportFormat: options.exportFormat } : {}), + allowSyntheticProbe: options.allowSyntheticProbe === true, + ...(options.receiptSigningSecret !== undefined ? { receiptSigningSecret: options.receiptSigningSecret } : {}), + ...(options.verifyReceiptSignature !== undefined ? { verifyReceiptSignature: options.verifyReceiptSignature } : {}), + ...(options.dispatchManifest !== undefined ? { dispatchManifest: options.dispatchManifest } : {}), + scrubber, + }); + } catch (err: unknown) { + await store.close().catch(() => undefined); + throw err; + } +} + +async function withReadStore( + options: { + readonly campaignRoot: string; + readonly store?: EvolutionCampaignStore | undefined; + readonly clock?: CampaignClockSource | undefined; + }, + fn: (store: EvolutionCampaignStore) => Promise, +): Promise { + if (options.store !== undefined) { + return fn(options.store); + } + const opened = await EvolutionCampaignStore.open({ + campaignRoot: options.campaignRoot, + ...(options.clock !== undefined ? { clock: options.clock } : {}), + createIfMissing: false, + }); + try { + return await fn(opened); + } finally { + await opened.close(); + } +} + +async function resolveTargetCampaign( + store: EvolutionCampaignStore, + campaignId: string | undefined, +): Promise { + if (campaignId !== undefined) { + const found = await store.getCampaign(campaignId); + if (found === null) { + throw new EvolutionError('EVOLUTION_NOT_FOUND', `campaign "${campaignId}" not found`); + } + return found; + } + const list = await store.listCampaigns(); + if (list.length === 0) { + throw new EvolutionError('EVOLUTION_NOT_FOUND', 'no campaigns found in campaign.sqlite'); + } + return list[0]!; +} + +/** + * Read concise campaign status, counts by status, active teams, and Pareto frontier for CLI `status`. + */ +export async function getEvolutionCampaignStatus( + options: GetEvolutionCampaignStatusOptions, +): Promise { + return withReadStore(options, async store => { + const campaign = await resolveTargetCampaign(store, options.campaignId); + const islands = await store.listIslands(campaign.campaignId); + const individuals = await store.listIndividuals(campaign.campaignId); + const allTeams = await store.listTeamConfigs(campaign.campaignId); + const activeTeamIds = new Set(islands.map(i => i.activeTeamConfigId)); + const activeTeams = allTeams.filter(tc => activeTeamIds.has(tc.teamConfigId)); + const latestScratchpad = await store.getLatestScratchpadSnapshot(campaign.campaignId); + + let passed = 0; + let softPassed = 0; + let failed = 0; + let preempted = 0; + let noveltyRejected = 0; + + for (const ind of individuals) { + if (ind.status === 'passed') passed += 1; + else if (ind.status === 'soft_passed') softPassed += 1; + else if (ind.status === 'preempted') preempted += 1; + else { + failed += 1; + if (ind.failureReason === 'NOVELTY_CLONE_REJECTED') noveltyRejected += 1; + } + } + + const paretoFrontier = individuals.filter(ind => ind.status === 'passed' && ind.paretoRank === 1); + + return Object.freeze({ + campaign, + islands: Object.freeze(islands), + paretoFrontier: Object.freeze(paretoFrontier), + countsByStatus: Object.freeze({ + passed, + soft_passed: softPassed, + failed, + preempted, + noveltyRejected, + }), + activeTeams: Object.freeze(activeTeams), + latestScratchpad, + }); + }); +} + +/** + * Read complete campaign archive, MAP-Elites niche grids, `team_configs` history, lineage DAG, + * model bandit arms, and scratchpads for CLI `inspect`. + */ +export async function inspectEvolutionCampaign( + options: InspectEvolutionCampaignOptions, +): Promise { + return withReadStore(options, async store => { + const campaign = await resolveTargetCampaign(store, options.campaignId); + const islands = await store.listIslands(campaign.campaignId); + const individuals = await store.listIndividuals(campaign.campaignId); + const teamConfigs = await store.listTeamConfigs(campaign.campaignId); + const lineageEdges = await store.listLineageEdges(campaign.campaignId); + const modelBanditArms = await store.listModelBanditArms(campaign.campaignId); + const scratchpadSnapshots = await store.listScratchpadSnapshots(campaign.campaignId); + + const bucketTargets: readonly (string | null)[] = campaign.manifest.spec.stages.mode === 'specialist-then-portfolio' + ? [ + ...campaign.manifest.spec.stages.specialistBuckets.map(b => b.id), + campaign.manifest.spec.stages.portfolioHeldOutWorkloadId, + ] + : [null]; + + const nicheArchives: IslandNicheArchiveView[] = []; + for (const isl of islands) { + for (const bId of bucketTargets) { + const nicheMap = await store.getIslandNicheElites(campaign.campaignId, isl.islandId, bId); + nicheArchives.push( + Object.freeze({ + islandId: isl.islandId, + bucketId: bId, + elites: Object.freeze([...nicheMap.values()]), + }), + ); + } + } + + const paretoFrontier = individuals.filter(ind => ind.status === 'passed' && ind.paretoRank === 1); + + return Object.freeze({ + campaign, + islands: Object.freeze(islands), + paretoFrontier: Object.freeze(paretoFrontier), + nicheArchives: Object.freeze(nicheArchives), + teamConfigs: Object.freeze(teamConfigs), + individuals: Object.freeze(individuals), + lineageEdges: Object.freeze(lineageEdges), + modelBanditArms: Object.freeze(modelBanditArms), + scratchpadSnapshots: Object.freeze(scratchpadSnapshots), + }); + }); +} diff --git a/packages/evolution/src/index.ts b/packages/evolution/src/index.ts new file mode 100644 index 0000000..7012991 --- /dev/null +++ b/packages/evolution/src/index.ts @@ -0,0 +1,52 @@ +import { DatabaseSync } from 'node:sqlite'; + +export const EVOLUTION_PACKAGE_NAME = '@loopwright/evolution' as const; +export const EVOLUTION_SCAFFOLD_VERSION = 1 as const; + +export interface EvolutionPackageDescriptor { + readonly name: typeof EVOLUTION_PACKAGE_NAME; + readonly version: typeof EVOLUTION_SCAFFOLD_VERSION; + readonly sqliteBuiltin: boolean; + readonly sqliteVersion: string; +} + +export interface NodeSqliteProbeResult { + readonly strictTablesSupported: boolean; + readonly journalMode: string; +} + +/** Return frozen metadata describing the `@loopwright/evolution` package scaffold and SQLite runtime. */ +export function getEvolutionPackageDescriptor(): EvolutionPackageDescriptor { + return Object.freeze({ + name: EVOLUTION_PACKAGE_NAME, + version: EVOLUTION_SCAFFOLD_VERSION, + sqliteBuiltin: typeof DatabaseSync === 'function', + sqliteVersion: process.versions.sqlite ?? '', + }); +} + +/** Verify built-in `node:sqlite` `STRICT` table creation and pragma querying against an in-memory database. */ +export function probeNodeSqliteSupport(): NodeSqliteProbeResult { + const db = new DatabaseSync(':memory:'); + try { + db.exec('CREATE TABLE scaffold_probe (id INTEGER PRIMARY KEY) STRICT;'); + const row = db.prepare('PRAGMA journal_mode;').get() as { readonly journal_mode?: unknown } | undefined; + const journalMode = typeof row?.journal_mode === 'string' ? row.journal_mode : ''; + return Object.freeze({ + strictTablesSupported: true, + journalMode, + }); + } finally { + db.close(); + } +} + +export * from './types.js'; +export * from './schema.js'; +export * from './store.js'; +export * from './pareto.js'; +export * from './sampler.js'; +export * from './scratchpad.js'; +export * from './bundle.js'; +export * from './team-supervisor.js'; +export * from './campaign.js'; diff --git a/packages/evolution/src/pareto.ts b/packages/evolution/src/pareto.ts new file mode 100644 index 0000000..01019c3 --- /dev/null +++ b/packages/evolution/src/pareto.ts @@ -0,0 +1,624 @@ +import type { HardwareDiagnostics, MetricValue } from '@loopwright/core'; +import { + EvolutionError, + type EvolutionNicheAxis, + type ObjectiveDirectionSpec, +} from './types.js'; + +export interface ParetoCandidateEntry { + readonly individualId: string; + readonly metrics: Readonly>; +} + +export interface RankedParetoEntry { + readonly individualId: string; + readonly metrics: Readonly>; + readonly paretoRank: number; + readonly crowdingDistance: number; +} + +export interface ObjectiveMetricStats { + readonly min: number; + readonly max: number; + readonly weight?: number; +} + +export type ObjectiveReferenceStats = Readonly>; + +function getOwnFiniteMetric( + record: Readonly>, + metric: string, +): number | undefined { + if (!Object.hasOwn(record, metric)) return undefined; + const val = record[metric]; + if (typeof val !== 'number' || !Number.isFinite(val)) return undefined; + return Object.is(val, -0) ? 0 : val; +} + +/** + * Return `true` iff `candidate` is at least as good as `incumbent` on every declared + * objective and strictly better on at least one objective. + */ +export function dominatesObjectives( + candidate: Readonly>, + incumbent: Readonly>, + objectives: readonly ObjectiveDirectionSpec[], +): boolean { + if (objectives.length === 0) return false; + let strictlyBetterInAtLeastOne = false; + for (const obj of objectives) { + const a = getOwnFiniteMetric(candidate, obj.metric); + const b = getOwnFiniteMetric(incumbent, obj.metric); + if (a === undefined || b === undefined || !Number.isFinite(a) || !Number.isFinite(b)) { + return false; + } + if (obj.direction === 'minimize') { + if (a > b) return false; + if (a < b) strictlyBetterInAtLeastOne = true; + } else { + if (a < b) return false; + if (a > b) strictlyBetterInAtLeastOne = true; + } + } + return strictlyBetterInAtLeastOne; +} + +function normalizedMinVector( + metrics: Readonly>, + objectives: readonly ObjectiveDirectionSpec[], + individualId: string, +): readonly number[] { + const vec: number[] = []; + for (const obj of objectives) { + const raw = getOwnFiniteMetric(metrics, obj.metric); + if (raw === undefined || Object.is(metrics[obj.metric], -0)) { + throw new EvolutionError( + 'EVOLUTION_SCHEMA_INVALID', + `individual "${individualId}" missing finite non-negative-zero metric "${obj.metric}"`, + ); + } + vec.push(obj.direction === 'minimize' ? raw : -raw); + } + return vec; +} + +function compareLexicographicVectors( + vecA: readonly number[], + idA: string, + vecB: readonly number[], + idB: string, +): number { + for (let i = 0; i < vecA.length; i++) { + const a = vecA[i]!; + const b = vecB[i]!; + if (a !== b) return a < b ? -1 : 1; + } + return idA < idB ? -1 : idA > idB ? 1 : 0; +} + +interface InternalCandidate { + readonly entry: ParetoCandidateEntry; + readonly normVec: readonly number[]; +} + +/** + * Deterministic NSGA-II non-dominated sorting (`paretoRank = 1..k`) and crowding distance + * computation with permutation-invariant tie-breaking by objective vector and `individualId`. + */ +export function computeNsga2Ranking( + entries: readonly ParetoCandidateEntry[], + objectives: readonly ObjectiveDirectionSpec[], +): readonly RankedParetoEntry[] { + if (objectives.length === 0) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'objectives must contain at least 1 entry'); + } + if (entries.length === 0) { + return []; + } + + const seenIds = new Set(); + const canonical: InternalCandidate[] = []; + for (const entry of entries) { + if (typeof entry.individualId !== 'string' || entry.individualId.length === 0) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'individualId must be a non-empty string'); + } + if (seenIds.has(entry.individualId)) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', `duplicate individualId "${entry.individualId}"`); + } + seenIds.add(entry.individualId); + canonical.push({ + entry, + normVec: normalizedMinVector(entry.metrics, objectives, entry.individualId), + }); + } + + // Canonicalize order upfront so all downstream comparisons are 100% input-permutation-invariant. + canonical.sort((a, b) => + compareLexicographicVectors(a.normVec, a.entry.individualId, b.normVec, b.entry.individualId), + ); + + const count = canonical.length; + const dominationCount = new Int32Array(count); + const dominatedSets: number[][] = Array.from({ length: count }, () => []); + + for (let p = 0; p < count; p++) { + const candP = canonical[p]!.entry.metrics; + for (let q = p + 1; q < count; q++) { + const candQ = canonical[q]!.entry.metrics; + if (dominatesObjectives(candP, candQ, objectives)) { + dominatedSets[p]!.push(q); + dominationCount[q] = dominationCount[q]! + 1; + } else if (dominatesObjectives(candQ, candP, objectives)) { + dominatedSets[q]!.push(p); + dominationCount[p] = dominationCount[p]! + 1; + } + } + } + + const fronts: number[][] = []; + let currentFront: number[] = []; + for (let i = 0; i < count; i++) { + if (dominationCount[i] === 0) currentFront.push(i); + } + + while (currentFront.length > 0) { + fronts.push(currentFront); + const nextFront: number[] = []; + for (const p of currentFront) { + for (const q of dominatedSets[p]!) { + const nextDom = dominationCount[q]! - 1; + dominationCount[q] = nextDom; + if (nextDom === 0) nextFront.push(q); + } + } + currentFront = nextFront; + } + + const results: RankedParetoEntry[] = []; + for (let frontIdx = 0; frontIdx < fronts.length; frontIdx++) { + const front = fronts[frontIdx]!; + const paretoRank = frontIdx + 1; + const distances = new Map(); + + if (front.length <= 2) { + for (const idx of front) { + distances.set(idx, Number.POSITIVE_INFINITY); + } + } else { + for (const idx of front) { + distances.set(idx, 0); + } + for (let m = 0; m < objectives.length; m++) { + const sortedByObj = [...front].sort((idxA, idxB) => { + const itemA = canonical[idxA]!; + const itemB = canonical[idxB]!; + const valA = itemA.normVec[m]!; + const valB = itemB.normVec[m]!; + if (valA !== valB) return valA < valB ? -1 : 1; + return compareLexicographicVectors( + itemA.normVec, + itemA.entry.individualId, + itemB.normVec, + itemB.entry.individualId, + ); + }); + + const minVal = canonical[sortedByObj[0]!]!.normVec[m]!; + const maxVal = canonical[sortedByObj[sortedByObj.length - 1]!]!.normVec[m]!; + const span = maxVal - minVal; + if (span <= 0) continue; + + distances.set(sortedByObj[0]!, Number.POSITIVE_INFINITY); + distances.set(sortedByObj[sortedByObj.length - 1]!, Number.POSITIVE_INFINITY); + for (let pos = 1; pos < sortedByObj.length - 1; pos++) { + const curIdx = sortedByObj[pos]!; + const prevDistance = distances.get(curIdx)!; + if (!Number.isFinite(prevDistance)) continue; + const prevVal = canonical[sortedByObj[pos - 1]!]!.normVec[m]!; + const nextVal = canonical[sortedByObj[pos + 1]!]!.normVec[m]!; + distances.set(curIdx, prevDistance + (nextVal - prevVal) / span); + } + } + } + + const frontRanked = front.map(idx => { + const item = canonical[idx]!; + const rawDist = distances.get(idx) ?? 0; + const crowdingDistance = Object.is(rawDist, -0) ? 0 : rawDist; + return { + item, + ranked: Object.freeze({ + individualId: item.entry.individualId, + metrics: item.entry.metrics, + paretoRank, + crowdingDistance, + }), + }; + }); + + frontRanked.sort((a, b) => { + const dA = a.ranked.crowdingDistance; + const dB = b.ranked.crowdingDistance; + if (dA !== dB) return dB > dA ? 1 : -1; + return compareLexicographicVectors( + a.item.normVec, + a.ranked.individualId, + b.item.normVec, + b.ranked.individualId, + ); + }); + + for (const r of frontRanked) { + results.push(r.ranked); + } + } + + return Object.freeze(results); +} + +// --------------------------------------------------------------------------- +// Exact deterministic reference-point Hypervolume (1D / 2D / 3D / d-D HSO sweep) +// --------------------------------------------------------------------------- + +function boxDominatesOrEquals(a: readonly number[], b: readonly number[], dims: number): boolean { + for (let i = 0; i < dims; i++) { + if (a[i]! < b[i]!) return false; + } + return true; +} + +function compareBoxLexDesc(a: readonly number[], b: readonly number[], dims: number): number { + for (let i = 0; i < dims; i++) { + if (a[i]! !== b[i]!) return b[i]! - a[i]!; + } + return 0; +} + +function filterNonDominatedBoxes(boxes: readonly (readonly number[])[], dims: number): (readonly number[])[] { + if (boxes.length <= 1) return [...boxes]; + const sorted = [...boxes].sort((a, b) => compareBoxLexDesc(a, b, dims)); + const kept: (readonly number[])[] = []; + for (const cand of sorted) { + let dominated = false; + for (const existing of kept) { + if (boxDominatesOrEquals(existing, cand, dims)) { + dominated = true; + break; + } + } + if (!dominated) kept.push(cand); + } + return kept; +} + +function computeOriginAnchoredBoxUnionVolume( + rawBoxes: readonly (readonly number[])[], + dims: number, +): number { + if (rawBoxes.length === 0) return 0; + if (dims === 1) { + let maxLen = 0; + for (const box of rawBoxes) { + if (box[0]! > maxLen) maxLen = box[0]!; + } + return maxLen; + } + + const boxes = filterNonDominatedBoxes(rawBoxes, dims); + if (dims === 2) { + // Sorted by dim 0 descending -> non-dominated 2D boxes have strictly increasing dim 1. + let volume = 0; + let coveredDim1 = 0; + for (const box of boxes) { + const l0 = box[0]!; + const l1 = box[1]!; + if (l1 > coveredDim1) { + volume += l0 * (l1 - coveredDim1); + coveredDim1 = l1; + } + } + return volume; + } + + // Exact dimension-sweep along coordinate `lastDim = dims - 1` descending. + const lastDim = dims - 1; + const byHeightDesc = [...boxes].sort((a, b) => { + if (a[lastDim]! !== b[lastDim]!) return b[lastDim]! - a[lastDim]!; + return compareBoxLexDesc(a, b, lastDim); + }); + + let totalVolume = 0; + const activeProjected: (readonly number[])[] = []; + for (let i = 0; i < byHeightDesc.length; i++) { + const current = byHeightDesc[i]!; + activeProjected.push(current); + const currentHeight = current[lastDim]!; + const nextHeight = i + 1 < byHeightDesc.length ? byHeightDesc[i + 1]![lastDim]! : 0; + const sliceThickness = currentHeight - nextHeight; + if (sliceThickness > 0) { + const sliceMeasure = computeOriginAnchoredBoxUnionVolume(activeProjected, lastDim); + totalVolume += sliceThickness * sliceMeasure; + } + } + return totalVolume; +} + +/** + * Compute exact deterministic bounded hypervolume of `points` strictly dominating `referencePoint` + * across `objectives` (`1..8` objectives, Monte-Carlo-free). + */ +export function computeHypervolume( + points: readonly Readonly>[], + objectives: readonly ObjectiveDirectionSpec[], + referencePoint: Readonly>, +): number { + if (objectives.length === 0 || objectives.length > 8) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'objectives length must be within 1..8'); + } + const refCoords: number[] = []; + for (const obj of objectives) { + const r = getOwnFiniteMetric(referencePoint, obj.metric); + if (r === undefined) { + throw new EvolutionError( + 'EVOLUTION_SCHEMA_INVALID', + `referencePoint missing finite coordinate for "${obj.metric}"`, + ); + } + refCoords.push(r); + } + + if (points.length === 0) return 0; + + const boxes: (readonly number[])[] = []; + for (const pt of points) { + const lengths: number[] = []; + let strictlyDominatesRef = true; + for (let m = 0; m < objectives.length; m++) { + const obj = objectives[m]!; + const val = getOwnFiniteMetric(pt, obj.metric); + if (val === undefined) { + strictlyDominatesRef = false; + break; + } + const refVal = refCoords[m]!; + const len = obj.direction === 'minimize' ? refVal - val : val - refVal; + if (len <= 0) { + strictlyDominatesRef = false; + break; + } + lengths.push(len); + } + if (strictlyDominatesRef) { + boxes.push(lengths); + } + } + + const hv = computeOriginAnchoredBoxUnionVolume(boxes, objectives.length); + return Object.is(hv, -0) ? 0 : hv; +} + +/** Compute exact deterministic hypervolume delta `HV(nextPoints) - HV(previousPoints)`. */ +export function computeHypervolumeDelta( + previousPoints: readonly Readonly>[], + nextPoints: readonly Readonly>[], + objectives: readonly ObjectiveDirectionSpec[], + referencePoint: Readonly>, +): number { + const prevHv = computeHypervolume(previousPoints, objectives, referencePoint); + const nextHv = computeHypervolume(nextPoints, objectives, referencePoint); + const delta = nextHv - prevHv; + return Object.is(delta, -0) ? 0 : delta; +} + +// --------------------------------------------------------------------------- +// Deterministic MAP-Elites Niche Key & Fitness Scalarization +// --------------------------------------------------------------------------- + +const DIAGNOSTIC_FIELD_ALIASES: Readonly> = Object.freeze({ + bound_pipeline: 'boundPipeline', + boundPipeline: 'boundPipeline', + roofline_headroom: 'rooflineHeadroom', + rooflineHeadroom: 'rooflineHeadroom', + achieved_sol_pct: 'achievedSolPct', + achievedSolPct: 'achievedSolPct', + arithmetic_intensity: 'arithmeticIntensity', + arithmeticIntensity: 'arithmeticIntensity', + occupancy_band: 'occupancyPct', + occupancy_pct: 'occupancyPct', + occupancyPct: 'occupancyPct', + register_count: 'registerCount', + registerCount: 'registerCount', + shared_mem_bytes: 'sharedMemBytes', + sharedMemBytes: 'sharedMemBytes', + local_spill_bytes: 'localSpillBytes', + localSpillBytes: 'localSpillBytes', + l2_hit_pct: 'l2HitPct', + l2HitPct: 'l2HitPct', + bank_conflict_pct: 'bankConflictPct', + bankConflictPct: 'bankConflictPct', +}); + +function lookupDiagnosticField( + diagnostics: HardwareDiagnostics | undefined, + key: string, +): string | number | undefined { + if (!diagnostics) return undefined; + const mappedKey = Object.hasOwn(DIAGNOSTIC_FIELD_ALIASES, key) + ? DIAGNOSTIC_FIELD_ALIASES[key] + : undefined; + if (mappedKey !== undefined && Object.hasOwn(diagnostics, mappedKey)) { + const val = diagnostics[mappedKey]; + if (typeof val === 'string' || typeof val === 'number') return val; + } + return undefined; +} + +function formatEdgeNumber(value: number): string { + return Object.is(value, -0) ? '0' : String(value); +} + +/** + * Map `metrics` and optional `hardwareDiagnostics` onto a canonical MAP-Elites `nicheKey` + * across `1..4` declared `enum` or `numeric_bins` axes. + */ +export function computeNicheKey( + nicheAxes: readonly EvolutionNicheAxis[], + metrics: Readonly>, + hardwareDiagnostics?: HardwareDiagnostics, +): string { + if (nicheAxes.length < 1 || nicheAxes.length > 4) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'nicheAxes length must be within 1..4'); + } + + const tokens: string[] = []; + for (const axis of nicheAxes) { + const targetField = axis.field ?? axis.id; + if (axis.kind === 'enum') { + let observed: string | undefined; + if (Object.hasOwn(metrics, targetField) && typeof metrics[targetField] === 'string') { + observed = metrics[targetField] as string; + } else { + const diagVal = lookupDiagnosticField(hardwareDiagnostics, targetField); + if (typeof diagVal === 'string') observed = diagVal; + } + if (observed !== undefined && axis.values.includes(observed)) { + tokens.push(`${axis.id}=${observed}`); + } else { + tokens.push(`${axis.id}=~unclassified`); + } + } else { + const edges = axis.edges; + if (edges.length < 2) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', `numeric_bins axis "${axis.id}" requires >= 2 edges`); + } + let numericVal: number | undefined; + if (Object.hasOwn(metrics, targetField) && typeof metrics[targetField] === 'number') { + const mVal = metrics[targetField] as number; + if (Number.isFinite(mVal)) numericVal = mVal; + } + if (numericVal === undefined) { + const diagVal = lookupDiagnosticField(hardwareDiagnostics, targetField); + if (typeof diagVal === 'number' && Number.isFinite(diagVal)) numericVal = diagVal; + } + + if (numericVal === undefined) { + tokens.push(`${axis.id}=~missing`); + continue; + } + const firstEdge = edges[0]!; + const lastEdge = edges[edges.length - 1]!; + if (numericVal < firstEdge) { + tokens.push(`${axis.id}=<-inf,${formatEdgeNumber(firstEdge)})`); + } else if (numericVal > lastEdge) { + tokens.push(`${axis.id}=(${formatEdgeNumber(lastEdge)},+inf)`); + } else { + let placed = false; + for (let i = 0; i < edges.length - 1; i++) { + const low = edges[i]!; + const high = edges[i + 1]!; + const isLastBin = i === edges.length - 2; + if (numericVal >= low && (isLastBin ? numericVal <= high : numericVal < high)) { + const closeBracket = isLastBin ? ']' : ')'; + tokens.push(`${axis.id}=[${formatEdgeNumber(low)},${formatEdgeNumber(high)}${closeBracket}`); + placed = true; + break; + } + } + if (!placed) { + tokens.push(`${axis.id}=~missing`); + } + } + } + } + + return tokens.join('|'); +} + +/** Build `[min, max]` normalization reference statistics across observed metric records. */ +export function computeObjectiveReferenceStats( + entries: readonly Readonly>[], + objectives: readonly ObjectiveDirectionSpec[], +): ObjectiveReferenceStats { + const out = Object.create(null) as Record; + for (const obj of objectives) { + let min = Number.POSITIVE_INFINITY; + let max = Number.NEGATIVE_INFINITY; + for (const entry of entries) { + const val = getOwnFiniteMetric(entry, obj.metric); + if (val === undefined) continue; + if (val < min) min = val; + if (val > max) max = val; + } + if (Number.isFinite(min) && Number.isFinite(max)) { + const stat = Object.create(null) as { min: number; max: number }; + stat.min = min; + stat.max = max; + out[obj.metric] = stat; + } + } + return out; +} + +/** + * Compute higher-is-better scalar fitness over `objectives` for island median fitness + * and stepping-stone weight calculation. + */ +export function scalarizeFitness( + metrics: Readonly>, + objectives: readonly ObjectiveDirectionSpec[], + referenceStats?: ObjectiveReferenceStats, +): number { + if (objectives.length === 0) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'objectives must contain at least 1 entry'); + } + let weightedSum = 0; + let totalWeight = 0; + for (const obj of objectives) { + const val = getOwnFiniteMetric(metrics, obj.metric); + if (val === undefined) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', `metrics missing finite value for "${obj.metric}"`); + } + const stat = referenceStats && Object.hasOwn(referenceStats, obj.metric) + ? referenceStats[obj.metric] + : undefined; + const weight = stat?.weight ?? 1; + if (!Number.isFinite(weight) || weight <= 0) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', `objective weight for "${obj.metric}" must be > 0`); + } + let score: number; + if (stat !== undefined) { + const span = stat.max - stat.min; + if (span <= 0) { + score = 0.5; + } else if (obj.direction === 'minimize') { + score = (stat.max - val) / span; + } else { + score = (val - stat.min) / span; + } + } else { + score = obj.direction === 'minimize' ? -val : val; + } + weightedSum += weight * score; + totalWeight += weight; + } + const result = weightedSum / totalWeight; + return Object.is(result, -0) ? 0 : result; +} + +/** Compute deterministic median over finite scalar fitness values (`0` when empty). */ +export function computeMedianFitness(fitnessValues: readonly number[]): number { + if (fitnessValues.length === 0) return 0; + const sorted: number[] = []; + for (const v of fitnessValues) { + if (!Number.isFinite(v)) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'fitness value must be finite'); + } + sorted.push(Object.is(v, -0) ? 0 : v); + } + sorted.sort((a, b) => a - b); + const mid = Math.floor(sorted.length / 2); + const median = sorted.length % 2 === 1 + ? sorted[mid]! + : (sorted[mid - 1]! + sorted[mid]!) / 2; + return Object.is(median, -0) ? 0 : median; +} diff --git a/packages/evolution/src/sampler.ts b/packages/evolution/src/sampler.ts new file mode 100644 index 0000000..d999a2f --- /dev/null +++ b/packages/evolution/src/sampler.ts @@ -0,0 +1,784 @@ +import { createHash, randomBytes } from 'node:crypto'; +import { constants as fsConstants } from 'node:fs'; +import { chmod, lstat, mkdir, open, rename, unlink } from 'node:fs/promises'; +import { join, resolve } from 'node:path'; +import { SecretScrubber, type Digest } from '@loopwright/core'; +import { computeMedianFitness } from './pareto.js'; +import { canonicalizeJson } from './schema.js'; +import { + CONTEXT_SLICE_MAX_BYTES, + DISPATCH_MANIFEST_MAX_RULES, + EvolutionError, + type EvolutionModelBanditStrategy, + type IndividualRecord, + type LineageRole, + type ModelBanditArmRecord, +} from './types.js'; + +const DEFAULT_SECRET_SCRUBBER = new SecretScrubber(); +const DEFAULT_SLICE_MAX_BYTES = 16_384; +const DEFAULT_UCB1_EXPLORATION_C = Math.SQRT2; +const DEFAULT_REWARD_MAX_EXPONENT = 20; + +/** + * Stepping-stone novelty-decayed parent sampling weight: + * $w_i = \sigma(\lambda(F(P_i) - \alpha_0)) \cdot (1 + N(P_i))^{-1}$. + */ +export function computeSteppingStoneSamplingWeight( + fitness: number, + islandMedianFitness: number, + offspringCount: number, + noveltyDecayLambda: number, +): number { + if ( + !Number.isFinite(fitness) + || !Number.isFinite(islandMedianFitness) + || !Number.isFinite(offspringCount) + || !Number.isFinite(noveltyDecayLambda) + ) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'stepping-stone weight inputs must be finite numbers'); + } + const scaled = Math.max(-60, Math.min(60, noveltyDecayLambda * (fitness - islandMedianFitness))); + const performanceScore = 1 / (1 + Math.exp(-scaled)); + const noveltyFactor = 1 / (1 + Math.max(0, offspringCount)); + return performanceScore * noveltyFactor; +} + +function rotl32(x: number, k: number): number { + return ((x << k) | (x >>> (32 - k))) >>> 0; +} + +/** + * Create a deterministic `xoshiro128**` pseudo-random generator in `[0, 1)` seeded via SHA-256. + */ +export function createSeededPrng(seed: string | Uint8Array): () => number { + const digest = typeof seed === 'string' + ? createHash('sha256').update(seed, 'utf8').digest() + : createHash('sha256').update(seed).digest(); + + let s0 = digest.readUInt32LE(0); + let s1 = digest.readUInt32LE(4); + let s2 = digest.readUInt32LE(8); + let s3 = digest.readUInt32LE(12); + if ((s0 | s1 | s2 | s3) === 0) { + s0 = 0x9e3779b9; + } + + return (): number => { + const result = Math.imul(rotl32(Math.imul(s1, 5) >>> 0, 7), 9) >>> 0; + const t = (s1 << 9) >>> 0; + s2 = (s2 ^ s0) >>> 0; + s3 = (s3 ^ s1) >>> 0; + s1 = (s1 ^ s2) >>> 0; + s0 = (s0 ^ s3) >>> 0; + s2 = (s2 ^ t) >>> 0; + s3 = rotl32(s3, 11); + return result / 4_294_967_296; + }; +} + +export interface SampledParentEntry { + readonly individual: IndividualRecord; + readonly role: LineageRole; + readonly sourceIslandId: number; + readonly weight: number; +} + +export interface SampledParentSelection { + readonly primary: SampledParentEntry; + readonly secondary: readonly SampledParentEntry[]; + readonly islandMedianFitness: number; +} + +export interface SampleParentsOptions { + readonly islandId: number; + readonly localCandidates: readonly IndividualRecord[]; + readonly inspirationCandidates?: readonly IndividualRecord[]; + readonly maxCrossoversPerPrompt: number; + readonly noveltyDecayLambda: number; + readonly seed: string | Uint8Array; +} + +function isFertileCandidate(ind: IndividualRecord): boolean { + return ind.status === 'passed' || ind.status === 'soft_passed'; +} + +function resolveCandidateFitness(ind: IndividualRecord): number { + return ind.scalarFitness !== null && Number.isFinite(ind.scalarFitness) ? ind.scalarFitness : 0; +} + +function weightedPickIndex(weights: readonly number[], prng: () => number): number { + let total = 0; + for (const w of weights) total += w; + if (total <= 0) { + return Math.min(weights.length - 1, Math.floor(prng() * weights.length)); + } + const threshold = prng() * total; + let cumulative = 0; + for (let i = 0; i < weights.length; i++) { + cumulative += weights[i]!; + if (threshold < cumulative) return i; + } + return weights.length - 1; +} + +/** + * Deterministically sample `1` local primary parent plus up to `maxCrossoversPerPrompt` (`0..4`) + * distinct `crossover_donor` or `inspiration` parents using stepping-stone novelty-decayed weights. + */ +export function sampleParents(options: SampleParentsOptions): SampledParentSelection { + if (!Number.isSafeInteger(options.maxCrossoversPerPrompt) || options.maxCrossoversPerPrompt < 0 || options.maxCrossoversPerPrompt > 4) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'maxCrossoversPerPrompt must be within 0..4'); + } + if (!Number.isFinite(options.noveltyDecayLambda) || options.noveltyDecayLambda <= 0) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'noveltyDecayLambda must be > 0'); + } + + const fertileLocal = options.localCandidates + .filter(c => isFertileCandidate(c) && c.islandId === options.islandId) + .sort((a, b) => (a.individualId < b.individualId ? -1 : a.individualId > b.individualId ? 1 : 0)); + + if (fertileLocal.length === 0) { + throw new EvolutionError( + 'EVOLUTION_NOT_FOUND', + `island ${options.islandId} has zero fertile local parent candidates`, + ); + } + + const islandMedianFitness = computeMedianFitness(fertileLocal.map(c => resolveCandidateFitness(c))); + const prng = createSeededPrng(options.seed); + + const localWeights = fertileLocal.map(c => + computeSteppingStoneSamplingWeight( + resolveCandidateFitness(c), + islandMedianFitness, + c.offspringCount, + options.noveltyDecayLambda, + ), + ); + const primaryIdx = weightedPickIndex(localWeights, prng); + const primaryIndividual = fertileLocal[primaryIdx]!; + const primary: SampledParentEntry = Object.freeze({ + individual: primaryIndividual, + role: 'primary', + sourceIslandId: primaryIndividual.islandId, + weight: localWeights[primaryIdx]!, + }); + + const usedIds = new Set([primaryIndividual.individualId]); + const pool: SampledParentEntry[] = []; + + for (let i = 0; i < fertileLocal.length; i++) { + const cand = fertileLocal[i]!; + if (usedIds.has(cand.individualId)) continue; + usedIds.add(cand.individualId); + pool.push({ + individual: cand, + role: 'crossover_donor', + sourceIslandId: cand.islandId, + weight: localWeights[i]!, + }); + } + + const inspirations = (options.inspirationCandidates ?? []) + .filter(c => isFertileCandidate(c)) + .sort((a, b) => (a.individualId < b.individualId ? -1 : a.individualId > b.individualId ? 1 : 0)); + for (const insp of inspirations) { + if (usedIds.has(insp.individualId)) continue; + usedIds.add(insp.individualId); + const weight = computeSteppingStoneSamplingWeight( + resolveCandidateFitness(insp), + islandMedianFitness, + insp.offspringCount, + options.noveltyDecayLambda, + ); + pool.push({ + individual: insp, + role: 'inspiration', + sourceIslandId: insp.islandId, + weight, + }); + } + + const secondary: SampledParentEntry[] = []; + const targetSecondaryCount = Math.min(options.maxCrossoversPerPrompt, pool.length); + for (let pick = 0; pick < targetSecondaryCount; pick++) { + const idx = weightedPickIndex(pool.map(p => p.weight), prng); + const chosen = pool.splice(idx, 1)[0]!; + secondary.push(Object.freeze(chosen)); + } + + return Object.freeze({ + primary, + secondary: Object.freeze(secondary), + islandMedianFitness, + }); +} + +// --------------------------------------------------------------------------- +// Island Elitism Ring Migration +// --------------------------------------------------------------------------- + +export interface RingMigrationElite { + readonly sourceIslandId: number; + readonly targetIslandId: number; + readonly individual: IndividualRecord; + readonly role: 'inspiration'; +} + +export interface SelectRingMigrationOptions { + readonly generation: number; + readonly islands: number; + readonly migrationIntervalGenerations: number; + readonly maxMigrationElites: number; + readonly individuals: readonly IndividualRecord[]; +} + +function compareEliteQuality(a: IndividualRecord, b: IndividualRecord): number { + const rankA = a.paretoRank ?? Number.MAX_SAFE_INTEGER; + const rankB = b.paretoRank ?? Number.MAX_SAFE_INTEGER; + if (rankA !== rankB) return rankA - rankB; + + const fitA = a.scalarFitness ?? Number.NEGATIVE_INFINITY; + const fitB = b.scalarFitness ?? Number.NEGATIVE_INFINITY; + if (fitA !== fitB) return fitB - fitA; + + const crowdA = a.crowdingDistance ?? -1; + const crowdB = b.crowdingDistance ?? -1; + if (crowdA !== crowdB) return crowdB > crowdA ? 1 : -1; + + return a.individualId < b.individualId ? -1 : a.individualId > b.individualId ? 1 : 0; +} + +/** + * Select ring-migration elites across `(i + 1) % islands` on `migrationIntervalGenerations` + * boundaries while strictly keeping every island's rank-1 leader(s) local (**Island Elitism**). + */ +export function selectRingMigrationElites( + options: SelectRingMigrationOptions, +): readonly RingMigrationElite[] { + if ( + !Number.isSafeInteger(options.islands) || options.islands < 1 || options.islands > 16 + || !Number.isSafeInteger(options.migrationIntervalGenerations) || options.migrationIntervalGenerations < 1 + || !Number.isSafeInteger(options.maxMigrationElites) || options.maxMigrationElites < 0 + || !Number.isSafeInteger(options.generation) || options.generation < 0 + ) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'invalid ring migration parameters'); + } + + if ( + options.islands <= 1 + || options.maxMigrationElites === 0 + || options.generation === 0 + || options.generation % options.migrationIntervalGenerations !== 0 + ) { + return Object.freeze([]); + } + + const migrations: RingMigrationElite[] = []; + for (let sourceIslandId = 0; sourceIslandId < options.islands; sourceIslandId++) { + const targetIslandId = (sourceIslandId + 1) % options.islands; + const bestByNiche = new Map(); + + for (const ind of options.individuals) { + if (ind.islandId !== sourceIslandId || !isFertileCandidate(ind) || ind.nicheKey === null) { + continue; + } + const incumbent = bestByNiche.get(ind.nicheKey); + if (!incumbent || compareEliteQuality(ind, incumbent) < 0) { + bestByNiche.set(ind.nicheKey, ind); + } + } + + // Island Elitism: strictly exclude all rank-1 leaders (only paretoRank >= 2 may migrate). + const nonRank1Elites = [...bestByNiche.values()] + .filter(elite => elite.paretoRank !== null && elite.paretoRank > 1) + .sort(compareEliteQuality); + + const selected = nonRank1Elites.slice(0, options.maxMigrationElites); + for (const individual of selected) { + migrations.push( + Object.freeze({ + sourceIslandId, + targetIslandId, + individual, + role: 'inspiration' as const, + }), + ); + } + } + + return Object.freeze(migrations); +} + +// --------------------------------------------------------------------------- +// Read-only (0o400) O_NOFOLLOW Multi-Parent Context File Staging +// --------------------------------------------------------------------------- + +export interface ParentContextInput { + readonly individual: IndividualRecord; + readonly role: Exclude; + readonly codeSlice: string; +} + +export interface StagedParentContextFile { + readonly individualId: string; + readonly role: LineageRole; + readonly fileName: string; + readonly filePath: string; + readonly byteLength: number; + readonly digest: Digest; +} + +export interface StagedMultiParentContext { + readonly stagingDir: string; + readonly files: readonly StagedParentContextFile[]; +} + +export interface StageMultiParentContextOptions { + readonly stagingDir: string; + readonly parents: readonly ParentContextInput[]; + readonly maxCrossoversPerPrompt: number; + readonly maxCodeSliceBytes?: number; + readonly scrubber?: SecretScrubber; +} + +export interface PortfolioSpecialistContextInput { + readonly individual: IndividualRecord; + readonly bucketId?: string | null; + readonly codeSlice: string; +} + +export interface StagePortfolioSpecialistContextOptions { + readonly stagingDir: string; + readonly specialists: readonly PortfolioSpecialistContextInput[]; + readonly maxSpecialists?: number; + readonly maxCodeSliceBytes?: number; + readonly scrubber?: SecretScrubber; +} + +function truncateUtf8ByBytes(text: string, maxBytes: number): string { + if (Buffer.byteLength(text, 'utf8') <= maxBytes) return text; + const buf = Buffer.from(text, 'utf8'); + let end = maxBytes; + while (end > 0 && (buf[end]! & 0xc0) === 0x80) { + end--; + } + return buf.subarray(0, end).toString('utf8'); +} + +async function ensureContextStagingDir(dirPath: string): Promise { + const existing = await lstat(dirPath).catch((err: NodeJS.ErrnoException) => { + if (err.code === 'ENOENT') return null; + if (err.code === 'ELOOP') { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `symlink forbidden along ${dirPath}`, dirPath); + } + throw err; + }); + + if (existing === null) { + await mkdir(dirPath, { mode: 0o700, recursive: false }).catch((err: NodeJS.ErrnoException) => { + if (err.code !== 'EEXIST') throw err; + }); + } else if (existing.isSymbolicLink()) { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `stagingDir cannot be a symlink: ${dirPath}`, dirPath); + } else if (!existing.isDirectory()) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', `stagingDir must be a directory: ${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('EVOLUTION_SYMLINK_FORBIDDEN', `symlink stagingDir forbidden: ${dirPath}`, dirPath); + } + throw err; + }); + await handle.close(); +} + +/** + * Stage bounded, `SecretScrubber`-clean, `O_NOFOLLOW`, `0o400` read-only parent context files + * containing bounded code slices, `bucketMetrics`, and `hardwareDiagnostics`. + */ +export async function stageMultiParentContextFiles( + options: StageMultiParentContextOptions, +): Promise { + if (!Number.isSafeInteger(options.maxCrossoversPerPrompt) || options.maxCrossoversPerPrompt < 0 || options.maxCrossoversPerPrompt > 4) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'maxCrossoversPerPrompt must be within 0..4'); + } + const maxSliceBytes = options.maxCodeSliceBytes ?? DEFAULT_SLICE_MAX_BYTES; + if (!Number.isSafeInteger(maxSliceBytes) || maxSliceBytes < 64 || maxSliceBytes > CONTEXT_SLICE_MAX_BYTES) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', `maxCodeSliceBytes must be within 64..${CONTEXT_SLICE_MAX_BYTES}`); + } + if (options.parents.length < 1 || options.parents.length > 1 + options.maxCrossoversPerPrompt) { + throw new EvolutionError( + 'EVOLUTION_SCHEMA_INVALID', + `parents length must be within 1..${1 + options.maxCrossoversPerPrompt}`, + ); + } + + const primaryCount = options.parents.filter(p => p.role === 'primary').length; + if (primaryCount !== 1) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'parents must include exactly 1 primary parent'); + } + + const seenParentIds = new Set(); + for (const parent of options.parents) { + if (seenParentIds.has(parent.individual.individualId)) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', `duplicate parent individual "${parent.individual.individualId}"`); + } + seenParentIds.add(parent.individual.individualId); + } + + const scrubber = options.scrubber ?? DEFAULT_SECRET_SCRUBBER; + const resolvedDir = resolve(options.stagingDir); + await ensureContextStagingDir(resolvedDir); + + const noFollow = 'O_NOFOLLOW' in fsConstants ? fsConstants.O_NOFOLLOW : 0; + const files: StagedParentContextFile[] = []; + + for (let i = 0; i < options.parents.length; i++) { + const item = options.parents[i]!; + const boundedSlice = truncateUtf8ByBytes(item.codeSlice, maxSliceBytes); + const payload: Record = { + individualId: item.individual.individualId, + role: item.role, + islandId: item.individual.islandId, + generation: item.individual.generation, + nicheKey: item.individual.nicheKey, + paretoRank: item.individual.paretoRank, + metrics: item.individual.metrics, + codeSlice: boundedSlice, + ...(item.individual.bucketMetrics !== undefined ? { bucketMetrics: item.individual.bucketMetrics } : {}), + ...(item.individual.hardwareDiagnostics !== undefined ? { hardwareDiagnostics: item.individual.hardwareDiagnostics } : {}), + }; + + const serialized = `${canonicalizeJson(payload)}\n`; + if (scrubber.containsSecret(serialized)) { + throw new EvolutionError( + 'SECRET_LEAK_DETECTED', + `secret material detected in parent context for "${item.individual.individualId}"`, + ); + } + + const safeSlug = item.individual.individualId.replace(/[^A-Za-z0-9._-]/g, '_'); + const fileName = `parent-${i}-${item.role}-${safeSlug}.json`; + const finalPath = join(resolvedDir, fileName); + + const existing = await lstat(finalPath).catch((err: NodeJS.ErrnoException) => { + if (err.code === 'ENOENT') return null; + if (err.code === 'ELOOP') { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `symlink forbidden at ${finalPath}`, finalPath); + } + throw err; + }); + if (existing !== null) { + if (existing.isSymbolicLink()) { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `target context file is a symlink: ${finalPath}`, finalPath); + } + throw new EvolutionError('EVOLUTION_CONFLICT', `context file already exists: ${finalPath}`, finalPath); + } + + const bytes = Buffer.from(serialized, 'utf8'); + const hex = createHash('sha256').update(bytes).digest('hex'); + const tempPath = join(resolvedDir, `.tmp-${fileName}-${randomBytes(6).toString('hex')}`); + + const handle = await open( + tempPath, + fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_WRONLY | noFollow, + 0o600, + ); + try { + let written = 0; + while (written < bytes.byteLength) { + const res = await handle.write(bytes, written, bytes.byteLength - written, written); + written += res.bytesWritten; + } + await handle.sync(); + } catch (err) { + await handle.close().catch(() => undefined); + await unlink(tempPath).catch(() => undefined); + throw err; + } + await handle.close(); + + try { + await chmod(tempPath, 0o400); + await rename(tempPath, finalPath); + } catch (err) { + await chmod(tempPath, 0o600).catch(() => undefined); + await unlink(tempPath).catch(() => undefined); + throw err; + } + + files.push( + Object.freeze({ + individualId: item.individual.individualId, + role: item.role, + fileName, + filePath: finalPath, + byteLength: bytes.byteLength, + digest: Object.freeze({ algorithm: 'sha256' as const, hex }), + }), + ); + } + + return Object.freeze({ + stagingDir: resolvedDir, + files: Object.freeze(files), + }); +} + +/** + * Stage bounded, `SecretScrubber`-clean, `O_NOFOLLOW`, `0o400` read-only specialist context files + * (`1..64` specialist winners matching `DISPATCH_MANIFEST_MAX_RULES`) for portfolio synthesis. + */ +export async function stagePortfolioSpecialistContextFiles( + options: StagePortfolioSpecialistContextOptions, +): Promise { + const maxSpecialists = options.maxSpecialists ?? DISPATCH_MANIFEST_MAX_RULES; + if (!Number.isSafeInteger(maxSpecialists) || maxSpecialists < 1 || maxSpecialists > DISPATCH_MANIFEST_MAX_RULES) { + throw new EvolutionError( + 'EVOLUTION_SCHEMA_INVALID', + `maxSpecialists must be within 1..${DISPATCH_MANIFEST_MAX_RULES}`, + ); + } + const maxSliceBytes = options.maxCodeSliceBytes ?? DEFAULT_SLICE_MAX_BYTES; + if (!Number.isSafeInteger(maxSliceBytes) || maxSliceBytes < 64 || maxSliceBytes > CONTEXT_SLICE_MAX_BYTES) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', `maxCodeSliceBytes must be within 64..${CONTEXT_SLICE_MAX_BYTES}`); + } + if (options.specialists.length < 1 || options.specialists.length > maxSpecialists) { + throw new EvolutionError( + 'EVOLUTION_SCHEMA_INVALID', + `specialists length must be within 1..${maxSpecialists}`, + ); + } + + const seenSpecialistIds = new Set(); + for (const spec of options.specialists) { + if (seenSpecialistIds.has(spec.individual.individualId)) { + throw new EvolutionError( + 'EVOLUTION_SCHEMA_INVALID', + `duplicate portfolio specialist individual "${spec.individual.individualId}"`, + ); + } + seenSpecialistIds.add(spec.individual.individualId); + } + + const scrubber = options.scrubber ?? DEFAULT_SECRET_SCRUBBER; + const resolvedDir = resolve(options.stagingDir); + await ensureContextStagingDir(resolvedDir); + + const noFollow = 'O_NOFOLLOW' in fsConstants ? fsConstants.O_NOFOLLOW : 0; + const files: StagedParentContextFile[] = []; + + for (let i = 0; i < options.specialists.length; i++) { + const item = options.specialists[i]!; + const boundedSlice = truncateUtf8ByBytes(item.codeSlice, maxSliceBytes); + const effectiveBucketId = item.bucketId !== undefined ? item.bucketId : item.individual.bucketId; + const payload: Record = { + individualId: item.individual.individualId, + role: 'portfolio_member', + bucketId: effectiveBucketId, + islandId: item.individual.islandId, + generation: item.individual.generation, + nicheKey: item.individual.nicheKey, + paretoRank: item.individual.paretoRank, + metrics: item.individual.metrics, + codeSlice: boundedSlice, + ...(item.individual.bucketMetrics !== undefined ? { bucketMetrics: item.individual.bucketMetrics } : {}), + ...(item.individual.hardwareDiagnostics !== undefined ? { hardwareDiagnostics: item.individual.hardwareDiagnostics } : {}), + }; + + const serialized = `${canonicalizeJson(payload)}\n`; + if (scrubber.containsSecret(serialized)) { + throw new EvolutionError( + 'SECRET_LEAK_DETECTED', + `secret material detected in portfolio specialist context for "${item.individual.individualId}"`, + ); + } + + const safeBucket = (effectiveBucketId ?? 'bucket').replace(/[^A-Za-z0-9._-]/g, '_').slice(0, 32); + const safeSlug = item.individual.individualId.replace(/[^A-Za-z0-9._-]/g, '_'); + const fileName = `specialist-${i}-${safeBucket}-${safeSlug}.json`; + const finalPath = join(resolvedDir, fileName); + + const existing = await lstat(finalPath).catch((err: NodeJS.ErrnoException) => { + if (err.code === 'ENOENT') return null; + if (err.code === 'ELOOP') { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `symlink forbidden at ${finalPath}`, finalPath); + } + throw err; + }); + if (existing !== null) { + if (existing.isSymbolicLink()) { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `target context file is a symlink: ${finalPath}`, finalPath); + } + throw new EvolutionError('EVOLUTION_CONFLICT', `context file already exists: ${finalPath}`, finalPath); + } + + const bytes = Buffer.from(serialized, 'utf8'); + const hex = createHash('sha256').update(bytes).digest('hex'); + const tempPath = join(resolvedDir, `.tmp-${fileName}-${randomBytes(6).toString('hex')}`); + + const handle = await open( + tempPath, + fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_WRONLY | noFollow, + 0o600, + ); + try { + let written = 0; + while (written < bytes.byteLength) { + const res = await handle.write(bytes, written, bytes.byteLength - written, written); + written += res.bytesWritten; + } + await handle.sync(); + } catch (err) { + await handle.close().catch(() => undefined); + await unlink(tempPath).catch(() => undefined); + throw err; + } + await handle.close(); + + try { + await chmod(tempPath, 0o400); + await rename(tempPath, finalPath); + } catch (err) { + await chmod(tempPath, 0o600).catch(() => undefined); + await unlink(tempPath).catch(() => undefined); + throw err; + } + + files.push( + Object.freeze({ + individualId: item.individual.individualId, + role: 'portfolio_member' as const, + fileName, + filePath: finalPath, + byteLength: bytes.byteLength, + digest: Object.freeze({ algorithm: 'sha256' as const, hex }), + }), + ); + } + + return Object.freeze({ + stagingDir: resolvedDir, + files: Object.freeze(files), + }); +} + +// --------------------------------------------------------------------------- +// Model Selector (`deterministic-round-robin` | `ucb1`) & Truncated Exp Reward +// --------------------------------------------------------------------------- + +/** + * Truncated parent-relative improvement reward: + * $r_u = \exp(\max(r - r_{\text{parent}}, 0)) - 1$. + */ +export function computeTruncatedImprovementReward( + childFitness: number, + parentFitness: number, + maxExponent = DEFAULT_REWARD_MAX_EXPONENT, +): number { + if (!Number.isFinite(childFitness) || !Number.isFinite(parentFitness) || !Number.isFinite(maxExponent) || maxExponent <= 0) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'reward inputs must be finite numbers'); + } + const improvement = Math.max(0, childFitness - parentFitness); + if (improvement === 0) return 0; + const clamped = Math.min(improvement, maxExponent); + return Math.expm1(clamped); +} + +export interface SelectModelCandidateOptions { + readonly strategy: EvolutionModelBanditStrategy; + readonly modelIds: readonly string[]; + readonly arms: readonly ModelBanditArmRecord[]; + readonly sequenceIndex: number; + readonly explorationConstant?: number; +} + +export interface SelectedModelCandidate { + readonly modelId: string; + readonly reason: 'round_robin' | 'initial_exploration' | 'ucb1_score'; + readonly score: number | null; +} + +/** + * Deterministically select the next model from `1..16` declared `modelIds` using + * `'deterministic-round-robin'` or `'ucb1'`. + */ +export function selectModelCandidate(options: SelectModelCandidateOptions): SelectedModelCandidate { + if (options.modelIds.length < 1 || options.modelIds.length > 16) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'modelIds length must be within 1..16'); + } + if (!Number.isSafeInteger(options.sequenceIndex) || options.sequenceIndex < 0) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'sequenceIndex must be an integer >= 0'); + } + const seenModels = new Set(); + for (const modelId of options.modelIds) { + if (typeof modelId !== 'string' || modelId.trim().length === 0) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'modelId must be a non-empty string'); + } + if (seenModels.has(modelId)) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', `duplicate modelId "${modelId}"`); + } + seenModels.add(modelId); + } + + if (options.strategy === 'deterministic-round-robin') { + const chosen = options.modelIds[options.sequenceIndex % options.modelIds.length]!; + return Object.freeze({ + modelId: chosen, + reason: 'round_robin', + score: null, + }); + } + + const explorationC = options.explorationConstant ?? DEFAULT_UCB1_EXPLORATION_C; + if (!Number.isFinite(explorationC) || explorationC <= 0) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'explorationConstant must be > 0'); + } + + const armByModel = new Map(); + for (const arm of options.arms) { + armByModel.set(arm.modelId, arm); + } + + // Pull every unpulled arm once in deterministic declaration order first. + for (const modelId of options.modelIds) { + const arm = armByModel.get(modelId); + if (!arm || arm.pullCount <= 0) { + return Object.freeze({ + modelId, + reason: 'initial_exploration', + score: Number.POSITIVE_INFINITY, + }); + } + } + + let totalPulls = 0; + for (const modelId of options.modelIds) { + totalPulls += armByModel.get(modelId)!.pullCount; + } + + let bestModelId = options.modelIds[0]!; + let bestScore = Number.NEGATIVE_INFINITY; + const logTotal = Math.log(Math.max(1, totalPulls)); + + for (const modelId of options.modelIds) { + const arm = armByModel.get(modelId)!; + const bonus = explorationC * Math.sqrt(logTotal / arm.pullCount); + const ucbScore = arm.meanReward + bonus; + if (ucbScore > bestScore) { + bestScore = ucbScore; + bestModelId = modelId; + } + } + + return Object.freeze({ + modelId: bestModelId, + reason: 'ucb1_score', + score: bestScore, + }); +} diff --git a/packages/evolution/src/schema.ts b/packages/evolution/src/schema.ts new file mode 100644 index 0000000..a34e711 --- /dev/null +++ b/packages/evolution/src/schema.ts @@ -0,0 +1,2001 @@ +import { lstat } from 'node:fs/promises'; +import { + HANDOFF_LIMITS, + LIMITS, + SecretScrubber, + validateBucketMetrics, + validateHardwareDiagnostics, + validateRelativePath, + type ArtifactRef, + type BucketMetricEntry, + type Digest, + type FindingSeverity, + type HardwareDiagnostics, + type HardwareProvenance, + type ReworkPolicy, + type StepHandoffSelect, + type StepHandoffSelector, + type StepHandoffSource, + type StructuredFinding, +} from '@loopwright/core'; +import { + parseYamlDocument, + readBoundedRegularFile, + TaskpackError, +} from '@loopwright/taskpack'; +import { + DISPATCH_MANIFEST_MAX_BYTES, + DISPATCH_MANIFEST_MAX_RULES, + EVOLUTION_API_VERSION, + EVOLUTION_CAMPAIGN_KIND, + EVOLUTION_CAMPAIGN_MAX_BYTES, + EvolutionError, + TEAM_PATCH_DIAGNOSIS_MAX_BYTES, + TEAM_PATCH_KIND, + TEAM_PATCH_MAX_BYTES, + TEAM_PATCH_SCHEMA_VERSION, + type DispatchDimensionRange, + type DispatchManifestV1, + type DispatchRuleV1, + type EvolutionBudgetsSpec, + type EvolutionCampaignManifest, + type EvolutionCampaignMetadata, + type EvolutionCampaignSpec, + type EvolutionEnumNicheAxis, + type EvolutionExportFormat, + type EvolutionExportSpec, + type EvolutionModelBanditStrategy, + type EvolutionMutationWeights, + type EvolutionNicheAxis, + type EvolutionNumericBinsNicheAxis, + type EvolutionPopulationSpec, + type EvolutionSamplingSpec, + type EvolutionSpecialistBucket, + type EvolutionStagesSpec, + type EvolutionTeamSpec, + type ObjectiveDirectionSpec, + type TeamPatchDiagnosis, + type TeamPatchRole, + type TeamPatchStep, + type TeamPatchV1, + type TeamPlateauCategory, +} from './types.js'; + +export type NullProtoJson = + | null + | boolean + | number + | string + | readonly NullProtoJson[] + | { readonly [key: string]: NullProtoJson }; + +const FORBIDDEN_PROTOTYPE_KEYS: ReadonlySet = new Set(['__proto__', 'constructor', 'prototype']); +const LONE_SURROGATE_RE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(? = new Set([ + 'measurement_mismatch', + 'coupled_responsibilities', + 'local_optimum_anchor', + 'resource_spill_trap', + 'correctness_ping_pong', + 'other', +]); + +const DEFAULT_SECRET_SCRUBBER = new SecretScrubber(); + +const MAX_JSON_NODES = 4_096; +const MAX_JSON_DEPTH = 16; +const MAX_JSON_COLLECTION = 512; +const MAX_JSON_STRING = 16_384; + +function schemaInvalid(message: string, path = '/'): never { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', message, path); +} + +function hasControlChar(value: string): boolean { + for (let i = 0; i < value.length; i++) { + const code = value.charCodeAt(i); + if (code < 0x20 || code === 0x7f) return true; + } + return false; +} + +function hasDisallowedInlineControlChar(value: string): boolean { + for (let i = 0; i < value.length; i++) { + const code = value.charCodeAt(i); + if (code === 0x09 || code === 0x0a || code === 0x0d) continue; + if (code < 0x20 || code === 0x7f) return true; + } + return false; +} + +function assertValidStringContent(value: string, maxChars: number, path: string): void { + if (value.length > maxChars) { + schemaInvalid(`string exceeds maximum length ${maxChars}`, path); + } + if (LONE_SURROGATE_RE.test(value)) { + schemaInvalid('string contains lone UTF-16 surrogate', path); + } +} + +function createNullRecord>(): T { + return Object.create(null) as T; +} + +function decodeUtf8Strict(bytes: Uint8Array, path: string): string { + try { + return new TextDecoder('utf-8', { fatal: true }).decode(bytes); + } catch { + schemaInvalid('input bytes are not valid UTF-8', path); + } +} + +export interface SanitizeUntrustedOptions { + readonly maxBytes?: number; + readonly maxNodes?: number; + readonly maxDepth?: number; + readonly maxCollection?: number; + readonly maxString?: number; + readonly path?: string; +} + +/** + * Strictly parse a JSON string into null-prototype objects, rejecting duplicate keys, + * prototype keys (`__proto__`, `constructor`, `prototype`), lone surrogates, `NaN`, `Infinity`, and `-0`. + */ +export function parseNullProtoJson( + source: string, + maxBytes: number = EVOLUTION_CAMPAIGN_MAX_BYTES, + diagPath = '/', +): NullProtoJson { + if (typeof source !== 'string') { + schemaInvalid('expected JSON string', diagPath); + } + if (Buffer.byteLength(source, 'utf8') > maxBytes) { + schemaInvalid(`JSON payload exceeds ${maxBytes} bytes`, diagPath); + } + if (LONE_SURROGATE_RE.test(source)) { + schemaInvalid('JSON payload contains lone UTF-16 surrogate', diagPath); + } + + let offset = 0; + let nodes = 0; + + const skipSpace = (): void => { + while (offset < source.length) { + const ch = source.charCodeAt(offset); + if (ch === 0x20 || ch === 0x09 || ch === 0x0a || ch === 0x0d) { + offset++; + } else { + break; + } + } + }; + + const readString = (path: string): string => { + const start = offset++; + let closed = false; + while (offset < source.length) { + const ch = source.charAt(offset++); + if (ch === '"') { + closed = true; + break; + } + if (ch === '\\') { + if (offset >= source.length) schemaInvalid('unterminated JSON escape', path); + offset++; + } + } + if (!closed) schemaInvalid('unterminated JSON string', path); + let parsed: unknown; + try { + parsed = JSON.parse(source.slice(start, offset)); + } catch { + schemaInvalid('invalid JSON string literal', path); + } + if (typeof parsed !== 'string') { + schemaInvalid('invalid JSON string literal', path); + } + assertValidStringContent(parsed, MAX_JSON_STRING, path); + return parsed; + }; + + const readValue = (depth: number, path: string): NullProtoJson => { + if (++nodes > MAX_JSON_NODES || depth > MAX_JSON_DEPTH) { + schemaInvalid('JSON document exceeds node or depth limits', path); + } + skipSpace(); + const first = source.charAt(offset); + if (first === '{') { + offset++; + const out = createNullRecord>(); + const seen = new Set(); + skipSpace(); + if (source.charAt(offset) === '}') { + offset++; + return out; + } + while (true) { + skipSpace(); + if (source.charAt(offset) !== '"') { + schemaInvalid('JSON object member key must be a double-quoted string', path); + } + const key = readString(path); + if (FORBIDDEN_PROTOTYPE_KEYS.has(key)) { + schemaInvalid(`forbidden prototype key "${key}"`, `${path}/${key}`); + } + if (seen.has(key)) { + schemaInvalid(`duplicate JSON key "${key}"`, `${path}/${key}`); + } + if (seen.size >= MAX_JSON_COLLECTION) { + schemaInvalid('JSON object exceeds property limits', path); + } + seen.add(key); + skipSpace(); + if (source.charAt(offset++) !== ':') { + schemaInvalid('expected ":" after JSON key', `${path}/${key}`); + } + out[key] = readValue(depth + 1, `${path}/${key}`); + skipSpace(); + const sep = source.charAt(offset++); + if (sep === '}') return out; + if (sep !== ',') schemaInvalid('expected "," or "}" in JSON object', path); + } + } + if (first === '[') { + offset++; + const arr: NullProtoJson[] = []; + skipSpace(); + if (source.charAt(offset) === ']') { + offset++; + return arr; + } + while (true) { + if (arr.length >= MAX_JSON_COLLECTION) { + schemaInvalid('JSON array exceeds collection limits', path); + } + arr.push(readValue(depth + 1, `${path}/${arr.length}`)); + skipSpace(); + const sep = source.charAt(offset++); + if (sep === ']') return arr; + if (sep !== ',') schemaInvalid('expected "," or "]" in JSON array', path); + } + } + if (first === '"') { + return readString(path); + } + const tokenMatch = /^(?:true|false|null|-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?)/.exec( + source.slice(offset), + ); + if (tokenMatch === null) { + schemaInvalid('invalid JSON token', path); + } + const rawToken = tokenMatch[0]; + offset += rawToken.length; + if (rawToken === 'true') return true; + if (rawToken === 'false') return false; + if (rawToken === 'null') return null; + const numeric = Number(rawToken); + if (!Number.isFinite(numeric) || Object.is(numeric, -0)) { + schemaInvalid('JSON number must be finite and non-negative-zero', path); + } + return numeric; + }; + + const root = readValue(1, diagPath); + skipSpace(); + if (offset !== source.length) { + schemaInvalid('unexpected trailing content after JSON value', diagPath); + } + return root; +} + +/** + * Convert an untrusted value into a deep null-prototype tree while enforcing byte, + * depth, collection, prototype-key, surrogate, and finite non-`-0` number guards. + */ +export function sanitizeUntrustedValue( + input: unknown, + options: SanitizeUntrustedOptions = {}, +): NullProtoJson { + const maxBytes = options.maxBytes ?? EVOLUTION_CAMPAIGN_MAX_BYTES; + 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; + const rootPath = options.path ?? '/'; + + let nodes = 0; + let estimatedBytes = 0; + const active = new WeakSet(); + + const chargeBytes = (count: number, path: string): void => { + estimatedBytes += count; + if (estimatedBytes > maxBytes) { + schemaInvalid(`payload exceeds ${maxBytes} bytes`, path); + } + }; + + const visit = (val: unknown, depth: number, path: string): NullProtoJson => { + if (++nodes > maxNodes || depth > maxDepth) { + schemaInvalid('value exceeds node or depth limits', path); + } + if (val === null || typeof val === 'boolean') { + chargeBytes(5, path); + return val; + } + if (typeof val === 'number') { + if (!Number.isFinite(val) || Object.is(val, -0)) { + schemaInvalid('number must be finite and not -0', path); + } + chargeBytes(Buffer.byteLength(String(val), 'utf8'), path); + return val; + } + if (typeof val === 'string') { + assertValidStringContent(val, maxString, path); + chargeBytes(Buffer.byteLength(val, 'utf8') + 2, path); + return val; + } + if (typeof val !== 'object') { + schemaInvalid(`unsupported value type "${typeof val}"`, path); + } + if (active.has(val)) { + schemaInvalid('cyclic object reference is forbidden', path); + } + const proto: unknown = Object.getPrototypeOf(val); + if (Array.isArray(val)) { + if (proto !== Array.prototype) { + schemaInvalid('unsupported array prototype', path); + } + const ownKeys = Reflect.ownKeys(val); + if (ownKeys.some(k => typeof k === 'symbol') || ownKeys.length !== val.length + 1) { + schemaInvalid('sparse or symbol-keyed arrays are forbidden', path); + } + if (val.length > maxCollection) { + schemaInvalid(`array exceeds maximum length ${maxCollection}`, path); + } + active.add(val); + try { + chargeBytes(2, path); + const out: NullProtoJson[] = []; + for (let i = 0; i < val.length; i++) { + const desc = Object.getOwnPropertyDescriptor(val, String(i)); + if (!desc || !('value' in desc) || !desc.enumerable) { + schemaInvalid('array element must be an enumerable data property', `${path}/${i}`); + } + out.push(visit(desc.value, depth + 1, `${path}/${i}`)); + } + return out; + } finally { + active.delete(val); + } + } + if (proto !== Object.prototype && proto !== null) { + schemaInvalid('unsupported object prototype', path); + } + const ownKeys = Reflect.ownKeys(val); + if (ownKeys.some(k => typeof k === 'symbol')) { + schemaInvalid('symbol keys are forbidden', path); + } + const stringKeys = ownKeys as string[]; + if (stringKeys.length > maxCollection) { + schemaInvalid(`object exceeds maximum key count ${maxCollection}`, path); + } + active.add(val); + try { + chargeBytes(2, path); + const out = createNullRecord>(); + for (const key of stringKeys) { + if (FORBIDDEN_PROTOTYPE_KEYS.has(key)) { + schemaInvalid(`forbidden prototype key "${key}"`, `${path}/${key}`); + } + assertValidStringContent(key, 256, `${path}/${key}`); + const desc = Object.getOwnPropertyDescriptor(val, key); + if (!desc || !('value' in desc) || !desc.enumerable) { + schemaInvalid('object property must be an enumerable data property', `${path}/${key}`); + } + if (desc.value === undefined) continue; + chargeBytes(Buffer.byteLength(key, 'utf8') + 3, `${path}/${key}`); + out[key] = visit(desc.value, depth + 1, `${path}/${key}`); + } + return out; + } finally { + active.delete(val); + } + }; + + return visit(input, 1, rootPath); +} + +/** 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 }); + const render = (node: NullProtoJson): string => { + if (node === null || typeof node === 'boolean' || typeof node === 'number' || typeof node === 'string') { + return JSON.stringify(node); + } + if (Array.isArray(node)) { + return `[${node.map(item => render(item)).join(',')}]`; + } + const recordNode = node as { readonly [key: string]: NullProtoJson }; + const keys = Object.keys(recordNode).sort(); + const pairs: string[] = []; + for (const key of keys) { + if (!Object.hasOwn(recordNode, key)) continue; + const child = recordNode[key]; + if (child !== undefined) { + pairs.push(`${JSON.stringify(key)}:${render(child)}`); + } + } + return `{${pairs.join(',')}}`; + }; + return render(sanitized); +} + +function parseYamlOrJsonInput( + input: unknown, + maxBytes: number, + rootPath = '/', +): NullProtoJson { + if (typeof input === 'string' || input instanceof Uint8Array) { + const text = typeof input === 'string' ? input : decodeUtf8Strict(input, rootPath); + if (Buffer.byteLength(text, 'utf8') > maxBytes) { + schemaInvalid(`document exceeds ${maxBytes} bytes`, rootPath); + } + if (LONE_SURROGATE_RE.test(text)) { + schemaInvalid('document contains lone UTF-16 surrogate', rootPath); + } + let rawParsed: unknown; + try { + rawParsed = parseYamlDocument(text); + } catch (err) { + if (err instanceof TaskpackError) { + schemaInvalid(err.message, err.path ?? rootPath); + } + schemaInvalid(err instanceof Error ? err.message : 'invalid YAML/JSON syntax', rootPath); + } + return sanitizeUntrustedValue(rawParsed, { maxBytes, path: rootPath }); + } + return sanitizeUntrustedValue(input, { maxBytes, path: rootPath }); +} + +function expectObject( + value: NullProtoJson, + allowedKeys: ReadonlySet, + requiredKeys: readonly string[], + path: string, +): Record { + if (value === null || typeof value !== 'object' || Array.isArray(value)) { + schemaInvalid('expected mapping object', 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)) { + schemaInvalid(`unknown or forbidden field "${key}"`, `${path}/${key}`); + } + } + for (const req of requiredKeys) { + if (!Object.hasOwn(obj, req) || obj[req] === undefined) { + schemaInvalid(`missing required field "${req}"`, `${path}/${req}`); + } + } + return obj; +} + +function expectString(value: NullProtoJson | undefined, minLen: number, maxLen: number, path: string): string { + if (typeof value !== 'string') { + schemaInvalid('expected string', path); + } + if (value.length < minLen || value.length > maxLen) { + schemaInvalid(`string length must be within ${minLen}..${maxLen}`, path); + } + if (LONE_SURROGATE_RE.test(value)) { + schemaInvalid('string contains lone UTF-16 surrogate', path); + } + return value; +} + +function expectIdentifier(value: NullProtoJson | undefined, path: string): string { + const s = expectString(value, 1, LIMITS.identifier, path); + if (FORBIDDEN_PROTOTYPE_KEYS.has(s) || !IDENTIFIER_RE.test(s)) { + schemaInvalid(`invalid identifier "${s}"`, path); + } + return s; +} + +function expectBucketId(value: NullProtoJson | undefined, path: string): string { + const s = expectString(value, 1, LIMITS.bucketId, path); + if (FORBIDDEN_PROTOTYPE_KEYS.has(s) || !BUCKET_ID_RE.test(s)) { + schemaInvalid(`invalid bucket id "${s}"`, path); + } + return s; +} + +function expectMetricKey(value: NullProtoJson | undefined, path: string): string { + const s = expectString(value, 1, LIMITS.metricKey, path); + if (FORBIDDEN_PROTOTYPE_KEYS.has(s) || !METRIC_KEY_RE.test(s)) { + schemaInvalid(`invalid metric key "${s}"`, path); + } + return s; +} + +function expectBoolean(value: NullProtoJson | undefined, path: string): boolean { + if (typeof value !== 'boolean') { + schemaInvalid('expected boolean', path); + } + return value; +} + +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) { + schemaInvalid(`expected integer within ${min}..${max}`, path); + } + return value; +} + +function expectFiniteNumber( + value: NullProtoJson | undefined, + options: { readonly min?: number; readonly minExclusive?: number; readonly max?: number }, + path: string, +): number { + if (typeof value !== 'number' || !Number.isFinite(value) || Object.is(value, -0)) { + schemaInvalid('expected finite non-negative-zero number', path); + } + if (options.min !== undefined && value < options.min) { + schemaInvalid(`number must be >= ${options.min}`, path); + } + if (options.minExclusive !== undefined && value <= options.minExclusive) { + schemaInvalid(`number must be > ${options.minExclusive}`, path); + } + if (options.max !== undefined && value > options.max) { + schemaInvalid(`number must be <= ${options.max}`, path); + } + return value; +} + +function expectEnum( + value: NullProtoJson | undefined, + allowed: readonly T[], + path: string, +): T { + if (typeof value !== 'string' || !allowed.includes(value as T)) { + schemaInvalid(`expected one of [${allowed.join(', ')}]`, path); + } + return value as T; +} + +function expectArray( + value: NullProtoJson | undefined, + minLen: number, + maxLen: number, + path: string, +): readonly NullProtoJson[] { + if (!Array.isArray(value)) { + schemaInvalid('expected array', path); + } + if (value.length < minLen || value.length > maxLen) { + schemaInvalid(`array length must be within ${minLen}..${maxLen}`, path); + } + return value; +} + +function expectSafeRelativePath(value: NullProtoJson | undefined, path: string): string { + const raw = expectString(value, 1, LIMITS.path, path); + if (raw.startsWith('/') || raw.endsWith('/') || raw.includes('\\') || hasControlChar(raw)) { + schemaInvalid('expected normalized relative POSIX path', path); + } + const segments = raw.split('/'); + if (segments.length > LIMITS.segments) { + schemaInvalid('path exceeds segment depth limit', path); + } + for (const segment of segments) { + if ( + segment.length === 0 + || segment === '.' + || segment === '..' + || segment.endsWith('.') + || FORBIDDEN_PROTOTYPE_KEYS.has(segment) + || RESERVED_PATH_SEGMENT_RE.test(segment) + || !PRINTABLE_ASCII_RE.test(segment) + ) { + schemaInvalid(`invalid relative path segment "${segment}"`, path); + } + } + return raw; +} + +function expectDigest(value: NullProtoJson | undefined, path: string): Digest { + if (value === undefined) schemaInvalid('missing digest', path); + const obj = expectObject(value, new Set(['algorithm', 'hex']), ['algorithm', 'hex'], path); + const algorithm = expectEnum(obj['algorithm'], ['sha256'] as const, `${path}/algorithm`); + const hex = expectString(obj['hex'], 64, 64, `${path}/hex`); + if (!SHA256_HEX_RE.test(hex)) { + schemaInvalid('digest hex must be 64 lowercase hexadecimal characters', `${path}/hex`); + } + const out = createNullRecord<{ algorithm: 'sha256'; hex: string }>(); + out.algorithm = algorithm; + out.hex = hex; + return out; +} + +function assertCleanSecrets(serialized: string, scrubber: SecretScrubber, path: string): void { + if (scrubber.containsSecret(serialized)) { + throw new EvolutionError('SECRET_LEAK_DETECTED', `secret material detected at ${path}`, path); + } +} + +export interface ParseEvolutionCampaignOptions { + readonly scrubber?: SecretScrubber; +} + +const ROOT_CAMPAIGN_KEYS = new Set(['apiVersion', 'kind', 'metadata', 'spec']); +const METADATA_KEYS = new Set(['name', 'description']); +const SPEC_KEYS = new Set([ + 'taskpack', + 'targetCellId', + 'heldOutWorkloadId', + 'tracks', + 'stages', + 'population', + 'sampling', + 'teamEvolution', + 'objectives', + 'budgets', + 'export', +]); +const STAGES_KEYS = new Set(['mode', 'heldOutWorkloadId', 'specialistBuckets', 'portfolioHeldOutWorkloadId']); +const SPECIALIST_BUCKET_KEYS = new Set(['id', 'heldOutWorkloadId']); +const POPULATION_KEYS = new Set(['islands', 'migrationIntervalGenerations', 'maxMigrationElites', 'nicheAxes']); +const ENUM_AXIS_KEYS = new Set(['id', 'kind', 'field', 'values']); +const NUMERIC_BINS_AXIS_KEYS = new Set(['id', 'kind', 'field', 'edges']); +const SAMPLING_KEYS = new Set(['noveltyDecayLambda', 'mutationWeights', 'modelBandit', 'maxCrossoversPerPrompt']); +const MUTATION_WEIGHTS_KEYS = new Set(['diff_tune', 'full_rewrite', 'crossover']); +const TEAM_EVOLUTION_KEYS = new Set([ + 'enabled', + 'supervisorRoleId', + 'allowedArchetypeRoles', + 'stallGenerations', + 'minHypervolumeDelta', + 'triggerOnRunEvalPathology', + 'trialGenerations', + 'maxTeamSize', + 'maxTeamSteps', +]); +const OBJECTIVE_KEYS = new Set(['metric', 'direction']); +const BUDGETS_KEYS = new Set([ + 'maxGenerations', + 'maxEvaluations', + 'maxConcurrentEvaluations', + 'targetRooflineHeadroom', + 'scratchpadIntervalGenerations', +]); +const EXPORT_KEYS = new Set(['format', 'outputDir']); + +/** Parse and validate an `EvolutionCampaign` YAML/JSON document (`<= 65,536` bytes) into null-prototype records. */ +export function parseEvolutionCampaignDocument( + input: unknown, + options: ParseEvolutionCampaignOptions = {}, +): EvolutionCampaignManifest { + const scrubber = options.scrubber ?? DEFAULT_SECRET_SCRUBBER; + const rootVal = parseYamlOrJsonInput(input, EVOLUTION_CAMPAIGN_MAX_BYTES, ''); + const root = expectObject(rootVal, ROOT_CAMPAIGN_KEYS, ['apiVersion', 'kind', 'metadata', 'spec'], ''); + + if (root['apiVersion'] !== EVOLUTION_API_VERSION) { + schemaInvalid(`unsupported apiVersion "${String(root['apiVersion'])}"`, '/apiVersion'); + } + if (root['kind'] !== EVOLUTION_CAMPAIGN_KIND) { + schemaInvalid(`expected kind "${EVOLUTION_CAMPAIGN_KIND}"`, '/kind'); + } + + const metaObj = expectObject(root['metadata']!, METADATA_KEYS, ['name'], '/metadata'); + const metadata = createNullRecord<{ name: string; description?: string }>(); + metadata.name = expectIdentifier(metaObj['name'], '/metadata/name'); + if (Object.hasOwn(metaObj, 'description') && metaObj['description'] !== undefined) { + const desc = expectString(metaObj['description'], 1, 1_024, '/metadata/description'); + if (hasDisallowedInlineControlChar(desc)) schemaInvalid('invalid control character in description', '/metadata/description'); + metadata.description = desc; + } + + const specObj = expectObject( + root['spec']!, + SPEC_KEYS, + ['taskpack', 'targetCellId', 'population', 'sampling', 'objectives', 'budgets'], + '/spec', + ); + + const taskpack = expectSafeRelativePath(specObj['taskpack'], '/spec/taskpack'); + const targetCellId = expectIdentifier(specObj['targetCellId'], '/spec/targetCellId'); + + let topHeldOutWorkloadId: string | undefined; + if (Object.hasOwn(specObj, 'heldOutWorkloadId') && specObj['heldOutWorkloadId'] !== undefined) { + topHeldOutWorkloadId = expectIdentifier(specObj['heldOutWorkloadId'], '/spec/heldOutWorkloadId'); + } + + let tracks: readonly string[] | undefined; + if (Object.hasOwn(specObj, 'tracks') && specObj['tracks'] !== undefined) { + const rawTracks = expectArray(specObj['tracks'], 1, 32, '/spec/tracks'); + const seenTracks = new Set(); + const parsedTracks: string[] = []; + for (let i = 0; i < rawTracks.length; i++) { + const trackId = expectIdentifier(rawTracks[i], `/spec/tracks/${i}`); + if (seenTracks.has(trackId)) schemaInvalid(`duplicate track "${trackId}"`, `/spec/tracks/${i}`); + seenTracks.add(trackId); + parsedTracks.push(trackId); + } + tracks = parsedTracks; + } + + // Stages + let stages: EvolutionStagesSpec; + if (!Object.hasOwn(specObj, 'stages') || specObj['stages'] === undefined) { + const singleStages = createNullRecord<{ mode: 'single-target'; heldOutWorkloadId?: string }>(); + singleStages.mode = 'single-target'; + if (topHeldOutWorkloadId !== undefined) { + singleStages.heldOutWorkloadId = topHeldOutWorkloadId; + } + stages = singleStages; + } else { + const stagesObj = expectObject(specObj['stages'], STAGES_KEYS, [], '/spec/stages'); + const mode = Object.hasOwn(stagesObj, 'mode') && stagesObj['mode'] !== undefined + ? expectEnum(stagesObj['mode'], ['single-target', 'specialist-then-portfolio'] as const, '/spec/stages/mode') + : 'single-target'; + if (mode === 'single-target') { + if (Object.hasOwn(stagesObj, 'specialistBuckets') || Object.hasOwn(stagesObj, 'portfolioHeldOutWorkloadId')) { + schemaInvalid('specialistBuckets and portfolioHeldOutWorkloadId require specialist-then-portfolio mode', '/spec/stages'); + } + const singleStages = createNullRecord<{ mode: 'single-target'; heldOutWorkloadId?: string }>(); + singleStages.mode = 'single-target'; + if (Object.hasOwn(stagesObj, 'heldOutWorkloadId') && stagesObj['heldOutWorkloadId'] !== undefined) { + singleStages.heldOutWorkloadId = expectIdentifier(stagesObj['heldOutWorkloadId'], '/spec/stages/heldOutWorkloadId'); + } else if (topHeldOutWorkloadId !== undefined) { + singleStages.heldOutWorkloadId = topHeldOutWorkloadId; + } + stages = singleStages; + } else { + if (Object.hasOwn(stagesObj, 'heldOutWorkloadId') || topHeldOutWorkloadId !== undefined) { + schemaInvalid( + 'heldOutWorkloadId is not valid on specialist-then-portfolio stages', + topHeldOutWorkloadId !== undefined ? '/spec/heldOutWorkloadId' : '/spec/stages/heldOutWorkloadId', + ); + } + if (!Object.hasOwn(stagesObj, 'specialistBuckets') || !Object.hasOwn(stagesObj, 'portfolioHeldOutWorkloadId')) { + schemaInvalid('specialist-then-portfolio requires specialistBuckets and portfolioHeldOutWorkloadId', '/spec/stages'); + } + const rawBuckets = expectArray(stagesObj['specialistBuckets'], 1, 64, '/spec/stages/specialistBuckets'); + const seenBucketIds = new Set(); + const specialistBuckets: EvolutionSpecialistBucket[] = []; + for (let i = 0; i < rawBuckets.length; i++) { + const bPath = `/spec/stages/specialistBuckets/${i}`; + const bObj = expectObject(rawBuckets[i]!, SPECIALIST_BUCKET_KEYS, ['id', 'heldOutWorkloadId'], bPath); + const id = expectBucketId(bObj['id'], `${bPath}/id`); + if (seenBucketIds.has(id)) schemaInvalid(`duplicate specialist bucket "${id}"`, `${bPath}/id`); + seenBucketIds.add(id); + const heldOutWorkloadId = expectIdentifier(bObj['heldOutWorkloadId'], `${bPath}/heldOutWorkloadId`); + const bucketRec = createNullRecord<{ id: string; heldOutWorkloadId: string }>(); + bucketRec.id = id; + bucketRec.heldOutWorkloadId = heldOutWorkloadId; + specialistBuckets.push(bucketRec); + } + const portfolioHeldOutWorkloadId = expectIdentifier( + stagesObj['portfolioHeldOutWorkloadId'], + '/spec/stages/portfolioHeldOutWorkloadId', + ); + const portfolioStages = createNullRecord<{ + mode: 'specialist-then-portfolio'; + specialistBuckets: readonly EvolutionSpecialistBucket[]; + portfolioHeldOutWorkloadId: string; + }>(); + portfolioStages.mode = 'specialist-then-portfolio'; + portfolioStages.specialistBuckets = specialistBuckets; + portfolioStages.portfolioHeldOutWorkloadId = portfolioHeldOutWorkloadId; + stages = portfolioStages; + } + } + + // Population + const popObj = expectObject( + specObj['population']!, + POPULATION_KEYS, + ['islands', 'migrationIntervalGenerations', 'maxMigrationElites', 'nicheAxes'], + '/spec/population', + ); + const islands = expectInteger(popObj['islands'], 1, 16, '/spec/population/islands'); + const migrationIntervalGenerations = expectInteger( + popObj['migrationIntervalGenerations'], + 1, + 1_024, + '/spec/population/migrationIntervalGenerations', + ); + const maxMigrationElites = expectInteger( + popObj['maxMigrationElites'], + 0, + 16, + '/spec/population/maxMigrationElites', + ); + const rawAxes = expectArray(popObj['nicheAxes'], 1, 4, '/spec/population/nicheAxes'); + const seenAxisIds = new Set(); + const nicheAxes: EvolutionNicheAxis[] = []; + for (let i = 0; i < rawAxes.length; i++) { + const aPath = `/spec/population/nicheAxes/${i}`; + const rawAxis = rawAxes[i]!; + if (rawAxis === null || typeof rawAxis !== 'object' || Array.isArray(rawAxis)) { + schemaInvalid('niche axis must be an object', aPath); + } + const axisRecord = rawAxis as Record; + const kind = expectEnum(axisRecord['kind'], ['enum', 'numeric_bins'] as const, `${aPath}/kind`); + if (kind === 'enum') { + const enumObj = expectObject(rawAxis, ENUM_AXIS_KEYS, ['id', 'kind', 'values'], aPath); + const id = expectMetricKey(enumObj['id'], `${aPath}/id`); + if (seenAxisIds.has(id)) schemaInvalid(`duplicate niche axis "${id}"`, `${aPath}/id`); + seenAxisIds.add(id); + const rawValues = expectArray(enumObj['values'], 1, 32, `${aPath}/values`); + const seenValues = new Set(); + const values: string[] = []; + for (let j = 0; j < rawValues.length; j++) { + const val = expectMetricKey(rawValues[j], `${aPath}/values/${j}`); + if (seenValues.has(val)) schemaInvalid(`duplicate enum value "${val}"`, `${aPath}/values/${j}`); + seenValues.add(val); + values.push(val); + } + const axis = createNullRecord<{ + id: string; + kind: 'enum'; + field?: string; + values: readonly string[]; + }>(); + axis.id = id; + axis.kind = 'enum'; + if (Object.hasOwn(enumObj, 'field') && enumObj['field'] !== undefined) { + axis.field = expectMetricKey(enumObj['field'], `${aPath}/field`); + } + axis.values = values; + nicheAxes.push(axis as EvolutionEnumNicheAxis); + } else { + const binsObj = expectObject(rawAxis, NUMERIC_BINS_AXIS_KEYS, ['id', 'kind', 'edges'], aPath); + const id = expectMetricKey(binsObj['id'], `${aPath}/id`); + if (seenAxisIds.has(id)) schemaInvalid(`duplicate niche axis "${id}"`, `${aPath}/id`); + seenAxisIds.add(id); + const rawEdges = expectArray(binsObj['edges'], 2, 32, `${aPath}/edges`); + const edges: number[] = []; + for (let j = 0; j < rawEdges.length; j++) { + const edge = expectFiniteNumber(rawEdges[j], {}, `${aPath}/edges/${j}`); + if (j > 0 && edge <= edges[j - 1]!) { + schemaInvalid('numeric_bins edges must be strictly increasing', `${aPath}/edges/${j}`); + } + edges.push(edge); + } + const axis = createNullRecord<{ + id: string; + kind: 'numeric_bins'; + field?: string; + edges: readonly number[]; + }>(); + axis.id = id; + axis.kind = 'numeric_bins'; + if (Object.hasOwn(binsObj, 'field') && binsObj['field'] !== undefined) { + axis.field = expectMetricKey(binsObj['field'], `${aPath}/field`); + } + axis.edges = edges; + nicheAxes.push(axis as EvolutionNumericBinsNicheAxis); + } + } + const population = createNullRecord<{ + islands: number; + migrationIntervalGenerations: number; + maxMigrationElites: number; + nicheAxes: readonly EvolutionNicheAxis[]; + }>(); + population.islands = islands; + population.migrationIntervalGenerations = migrationIntervalGenerations; + population.maxMigrationElites = maxMigrationElites; + population.nicheAxes = nicheAxes; + + // Sampling + const sampObj = expectObject( + specObj['sampling']!, + SAMPLING_KEYS, + ['noveltyDecayLambda', 'mutationWeights', 'maxCrossoversPerPrompt'], + '/spec/sampling', + ); + const noveltyDecayLambda = expectFiniteNumber( + sampObj['noveltyDecayLambda'], + { minExclusive: 0, max: 100 }, + '/spec/sampling/noveltyDecayLambda', + ); + const weightsObj = expectObject( + sampObj['mutationWeights']!, + MUTATION_WEIGHTS_KEYS, + ['diff_tune', 'full_rewrite', 'crossover'], + '/spec/sampling/mutationWeights', + ); + const diffTune = expectFiniteNumber(weightsObj['diff_tune'], { min: 0, max: 1_000 }, '/spec/sampling/mutationWeights/diff_tune'); + const fullRewrite = expectFiniteNumber(weightsObj['full_rewrite'], { min: 0, max: 1_000 }, '/spec/sampling/mutationWeights/full_rewrite'); + const crossover = expectFiniteNumber(weightsObj['crossover'], { min: 0, max: 1_000 }, '/spec/sampling/mutationWeights/crossover'); + if (diffTune + fullRewrite + crossover <= 0) { + schemaInvalid('mutationWeights sum must be > 0', '/spec/sampling/mutationWeights'); + } + const mutationWeights = createNullRecord<{ + diff_tune: number; + full_rewrite: number; + crossover: number; + }>(); + mutationWeights.diff_tune = diffTune; + mutationWeights.full_rewrite = fullRewrite; + mutationWeights.crossover = crossover; + + const modelBandit: EvolutionModelBanditStrategy = Object.hasOwn(sampObj, 'modelBandit') && sampObj['modelBandit'] !== undefined + ? expectEnum(sampObj['modelBandit'], ['deterministic-round-robin', 'ucb1'] as const, '/spec/sampling/modelBandit') + : 'deterministic-round-robin'; + const maxCrossoversPerPrompt = expectInteger( + sampObj['maxCrossoversPerPrompt'], + 0, + 4, + '/spec/sampling/maxCrossoversPerPrompt', + ); + const sampling = createNullRecord<{ + noveltyDecayLambda: number; + mutationWeights: EvolutionMutationWeights; + modelBandit: EvolutionModelBanditStrategy; + maxCrossoversPerPrompt: number; + }>(); + sampling.noveltyDecayLambda = noveltyDecayLambda; + sampling.mutationWeights = mutationWeights; + sampling.modelBandit = modelBandit; + sampling.maxCrossoversPerPrompt = maxCrossoversPerPrompt; + + // Optional teamEvolution + let teamEvolution: EvolutionTeamSpec | undefined; + if (Object.hasOwn(specObj, 'teamEvolution') && specObj['teamEvolution'] !== undefined) { + const teamObj = expectObject( + specObj['teamEvolution'], + TEAM_EVOLUTION_KEYS, + ['enabled', 'supervisorRoleId', 'allowedArchetypeRoles'], + '/spec/teamEvolution', + ); + const enabled = expectBoolean(teamObj['enabled'], '/spec/teamEvolution/enabled'); + const supervisorRoleId = expectIdentifier(teamObj['supervisorRoleId'], '/spec/teamEvolution/supervisorRoleId'); + const rawArchetypes = expectArray( + teamObj['allowedArchetypeRoles'], + enabled ? 1 : 0, + 16, + '/spec/teamEvolution/allowedArchetypeRoles', + ); + const seenArchetypes = new Set(); + const allowedArchetypeRoles: string[] = []; + for (let i = 0; i < rawArchetypes.length; i++) { + const roleId = expectIdentifier(rawArchetypes[i], `/spec/teamEvolution/allowedArchetypeRoles/${i}`); + if (seenArchetypes.has(roleId)) { + schemaInvalid(`duplicate archetype role "${roleId}"`, `/spec/teamEvolution/allowedArchetypeRoles/${i}`); + } + seenArchetypes.add(roleId); + allowedArchetypeRoles.push(roleId); + } + const stallGenerations = Object.hasOwn(teamObj, 'stallGenerations') && teamObj['stallGenerations'] !== undefined + ? expectInteger(teamObj['stallGenerations'], 1, 32, '/spec/teamEvolution/stallGenerations') + : 4; + const minHypervolumeDelta = Object.hasOwn(teamObj, 'minHypervolumeDelta') && teamObj['minHypervolumeDelta'] !== undefined + ? expectFiniteNumber(teamObj['minHypervolumeDelta'], { min: 0 }, '/spec/teamEvolution/minHypervolumeDelta') + : 0.001; + const triggerOnRunEvalPathology = Object.hasOwn(teamObj, 'triggerOnRunEvalPathology') && teamObj['triggerOnRunEvalPathology'] !== undefined + ? expectBoolean(teamObj['triggerOnRunEvalPathology'], '/spec/teamEvolution/triggerOnRunEvalPathology') + : true; + const trialGenerations = Object.hasOwn(teamObj, 'trialGenerations') && teamObj['trialGenerations'] !== undefined + ? expectInteger(teamObj['trialGenerations'], 1, 8, '/spec/teamEvolution/trialGenerations') + : 2; + const maxTeamSize = Object.hasOwn(teamObj, 'maxTeamSize') && teamObj['maxTeamSize'] !== undefined + ? expectInteger(teamObj['maxTeamSize'], 1, 4, '/spec/teamEvolution/maxTeamSize') + : 4; + const maxTeamSteps = Object.hasOwn(teamObj, 'maxTeamSteps') && teamObj['maxTeamSteps'] !== undefined + ? expectInteger(teamObj['maxTeamSteps'], 1, 6, '/spec/teamEvolution/maxTeamSteps') + : 6; + + const teamRec = createNullRecord<{ + enabled: boolean; + supervisorRoleId: string; + allowedArchetypeRoles: readonly string[]; + stallGenerations: number; + minHypervolumeDelta: number; + triggerOnRunEvalPathology: boolean; + trialGenerations: number; + maxTeamSize: number; + maxTeamSteps: number; + }>(); + teamRec.enabled = enabled; + teamRec.supervisorRoleId = supervisorRoleId; + teamRec.allowedArchetypeRoles = allowedArchetypeRoles; + teamRec.stallGenerations = stallGenerations; + teamRec.minHypervolumeDelta = minHypervolumeDelta; + teamRec.triggerOnRunEvalPathology = triggerOnRunEvalPathology; + teamRec.trialGenerations = trialGenerations; + teamRec.maxTeamSize = maxTeamSize; + teamRec.maxTeamSteps = maxTeamSteps; + teamEvolution = teamRec; + } + + // Objectives + const rawObjectives = expectArray(specObj['objectives'], 1, 8, '/spec/objectives'); + const seenMetrics = new Set(); + const objectives: ObjectiveDirectionSpec[] = []; + for (let i = 0; i < rawObjectives.length; i++) { + const oPath = `/spec/objectives/${i}`; + const oObj = expectObject(rawObjectives[i]!, OBJECTIVE_KEYS, ['metric', 'direction'], oPath); + const metric = expectMetricKey(oObj['metric'], `${oPath}/metric`); + if (seenMetrics.has(metric)) { + schemaInvalid(`duplicate objective metric "${metric}"`, `${oPath}/metric`); + } + seenMetrics.add(metric); + const direction = expectEnum(oObj['direction'], ['minimize', 'maximize'] as const, `${oPath}/direction`); + const objRec = createNullRecord<{ metric: string; direction: 'minimize' | 'maximize' }>(); + objRec.metric = metric; + objRec.direction = direction; + objectives.push(objRec); + } + + // Budgets + const budObj = expectObject( + specObj['budgets']!, + BUDGETS_KEYS, + ['maxGenerations', 'maxEvaluations', 'maxConcurrentEvaluations'], + '/spec/budgets', + ); + const maxGenerations = expectInteger(budObj['maxGenerations'], 1, 10_000, '/spec/budgets/maxGenerations'); + const maxEvaluations = expectInteger(budObj['maxEvaluations'], 1, 100_000, '/spec/budgets/maxEvaluations'); + const maxConcurrentEvaluations = expectInteger( + budObj['maxConcurrentEvaluations'], + 1, + 64, + '/spec/budgets/maxConcurrentEvaluations', + ); + if (maxConcurrentEvaluations > maxEvaluations) { + schemaInvalid('maxConcurrentEvaluations cannot exceed maxEvaluations', '/spec/budgets/maxConcurrentEvaluations'); + } + const scratchpadIntervalGenerations = Object.hasOwn(budObj, 'scratchpadIntervalGenerations') && budObj['scratchpadIntervalGenerations'] !== undefined + ? expectInteger(budObj['scratchpadIntervalGenerations'], 1, 32, '/spec/budgets/scratchpadIntervalGenerations') + : 5; + const budgets = createNullRecord<{ + maxGenerations: number; + maxEvaluations: number; + maxConcurrentEvaluations: number; + targetRooflineHeadroom?: number; + scratchpadIntervalGenerations: number; + }>(); + budgets.maxGenerations = maxGenerations; + budgets.maxEvaluations = maxEvaluations; + budgets.maxConcurrentEvaluations = maxConcurrentEvaluations; + if (Object.hasOwn(budObj, 'targetRooflineHeadroom') && budObj['targetRooflineHeadroom'] !== undefined) { + budgets.targetRooflineHeadroom = expectFiniteNumber( + budObj['targetRooflineHeadroom'], + { min: 1.0 }, + '/spec/budgets/targetRooflineHeadroom', + ); + } + budgets.scratchpadIntervalGenerations = scratchpadIntervalGenerations; + + // Optional export + let exportSpec: EvolutionExportSpec | undefined; + if (Object.hasOwn(specObj, 'export') && specObj['export'] !== undefined) { + const expObj = expectObject(specObj['export'], EXPORT_KEYS, ['outputDir'], '/spec/export'); + const format: EvolutionExportFormat = Object.hasOwn(expObj, 'format') && expObj['format'] !== undefined + ? expectEnum(expObj['format'], ['dir', 'oci-layout'] as const, '/spec/export/format') + : 'dir'; + const outputDir = expectSafeRelativePath(expObj['outputDir'], '/spec/export/outputDir'); + const expRec = createNullRecord<{ format: EvolutionExportFormat; outputDir: string }>(); + expRec.format = format; + expRec.outputDir = outputDir; + exportSpec = expRec; + } + + const spec = createNullRecord<{ + taskpack: string; + targetCellId: string; + heldOutWorkloadId?: string; + tracks?: readonly string[]; + stages: EvolutionStagesSpec; + population: EvolutionPopulationSpec; + sampling: EvolutionSamplingSpec; + teamEvolution?: EvolutionTeamSpec; + objectives: readonly ObjectiveDirectionSpec[]; + budgets: EvolutionBudgetsSpec; + export?: EvolutionExportSpec; + }>(); + spec.taskpack = taskpack; + spec.targetCellId = targetCellId; + if (topHeldOutWorkloadId !== undefined) spec.heldOutWorkloadId = topHeldOutWorkloadId; + if (tracks !== undefined) spec.tracks = tracks; + spec.stages = stages; + spec.population = population as EvolutionPopulationSpec; + spec.sampling = sampling as EvolutionSamplingSpec; + if (teamEvolution !== undefined) spec.teamEvolution = teamEvolution; + spec.objectives = objectives; + spec.budgets = budgets as EvolutionBudgetsSpec; + if (exportSpec !== undefined) spec.export = exportSpec; + + const manifest = createNullRecord<{ + apiVersion: typeof EVOLUTION_API_VERSION; + kind: typeof EVOLUTION_CAMPAIGN_KIND; + metadata: EvolutionCampaignMetadata; + spec: EvolutionCampaignSpec; + }>(); + manifest.apiVersion = EVOLUTION_API_VERSION; + manifest.kind = EVOLUTION_CAMPAIGN_KIND; + manifest.metadata = metadata; + manifest.spec = spec as EvolutionCampaignSpec; + + assertCleanSecrets(canonicalizeJson(manifest), scrubber, '/'); + return manifest as EvolutionCampaignManifest; +} + +/** Load an `EvolutionCampaign` file (`O_NOFOLLOW`, `<= 65,536` bytes), rejecting symlinks fail-closed. */ +export async function loadEvolutionCampaignFile( + filePath: string, + options: ParseEvolutionCampaignOptions = {}, +): Promise { + if (typeof filePath !== 'string' || filePath.length === 0) { + schemaInvalid('filePath must be a non-empty string', '/filePath'); + } + const st = await lstat(filePath).catch((err: NodeJS.ErrnoException) => { + if (err.code === 'ELOOP') { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `symlink forbidden along ${filePath}`, filePath); + } + return null; + }); + if (st !== null && st.isSymbolicLink()) { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `campaign manifest cannot be a symlink: ${filePath}`, filePath); + } + const bytes = await readBoundedRegularFile(filePath, EVOLUTION_CAMPAIGN_MAX_BYTES, message => { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', message, filePath); + }); + return parseEvolutionCampaignDocument(bytes, options); +} + +// --------------------------------------------------------------------------- +// TeamPatchV1 (`team-patch.v1`) parser & strict acyclic DAG validator +// --------------------------------------------------------------------------- + +export interface ParseTeamPatchOptions { + readonly maxTeamSize?: number; + readonly maxTeamSteps?: number; + readonly scrubber?: SecretScrubber; +} + +const TEAM_PATCH_ROOT_KEYS = new Set(['kind', 'schemaVersion', 'diagnosis', 'roles', 'steps']); +const TEAM_DIAGNOSIS_KEYS = new Set(['summary', 'plateauCategory', 'rationale']); +const TEAM_ROLE_KEYS = new Set([ + 'id', + 'archetypeRoleId', + 'purpose', + 'prompt', + 'model', + 'thinking', + 'tools', + 'resourceIds', + 'timeoutSeconds', +]); +const TEAM_STEP_KEYS = new Set(['id', 'roleId', 'dependsOn', 'handoffs', 'onRework']); +const REWORK_POLICY_KEYS = new Set(['rejectTo', 'maxReworks']); +const HANDOFF_SELECTOR_KEYS = new Set(['id', 'fromStep', 'source', 'select', 'maxBytes', 'required']); + +function parseHandoffHeading(raw: string, path: string): string { + if (raw.length < 1 || raw.length > HANDOFF_LIMITS.maxHeadingChars || hasControlChar(raw) || raw.trim().length === 0) { + schemaInvalid('invalid markdown handoff heading', path); + } + const trimmed = raw.trim(); + const headingBody = /^(#{1,6})(?:[ \t]+(.*)|[ \t]*)$/.exec(trimmed)?.[2] ?? trimmed; + const cleaned = headingBody.replace(/[ \t]+$/, ''); + const title = /^#+$/.test(cleaned) ? '' : cleaned.replace(/[ \t]+#+$/, '').trim(); + if (title.length === 0) { + schemaInvalid('markdown heading title cannot be empty', path); + } + return raw; +} + +function parseRfc6901JsonPointer(raw: string, path: string): string { + if (raw.length > HANDOFF_LIMITS.maxPointerChars || hasControlChar(raw)) { + schemaInvalid('invalid JSON pointer', path); + } + if (raw === '') return raw; + if (!raw.startsWith('/')) { + schemaInvalid('non-empty JSON pointer must start with "/"', path); + } + const segments = raw.slice(1).split('/'); + if (segments.length > LIMITS.segments) { + schemaInvalid('JSON pointer exceeds segment depth limit', path); + } + for (const seg of segments) { + let decoded = ''; + for (let i = 0; i < seg.length; i++) { + const ch = seg.charAt(i); + if (ch === '~') { + const next = seg.charAt(i + 1); + if (next === '0') { + decoded += '~'; + i++; + } else if (next === '1') { + decoded += '/'; + i++; + } else { + schemaInvalid('invalid JSON pointer "~" escape', path); + } + } else { + decoded += ch; + } + } + if (FORBIDDEN_PROTOTYPE_KEYS.has(decoded)) { + schemaInvalid(`forbidden prototype key in JSON pointer "${decoded}"`, path); + } + } + return raw; +} + +function parseStepHandoffSelectorValue(value: NullProtoJson, path: string): StepHandoffSelector { + const obj = expectObject(value, HANDOFF_SELECTOR_KEYS, ['fromStep', 'source', 'select'], path); + const fromStep = expectIdentifier(obj['fromStep'], `${path}/fromStep`); + + const srcVal = obj['source']!; + if (srcVal === null || typeof srcVal !== 'object' || Array.isArray(srcVal)) { + schemaInvalid('handoff source must be an object', `${path}/source`); + } + const srcKind = expectEnum( + (srcVal as Record)['kind'], + ['artifact', 'submission', 'verdict'] as const, + `${path}/source/kind`, + ); + let source: StepHandoffSource; + if (srcKind === 'artifact') { + const artObj = expectObject(srcVal, new Set(['kind', 'path']), ['kind', 'path'], `${path}/source`); + const relPath = expectString(artObj['path'], 1, LIMITS.path, `${path}/source/path`); + const vRes = validateRelativePath(relPath); + if (!vRes.ok) schemaInvalid('invalid handoff artifact relative path', `${path}/source/path`); + const rec = createNullRecord<{ kind: 'artifact'; path: string }>(); + rec.kind = 'artifact'; + rec.path = vRes.value; + source = rec; + } else if (srcKind === 'submission') { + expectObject(srcVal, new Set(['kind']), ['kind'], `${path}/source`); + const rec = createNullRecord<{ kind: 'submission' }>(); + rec.kind = 'submission'; + source = rec; + } else { + expectObject(srcVal, new Set(['kind']), ['kind'], `${path}/source`); + const rec = createNullRecord<{ kind: 'verdict' }>(); + rec.kind = 'verdict'; + source = rec; + } + + const selVal = obj['select']!; + if (selVal === null || typeof selVal !== 'object' || Array.isArray(selVal)) { + schemaInvalid('handoff select must be an object', `${path}/select`); + } + const selKind = expectEnum( + (selVal as Record)['kind'], + ['markdown_heading', 'json_pointer', 'full'] as const, + `${path}/select/kind`, + ); + let select: StepHandoffSelect; + if (selKind === 'markdown_heading') { + const mhObj = expectObject( + selVal, + new Set(['kind', 'heading', 'includeSubheadings']), + ['kind', 'heading'], + `${path}/select`, + ); + const heading = parseHandoffHeading( + expectString(mhObj['heading'], 1, HANDOFF_LIMITS.maxHeadingChars, `${path}/select/heading`), + `${path}/select/heading`, + ); + const rec = createNullRecord<{ kind: 'markdown_heading'; heading: string; includeSubheadings?: boolean }>(); + rec.kind = 'markdown_heading'; + rec.heading = heading; + if (Object.hasOwn(mhObj, 'includeSubheadings') && mhObj['includeSubheadings'] !== undefined) { + rec.includeSubheadings = expectBoolean(mhObj['includeSubheadings'], `${path}/select/includeSubheadings`); + } + select = rec; + } else if (selKind === 'json_pointer') { + const jpObj = expectObject(selVal, new Set(['kind', 'pointers']), ['kind', 'pointers'], `${path}/select`); + const rawPtrs = expectArray(jpObj['pointers'], 1, HANDOFF_LIMITS.maxPointers, `${path}/select/pointers`); + const seenPtrs = new Set(); + const pointers: string[] = []; + for (let i = 0; i < rawPtrs.length; i++) { + const ptr = parseRfc6901JsonPointer( + expectString(rawPtrs[i], 0, HANDOFF_LIMITS.maxPointerChars, `${path}/select/pointers/${i}`), + `${path}/select/pointers/${i}`, + ); + if (seenPtrs.has(ptr)) schemaInvalid(`duplicate JSON pointer "${ptr}"`, `${path}/select/pointers/${i}`); + seenPtrs.add(ptr); + pointers.push(ptr); + } + const rec = createNullRecord<{ kind: 'json_pointer'; pointers: readonly string[] }>(); + rec.kind = 'json_pointer'; + rec.pointers = pointers; + select = rec; + } else { + expectObject(selVal, new Set(['kind']), ['kind'], `${path}/select`); + const rec = createNullRecord<{ kind: 'full' }>(); + rec.kind = 'full'; + select = rec; + } + + const out = createNullRecord<{ + id?: string; + fromStep: string; + source: StepHandoffSource; + select: StepHandoffSelect; + maxBytes?: number; + required?: boolean; + }>(); + if (Object.hasOwn(obj, 'id') && obj['id'] !== undefined) { + out.id = expectIdentifier(obj['id'], `${path}/id`); + } + out.fromStep = fromStep; + out.source = source; + out.select = select; + if (Object.hasOwn(obj, 'maxBytes') && obj['maxBytes'] !== undefined) { + out.maxBytes = expectInteger(obj['maxBytes'], HANDOFF_LIMITS.minBytes, HANDOFF_LIMITS.maxBytes, `${path}/maxBytes`); + } + if (Object.hasOwn(obj, 'required') && obj['required'] !== undefined) { + out.required = expectBoolean(obj['required'], `${path}/required`); + } + return out as StepHandoffSelector; +} + +export function parseTeamDiagnosisValue(value: NullProtoJson, path: string): TeamPatchDiagnosis { + const diagObj = expectObject(value, TEAM_DIAGNOSIS_KEYS, ['summary', 'plateauCategory', 'rationale'], path); + const summary = expectString(diagObj['summary'], 1, TEAM_PATCH_DIAGNOSIS_MAX_BYTES, `${path}/summary`); + if (hasDisallowedInlineControlChar(summary) || summary.trim().length === 0) { + schemaInvalid('diagnosis.summary must be non-empty printable text', `${path}/summary`); + } + const plateauCategoryRaw = expectString(diagObj['plateauCategory'], 1, 64, `${path}/plateauCategory`); + if (!PLATEAU_CATEGORIES.has(plateauCategoryRaw as TeamPlateauCategory)) { + schemaInvalid(`invalid plateauCategory "${plateauCategoryRaw}"`, `${path}/plateauCategory`); + } + const rationale = expectString(diagObj['rationale'], 1, TEAM_PATCH_DIAGNOSIS_MAX_BYTES, `${path}/rationale`); + if (hasDisallowedInlineControlChar(rationale) || rationale.trim().length === 0) { + schemaInvalid('diagnosis.rationale must be non-empty printable text', `${path}/rationale`); + } + + const diagnosis = createNullRecord<{ + summary: string; + plateauCategory: TeamPlateauCategory; + rationale: string; + }>(); + diagnosis.summary = summary; + diagnosis.plateauCategory = plateauCategoryRaw as TeamPlateauCategory; + diagnosis.rationale = rationale; + + if (Buffer.byteLength(canonicalizeJson(diagnosis), 'utf8') > TEAM_PATCH_DIAGNOSIS_MAX_BYTES) { + schemaInvalid(`diagnosis exceeds ${TEAM_PATCH_DIAGNOSIS_MAX_BYTES} bytes`, path); + } + return diagnosis; +} + +export function parseTeamDiagnosisJson(rawJson: string): TeamPatchDiagnosis { + const parsed = parseNullProtoJson(rawJson, TEAM_PATCH_DIAGNOSIS_MAX_BYTES, '/diagnosis'); + return parseTeamDiagnosisValue(parsed, '/diagnosis'); +} + +function collectStrictAncestors( + stepId: string, + depsByStep: ReadonlyMap, +): ReadonlySet { + const ancestors = new Set(); + const stack = [...(depsByStep.get(stepId) ?? [])]; + while (stack.length > 0) { + const cur = stack.pop()!; + if (ancestors.has(cur)) continue; + ancestors.add(cur); + for (const parent of depsByStep.get(cur) ?? []) { + stack.push(parent); + } + } + return ancestors; +} + +/** + * Parse and validate `team-patch.v1` (`<= 32,768` bytes, `diagnosis <= 4,096` bytes), + * enforcing role references, strict acyclic DAG steps, and strict-ancestor handoff/rework edges. + */ +export function parseTeamPatchV1( + input: unknown, + options: ParseTeamPatchOptions = {}, +): TeamPatchV1 { + const maxTeamSize = options.maxTeamSize ?? 4; + const maxTeamSteps = options.maxTeamSteps ?? 6; + const scrubber = options.scrubber ?? DEFAULT_SECRET_SCRUBBER; + + if (!Number.isSafeInteger(maxTeamSize) || maxTeamSize < 1 || maxTeamSize > 4) { + schemaInvalid('maxTeamSize must be within 1..4', '/options/maxTeamSize'); + } + if (!Number.isSafeInteger(maxTeamSteps) || maxTeamSteps < 1 || maxTeamSteps > 6) { + schemaInvalid('maxTeamSteps must be within 1..6', '/options/maxTeamSteps'); + } + + const rootVal = parseYamlOrJsonInput(input, TEAM_PATCH_MAX_BYTES, ''); + const root = expectObject(rootVal, TEAM_PATCH_ROOT_KEYS, ['kind', 'schemaVersion', 'diagnosis', 'roles', 'steps'], ''); + + if (root['kind'] !== TEAM_PATCH_KIND) { + schemaInvalid(`expected kind "${TEAM_PATCH_KIND}"`, '/kind'); + } + if (root['schemaVersion'] !== TEAM_PATCH_SCHEMA_VERSION) { + schemaInvalid(`expected schemaVersion "${TEAM_PATCH_SCHEMA_VERSION}"`, '/schemaVersion'); + } + + const diagnosis = parseTeamDiagnosisValue(root['diagnosis']!, '/diagnosis'); + + const rawRoles = expectArray(root['roles'], 1, maxTeamSize, '/roles'); + const seenRoleIds = new Set(); + const roles: TeamPatchRole[] = []; + for (let i = 0; i < rawRoles.length; i++) { + const rPath = `/roles/${i}`; + const rObj = expectObject( + rawRoles[i]!, + TEAM_ROLE_KEYS, + ['id', 'archetypeRoleId', 'purpose', 'prompt', 'tools'], + rPath, + ); + const id = expectIdentifier(rObj['id'], `${rPath}/id`); + if (seenRoleIds.has(id)) schemaInvalid(`duplicate role id "${id}"`, `${rPath}/id`); + seenRoleIds.add(id); + + const archetypeRoleId = expectIdentifier(rObj['archetypeRoleId'], `${rPath}/archetypeRoleId`); + const purpose = expectEnum(rObj['purpose'], ['task', 'review'] as const, `${rPath}/purpose`); + const prompt = expectString(rObj['prompt'], 1, LIMITS.string, `${rPath}/prompt`); + if (hasDisallowedInlineControlChar(prompt) || prompt.trim().length === 0) { + schemaInvalid('role prompt must be non-empty text', `${rPath}/prompt`); + } + + const rawTools = expectArray(rObj['tools'], 0, LIMITS.tools, `${rPath}/tools`); + const seenTools = new Set(); + const tools: string[] = []; + for (let j = 0; j < rawTools.length; j++) { + const tool = expectString(rawTools[j], 1, LIMITS.toolName, `${rPath}/tools/${j}`); + if (FORBIDDEN_PROTOTYPE_KEYS.has(tool) || !TOOL_NAME_RE.test(tool)) { + schemaInvalid(`invalid tool name "${tool}"`, `${rPath}/tools/${j}`); + } + if (seenTools.has(tool)) schemaInvalid(`duplicate tool "${tool}"`, `${rPath}/tools/${j}`); + seenTools.add(tool); + tools.push(tool); + } + + const roleRec = createNullRecord<{ + id: string; + archetypeRoleId: string; + purpose: 'task' | 'review'; + prompt: string; + model?: string; + thinking?: string; + tools: readonly string[]; + resourceIds?: readonly string[]; + timeoutSeconds?: number; + }>(); + roleRec.id = id; + roleRec.archetypeRoleId = archetypeRoleId; + roleRec.purpose = purpose; + roleRec.prompt = prompt; + if (Object.hasOwn(rObj, 'model') && rObj['model'] !== undefined) { + const model = expectString(rObj['model'], 1, 128, `${rPath}/model`); + if (!MODEL_LABEL_RE.test(model)) schemaInvalid('invalid model label', `${rPath}/model`); + roleRec.model = model; + } + if (Object.hasOwn(rObj, 'thinking') && rObj['thinking'] !== undefined) { + const thinking = expectString(rObj['thinking'], 1, 64, `${rPath}/thinking`); + if (!MODEL_LABEL_RE.test(thinking)) schemaInvalid('invalid thinking level', `${rPath}/thinking`); + roleRec.thinking = thinking; + } + roleRec.tools = tools; + if (Object.hasOwn(rObj, 'resourceIds') && rObj['resourceIds'] !== undefined) { + const rawRes = expectArray(rObj['resourceIds'], 0, LIMITS.resources, `${rPath}/resourceIds`); + const seenRes = new Set(); + const resourceIds: string[] = []; + for (let j = 0; j < rawRes.length; j++) { + const resId = expectIdentifier(rawRes[j], `${rPath}/resourceIds/${j}`); + if (seenRes.has(resId)) schemaInvalid(`duplicate resourceId "${resId}"`, `${rPath}/resourceIds/${j}`); + seenRes.add(resId); + resourceIds.push(resId); + } + roleRec.resourceIds = resourceIds; + } + if (Object.hasOwn(rObj, 'timeoutSeconds') && rObj['timeoutSeconds'] !== undefined) { + roleRec.timeoutSeconds = expectInteger(rObj['timeoutSeconds'], 1, 86_400, `${rPath}/timeoutSeconds`); + } + roles.push(roleRec as TeamPatchRole); + } + + const rawSteps = expectArray(root['steps'], 1, maxTeamSteps, '/steps'); + const seenStepIds = new Set(); + const steps: TeamPatchStep[] = []; + for (let i = 0; i < rawSteps.length; i++) { + const sPath = `/steps/${i}`; + const sObj = expectObject(rawSteps[i]!, TEAM_STEP_KEYS, ['id', 'roleId', 'dependsOn'], sPath); + const id = expectIdentifier(sObj['id'], `${sPath}/id`); + if (seenStepIds.has(id)) schemaInvalid(`duplicate step id "${id}"`, `${sPath}/id`); + seenStepIds.add(id); + + const roleId = expectIdentifier(sObj['roleId'], `${sPath}/roleId`); + if (!seenRoleIds.has(roleId)) { + schemaInvalid(`step "${id}" references unknown roleId "${roleId}"`, `${sPath}/roleId`); + } + + const rawDeps = expectArray(sObj['dependsOn'], 0, maxTeamSteps, `${sPath}/dependsOn`); + const seenDeps = new Set(); + const dependsOn: string[] = []; + for (let j = 0; j < rawDeps.length; j++) { + const dep = expectIdentifier(rawDeps[j], `${sPath}/dependsOn/${j}`); + if (dep === id) schemaInvalid(`step "${id}" cannot depend on itself`, `${sPath}/dependsOn/${j}`); + if (seenDeps.has(dep)) schemaInvalid(`duplicate dependency "${dep}"`, `${sPath}/dependsOn/${j}`); + seenDeps.add(dep); + dependsOn.push(dep); + } + + const stepRec = createNullRecord<{ + id: string; + roleId: string; + dependsOn: readonly string[]; + handoffs?: readonly StepHandoffSelector[]; + onRework?: ReworkPolicy; + }>(); + stepRec.id = id; + stepRec.roleId = roleId; + stepRec.dependsOn = dependsOn; + + if (Object.hasOwn(sObj, 'handoffs') && sObj['handoffs'] !== undefined) { + const rawHandoffs = expectArray(sObj['handoffs'], 1, HANDOFF_LIMITS.maxPerStep, `${sPath}/handoffs`); + const seenHandoffIds = new Set(); + let aggregateBytes = 0; + const handoffs: StepHandoffSelector[] = []; + for (let j = 0; j < rawHandoffs.length; j++) { + const handoff = parseStepHandoffSelectorValue(rawHandoffs[j]!, `${sPath}/handoffs/${j}`); + const effectiveId = handoff.id ?? `handoff-${j + 1}`; + if (seenHandoffIds.has(effectiveId)) { + schemaInvalid(`duplicate handoff id "${effectiveId}"`, `${sPath}/handoffs/${j}/id`); + } + seenHandoffIds.add(effectiveId); + aggregateBytes += handoff.maxBytes ?? HANDOFF_LIMITS.defaultBytes; + if (aggregateBytes > HANDOFF_LIMITS.maxAggregateBytes) { + schemaInvalid('step handoffs exceed aggregate byte limit', `${sPath}/handoffs/${j}`); + } + handoffs.push(handoff); + } + stepRec.handoffs = handoffs; + } + + if (Object.hasOwn(sObj, 'onRework') && sObj['onRework'] !== undefined) { + const rwObj = expectObject(sObj['onRework'], REWORK_POLICY_KEYS, ['rejectTo', 'maxReworks'], `${sPath}/onRework`); + const rework = createNullRecord<{ rejectTo: string; maxReworks: number }>(); + rework.rejectTo = expectIdentifier(rwObj['rejectTo'], `${sPath}/onRework/rejectTo`); + rework.maxReworks = expectInteger(rwObj['maxReworks'], 1, LIMITS.maxReworks, `${sPath}/onRework/maxReworks`); + stepRec.onRework = rework; + } + steps.push(stepRec as TeamPatchStep); + } + + // Verify dependsOn references and strict DAG acyclicity via Kahn topological sort + const inDegree = new Map(); + const childrenByStep = new Map(); + const depsByStep = new Map(); + for (const step of steps) { + inDegree.set(step.id, step.dependsOn.length); + childrenByStep.set(step.id, []); + depsByStep.set(step.id, step.dependsOn); + } + for (let i = 0; i < steps.length; i++) { + const step = steps[i]!; + for (let j = 0; j < step.dependsOn.length; j++) { + const dep = step.dependsOn[j]!; + if (!seenStepIds.has(dep)) { + schemaInvalid(`step "${step.id}" depends on unknown step "${dep}"`, `/steps/${i}/dependsOn/${j}`); + } + childrenByStep.get(dep)!.push(step.id); + } + } + + const ready: string[] = []; + for (const [stepId, deg] of inDegree) { + if (deg === 0) ready.push(stepId); + } + let visitedCount = 0; + while (ready.length > 0) { + const current = ready.shift()!; + visitedCount++; + for (const child of childrenByStep.get(current) ?? []) { + const nextDeg = (inDegree.get(child) ?? 0) - 1; + inDegree.set(child, nextDeg); + if (nextDeg === 0) ready.push(child); + } + } + if (visitedCount !== steps.length) { + schemaInvalid('team-patch.v1 steps[] contains a dependency cycle', '/steps'); + } + + // Verify handoffs and onRework reference strict DAG ancestors + for (let i = 0; i < steps.length; i++) { + const step = steps[i]!; + if (step.handoffs === undefined && step.onRework === undefined) continue; + const ancestors = collectStrictAncestors(step.id, depsByStep); + if (step.onRework !== undefined) { + if (!seenStepIds.has(step.onRework.rejectTo) || !ancestors.has(step.onRework.rejectTo)) { + schemaInvalid('onRework.rejectTo must reference a strict ancestor step', `/steps/${i}/onRework/rejectTo`); + } + } + if (step.handoffs !== undefined) { + for (let j = 0; j < step.handoffs.length; j++) { + const fromStep = step.handoffs[j]!.fromStep; + if (!seenStepIds.has(fromStep) || !ancestors.has(fromStep)) { + schemaInvalid('handoff.fromStep must reference a strict ancestor step', `/steps/${i}/handoffs/${j}/fromStep`); + } + } + } + } + + const patch = createNullRecord<{ + kind: typeof TEAM_PATCH_KIND; + schemaVersion: typeof TEAM_PATCH_SCHEMA_VERSION; + diagnosis: TeamPatchDiagnosis; + roles: readonly TeamPatchRole[]; + steps: readonly TeamPatchStep[]; + }>(); + patch.kind = TEAM_PATCH_KIND; + patch.schemaVersion = TEAM_PATCH_SCHEMA_VERSION; + patch.diagnosis = diagnosis; + patch.roles = roles; + patch.steps = steps; + + const serialized = canonicalizeJson(patch); + if (Buffer.byteLength(serialized, 'utf8') > TEAM_PATCH_MAX_BYTES) { + schemaInvalid(`team-patch.v1 exceeds ${TEAM_PATCH_MAX_BYTES} bytes`, '/'); + } + assertCleanSecrets(serialized, scrubber, '/'); + return patch as TeamPatchV1; +} + +// --------------------------------------------------------------------------- +// DispatchManifestV1 (`dispatch-manifest.json`) parser +// --------------------------------------------------------------------------- + +export interface ParseDispatchManifestOptions { + readonly scrubber?: SecretScrubber; +} + +const DISPATCH_ROOT_KEYS = new Set(['version', 'fallback', 'rules']); +const DISPATCH_RULE_KEYS = new Set([ + 'bucketId', + 'dimensionBounds', + 'dtypes', + 'alignmentBytes', + 'blobDigest', + 'blobPath', + 'entrypoint', +]); +const DIMENSION_RANGE_KEYS = new Set(['min', 'max']); + +/** Parse and validate `dispatch-manifest.json` (`1..64` rules, mandatory `fallback: 'baseline'`). */ +export function parseDispatchManifestV1( + input: unknown, + options: ParseDispatchManifestOptions = {}, +): DispatchManifestV1 { + const scrubber = options.scrubber ?? DEFAULT_SECRET_SCRUBBER; + const rootVal = typeof input === 'string' + ? parseNullProtoJson(input, DISPATCH_MANIFEST_MAX_BYTES, '') + : input instanceof Uint8Array + ? parseNullProtoJson(decodeUtf8Strict(input, ''), DISPATCH_MANIFEST_MAX_BYTES, '') + : sanitizeUntrustedValue(input, { maxBytes: DISPATCH_MANIFEST_MAX_BYTES, path: '' }); + + const root = expectObject(rootVal, DISPATCH_ROOT_KEYS, ['version', 'fallback', 'rules'], ''); + if (root['version'] !== 1) { + schemaInvalid('dispatch manifest version must be 1', '/version'); + } + if (root['fallback'] !== 'baseline') { + schemaInvalid('dispatch manifest fallback must be "baseline"', '/fallback'); + } + + const rawRules = expectArray(root['rules'], 1, DISPATCH_MANIFEST_MAX_RULES, '/rules'); + const rules: DispatchRuleV1[] = []; + for (let i = 0; i < rawRules.length; i++) { + const rPath = `/rules/${i}`; + const rObj = expectObject(rawRules[i]!, DISPATCH_RULE_KEYS, ['bucketId', 'blobDigest', 'entrypoint'], rPath); + const bucketId = expectBucketId(rObj['bucketId'], `${rPath}/bucketId`); + const blobDigest = expectDigest(rObj['blobDigest'], `${rPath}/blobDigest`); + const entrypoint = expectString(rObj['entrypoint'], 1, 256, `${rPath}/entrypoint`); + if (!ENTRYPOINT_SYMBOL_RE.test(entrypoint)) { + schemaInvalid(`invalid entrypoint symbol "${entrypoint}"`, `${rPath}/entrypoint`); + } + + const ruleRec = createNullRecord<{ + bucketId: string; + dimensionBounds?: Readonly>; + dtypes?: readonly string[]; + alignmentBytes?: number; + blobDigest: Digest; + blobPath?: string; + entrypoint: string; + }>(); + ruleRec.bucketId = bucketId; + + if (Object.hasOwn(rObj, 'dimensionBounds') && rObj['dimensionBounds'] !== undefined) { + const dimVal = rObj['dimensionBounds']; + if (dimVal === null || typeof dimVal !== 'object' || Array.isArray(dimVal)) { + schemaInvalid('dimensionBounds must be an object', `${rPath}/dimensionBounds`); + } + const dimObj = dimVal as Record; + const dimKeys = Object.keys(dimObj).sort(); + if (dimKeys.length > LIMITS.bucketDimensionEntries) { + schemaInvalid('dimensionBounds exceeds maximum dimension keys', `${rPath}/dimensionBounds`); + } + const boundsMap = createNullRecord>(); + for (const dimKey of dimKeys) { + if (!Object.hasOwn(dimObj, dimKey)) continue; + expectMetricKey(dimKey, `${rPath}/dimensionBounds/${dimKey}`); + const rangeObj = expectObject(dimObj[dimKey]!, DIMENSION_RANGE_KEYS, [], `${rPath}/dimensionBounds/${dimKey}`); + const hasMin = Object.hasOwn(rangeObj, 'min') && rangeObj['min'] !== undefined; + const hasMax = Object.hasOwn(rangeObj, 'max') && rangeObj['max'] !== undefined; + if (!hasMin && !hasMax) { + schemaInvalid('dimension range must specify min and/or max', `${rPath}/dimensionBounds/${dimKey}`); + } + const rangeRec = createNullRecord<{ min?: number; max?: number }>(); + if (hasMin) { + rangeRec.min = expectFiniteNumber(rangeObj['min'], {}, `${rPath}/dimensionBounds/${dimKey}/min`); + } + if (hasMax) { + rangeRec.max = expectFiniteNumber(rangeObj['max'], {}, `${rPath}/dimensionBounds/${dimKey}/max`); + } + if (rangeRec.min !== undefined && rangeRec.max !== undefined && rangeRec.min > rangeRec.max) { + schemaInvalid('dimension range min cannot exceed max', `${rPath}/dimensionBounds/${dimKey}`); + } + boundsMap[dimKey] = rangeRec; + } + ruleRec.dimensionBounds = boundsMap; + } + + if (Object.hasOwn(rObj, 'dtypes') && rObj['dtypes'] !== undefined) { + const rawDtypes = expectArray(rObj['dtypes'], 1, 16, `${rPath}/dtypes`); + const seenDtypes = new Set(); + const dtypes: string[] = []; + for (let j = 0; j < rawDtypes.length; j++) { + const dt = expectString(rawDtypes[j], 1, 32, `${rPath}/dtypes/${j}`); + if (!DTYPE_TOKEN_RE.test(dt)) schemaInvalid(`invalid dtype "${dt}"`, `${rPath}/dtypes/${j}`); + if (seenDtypes.has(dt)) schemaInvalid(`duplicate dtype "${dt}"`, `${rPath}/dtypes/${j}`); + seenDtypes.add(dt); + dtypes.push(dt); + } + ruleRec.dtypes = dtypes; + } + + if (Object.hasOwn(rObj, 'alignmentBytes') && rObj['alignmentBytes'] !== undefined) { + ruleRec.alignmentBytes = expectInteger(rObj['alignmentBytes'], 1, 4_096, `${rPath}/alignmentBytes`); + } + + ruleRec.blobDigest = blobDigest; + if (Object.hasOwn(rObj, 'blobPath') && rObj['blobPath'] !== undefined) { + const blobPath = expectString(rObj['blobPath'], 1, 128, `${rPath}/blobPath`); + const expectedPath = `blobs/sha256/${blobDigest.hex}`; + if (blobPath !== expectedPath) { + schemaInvalid(`blobPath must equal "${expectedPath}"`, `${rPath}/blobPath`); + } + ruleRec.blobPath = blobPath; + } + ruleRec.entrypoint = entrypoint; + rules.push(ruleRec as DispatchRuleV1); + } + + const manifest = createNullRecord<{ + version: 1; + fallback: 'baseline'; + rules: readonly DispatchRuleV1[]; + }>(); + manifest.version = 1; + manifest.fallback = 'baseline'; + manifest.rules = rules; + + assertCleanSecrets(canonicalizeJson(manifest), scrubber, '/'); + return manifest as DispatchManifestV1; +} + +// --------------------------------------------------------------------------- +// Strict SQLite JSON column validators into null-prototype records +// --------------------------------------------------------------------------- + +export function parseMetricsRecordJson(rawJson: string | Readonly>, path = '/metrics'): Readonly> { + const val = typeof rawJson === 'string' + ? parseNullProtoJson(rawJson, 16_384, path) + : sanitizeUntrustedValue(rawJson, { maxBytes: 16_384, path }); + if (val === null || typeof val !== 'object' || Array.isArray(val)) { + schemaInvalid('metrics must be an object', path); + } + const rec = val as Record; + const keys = Object.keys(rec).sort(); + if (keys.length > LIMITS.metricEntries) { + schemaInvalid('metrics exceeds maximum entry count', path); + } + const out = createNullRecord>(); + for (const key of keys) { + if (!Object.hasOwn(rec, key)) continue; + expectMetricKey(key, `${path}/${key}`); + out[key] = expectFiniteNumber(rec[key], {}, `${path}/${key}`); + } + return out; +} + +const ARTIFACT_REF_KEYS = new Set(['name', 'digest', 'byteLength', 'uri', 'mediaType']); + +export function parseArtifactRefsJson(rawJson: string | readonly ArtifactRef[], path = '/outputArtifacts'): readonly ArtifactRef[] { + const val = typeof rawJson === 'string' + ? parseNullProtoJson(rawJson, 65_536, path) + : sanitizeUntrustedValue(rawJson, { maxBytes: 65_536, path }); + const arr = expectArray(val, 0, LIMITS.manifest, path); + const out: ArtifactRef[] = []; + for (let i = 0; i < arr.length; i++) { + const aPath = `${path}/${i}`; + const obj = expectObject(arr[i]!, ARTIFACT_REF_KEYS, ['name', 'digest', 'byteLength'], aPath); + const rawName = expectString(obj['name'], 1, LIMITS.path, `${aPath}/name`); + const vPath = validateRelativePath(rawName); + if (!vPath.ok) schemaInvalid('invalid artifact relative path', `${aPath}/name`); + const digest = expectDigest(obj['digest'], `${aPath}/digest`); + const byteLength = expectInteger(obj['byteLength'], 0, Number.MAX_SAFE_INTEGER, `${aPath}/byteLength`); + const ref = createNullRecord<{ + name: string; + digest: Digest; + byteLength: number; + uri?: string | null; + mediaType?: string | null; + }>(); + ref.name = vPath.value; + ref.digest = digest; + ref.byteLength = byteLength; + if (Object.hasOwn(obj, 'uri')) { + ref.uri = obj['uri'] === null ? null : expectString(obj['uri'], 1, LIMITS.artifactUri, `${aPath}/uri`); + } + if (Object.hasOwn(obj, 'mediaType')) { + ref.mediaType = obj['mediaType'] === null ? null : expectString(obj['mediaType'], 1, LIMITS.mediaType, `${aPath}/mediaType`); + } + out.push(ref as ArtifactRef); + } + return out; +} + +export function parseBucketMetricsJson( + rawJson: string | readonly BucketMetricEntry[], + scrubber: SecretScrubber = DEFAULT_SECRET_SCRUBBER, +): readonly BucketMetricEntry[] { + const val = typeof rawJson === 'string' + ? parseNullProtoJson(rawJson, 49_152, '/bucketMetrics') + : sanitizeUntrustedValue(rawJson, { maxBytes: 49_152, path: '/bucketMetrics' }); + const res = validateBucketMetrics(val, scrubber); + if (!res.ok) { + schemaInvalid(`invalid bucketMetrics (${res.errors[0]?.code ?? 'INVALID'})`, res.errors[0]?.path ?? '/bucketMetrics'); + } + return res.value; +} + +export function parseHardwareDiagnosticsJson( + rawJson: string | HardwareDiagnostics, + scrubber: SecretScrubber = DEFAULT_SECRET_SCRUBBER, +): HardwareDiagnostics { + const val = typeof rawJson === 'string' + ? parseNullProtoJson(rawJson, 16_384, '/hardwareDiagnostics') + : sanitizeUntrustedValue(rawJson, { maxBytes: 16_384, path: '/hardwareDiagnostics' }); + const res = validateHardwareDiagnostics(val, scrubber); + if (!res.ok) { + schemaInvalid(`invalid hardwareDiagnostics (${res.errors[0]?.code ?? 'INVALID'})`, res.errors[0]?.path ?? '/hardwareDiagnostics'); + } + return res.value; +} + +const HARDWARE_PROVENANCE_KEYS = new Set([ + 'targetCellId', + 'probeKind', + 'vendor', + 'deviceModel', + 'accelerator', + 'isolationMode', + 'deviceCount', + 'driverVersion', + 'runtimeVersion', + 'topology', + 'workloadDigest', + 'clockLockMode', +]); + +export function parseHardwareProvenanceJson(rawJson: string | HardwareProvenance, path = '/hardwareProvenance'): HardwareProvenance { + const val = typeof rawJson === 'string' + ? parseNullProtoJson(rawJson, 16_384, path) + : sanitizeUntrustedValue(rawJson, { maxBytes: 16_384, path }); + const obj = expectObject( + val, + HARDWARE_PROVENANCE_KEYS, + [ + 'targetCellId', + 'probeKind', + 'vendor', + 'deviceModel', + 'accelerator', + 'isolationMode', + 'deviceCount', + 'driverVersion', + 'runtimeVersion', + 'workloadDigest', + 'clockLockMode', + ], + path, + ); + const prov = createNullRecord<{ + targetCellId: string; + probeKind: 'physical' | 'synthetic_fixture'; + vendor: string; + deviceModel: string; + accelerator: string; + isolationMode: 'whole_device' | 'sliced'; + deviceCount: number; + driverVersion: string; + runtimeVersion: string; + topology?: string; + workloadDigest: Digest; + clockLockMode: 'locked' | 'unlocked' | 'unknown'; + }>(); + prov.targetCellId = expectIdentifier(obj['targetCellId'], `${path}/targetCellId`); + prov.probeKind = expectEnum(obj['probeKind'], ['physical', 'synthetic_fixture'] as const, `${path}/probeKind`); + prov.vendor = expectString(obj['vendor'], 1, 128, `${path}/vendor`); + prov.deviceModel = expectString(obj['deviceModel'], 1, 128, `${path}/deviceModel`); + prov.accelerator = expectString(obj['accelerator'], 1, 64, `${path}/accelerator`); + prov.isolationMode = expectEnum(obj['isolationMode'], ['whole_device', 'sliced'] as const, `${path}/isolationMode`); + prov.deviceCount = expectInteger(obj['deviceCount'], 1, 64, `${path}/deviceCount`); + prov.driverVersion = expectString(obj['driverVersion'], 1, 128, `${path}/driverVersion`); + prov.runtimeVersion = expectString(obj['runtimeVersion'], 1, 128, `${path}/runtimeVersion`); + if (Object.hasOwn(obj, 'topology') && obj['topology'] !== undefined) { + prov.topology = expectString(obj['topology'], 1, 128, `${path}/topology`); + } + prov.workloadDigest = expectDigest(obj['workloadDigest'], `${path}/workloadDigest`); + prov.clockLockMode = expectEnum(obj['clockLockMode'], ['locked', 'unlocked', 'unknown'] as const, `${path}/clockLockMode`); + return prov as HardwareProvenance; +} + +const FINDING_KEYS = new Set(['title', 'severity', 'path', 'line', 'evidence']); + +export function parseStructuredFindingsJson( + rawJson: string | readonly StructuredFinding[], + path = '/findings', +): readonly StructuredFinding[] { + const val = typeof rawJson === 'string' + ? parseNullProtoJson(rawJson, 65_536, path) + : sanitizeUntrustedValue(rawJson, { maxBytes: 65_536, path }); + const arr = expectArray(val, 0, LIMITS.findings, path); + const out: StructuredFinding[] = []; + for (let i = 0; i < arr.length; i++) { + const fPath = `${path}/${i}`; + const obj = expectObject(arr[i]!, FINDING_KEYS, ['title', 'severity', 'evidence'], fPath); + const f = createNullRecord<{ + title: string; + severity: FindingSeverity; + path?: string | null; + line?: number | null; + evidence: string; + }>(); + f.title = expectString(obj['title'], 1, LIMITS.findingTitle, `${fPath}/title`); + f.severity = expectEnum(obj['severity'], ['critical', 'high', 'medium', 'low'] as const, `${fPath}/severity`); + if (Object.hasOwn(obj, 'path')) { + if (obj['path'] === null) { + f.path = null; + } else { + const rel = expectString(obj['path'], 1, LIMITS.path, `${fPath}/path`); + const vRes = validateRelativePath(rel); + if (!vRes.ok) schemaInvalid('invalid finding path', `${fPath}/path`); + f.path = vRes.value; + } + } + if (Object.hasOwn(obj, 'line')) { + f.line = obj['line'] === null ? null : expectInteger(obj['line'], 1, Number.MAX_SAFE_INTEGER, `${fPath}/line`); + } + f.evidence = expectString(obj['evidence'], 1, LIMITS.findingEvidence, `${fPath}/evidence`); + out.push(f as StructuredFinding); + } + return out; +} diff --git a/packages/evolution/src/scratchpad.ts b/packages/evolution/src/scratchpad.ts new file mode 100644 index 0000000..38f8a84 --- /dev/null +++ b/packages/evolution/src/scratchpad.ts @@ -0,0 +1,353 @@ +import { SecretScrubber } from '@loopwright/core'; +import type { EvolutionCampaignStore } from './store.js'; +import { + EvolutionError, + SCRATCHPAD_MAX_BYTES, + type CampaignLease, + type IndividualRecord, + type ObjectiveDirectionSpec, + type ScratchpadSnapshotRecord, +} from './types.js'; + +const DEFAULT_SECRET_SCRUBBER = new SecretScrubber(); + +export interface ScratchpadNicheGainEntry { + readonly nicheKey: string; + readonly childIndividualId: string; + readonly parentIndividualId: string; + readonly primaryMetric: string; + readonly speedupRatio: number; + readonly relativeDeltaPct: number; + readonly pipelineShift: string; +} + +export interface ScratchpadFailurePatternEntry { + readonly patternKey: string; + readonly count: number; + readonly sampleDetail: string; +} + +export interface SynthesizeCampaignScratchpadOptions { + readonly store: EvolutionCampaignStore; + readonly lease: CampaignLease; + readonly campaignId: string; + readonly generation: number; + readonly snapshotId?: string; + readonly maxBytes?: number; + readonly scrubber?: SecretScrubber; +} + +export interface SynthesizedCampaignScratchpad { + readonly snapshot: ScratchpadSnapshotRecord; + readonly content: string; + readonly casFilePath: string; + readonly topGains: readonly ScratchpadNicheGainEntry[]; + readonly failurePatterns: readonly ScratchpadFailurePatternEntry[]; +} + +function sanitizeSingleLine(raw: string, maxChars: number, scrubber: SecretScrubber): string { + const scrubbed = scrubber.scrub(raw).replace(/[\r\n\t]+/g, ' ').trim(); + if (scrubbed.length <= maxChars) return scrubbed; + return `${scrubbed.slice(0, Math.max(0, maxChars - 3))}...`; +} + +function computePrimaryObjectiveGain( + child: IndividualRecord, + parent: IndividualRecord, + objective: ObjectiveDirectionSpec, +): { readonly speedupRatio: number; readonly relativeDeltaPct: number } | null { + if (!Object.hasOwn(child.metrics, objective.metric) || !Object.hasOwn(parent.metrics, objective.metric)) { + return null; + } + const cVal = child.metrics[objective.metric]; + const pVal = parent.metrics[objective.metric]; + if (cVal === undefined || pVal === undefined || !Number.isFinite(cVal) || !Number.isFinite(pVal)) { + return null; + } + + if (objective.direction === 'minimize') { + if (cVal >= pVal) return null; + if (cVal > 0 && pVal > 0) { + return { + speedupRatio: pVal / cVal, + relativeDeltaPct: ((cVal - pVal) / pVal) * 100, + }; + } + const diff = pVal - cVal; + return { + speedupRatio: 1 + diff, + relativeDeltaPct: pVal !== 0 ? ((cVal - pVal) / Math.abs(pVal)) * 100 : -100, + }; + } + + if (cVal <= pVal) return null; + if (pVal > 0) { + return { + speedupRatio: cVal / pVal, + relativeDeltaPct: ((cVal - pVal) / pVal) * 100, + }; + } + return { + speedupRatio: 1 + (cVal - pVal), + relativeDeltaPct: 100, + }; +} + +function classifyFailurePatternKey( + ind: IndividualRecord, + parent: IndividualRecord | undefined, +): string { + if (ind.status === 'failed') { + const baseReason = ind.failureReason ?? 'UNKNOWN_FAILURE'; + const joinedFindings = (ind.findings ?? []) + .map(f => `${f.title} ${f.evidence}`.toLowerCase()) + .join(' '); + if (baseReason === 'STAGE_A_STATIC_AUDIT_FAILED') { + return 'STAGE_A_STATIC_AUDIT_FAILED'; + } + if ( + (Object.hasOwn(ind.metrics, 'max_ulp') && (ind.metrics['max_ulp'] ?? 0) > 0) + || joinedFindings.includes('ulp') + ) { + return `${baseReason}:ULP_DRIFT`; + } + if ( + Object.hasOwn(ind.metrics, 'token_force_max_delta') + || joinedFindings.includes('token_force') + ) { + return `${baseReason}:TOKEN_FORCE_DRIFT`; + } + if (joinedFindings.includes('spill')) { + return `${baseReason}:SPILL_REGRESSION`; + } + return baseReason; + } + + const childSpill = ind.hardwareDiagnostics?.localSpillBytes; + const parentSpill = parent?.hardwareDiagnostics?.localSpillBytes ?? 0; + if (childSpill !== undefined && childSpill > parentSpill) { + return 'SPILL_REGRESSION'; + } + return 'OBJECTIVE_REGRESSION'; +} + +function renderScratchpadMarkdown( + campaignId: string, + campaignName: string, + generation: number, + gains: readonly ScratchpadNicheGainEntry[], + patterns: readonly ScratchpadFailurePatternEntry[], + maxGains: number, + maxPatterns: number, +): string { + const lines: string[] = [ + `# Campaign Scratchpad: ${campaignName}`, + '', + `- Campaign ID: \`${campaignId}\``, + `- Generation: ${generation}`, + '', + '## Top Niche Gains', + ]; + + const slicedGains = gains.slice(0, maxGains); + if (slicedGains.length === 0) { + lines.push('- None recorded yet.'); + } else { + for (const g of slicedGains) { + const sign = g.relativeDeltaPct >= 0 ? '+' : ''; + lines.push( + `- Niche \`${g.nicheKey}\`: \`${g.parentIndividualId}\` -> \`${g.childIndividualId}\` | ` + + `\`${g.primaryMetric}\` **${g.speedupRatio.toFixed(2)}x** (${sign}${g.relativeDeltaPct.toFixed(1)}%) | ` + + `pipeline \`${g.pipelineShift}\``, + ); + } + } + + lines.push('', '## Recurring Failure and Regression Patterns'); + const slicedPatterns = patterns.slice(0, maxPatterns); + if (slicedPatterns.length === 0) { + lines.push('- None recorded yet.'); + } else { + for (const p of slicedPatterns) { + lines.push(`- \`${p.patternKey}\` (${p.count}x): ${p.sampleDetail}`); + } + } + + lines.push(''); + return lines.join('\n'); +} + +/** + * Deterministically synthesize a `<= 16,384`-byte, `SecretScrubber`-clean campaign scratchpad + * from verified `campaign.sqlite` lineage deltas, persist to CAS (`0o400`, `O_NOFOLLOW`), + * and record metadata in `scratchpad_snapshots`. + */ +export async function synthesizeCampaignScratchpad( + options: SynthesizeCampaignScratchpadOptions, +): Promise { + const maxBytes = options.maxBytes ?? SCRATCHPAD_MAX_BYTES; + if (!Number.isSafeInteger(maxBytes) || maxBytes < 512 || maxBytes > SCRATCHPAD_MAX_BYTES) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', `maxBytes must be within 512..${SCRATCHPAD_MAX_BYTES}`); + } + if (!Number.isSafeInteger(options.generation) || options.generation < 0) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'generation must be an integer >= 0'); + } + + const scrubber = options.scrubber ?? DEFAULT_SECRET_SCRUBBER; + const campaign = await options.store.getCampaign(options.campaignId); + if (!campaign) { + throw new EvolutionError('EVOLUTION_NOT_FOUND', `campaign "${options.campaignId}" not found`); + } + + const individuals = await options.store.listIndividuals(options.campaignId); + const lineageEdges = await options.store.listLineageEdges(options.campaignId, { role: 'primary' }); + + const byId = new Map(); + for (const ind of individuals) { + byId.set(ind.individualId, ind); + } + + const primaryParentByChild = new Map(); + for (const edge of lineageEdges) { + const parent = byId.get(edge.parentIndividualId); + if (parent && !primaryParentByChild.has(edge.childIndividualId)) { + primaryParentByChild.set(edge.childIndividualId, parent); + } + } + + const primaryObjective = campaign.manifest.spec.objectives[0]!; + const bestGainByNiche = new Map(); + const patternBuckets = new Map(); + + const recordPattern = (key: string, rawDetail: string): void => { + const safeKey = sanitizeSingleLine(key, 96, scrubber); + const safeDetail = sanitizeSingleLine(rawDetail, 160, scrubber); + const existing = patternBuckets.get(safeKey); + if (!existing) { + patternBuckets.set(safeKey, { count: 1, sampleDetail: safeDetail }); + } else { + existing.count += 1; + } + }; + + for (const ind of individuals) { + if (ind.status === 'preempted') continue; + const parent = primaryParentByChild.get(ind.individualId); + + if (ind.status === 'failed') { + const patternKey = classifyFailurePatternKey(ind, parent); + const firstFinding = ind.findings?.[0]; + const detail = firstFinding + ? `${firstFinding.title} - ${firstFinding.evidence}` + : (ind.failureReason ?? 'candidate verification failed'); + recordPattern(patternKey, detail); + continue; + } + + if (!parent) continue; + const gain = computePrimaryObjectiveGain(ind, parent, primaryObjective); + if (gain !== null) { + const nicheKey = sanitizeSingleLine(ind.nicheKey ?? 'unclassified', 120, scrubber); + const parentPipe = parent.hardwareDiagnostics?.boundPipeline ?? 'unknown'; + const childPipe = ind.hardwareDiagnostics?.boundPipeline ?? 'unknown'; + const entry: ScratchpadNicheGainEntry = Object.freeze({ + nicheKey, + childIndividualId: ind.individualId, + parentIndividualId: parent.individualId, + primaryMetric: primaryObjective.metric, + speedupRatio: gain.speedupRatio, + relativeDeltaPct: gain.relativeDeltaPct, + pipelineShift: `${parentPipe} -> ${childPipe}`, + }); + const incumbent = bestGainByNiche.get(nicheKey); + if ( + !incumbent + || entry.speedupRatio > incumbent.speedupRatio + || (entry.speedupRatio === incumbent.speedupRatio && entry.childIndividualId < incumbent.childIndividualId) + ) { + bestGainByNiche.set(nicheKey, entry); + } + } else if ( + ind.hardwareDiagnostics?.localSpillBytes !== undefined + && ind.hardwareDiagnostics.localSpillBytes > (parent.hardwareDiagnostics?.localSpillBytes ?? 0) + ) { + recordPattern( + 'SPILL_REGRESSION', + `localSpillBytes increased ${parent.hardwareDiagnostics?.localSpillBytes ?? 0} -> ${ind.hardwareDiagnostics.localSpillBytes} in ${ind.individualId}`, + ); + } + } + + const topGains = [...bestGainByNiche.values()].sort((a, b) => { + if (b.speedupRatio !== a.speedupRatio) return b.speedupRatio - a.speedupRatio; + if (a.nicheKey !== b.nicheKey) return a.nicheKey < b.nicheKey ? -1 : 1; + return a.childIndividualId < b.childIndividualId ? -1 : a.childIndividualId > b.childIndividualId ? 1 : 0; + }); + + const failurePatterns: ScratchpadFailurePatternEntry[] = [...patternBuckets.entries()] + .map(([patternKey, info]) => + Object.freeze({ + patternKey, + count: info.count, + sampleDetail: info.sampleDetail, + }), + ) + .sort((a, b) => { + if (b.count !== a.count) return b.count - a.count; + return a.patternKey < b.patternKey ? -1 : a.patternKey > b.patternKey ? 1 : 0; + }); + + const safeName = sanitizeSingleLine(campaign.name, 64, scrubber); + const safeCampaignId = sanitizeSingleLine(campaign.campaignId, 64, scrubber); + + let maxGains = Math.min(topGains.length, 32); + let maxPatterns = Math.min(failurePatterns.length, 32); + let rendered = scrubber.scrub( + renderScratchpadMarkdown(safeCampaignId, safeName, options.generation, topGains, failurePatterns, maxGains, maxPatterns), + ); + + while (Buffer.byteLength(rendered, 'utf8') > maxBytes && (maxGains > 0 || maxPatterns > 0)) { + if (maxGains >= maxPatterns && maxGains > 0) { + maxGains--; + } else if (maxPatterns > 0) { + maxPatterns--; + } else { + break; + } + rendered = scrubber.scrub( + renderScratchpadMarkdown(safeCampaignId, safeName, options.generation, topGains, failurePatterns, maxGains, maxPatterns), + ); + } + + if (Buffer.byteLength(rendered, 'utf8') > maxBytes) { + const buf = Buffer.from(rendered, 'utf8'); + let end = maxBytes - 1; + while (end > 0 && (buf[end]! & 0xc0) === 0x80) end--; + rendered = `${scrubber.scrub(buf.subarray(0, end).toString('utf8'))}\n`; + } + + if (scrubber.containsSecret(rendered)) { + throw new EvolutionError('SECRET_LEAK_DETECTED', 'scratchpad synthesis output failed SecretScrubber check'); + } + + const casBlob = await options.store.writeCasBlob(rendered); + const snapshotId = options.snapshotId ?? `${options.campaignId}-gen${options.generation}-${casBlob.digest.hex.slice(0, 12)}`; + const snapshot = await options.store.recordScratchpadSnapshot(options.lease, { + snapshotId, + campaignId: options.campaignId, + generation: options.generation, + casDigest: casBlob.digest, + byteLength: casBlob.byteLength, + casRelPath: casBlob.casRelPath, + topGainsCount: maxGains, + failurePatternsCount: maxPatterns, + }); + + return Object.freeze({ + snapshot, + content: rendered, + casFilePath: casBlob.casPath, + topGains: Object.freeze(topGains.slice(0, maxGains)), + failurePatterns: Object.freeze(failurePatterns.slice(0, maxPatterns)), + }); +} diff --git a/packages/evolution/src/store.ts b/packages/evolution/src/store.ts new file mode 100644 index 0000000..dea0047 --- /dev/null +++ b/packages/evolution/src/store.ts @@ -0,0 +1,2094 @@ +import { createHash, randomBytes, randomUUID } from 'node:crypto'; +import { constants as fsConstants } from 'node:fs'; +import { chmod, lstat, mkdir, open, rename, unlink } from 'node:fs/promises'; +import { join, resolve } from 'node:path'; +import { DatabaseSync, type SQLInputValue, type SQLOutputValue } from 'node:sqlite'; +import type { + ArtifactRef, + BucketMetricEntry, + Digest, + HardwareDiagnostics, + HardwareProvenance, + StructuredFinding, +} from '@loopwright/core'; +import { + canonicalizeJson, + parseArtifactRefsJson, + parseBucketMetricsJson, + parseEvolutionCampaignDocument, + parseHardwareDiagnosticsJson, + parseHardwareProvenanceJson, + parseMetricsRecordJson, + parseStructuredFindingsJson, + parseTeamDiagnosisJson, + parseTeamDiagnosisValue, + sanitizeUntrustedValue, +} from './schema.js'; +import { + CAMPAIGN_APPLICATION_ID, + CAMPAIGN_CLOCK_MAX_DRIFT_MS, + CAMPAIGN_FORMAT_VERSION, + EvolutionError, + type CampaignClockSource, + type CampaignLease, + type CampaignMetaRecord, + type CampaignRecord, + type CampaignStagePhase, + type CampaignStatus, + type EvolutionCampaignManifest, + type IndividualMutationKind, + type IndividualRecord, + type IndividualStatus, + type IslandRecord, + type LineageEdgeRecord, + type LineageRole, + type ModelBanditArmRecord, + type ScratchpadSnapshotRecord, + type TeamConfigRecord, + type TeamConfigStatus, + type TeamPatchDiagnosis, +} from './types.js'; + +export const CAMPAIGN_SQLITE_FILENAME = 'campaign.sqlite' as const; + +export const DEFAULT_CAMPAIGN_CLOCK: CampaignClockSource = Object.freeze({ + nowMonotonicMs(): number { + return Number(process.hrtime.bigint() / 1_000_000n); + }, + nowWallMs(): number { + return Date.now(); + }, +}); + +const SHA256_HEX_RE = /^[0-9a-f]{64}$/; +const SAFE_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/; + +const CAMPAIGN_DDL = ` +CREATE TABLE IF NOT EXISTS campaign_meta ( + singleton INTEGER PRIMARY KEY CHECK (singleton = 1), + format_version INTEGER NOT NULL CHECK (format_version = 1), + lease_id TEXT, + fence_epoch INTEGER NOT NULL CHECK (fence_epoch >= 0), + created_monotonic_ms INTEGER NOT NULL CHECK (created_monotonic_ms >= 0), + created_wall_ms INTEGER NOT NULL CHECK (created_wall_ms >= 0), + last_monotonic_ms INTEGER NOT NULL CHECK (last_monotonic_ms >= 0), + last_wall_ms INTEGER NOT NULL CHECK (last_wall_ms >= 0) +) STRICT; + +CREATE TABLE IF NOT EXISTS campaigns ( + campaign_id TEXT PRIMARY KEY, + name TEXT NOT NULL, + status TEXT NOT NULL CHECK (status IN ('active', 'paused', 'completed', 'failed')), + stage_phase TEXT NOT NULL CHECK (stage_phase IN ('single-target', 'specialist', 'portfolio')), + active_bucket_id TEXT, + manifest_json TEXT NOT NULL, + manifest_digest_hex TEXT NOT NULL, + base_revision TEXT NOT NULL, + lock_hash_hex TEXT NOT NULL, + driver_constraint TEXT, + current_generation INTEGER NOT NULL CHECK (current_generation >= 0), + evaluations_used INTEGER NOT NULL CHECK (evaluations_used >= 0), + preemptions_count INTEGER NOT NULL CHECK (preemptions_count >= 0), + created_at_wall_ms INTEGER NOT NULL, + updated_at_wall_ms INTEGER NOT NULL +) STRICT; + +CREATE TABLE IF NOT EXISTS islands ( + campaign_id TEXT NOT NULL, + island_id INTEGER NOT NULL CHECK (island_id >= 0 AND island_id < 16), + active_team_config_id TEXT NOT NULL, + current_generation INTEGER NOT NULL CHECK (current_generation >= 0), + consecutive_no_gain_generations INTEGER NOT NULL CHECK (consecutive_no_gain_generations >= 0), + consecutive_pathology_runs INTEGER NOT NULL CHECK (consecutive_pathology_runs >= 0), + last_hypervolume REAL NOT NULL CHECK (last_hypervolume >= 0), + best_roofline_headroom REAL, + PRIMARY KEY (campaign_id, island_id), + FOREIGN KEY (campaign_id) REFERENCES campaigns(campaign_id) ON DELETE RESTRICT +) STRICT; + +CREATE TABLE IF NOT EXISTS team_configs ( + team_config_id TEXT PRIMARY KEY, + campaign_id TEXT NOT NULL, + island_id INTEGER NOT NULL CHECK (island_id >= 0 AND island_id < 16), + parent_team_config_id TEXT, + created_generation INTEGER NOT NULL CHECK (created_generation >= 0), + status TEXT NOT NULL CHECK (status IN ('baseline', 'trial', 'promoted', 'rolled_back')), + trial_budget_generations INTEGER NOT NULL CHECK (trial_budget_generations >= 0), + trial_used_generations INTEGER NOT NULL CHECK (trial_used_generations >= 0), + diagnosis_json TEXT, + patch_cas_digest_hex TEXT, + pareto_advances INTEGER NOT NULL CHECK (pareto_advances >= 0), + niche_discoveries INTEGER NOT NULL CHECK (niche_discoveries >= 0), + FOREIGN KEY (campaign_id) REFERENCES campaigns(campaign_id) ON DELETE RESTRICT, + FOREIGN KEY (parent_team_config_id) REFERENCES team_configs(team_config_id) ON DELETE RESTRICT +) STRICT; + +CREATE TABLE IF NOT EXISTS individuals ( + individual_id TEXT PRIMARY KEY, + campaign_id TEXT NOT NULL, + island_id INTEGER NOT NULL CHECK (island_id >= 0 AND island_id < 16), + generation INTEGER NOT NULL CHECK (generation >= 0), + bucket_id TEXT, + team_config_id TEXT NOT NULL, + model_id TEXT NOT NULL, + track_id TEXT, + mutation_kind TEXT NOT NULL CHECK (mutation_kind IN ('baseline', 'diff_tune', 'full_rewrite', 'crossover', 'portfolio')), + status TEXT NOT NULL CHECK (status IN ('passed', 'soft_passed', 'failed', 'preempted')), + failure_reason TEXT, + niche_key TEXT, + pareto_rank INTEGER, + crowding_distance REAL, + crowding_is_boundary INTEGER NOT NULL DEFAULT 0 CHECK (crowding_is_boundary IN (0, 1)), + scalar_fitness REAL, + offspring_count INTEGER NOT NULL CHECK (offspring_count >= 0), + code_slice_cas_digest_hex TEXT, + evidence_digest_hex TEXT, + verdict_receipt_cas_digest_hex TEXT, + output_artifacts_json TEXT NOT NULL, + metrics_json TEXT NOT NULL, + bucket_metrics_json TEXT, + hardware_diagnostics_json TEXT, + hardware_provenance_json TEXT, + findings_json TEXT, + created_at_wall_ms INTEGER NOT NULL, + FOREIGN KEY (campaign_id) REFERENCES campaigns(campaign_id) ON DELETE RESTRICT, + FOREIGN KEY (team_config_id) REFERENCES team_configs(team_config_id) ON DELETE RESTRICT +) STRICT; + +CREATE TABLE IF NOT EXISTS lineage_edges ( + campaign_id TEXT NOT NULL, + child_individual_id TEXT NOT NULL, + parent_individual_id TEXT NOT NULL, + role TEXT NOT NULL CHECK (role IN ('primary', 'crossover_donor', 'inspiration', 'portfolio_member')), + source_island_id INTEGER NOT NULL CHECK (source_island_id >= 0 AND source_island_id < 16), + created_generation INTEGER NOT NULL CHECK (created_generation >= 0), + PRIMARY KEY (campaign_id, child_individual_id, parent_individual_id, role), + FOREIGN KEY (campaign_id) REFERENCES campaigns(campaign_id) ON DELETE RESTRICT, + FOREIGN KEY (child_individual_id) REFERENCES individuals(individual_id) ON DELETE RESTRICT, + FOREIGN KEY (parent_individual_id) REFERENCES individuals(individual_id) ON DELETE RESTRICT, + CHECK (child_individual_id <> parent_individual_id) +) STRICT; + +CREATE TABLE IF NOT EXISTS model_bandit_arms ( + campaign_id TEXT NOT NULL, + model_id TEXT NOT NULL, + pull_count INTEGER NOT NULL CHECK (pull_count >= 0), + total_reward REAL NOT NULL CHECK (total_reward >= 0), + mean_reward REAL NOT NULL CHECK (mean_reward >= 0), + last_pulled_generation INTEGER, + PRIMARY KEY (campaign_id, model_id), + FOREIGN KEY (campaign_id) REFERENCES campaigns(campaign_id) ON DELETE RESTRICT +) STRICT; + +CREATE TABLE IF NOT EXISTS scratchpad_snapshots ( + snapshot_id TEXT PRIMARY KEY, + campaign_id TEXT NOT NULL, + generation INTEGER NOT NULL CHECK (generation >= 0), + cas_digest_hex TEXT NOT NULL, + byte_length INTEGER NOT NULL CHECK (byte_length >= 0 AND byte_length <= 16384), + cas_rel_path TEXT NOT NULL, + top_gains_count INTEGER NOT NULL CHECK (top_gains_count >= 0), + failure_patterns_count INTEGER NOT NULL CHECK (failure_patterns_count >= 0), + created_at_wall_ms INTEGER NOT NULL, + FOREIGN KEY (campaign_id) REFERENCES campaigns(campaign_id) ON DELETE RESTRICT +) STRICT; + +CREATE INDEX IF NOT EXISTS idx_individuals_campaign_island + ON individuals(campaign_id, island_id, status); +CREATE INDEX IF NOT EXISTS idx_individuals_niche + ON individuals(campaign_id, island_id, niche_key); +CREATE INDEX IF NOT EXISTS idx_lineage_child + ON lineage_edges(campaign_id, child_individual_id); +CREATE INDEX IF NOT EXISTS idx_lineage_parent + ON lineage_edges(campaign_id, parent_individual_id); +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); +`; + +type SqlRow = Record; + +function createNullRecord>(): T { + return Object.create(null) as T; +} + +function digestFromHex(hex: string): Digest { + if (!SHA256_HEX_RE.test(hex)) { + throw new EvolutionError('EVOLUTION_STORE_CORRUPT', `corrupt sha256 hex "${hex}"`); + } + const out = createNullRecord<{ algorithm: 'sha256'; hex: string }>(); + out.algorithm = 'sha256'; + out.hex = hex; + return out; +} + +function assertSafeId(value: string, label: string): void { + if (typeof value !== 'string' || !SAFE_ID_RE.test(value)) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', `invalid ${label} "${String(value)}"`, `/${label}`); + } +} + +function assertDigest(digest: Digest, label: string): void { + if (!digest || digest.algorithm !== 'sha256' || !SHA256_HEX_RE.test(digest.hex)) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', `invalid ${label} digest`, `/${label}`); + } +} + +async function ensureNonSymlinkDirectory(dirPath: string, createIfMissing: boolean): Promise { + const existing = await lstat(dirPath).catch((err: NodeJS.ErrnoException) => { + if (err.code === 'ENOENT') return null; + if (err.code === 'ELOOP') { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `symlink forbidden along ${dirPath}`, dirPath); + } + throw err; + }); + + if (existing === null) { + if (!createIfMissing) { + throw new EvolutionError('EVOLUTION_NOT_FOUND', `directory does not exist: ${dirPath}`, dirPath); + } + await mkdir(dirPath, { mode: 0o700, recursive: false }).catch((err: NodeJS.ErrnoException) => { + if (err.code !== 'EEXIST') throw err; + }); + } else if (existing.isSymbolicLink()) { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `directory cannot be a symlink: ${dirPath}`, dirPath); + } else if (!existing.isDirectory()) { + throw new EvolutionError('EVOLUTION_STORE_ERROR', `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('EVOLUTION_SYMLINK_FORBIDDEN', `symlink directory forbidden: ${dirPath}`, dirPath); + } + throw err; + }); + try { + const fdStat = await handle.stat(); + if (!fdStat.isDirectory()) { + throw new EvolutionError('EVOLUTION_STORE_ERROR', `expected directory at ${dirPath}`, dirPath); + } + } finally { + await handle.close(); + } +} + +async function prepareSqliteFileNoFollow(dbPath: string, createIfMissing: boolean): Promise { + const journalPath = `${dbPath}-journal`; + const journalStat = await lstat(journalPath).catch((err: NodeJS.ErrnoException) => { + if (err.code === 'ENOENT') return null; + if (err.code === 'ELOOP') { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `symlink journal forbidden: ${journalPath}`, journalPath); + } + throw err; + }); + if (journalStat !== null && journalStat.isSymbolicLink()) { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `journal cannot be a symlink: ${journalPath}`, journalPath); + } + + const before = await lstat(dbPath).catch((err: NodeJS.ErrnoException) => { + if (err.code === 'ENOENT') return null; + if (err.code === 'ELOOP') { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `symlink forbidden along ${dbPath}`, dbPath); + } + throw err; + }); + + const noFollow = 'O_NOFOLLOW' in fsConstants ? fsConstants.O_NOFOLLOW : 0; + if (before === null) { + if (!createIfMissing) { + throw new EvolutionError('EVOLUTION_NOT_FOUND', `campaign.sqlite does not exist at ${dbPath}`, dbPath); + } + const handle = await open( + dbPath, + fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_RDWR | noFollow, + 0o600, + ).catch((err: NodeJS.ErrnoException) => { + if (err.code === 'ELOOP' || err.code === 'EFTYPE') { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `symlink forbidden at ${dbPath}`, dbPath); + } + throw err; + }); + await handle.close(); + return true; + } + + if (before.isSymbolicLink()) { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `campaign.sqlite cannot be a symlink: ${dbPath}`, dbPath); + } + if (!before.isFile() || before.nlink !== 1) { + throw new EvolutionError('EVOLUTION_STORE_CORRUPT', `campaign.sqlite must be a regular unlinked file: ${dbPath}`, dbPath); + } + + const handle = await open(dbPath, fsConstants.O_RDONLY | noFollow).catch((err: NodeJS.ErrnoException) => { + if (err.code === 'ELOOP' || err.code === 'EFTYPE') { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `symlink forbidden at ${dbPath}`, dbPath); + } + throw err; + }); + try { + const fdStat = await handle.stat(); + if (!fdStat.isFile() || fdStat.nlink !== 1) { + throw new EvolutionError('EVOLUTION_STORE_CORRUPT', `campaign.sqlite failed fd stat verification: ${dbPath}`, dbPath); + } + return fdStat.size === 0; + } finally { + await handle.close(); + } +} + +export interface OpenCampaignStoreOptions { + readonly campaignRoot: string; + readonly clock?: CampaignClockSource; + readonly createIfMissing?: boolean; +} + +export interface CreateCampaignInput { + readonly campaignId: string; + readonly manifest: EvolutionCampaignManifest; + readonly manifestDigest: Digest; + readonly baseRevision: string; + readonly lockHash: Digest; + readonly driverConstraint?: string | null; + readonly stagePhase?: CampaignStagePhase; + readonly activeBucketId?: string | null; + readonly modelIds?: readonly string[]; +} + +export interface UpdateCampaignProgressInput { + readonly campaignId: string; + readonly status?: CampaignStatus; + readonly stagePhase?: CampaignStagePhase; + readonly activeBucketId?: string | null; + readonly driverConstraint?: string | null; + readonly currentGeneration?: number; +} + +export interface UpdateIslandProgressInput { + readonly campaignId: string; + readonly islandId: number; + readonly activeTeamConfigId?: string; + readonly currentGeneration?: number; + readonly consecutiveNoGainGenerations?: number; + readonly consecutivePathologyRuns?: number; + readonly lastHypervolume?: number; + readonly bestRooflineHeadroom?: number | null; +} + +export interface CreateTrialTeamConfigInput { + readonly teamConfigId: string; + readonly campaignId: string; + readonly islandId: number; + readonly parentTeamConfigId: string; + readonly createdGeneration: number; + readonly trialBudgetGenerations: number; + readonly diagnosis: TeamPatchDiagnosis; + readonly patchCasDigest: Digest; +} + +export interface RecordTeamTrialGenerationInput { + readonly teamConfigId: string; + readonly advancedPareto: boolean; + readonly discoveredNiche: boolean; + readonly preempted?: boolean; +} + +export interface RecordIndividualInput { + 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 scalarFitness: number | null; + readonly offspringCount?: number; + readonly countEvaluation?: boolean; + readonly codeSliceCasDigest: Digest | null; + readonly evidenceDigest: Digest | null; + readonly verdictReceiptCasDigest: Digest | null; + readonly outputArtifacts: readonly ArtifactRef[]; + readonly metrics: Readonly>; + readonly bucketMetrics?: readonly BucketMetricEntry[]; + readonly hardwareDiagnostics?: HardwareDiagnostics; + readonly hardwareProvenance?: HardwareProvenance; + readonly findings?: readonly StructuredFinding[]; + readonly lineageEdges?: readonly LineageEdgeRecord[]; +} + +export interface ListIndividualsFilter { + readonly islandId?: number; + readonly status?: readonly IndividualStatus[]; + readonly bucketId?: string | null; + readonly nicheKey?: string; +} + +export interface ParetoRankUpdate { + readonly individualId: string; + readonly paretoRank: number | null; + readonly crowdingDistance: number | null; + readonly scalarFitness?: number | null; +} + +export interface ListLineageEdgesFilter { + readonly childIndividualId?: string; + readonly parentIndividualId?: string; + readonly role?: LineageRole; +} + +export interface RecordModelBanditRewardInput { + readonly campaignId: string; + readonly modelId: string; + readonly reward: number; + readonly generation: number; +} + +export interface WrittenCasBlob { + readonly digest: Digest; + readonly byteLength: number; + readonly casPath: string; + readonly casRelPath: string; +} + +export interface RecordScratchpadSnapshotInput { + readonly snapshotId: string; + readonly campaignId: string; + readonly generation: number; + readonly casDigest: Digest; + readonly byteLength: number; + readonly casRelPath: string; + readonly topGainsCount: number; + readonly failurePatternsCount: number; +} + +export interface CampaignStorePragmasSnapshot { + readonly journalMode: string; + readonly synchronous: number; + readonly foreignKeys: number; + readonly busyTimeout: number; + readonly tables: readonly string[]; +} + +/** + * Single-writer fenced SQLite store for `@loopwright/evolution` (`/campaign.sqlite`), + * completely isolated from per-run `@loopwright/state` `LocalRunStore`. + */ +export class EvolutionCampaignStore { + readonly campaignRoot: string; + readonly dbPath: string; + readonly #db: DatabaseSync; + readonly #clock: CampaignClockSource; + readonly #sessionBaseMonoMs: number; + readonly #sessionBaseWallMs: number; + readonly #manifestCache = new Map(); + #reopenedNeedsClockReanchor: boolean; + #queue: Promise = Promise.resolve(); + #closed = false; + + private constructor( + campaignRoot: string, + dbPath: string, + db: DatabaseSync, + clock: CampaignClockSource, + sessionBaseMonoMs: number, + sessionBaseWallMs: number, + reopenedFromExisting: boolean, + ) { + this.campaignRoot = campaignRoot; + this.dbPath = dbPath; + this.#db = db; + this.#clock = clock; + this.#sessionBaseMonoMs = sessionBaseMonoMs; + this.#sessionBaseWallMs = sessionBaseWallMs; + this.#reopenedNeedsClockReanchor = reopenedFromExisting; + } + + static async open(options: OpenCampaignStoreOptions): Promise { + if (typeof options.campaignRoot !== 'string' || options.campaignRoot.length === 0) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'campaignRoot must be a non-empty path', '/campaignRoot'); + } + const createIfMissing = options.createIfMissing ?? true; + const clock = options.clock ?? DEFAULT_CAMPAIGN_CLOCK; + const campaignRoot = resolve(options.campaignRoot); + + await ensureNonSymlinkDirectory(campaignRoot, createIfMissing); + if (createIfMissing) { + await ensureNonSymlinkDirectory(join(campaignRoot, 'cas'), true); + await ensureNonSymlinkDirectory(join(campaignRoot, 'cas', 'sha256'), true); + } + + const dbPath = join(campaignRoot, CAMPAIGN_SQLITE_FILENAME); + const freshFile = await prepareSqliteFileNoFollow(dbPath, createIfMissing); + + const monoNow = clock.nowMonotonicMs(); + const wallNow = clock.nowWallMs(); + if ( + !Number.isSafeInteger(monoNow) || Object.is(monoNow, -0) || monoNow < 0 + || !Number.isSafeInteger(wallNow) || Object.is(wallNow, -0) || wallNow < 0 + ) { + throw new EvolutionError('EVOLUTION_CLOCK_DRIFT', 'clock source returned non-integer or negative timestamp'); + } + + const db = new DatabaseSync(dbPath, { + timeout: 250, + allowExtension: false, + defensive: true, + enableForeignKeyConstraints: true, + enableDoubleQuotedStringLiterals: false, + }); + + try { + db.exec('PRAGMA journal_mode = DELETE;'); + db.exec('PRAGMA synchronous = FULL;'); + db.exec('PRAGMA busy_timeout = 250;'); + db.exec('PRAGMA foreign_keys = ON;'); + db.exec('PRAGMA trusted_schema = OFF;'); + + const journalRow = db.prepare('PRAGMA journal_mode;').get() as { readonly journal_mode?: unknown } | undefined; + const syncRow = db.prepare('PRAGMA synchronous;').get() as { readonly synchronous?: unknown } | undefined; + const fkRow = db.prepare('PRAGMA foreign_keys;').get() as { readonly foreign_keys?: unknown } | undefined; + if (journalRow?.journal_mode !== 'delete' || syncRow?.synchronous !== 2 || fkRow?.foreign_keys !== 1) { + throw new EvolutionError('EVOLUTION_STORE_CORRUPT', 'failed to enforce SQLite DELETE/FULL/FK pragmas'); + } + + if (freshFile) { + db.exec('BEGIN IMMEDIATE;'); + try { + db.exec(CAMPAIGN_DDL); + db.exec(`PRAGMA application_id = ${CAMPAIGN_APPLICATION_ID}; PRAGMA user_version = ${CAMPAIGN_FORMAT_VERSION};`); + db.prepare( + `INSERT INTO campaign_meta ( + singleton, format_version, lease_id, fence_epoch, + created_monotonic_ms, created_wall_ms, last_monotonic_ms, last_wall_ms + ) VALUES (1, ?, NULL, 0, ?, ?, ?, ?);`, + ).run(CAMPAIGN_FORMAT_VERSION, monoNow, wallNow, monoNow, wallNow); + db.exec('COMMIT;'); + } catch (err) { + if (db.isTransaction) db.exec('ROLLBACK;'); + throw err; + } + } else { + const appRow = db.prepare('PRAGMA application_id;').get() as { readonly application_id?: unknown } | undefined; + const verRow = db.prepare('PRAGMA user_version;').get() as { readonly user_version?: unknown } | undefined; + if (appRow?.application_id !== CAMPAIGN_APPLICATION_ID || verRow?.user_version !== CAMPAIGN_FORMAT_VERSION) { + throw new EvolutionError('EVOLUTION_STORE_CORRUPT', 'unexpected campaign.sqlite header version'); + } + const metaRow = db.prepare('SELECT * FROM campaign_meta WHERE singleton = 1;').get() as SqlRow | undefined; + if (!metaRow || metaRow['format_version'] !== CAMPAIGN_FORMAT_VERSION) { + throw new EvolutionError('EVOLUTION_STORE_CORRUPT', 'missing or corrupt campaign_meta row'); + } + if (monoNow < Number(metaRow['last_monotonic_ms']) || wallNow < Number(metaRow['last_wall_ms'])) { + throw new EvolutionError('EVOLUTION_CLOCK_DRIFT', 'clock regressed behind persisted campaign_meta timestamp'); + } + const campaignCols = db.prepare('PRAGMA table_info(campaigns);').all() as SqlRow[]; + if (!campaignCols.some(col => String(col['name']) === 'driver_constraint')) { + db.exec('BEGIN IMMEDIATE;'); + try { + db.exec('ALTER TABLE campaigns ADD COLUMN driver_constraint TEXT;'); + db.exec('COMMIT;'); + } catch (err) { + if (db.isTransaction) db.exec('ROLLBACK;'); + throw err; + } + } + } + + return new EvolutionCampaignStore(campaignRoot, dbPath, db, clock, monoNow, wallNow, !freshFile); + } catch (err) { + try { + db.close(); + } catch { + // Ignore close error while surfacing open failure. + } + if (err instanceof EvolutionError) throw err; + throw new EvolutionError('EVOLUTION_STORE_ERROR', err instanceof Error ? err.message : String(err)); + } + } + + /** Single-writer in-process async coordinator queue serializing all SQLite reads and writes. */ + enqueue(operation: () => T | Promise): Promise { + const task = this.#queue.then(async () => { + this.#assertOpen(); + return await operation(); + }); + this.#queue = task.then( + () => undefined, + () => undefined, + ); + return task; + } + + #assertOpen(): void { + if (this.#closed) { + throw new EvolutionError('EVOLUTION_STORE_CLOSED', 'campaign store is closed'); + } + } + + #readMetaSync(): CampaignMetaRecord { + const row = this.#db.prepare('SELECT * FROM campaign_meta WHERE singleton = 1;').get() as SqlRow | undefined; + if (!row) { + throw new EvolutionError('EVOLUTION_STORE_CORRUPT', 'campaign_meta singleton row missing'); + } + const out = createNullRecord<{ + formatVersion: number; + leaseId: string | null; + fenceEpoch: number; + createdMonotonicMs: number; + createdWallMs: number; + lastMonotonicMs: number; + lastWallMs: number; + }>(); + out.formatVersion = Number(row['format_version']); + out.leaseId = row['lease_id'] === null ? null : String(row['lease_id']); + out.fenceEpoch = Number(row['fence_epoch']); + out.createdMonotonicMs = Number(row['created_monotonic_ms']); + out.createdWallMs = Number(row['created_wall_ms']); + out.lastMonotonicMs = Number(row['last_monotonic_ms']); + out.lastWallMs = Number(row['last_wall_ms']); + return out; + } + + #sampleAndVerifyClockSync( + meta: CampaignMetaRecord, + allowSessionReanchor = false, + ): { readonly monoMs: number; readonly wallMs: number } { + const monoMs = this.#clock.nowMonotonicMs(); + const wallMs = this.#clock.nowWallMs(); + if ( + !Number.isSafeInteger(monoMs) || Object.is(monoMs, -0) || monoMs < 0 + || !Number.isSafeInteger(wallMs) || Object.is(wallMs, -0) || wallMs < 0 + ) { + throw new EvolutionError('EVOLUTION_CLOCK_DRIFT', 'clock returned invalid sample'); + } + if (monoMs < meta.lastMonotonicMs || wallMs < meta.lastWallMs) { + throw new EvolutionError('EVOLUTION_CLOCK_DRIFT', 'clock regressed behind last committed campaign timestamp'); + } + const sessionDrift = Math.abs((wallMs - this.#sessionBaseWallMs) - (monoMs - this.#sessionBaseMonoMs)); + if (sessionDrift > CAMPAIGN_CLOCK_MAX_DRIFT_MS) { + throw new EvolutionError( + 'EVOLUTION_CLOCK_DRIFT', + `cumulative session clock drift ${sessionDrift}ms exceeds ${CAMPAIGN_CLOCK_MAX_DRIFT_MS}ms guard`, + ); + } + if (!allowSessionReanchor) { + const stepDrift = Math.abs((wallMs - meta.lastWallMs) - (monoMs - meta.lastMonotonicMs)); + if (stepDrift > CAMPAIGN_CLOCK_MAX_DRIFT_MS) { + throw new EvolutionError( + 'EVOLUTION_CLOCK_DRIFT', + `clock drift ${stepDrift}ms exceeds ${CAMPAIGN_CLOCK_MAX_DRIFT_MS}ms guard`, + ); + } + } + return { monoMs, wallMs }; + } + + #assertLeaseAndTickClockSync(lease: CampaignLease): { readonly monoMs: number; readonly wallMs: number } { + if ( + !lease + || typeof lease.leaseId !== 'string' + || lease.leaseId.length === 0 + || !Number.isSafeInteger(lease.fenceEpoch) + || lease.fenceEpoch < 1 + ) { + throw new EvolutionError('EVOLUTION_LEASE_FENCED', 'invalid lease credentials'); + } + const meta = this.#readMetaSync(); + if (meta.leaseId === null || meta.leaseId !== lease.leaseId || meta.fenceEpoch !== lease.fenceEpoch) { + throw new EvolutionError( + 'EVOLUTION_LEASE_FENCED', + `stale campaign lease (expected epoch ${meta.fenceEpoch}, got ${lease.fenceEpoch})`, + ); + } + const now = this.#sampleAndVerifyClockSync(meta); + this.#db + .prepare('UPDATE campaign_meta SET last_monotonic_ms = ?, last_wall_ms = ? WHERE singleton = 1;') + .run(now.monoMs, now.wallMs); + return now; + } + + #inWriteTransaction(lease: CampaignLease, fn: (now: { readonly monoMs: number; readonly wallMs: number }) => T): T { + this.#db.exec('BEGIN IMMEDIATE;'); + try { + const now = this.#assertLeaseAndTickClockSync(lease); + const res = fn(now); + this.#db.exec('COMMIT;'); + return res; + } catch (err) { + if (this.#db.isTransaction) { + this.#db.exec('ROLLBACK;'); + } + if (err instanceof EvolutionError) throw err; + const errCode = err !== null && typeof err === 'object' && 'errcode' in err && typeof err.errcode === 'number' + ? err.errcode & 255 + : 0; + if (errCode === 5 || errCode === 6) { + throw new EvolutionError('EVOLUTION_STORE_BUSY', err instanceof Error ? err.message : String(err)); + } + throw new EvolutionError('EVOLUTION_STORE_ERROR', err instanceof Error ? err.message : String(err)); + } + } + + inspectPragmas(): Promise { + return this.enqueue(() => { + const journal = this.#db.prepare('PRAGMA journal_mode;').get() as { readonly journal_mode?: unknown } | undefined; + const sync = this.#db.prepare('PRAGMA synchronous;').get() as { readonly synchronous?: unknown } | undefined; + const fk = this.#db.prepare('PRAGMA foreign_keys;').get() as { readonly foreign_keys?: unknown } | undefined; + const busy = this.#db.prepare('PRAGMA busy_timeout;').get() as { readonly timeout?: unknown } | undefined; + const tableRows = this.#db + .prepare("SELECT name, strict FROM pragma_table_list WHERE schema = 'main' AND type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name ASC;") + .all() as SqlRow[]; + for (const row of tableRows) { + if (row['strict'] !== 1) { + throw new EvolutionError('EVOLUTION_STORE_CORRUPT', `table ${String(row['name'])} is not STRICT`); + } + } + return Object.freeze({ + journalMode: String(journal?.journal_mode ?? ''), + synchronous: Number(sync?.synchronous ?? -1), + foreignKeys: Number(fk?.foreign_keys ?? 0), + busyTimeout: Number(busy?.timeout ?? 0), + tables: Object.freeze(tableRows.map(r => String(r['name']))), + }); + }); + } + + getMeta(): Promise { + return this.enqueue(() => this.#readMetaSync()); + } + + acquireLease(leaseId?: string): Promise { + return this.enqueue(() => { + const resolvedLeaseId = leaseId ?? randomUUID(); + assertSafeId(resolvedLeaseId, 'leaseId'); + this.#db.exec('BEGIN IMMEDIATE;'); + try { + const meta = this.#readMetaSync(); + const now = this.#sampleAndVerifyClockSync(meta, this.#reopenedNeedsClockReanchor); + this.#reopenedNeedsClockReanchor = false; + const nextEpoch = meta.fenceEpoch + 1; + this.#db + .prepare( + 'UPDATE campaign_meta SET lease_id = ?, fence_epoch = ?, last_monotonic_ms = ?, last_wall_ms = ? WHERE singleton = 1;', + ) + .run(resolvedLeaseId, nextEpoch, now.monoMs, now.wallMs); + this.#db.exec('COMMIT;'); + const out = createNullRecord<{ leaseId: string; fenceEpoch: number }>(); + out.leaseId = resolvedLeaseId; + out.fenceEpoch = nextEpoch; + return out; + } catch (err) { + if (this.#db.isTransaction) this.#db.exec('ROLLBACK;'); + if (err instanceof EvolutionError) throw err; + throw new EvolutionError('EVOLUTION_STORE_ERROR', err instanceof Error ? err.message : String(err)); + } + }); + } + + releaseLease(lease: CampaignLease): Promise { + return this.enqueue(() => { + this.#inWriteTransaction(lease, () => { + this.#db.prepare('UPDATE campaign_meta SET lease_id = NULL WHERE singleton = 1;').run(); + }); + }); + } + + #parseCachedManifest(campaignId: string, digestHex: string, manifestJson: string): EvolutionCampaignManifest { + const cacheKey = `${campaignId}:${digestHex}`; + const cached = this.#manifestCache.get(cacheKey); + if (cached) return cached; + const parsed = parseEvolutionCampaignDocument(manifestJson); + this.#manifestCache.set(cacheKey, parsed); + return parsed; + } + + #hydrateCampaignRow(row: SqlRow): CampaignRecord { + const campaignId = String(row['campaign_id']); + const manifestDigestHex = String(row['manifest_digest_hex']); + const manifest = this.#parseCachedManifest(campaignId, manifestDigestHex, String(row['manifest_json'])); + 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; + createdAtWallMs: number; + updatedAtWallMs: number; + }>(); + out.campaignId = String(row['campaign_id']); + out.name = String(row['name']); + out.status = String(row['status']) as CampaignStatus; + out.stagePhase = String(row['stage_phase']) as CampaignStagePhase; + out.activeBucketId = row['active_bucket_id'] === null ? null : String(row['active_bucket_id']); + out.manifest = manifest; + out.manifestDigest = digestFromHex(String(row['manifest_digest_hex'])); + out.baseRevision = String(row['base_revision']); + out.lockHash = digestFromHex(String(row['lock_hash_hex'])); + out.driverConstraint = row['driver_constraint'] === null || row['driver_constraint'] === undefined + ? null + : String(row['driver_constraint']); + out.currentGeneration = Number(row['current_generation']); + out.evaluationsUsed = Number(row['evaluations_used']); + out.preemptionsCount = Number(row['preemptions_count']); + out.createdAtWallMs = Number(row['created_at_wall_ms']); + out.updatedAtWallMs = Number(row['updated_at_wall_ms']); + return out; + } + + #hydrateIslandRow(row: SqlRow): IslandRecord { + const out = createNullRecord<{ + campaignId: string; + islandId: number; + activeTeamConfigId: string; + currentGeneration: number; + consecutiveNoGainGenerations: number; + consecutivePathologyRuns: number; + lastHypervolume: number; + bestRooflineHeadroom: number | null; + }>(); + out.campaignId = String(row['campaign_id']); + out.islandId = Number(row['island_id']); + out.activeTeamConfigId = String(row['active_team_config_id']); + out.currentGeneration = Number(row['current_generation']); + out.consecutiveNoGainGenerations = Number(row['consecutive_no_gain_generations']); + out.consecutivePathologyRuns = Number(row['consecutive_pathology_runs']); + out.lastHypervolume = Number(row['last_hypervolume']); + out.bestRooflineHeadroom = row['best_roofline_headroom'] === null ? null : Number(row['best_roofline_headroom']); + return out; + } + + #hydrateTeamConfigRow(row: SqlRow): TeamConfigRecord { + 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 = String(row['team_config_id']); + out.campaignId = String(row['campaign_id']); + out.islandId = Number(row['island_id']); + out.parentTeamConfigId = row['parent_team_config_id'] === null ? null : String(row['parent_team_config_id']); + out.createdGeneration = Number(row['created_generation']); + out.status = String(row['status']) as TeamConfigStatus; + out.trialBudgetGenerations = Number(row['trial_budget_generations']); + out.trialUsedGenerations = Number(row['trial_used_generations']); + out.diagnosis = row['diagnosis_json'] === null ? null : parseTeamDiagnosisJson(String(row['diagnosis_json'])); + out.patchCasDigest = row['patch_cas_digest_hex'] === null ? null : digestFromHex(String(row['patch_cas_digest_hex'])); + out.paretoAdvances = Number(row['pareto_advances']); + out.nicheDiscoveries = Number(row['niche_discoveries']); + return out; + } + + #hydrateIndividualRow(row: SqlRow): IndividualRecord { + 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; + scalarFitness: number | null; + offspringCount: number; + codeSliceCasDigest: Digest | null; + evidenceDigest: Digest | null; + verdictReceiptCasDigest: Digest | null; + outputArtifacts: readonly ArtifactRef[]; + metrics: Readonly>; + bucketMetrics?: readonly BucketMetricEntry[]; + hardwareDiagnostics?: HardwareDiagnostics; + hardwareProvenance?: HardwareProvenance; + findings?: readonly StructuredFinding[]; + createdAtWallMs: number; + }>(); + out.individualId = String(row['individual_id']); + out.campaignId = String(row['campaign_id']); + out.islandId = Number(row['island_id']); + out.generation = Number(row['generation']); + out.bucketId = row['bucket_id'] === null ? null : String(row['bucket_id']); + out.teamConfigId = String(row['team_config_id']); + out.modelId = String(row['model_id']); + out.trackId = row['track_id'] === null ? null : String(row['track_id']); + out.mutationKind = String(row['mutation_kind']) as IndividualMutationKind; + out.status = String(row['status']) as IndividualStatus; + out.failureReason = row['failure_reason'] === null ? null : String(row['failure_reason']); + out.nicheKey = row['niche_key'] === null ? null : String(row['niche_key']); + out.paretoRank = row['pareto_rank'] === null ? null : Number(row['pareto_rank']); + out.crowdingDistance = Number(row['crowding_is_boundary']) === 1 + ? Number.POSITIVE_INFINITY + : row['crowding_distance'] === null + ? null + : Number(row['crowding_distance']); + out.scalarFitness = row['scalar_fitness'] === null ? null : Number(row['scalar_fitness']); + out.offspringCount = Number(row['offspring_count']); + out.codeSliceCasDigest = row['code_slice_cas_digest_hex'] === null + ? null + : digestFromHex(String(row['code_slice_cas_digest_hex'])); + out.evidenceDigest = row['evidence_digest_hex'] === null + ? null + : digestFromHex(String(row['evidence_digest_hex'])); + out.verdictReceiptCasDigest = row['verdict_receipt_cas_digest_hex'] === null + ? null + : digestFromHex(String(row['verdict_receipt_cas_digest_hex'])); + out.outputArtifacts = parseArtifactRefsJson(String(row['output_artifacts_json'])); + out.metrics = parseMetricsRecordJson(String(row['metrics_json'])); + if (row['bucket_metrics_json'] !== null) { + out.bucketMetrics = parseBucketMetricsJson(String(row['bucket_metrics_json'])); + } + if (row['hardware_diagnostics_json'] !== null) { + out.hardwareDiagnostics = parseHardwareDiagnosticsJson(String(row['hardware_diagnostics_json'])); + } + if (row['hardware_provenance_json'] !== null) { + out.hardwareProvenance = parseHardwareProvenanceJson(String(row['hardware_provenance_json'])); + } + if (row['findings_json'] !== null) { + out.findings = parseStructuredFindingsJson(String(row['findings_json'])); + } + out.createdAtWallMs = Number(row['created_at_wall_ms']); + return out as IndividualRecord; + } + + createCampaign(lease: CampaignLease, input: CreateCampaignInput): Promise { + return this.enqueue(() => { + assertSafeId(input.campaignId, 'campaignId'); + assertDigest(input.manifestDigest, 'manifestDigest'); + assertDigest(input.lockHash, 'lockHash'); + const validatedManifest = parseEvolutionCampaignDocument(input.manifest); + const defaultPhase: CampaignStagePhase = validatedManifest.spec.stages.mode === 'specialist-then-portfolio' + ? 'specialist' + : 'single-target'; + const stagePhase = input.stagePhase ?? defaultPhase; + const activeBucketId = input.activeBucketId !== undefined + ? input.activeBucketId + : validatedManifest.spec.stages.mode === 'specialist-then-portfolio' + ? validatedManifest.spec.stages.specialistBuckets[0]!.id + : null; + + return this.#inWriteTransaction(lease, now => { + const existing = this.#db + .prepare('SELECT campaign_id FROM campaigns WHERE campaign_id = ?;') + .get(input.campaignId); + if (existing) { + throw new EvolutionError('EVOLUTION_CONFLICT', `campaign "${input.campaignId}" already exists`); + } + + 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'); + } + + const manifestJson = canonicalizeJson(validatedManifest); + 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 (?, ?, 'active', ?, ?, ?, ?, ?, ?, ?, 0, 0, 0, ?, ?);`, + ) + .run( + input.campaignId, + validatedManifest.metadata.name, + stagePhase, + activeBucketId, + manifestJson, + input.manifestDigest.hex, + input.baseRevision, + input.lockHash.hex, + driverConstraint, + now.wallMs, + now.wallMs, + ); + + for (let islandId = 0; islandId < validatedManifest.spec.population.islands; islandId++) { + const baselineTeamId = `${input.campaignId}-isl${islandId}-team-baseline`; + 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 (?, ?, ?, NULL, 0, 'baseline', 0, 0, NULL, NULL, 0, 0);`, + ) + .run(baselineTeamId, input.campaignId, islandId); + + 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 (?, ?, ?, 0, 0, 0, 0, NULL);`, + ) + .run(input.campaignId, islandId, baselineTeamId); + } + + if (input.modelIds !== undefined) { + for (const modelId of input.modelIds) { + this.#db + .prepare( + `INSERT INTO model_bandit_arms ( + campaign_id, model_id, pull_count, total_reward, mean_reward, last_pulled_generation + ) VALUES (?, ?, 0, 0, 0, NULL) + ON CONFLICT (campaign_id, model_id) DO NOTHING;`, + ) + .run(input.campaignId, modelId); + } + } + + const row = this.#db + .prepare('SELECT * FROM campaigns WHERE campaign_id = ?;') + .get(input.campaignId) as SqlRow; + return this.#hydrateCampaignRow(row); + }); + }); + } + + getCampaign(campaignId: string): Promise { + return this.enqueue(() => { + const row = this.#db + .prepare('SELECT * FROM campaigns WHERE campaign_id = ?;') + .get(campaignId) as SqlRow | undefined; + return row ? this.#hydrateCampaignRow(row) : null; + }); + } + + listCampaigns(): Promise { + return this.enqueue(() => { + const rows = this.#db + .prepare('SELECT * FROM campaigns ORDER BY created_at_wall_ms ASC, campaign_id ASC;') + .all() as SqlRow[]; + return rows.map(r => this.#hydrateCampaignRow(r)); + }); + } + + updateCampaignProgress(lease: CampaignLease, input: UpdateCampaignProgressInput): Promise { + return this.enqueue(() => { + return this.#inWriteTransaction(lease, now => { + const existing = this.#db + .prepare('SELECT * FROM campaigns WHERE campaign_id = ?;') + .get(input.campaignId) as SqlRow | undefined; + if (!existing) { + throw new EvolutionError('EVOLUTION_NOT_FOUND', `campaign "${input.campaignId}" not found`); + } + const nextStatus = input.status ?? String(existing['status']); + const nextPhase = input.stagePhase ?? String(existing['stage_phase']); + const nextBucket = input.activeBucketId !== undefined + ? input.activeBucketId + : (existing['active_bucket_id'] === null ? null : String(existing['active_bucket_id'])); + const nextDriverConstraint = input.driverConstraint !== undefined + ? input.driverConstraint + : (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'); + } + const nextGen = input.currentGeneration ?? Number(existing['current_generation']); + + this.#db + .prepare( + `UPDATE campaigns + SET status = ?, stage_phase = ?, active_bucket_id = ?, driver_constraint = ?, current_generation = ?, updated_at_wall_ms = ? + WHERE campaign_id = ?;`, + ) + .run(nextStatus, nextPhase, nextBucket, nextDriverConstraint, nextGen, now.wallMs, input.campaignId); + + const updated = this.#db + .prepare('SELECT * FROM campaigns WHERE campaign_id = ?;') + .get(input.campaignId) as SqlRow; + return this.#hydrateCampaignRow(updated); + }); + }); + } + + getIsland(campaignId: string, islandId: number): Promise { + return this.enqueue(() => { + const row = this.#db + .prepare('SELECT * FROM islands WHERE campaign_id = ? AND island_id = ?;') + .get(campaignId, islandId) as SqlRow | undefined; + return row ? this.#hydrateIslandRow(row) : null; + }); + } + + listIslands(campaignId: string): Promise { + return this.enqueue(() => { + const rows = this.#db + .prepare('SELECT * FROM islands WHERE campaign_id = ? ORDER BY island_id ASC;') + .all(campaignId) as SqlRow[]; + return rows.map(r => this.#hydrateIslandRow(r)); + }); + } + + updateIslandProgress(lease: CampaignLease, input: UpdateIslandProgressInput): Promise { + return this.enqueue(() => { + return this.#inWriteTransaction(lease, () => { + const existing = this.#db + .prepare('SELECT * FROM islands WHERE campaign_id = ? AND island_id = ?;') + .get(input.campaignId, input.islandId) as SqlRow | undefined; + if (!existing) { + throw new EvolutionError( + 'EVOLUTION_NOT_FOUND', + `island ${input.islandId} not found in campaign "${input.campaignId}"`, + ); + } + + const activeTeam = input.activeTeamConfigId ?? String(existing['active_team_config_id']); + const currentGen = input.currentGeneration ?? Number(existing['current_generation']); + const noGain = input.consecutiveNoGainGenerations ?? Number(existing['consecutive_no_gain_generations']); + const pathology = input.consecutivePathologyRuns ?? Number(existing['consecutive_pathology_runs']); + const lastHv = input.lastHypervolume ?? Number(existing['last_hypervolume']); + const bestHeadroom = input.bestRooflineHeadroom !== undefined + ? input.bestRooflineHeadroom + : (existing['best_roofline_headroom'] === null ? null : Number(existing['best_roofline_headroom'])); + + this.#db + .prepare( + `UPDATE islands + SET active_team_config_id = ?, current_generation = ?, consecutive_no_gain_generations = ?, + consecutive_pathology_runs = ?, last_hypervolume = ?, best_roofline_headroom = ? + WHERE campaign_id = ? AND island_id = ?;`, + ) + .run( + activeTeam, + currentGen, + noGain, + pathology, + lastHv, + bestHeadroom, + input.campaignId, + input.islandId, + ); + + const updated = this.#db + .prepare('SELECT * FROM islands WHERE campaign_id = ? AND island_id = ?;') + .get(input.campaignId, input.islandId) as SqlRow; + return this.#hydrateIslandRow(updated); + }); + }); + } + + createTrialTeamConfig(lease: CampaignLease, input: CreateTrialTeamConfigInput): Promise { + return this.enqueue(() => { + assertSafeId(input.teamConfigId, 'teamConfigId'); + assertSafeId(input.parentTeamConfigId, 'parentTeamConfigId'); + assertDigest(input.patchCasDigest, 'patchCasDigest'); + if (!Number.isSafeInteger(input.trialBudgetGenerations) || input.trialBudgetGenerations < 1 || input.trialBudgetGenerations > 8) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'trialBudgetGenerations must be within 1..8'); + } + const validatedDiagnosis = parseTeamDiagnosisValue( + sanitizeUntrustedValue(input.diagnosis, { maxBytes: 4_096, path: '/diagnosis' }), + '/diagnosis', + ); + + return this.#inWriteTransaction(lease, () => { + const diagJson = canonicalizeJson(validatedDiagnosis); + 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 (?, ?, ?, ?, ?, 'trial', ?, 0, ?, ?, 0, 0);`, + ) + .run( + input.teamConfigId, + input.campaignId, + input.islandId, + input.parentTeamConfigId, + input.createdGeneration, + input.trialBudgetGenerations, + diagJson, + input.patchCasDigest.hex, + ); + + this.#db + .prepare('UPDATE islands SET active_team_config_id = ? WHERE campaign_id = ? AND island_id = ?;') + .run(input.teamConfigId, input.campaignId, input.islandId); + + const row = this.#db + .prepare('SELECT * FROM team_configs WHERE team_config_id = ?;') + .get(input.teamConfigId) as SqlRow; + return this.#hydrateTeamConfigRow(row); + }); + }); + } + + getTeamConfig(teamConfigId: string): Promise { + return this.enqueue(() => { + const row = this.#db + .prepare('SELECT * FROM team_configs WHERE team_config_id = ?;') + .get(teamConfigId) as SqlRow | undefined; + return row ? this.#hydrateTeamConfigRow(row) : null; + }); + } + + listTeamConfigs(campaignId: string, islandId?: number): Promise { + return this.enqueue(() => { + const rows = islandId === undefined + ? (this.#db + .prepare('SELECT * FROM team_configs WHERE campaign_id = ? ORDER BY created_generation ASC, team_config_id ASC;') + .all(campaignId) as SqlRow[]) + : (this.#db + .prepare('SELECT * FROM team_configs WHERE campaign_id = ? AND island_id = ? ORDER BY created_generation ASC, team_config_id ASC;') + .all(campaignId, islandId) as SqlRow[]); + return rows.map(r => this.#hydrateTeamConfigRow(r)); + }); + } + + /** + * Record one generation's outcome against a `team_config`. + * Preempted runs never consume `trial_used_generations`. Advancing Pareto or niche elites + * promotes `'trial' -> 'promoted'`; exhausting `trial_budget_generations` without advance + * transitions `'trial' -> 'rolled_back'` and restores `parent_team_config_id` on the island. + */ + recordTeamTrialGeneration(lease: CampaignLease, input: RecordTeamTrialGenerationInput): Promise { + return this.enqueue(() => { + return this.#inWriteTransaction(lease, () => { + const row = this.#db + .prepare('SELECT * FROM team_configs WHERE team_config_id = ?;') + .get(input.teamConfigId) as SqlRow | undefined; + if (!row) { + throw new EvolutionError('EVOLUTION_NOT_FOUND', `team_config "${input.teamConfigId}" not found`); + } + if (input.preempted === true) { + return this.#hydrateTeamConfigRow(row); + } + + const currentStatus = String(row['status']) as TeamConfigStatus; + const paretoAdvances = Number(row['pareto_advances']) + (input.advancedPareto ? 1 : 0); + const nicheDiscoveries = Number(row['niche_discoveries']) + (input.discoveredNiche ? 1 : 0); + const trialBudget = Number(row['trial_budget_generations']); + const trialUsed = currentStatus === 'trial' + ? Number(row['trial_used_generations']) + 1 + : Number(row['trial_used_generations']); + + let nextStatus: TeamConfigStatus = currentStatus; + if (currentStatus === 'trial') { + if (paretoAdvances > 0 || nicheDiscoveries > 0) { + nextStatus = 'promoted'; + } else if (trialUsed >= trialBudget) { + nextStatus = 'rolled_back'; + } + } + + this.#db + .prepare( + `UPDATE team_configs + SET status = ?, trial_used_generations = ?, pareto_advances = ?, niche_discoveries = ? + WHERE team_config_id = ?;`, + ) + .run(nextStatus, trialUsed, paretoAdvances, nicheDiscoveries, input.teamConfigId); + + if (nextStatus === 'rolled_back' && row['parent_team_config_id'] !== null) { + this.#db + .prepare( + 'UPDATE islands SET active_team_config_id = ? WHERE campaign_id = ? AND island_id = ? AND active_team_config_id = ?;', + ) + .run( + String(row['parent_team_config_id']), + String(row['campaign_id']), + Number(row['island_id']), + input.teamConfigId, + ); + } + + const updated = this.#db + .prepare('SELECT * FROM team_configs WHERE team_config_id = ?;') + .get(input.teamConfigId) as SqlRow; + return this.#hydrateTeamConfigRow(updated); + }); + }); + } + + promoteTeamConfig(lease: CampaignLease, teamConfigId: string): Promise { + return this.enqueue(() => { + return this.#inWriteTransaction(lease, () => { + const row = this.#db + .prepare('SELECT * FROM team_configs WHERE team_config_id = ?;') + .get(teamConfigId) as SqlRow | undefined; + if (!row) { + throw new EvolutionError('EVOLUTION_NOT_FOUND', `team_config "${teamConfigId}" not found`); + } + this.#db + .prepare("UPDATE team_configs SET status = 'promoted' WHERE team_config_id = ?;") + .run(teamConfigId); + this.#db + .prepare('UPDATE islands SET active_team_config_id = ? WHERE campaign_id = ? AND island_id = ?;') + .run(teamConfigId, String(row['campaign_id']), Number(row['island_id'])); + const updated = this.#db + .prepare('SELECT * FROM team_configs WHERE team_config_id = ?;') + .get(teamConfigId) as SqlRow; + return this.#hydrateTeamConfigRow(updated); + }); + }); + } + + rollbackTeamConfig(lease: CampaignLease, teamConfigId: string): Promise { + return this.enqueue(() => { + return this.#inWriteTransaction(lease, () => { + const row = this.#db + .prepare('SELECT * FROM team_configs WHERE team_config_id = ?;') + .get(teamConfigId) as SqlRow | undefined; + if (!row) { + throw new EvolutionError('EVOLUTION_NOT_FOUND', `team_config "${teamConfigId}" not found`); + } + if (row['parent_team_config_id'] === null) { + throw new EvolutionError('EVOLUTION_STORE_ERROR', 'baseline team_config cannot be rolled back'); + } + this.#db + .prepare("UPDATE team_configs SET status = 'rolled_back' WHERE team_config_id = ?;") + .run(teamConfigId); + this.#db + .prepare( + 'UPDATE islands SET active_team_config_id = ? WHERE campaign_id = ? AND island_id = ? AND active_team_config_id = ?;', + ) + .run(String(row['parent_team_config_id']), String(row['campaign_id']), Number(row['island_id']), teamConfigId); + const updated = this.#db + .prepare('SELECT * FROM team_configs WHERE team_config_id = ?;') + .get(teamConfigId) as SqlRow; + return this.#hydrateTeamConfigRow(updated); + }); + }); + } + + 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; + } + } + + 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 this.#inWriteTransaction(lease, now => { + const campaignRow = this.#db + .prepare('SELECT evaluations_used, preemptions_count, manifest_digest_hex, manifest_json FROM campaigns WHERE campaign_id = ?;') + .get(input.campaignId) as SqlRow | undefined; + if (!campaignRow) { + throw new EvolutionError('EVOLUTION_NOT_FOUND', `campaign "${input.campaignId}" not found`); + } + + const teamRow = this.#db + .prepare('SELECT campaign_id, island_id FROM team_configs WHERE team_config_id = ?;') + .get(input.teamConfigId) as SqlRow | undefined; + if (!teamRow || String(teamRow['campaign_id']) !== input.campaignId || Number(teamRow['island_id']) !== input.islandId) { + throw new EvolutionError( + 'EVOLUTION_STORE_ERROR', + `team_config "${input.teamConfigId}" does not belong to (${input.campaignId}, island ${input.islandId})`, + ); + } + + const isPreempted = input.status === 'preempted'; + const shouldCountEvaluation = !isPreempted && (input.countEvaluation ?? true); + if (shouldCountEvaluation) { + const manifest = this.#parseCachedManifest( + input.campaignId, + String(campaignRow['manifest_digest_hex']), + String(campaignRow['manifest_json']), + ); + const used = Number(campaignRow['evaluations_used']); + if (used >= manifest.spec.budgets.maxEvaluations) { + throw new EvolutionError( + 'EVOLUTION_BUDGET_EXCEEDED', + `campaign maxEvaluations (${manifest.spec.budgets.maxEvaluations}) reached`, + ); + } + } + + 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, + ); + + if (input.lineageEdges !== undefined && input.lineageEdges.length > 0) { + this.#insertLineageEdgesSync(input.lineageEdges); + } + + if (isPreempted) { + this.#db + .prepare('UPDATE campaigns SET preemptions_count = preemptions_count + 1, updated_at_wall_ms = ? WHERE campaign_id = ?;') + .run(now.wallMs, input.campaignId); + } else if (shouldCountEvaluation) { + this.#db + .prepare('UPDATE campaigns SET evaluations_used = evaluations_used + 1, updated_at_wall_ms = ? WHERE campaign_id = ?;') + .run(now.wallMs, input.campaignId); + } + + const inserted = this.#db + .prepare('SELECT * FROM individuals WHERE individual_id = ?;') + .get(input.individualId) as SqlRow; + return this.#hydrateIndividualRow(inserted); + }); + }); + } + + getIndividual(individualId: string): Promise { + return this.enqueue(() => { + const row = this.#db + .prepare('SELECT * FROM individuals WHERE individual_id = ?;') + .get(individualId) as SqlRow | undefined; + return row ? this.#hydrateIndividualRow(row) : null; + }); + } + + listIndividuals(campaignId: string, filter: ListIndividualsFilter = {}): Promise { + return this.enqueue(() => { + const clauses: string[] = ['campaign_id = ?']; + const params: SQLInputValue[] = [campaignId]; + + if (filter.islandId !== undefined) { + clauses.push('island_id = ?'); + params.push(filter.islandId); + } + if (filter.status !== undefined && filter.status.length > 0) { + clauses.push(`status IN (${filter.status.map(() => '?').join(', ')})`); + for (const st of filter.status) params.push(st); + } + if (filter.bucketId !== undefined) { + if (filter.bucketId === null) { + clauses.push('bucket_id IS NULL'); + } else { + clauses.push('bucket_id = ?'); + params.push(filter.bucketId); + } + } + if (filter.nicheKey !== undefined) { + clauses.push('niche_key = ?'); + params.push(filter.nicheKey); + } + + const sql = `SELECT * FROM individuals WHERE ${clauses.join(' AND ')} ORDER BY generation ASC, individual_id ASC;`; + const rows = this.#db.prepare(sql).all(...params) as SqlRow[]; + return rows.map(r => this.#hydrateIndividualRow(r)); + }); + } + + /** + * Return the winning fertile elite per `nicheKey` on `(campaignId, islandId)`, breaking ties + * deterministically by `paretoRank` asc, `scalarFitness` desc, `crowdingDistance` desc, and `individualId` asc. + */ + getIslandNicheElites( + campaignId: string, + islandId: number, + bucketId?: string | null, + ): Promise> { + return this.enqueue(() => { + const clauses = [ + 'campaign_id = ?', + 'island_id = ?', + "status IN ('passed', 'soft_passed')", + 'niche_key IS NOT NULL', + ]; + const params: SQLInputValue[] = [campaignId, islandId]; + if (bucketId !== undefined) { + if (bucketId === null) { + clauses.push('bucket_id IS NULL'); + } else { + clauses.push('bucket_id = ?'); + params.push(bucketId); + } + } + const rows = this.#db + .prepare(`SELECT * FROM individuals WHERE ${clauses.join(' AND ')};`) + .all(...params) as SqlRow[]; + const elites = new Map(); + for (const row of rows) { + const candidate = this.#hydrateIndividualRow(row); + if (candidate.nicheKey === null) continue; + const incumbent = elites.get(candidate.nicheKey); + if (!incumbent || compareNicheEliteBetter(candidate, incumbent) < 0) { + elites.set(candidate.nicheKey, candidate); + } + } + return elites; + }); + } + + updateParetoRanks( + lease: CampaignLease, + campaignId: string, + updates: readonly ParetoRankUpdate[], + ): Promise { + return this.enqueue(() => { + this.#inWriteTransaction(lease, () => { + const stmt = this.#db.prepare( + `UPDATE individuals + SET pareto_rank = ?, crowding_distance = ?, crowding_is_boundary = ?, scalar_fitness = COALESCE(?, scalar_fitness) + WHERE campaign_id = ? AND individual_id = ?;`, + ); + for (const u of updates) { + let crowdVal: number | null = null; + let isBoundary = 0; + if (u.crowdingDistance !== null) { + if (u.crowdingDistance === Number.POSITIVE_INFINITY) { + isBoundary = 1; + } else if (!Number.isFinite(u.crowdingDistance) || Object.is(u.crowdingDistance, -0) || u.crowdingDistance < 0) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'invalid crowdingDistance in updateParetoRanks'); + } else { + crowdVal = u.crowdingDistance; + } + } + const scalarVal = u.scalarFitness === undefined ? null : u.scalarFitness; + stmt.run(u.paretoRank, crowdVal, isBoundary, scalarVal, campaignId, u.individualId); + } + }); + }); + } + + incrementOffspringCount(lease: CampaignLease, individualId: string, delta = 1): Promise { + return this.enqueue(() => { + if (!Number.isSafeInteger(delta) || delta < 1) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'delta must be an integer >= 1'); + } + return this.#inWriteTransaction(lease, () => { + const res = this.#db + .prepare('UPDATE individuals SET offspring_count = offspring_count + ? WHERE individual_id = ?;') + .run(delta, individualId); + if (Number(res.changes) !== 1) { + throw new EvolutionError('EVOLUTION_NOT_FOUND', `individual "${individualId}" not found`); + } + const row = this.#db + .prepare('SELECT * FROM individuals WHERE individual_id = ?;') + .get(individualId) as SqlRow; + return this.#hydrateIndividualRow(row); + }); + }); + } + + #insertLineageEdgesSync(edges: readonly LineageEdgeRecord[]): void { + const stmt = this.#db.prepare( + `INSERT INTO lineage_edges ( + campaign_id, child_individual_id, parent_individual_id, role, source_island_id, created_generation + ) VALUES (?, ?, ?, ?, ?, ?);`, + ); + for (const edge of edges) { + stmt.run( + edge.campaignId, + edge.childIndividualId, + edge.parentIndividualId, + edge.role, + edge.sourceIslandId, + edge.createdGeneration, + ); + } + } + + recordLineageEdges(lease: CampaignLease, edges: readonly LineageEdgeRecord[]): Promise { + return this.enqueue(() => { + this.#inWriteTransaction(lease, () => { + this.#insertLineageEdgesSync(edges); + }); + }); + } + + listLineageEdges(campaignId: string, filter: ListLineageEdgesFilter = {}): Promise { + return this.enqueue(() => { + const clauses = ['campaign_id = ?']; + const params: SQLInputValue[] = [campaignId]; + if (filter.childIndividualId !== undefined) { + clauses.push('child_individual_id = ?'); + params.push(filter.childIndividualId); + } + if (filter.parentIndividualId !== undefined) { + clauses.push('parent_individual_id = ?'); + params.push(filter.parentIndividualId); + } + if (filter.role !== undefined) { + clauses.push('role = ?'); + params.push(filter.role); + } + const rows = this.#db + .prepare( + `SELECT * FROM lineage_edges + WHERE ${clauses.join(' AND ')} + ORDER BY created_generation ASC, child_individual_id ASC, role ASC, parent_individual_id ASC;`, + ) + .all(...params) as SqlRow[]; + return rows.map(r => { + const out = createNullRecord<{ + campaignId: string; + childIndividualId: string; + parentIndividualId: string; + role: LineageRole; + sourceIslandId: number; + createdGeneration: number; + }>(); + out.campaignId = String(r['campaign_id']); + out.childIndividualId = String(r['child_individual_id']); + out.parentIndividualId = String(r['parent_individual_id']); + out.role = String(r['role']) as LineageRole; + out.sourceIslandId = Number(r['source_island_id']); + out.createdGeneration = Number(r['created_generation']); + return out; + }); + }); + } + + ensureModelBanditArms( + lease: CampaignLease, + campaignId: string, + modelIds: readonly string[], + ): Promise { + return this.enqueue(() => { + return this.#inWriteTransaction(lease, () => { + const stmt = this.#db.prepare( + `INSERT INTO model_bandit_arms ( + campaign_id, model_id, pull_count, total_reward, mean_reward, last_pulled_generation + ) VALUES (?, ?, 0, 0, 0, NULL) + ON CONFLICT (campaign_id, model_id) DO NOTHING;`, + ); + for (const modelId of modelIds) { + stmt.run(campaignId, modelId); + } + return this.#listModelBanditArmsSync(campaignId); + }); + }); + } + + #listModelBanditArmsSync(campaignId: string): readonly ModelBanditArmRecord[] { + const rows = this.#db + .prepare('SELECT * FROM model_bandit_arms WHERE campaign_id = ? ORDER BY model_id ASC;') + .all(campaignId) as SqlRow[]; + return rows.map(r => { + const out = createNullRecord<{ + campaignId: string; + modelId: string; + pullCount: number; + totalReward: number; + meanReward: number; + lastPulledGeneration: number | null; + }>(); + out.campaignId = String(r['campaign_id']); + out.modelId = String(r['model_id']); + out.pullCount = Number(r['pull_count']); + out.totalReward = Number(r['total_reward']); + out.meanReward = Number(r['mean_reward']); + out.lastPulledGeneration = r['last_pulled_generation'] === null ? null : Number(r['last_pulled_generation']); + return out; + }); + } + + listModelBanditArms(campaignId: string): Promise { + return this.enqueue(() => this.#listModelBanditArmsSync(campaignId)); + } + + recordModelBanditReward(lease: CampaignLease, input: RecordModelBanditRewardInput): Promise { + return this.enqueue(() => { + if (!Number.isFinite(input.reward) || Object.is(input.reward, -0) || input.reward < 0) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'bandit reward must be finite >= 0'); + } + return this.#inWriteTransaction(lease, () => { + const existing = this.#db + .prepare('SELECT * FROM model_bandit_arms WHERE campaign_id = ? AND model_id = ?;') + .get(input.campaignId, input.modelId) as SqlRow | undefined; + const nextPulls = existing ? Number(existing['pull_count']) + 1 : 1; + const nextTotal = (existing ? Number(existing['total_reward']) : 0) + input.reward; + const nextMean = nextTotal / nextPulls; + + this.#db + .prepare( + `INSERT INTO model_bandit_arms ( + campaign_id, model_id, pull_count, total_reward, mean_reward, last_pulled_generation + ) VALUES (?, ?, ?, ?, ?, ?) + ON CONFLICT (campaign_id, model_id) DO UPDATE SET + pull_count = excluded.pull_count, + total_reward = excluded.total_reward, + mean_reward = excluded.mean_reward, + last_pulled_generation = excluded.last_pulled_generation;`, + ) + .run(input.campaignId, input.modelId, nextPulls, nextTotal, nextMean, input.generation); + + const row = this.#db + .prepare('SELECT * FROM model_bandit_arms WHERE campaign_id = ? AND model_id = ?;') + .get(input.campaignId, input.modelId) as SqlRow; + const out = createNullRecord<{ + campaignId: string; + modelId: string; + pullCount: number; + totalReward: number; + meanReward: number; + lastPulledGeneration: number | null; + }>(); + out.campaignId = String(row['campaign_id']); + out.modelId = String(row['model_id']); + out.pullCount = Number(row['pull_count']); + out.totalReward = Number(row['total_reward']); + out.meanReward = Number(row['mean_reward']); + out.lastPulledGeneration = row['last_pulled_generation'] === null ? null : Number(row['last_pulled_generation']); + return out; + }); + }); + } + + /** + * Persist a content-addressed blob under `/cas/sha256/` with `O_NOFOLLOW`, + * `nlink === 1`, and `0o400` read-only permissions. + */ + writeCasBlob(content: Uint8Array | string): Promise { + return this.enqueue(async () => { + const bytes = typeof content === 'string' + ? Buffer.from(content, 'utf8') + : Buffer.from(content.buffer, content.byteOffset, content.byteLength); + const hex = createHash('sha256').update(bytes).digest('hex'); + + await ensureNonSymlinkDirectory(this.campaignRoot, false); + const casDir = join(this.campaignRoot, 'cas'); + const shaDir = join(casDir, 'sha256'); + await ensureNonSymlinkDirectory(casDir, true); + await ensureNonSymlinkDirectory(shaDir, true); + + const finalPath = join(shaDir, hex); + const casRelPath = `cas/sha256/${hex}`; + const noFollow = 'O_NOFOLLOW' in fsConstants ? fsConstants.O_NOFOLLOW : 0; + + const existing = await lstat(finalPath).catch((err: NodeJS.ErrnoException) => { + if (err.code === 'ENOENT') return null; + if (err.code === 'ELOOP') { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `symlink forbidden along ${finalPath}`, finalPath); + } + throw err; + }); + + if (existing !== null) { + if (existing.isSymbolicLink()) { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `CAS blob cannot be a symlink: ${finalPath}`, finalPath); + } + if (!existing.isFile() || existing.nlink !== 1) { + throw new EvolutionError('ARTIFACT_INVALID', `CAS blob must be an unlinked regular file: ${finalPath}`, finalPath); + } + const verified = await this.#readCasBlobRawNoQueue(hex, bytes.byteLength); + if (verified.byteLength !== bytes.byteLength) { + throw new EvolutionError('ARTIFACT_INVALID', `CAS blob size mismatch for ${hex}`, finalPath); + } + return { + digest: digestFromHex(hex), + byteLength: bytes.byteLength, + casPath: finalPath, + casRelPath, + }; + } + + const tempPath = join(shaDir, `.tmp-${hex}-${randomBytes(6).toString('hex')}`); + const handle = await open( + tempPath, + fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_WRONLY | noFollow, + 0o600, + ); + try { + let written = 0; + while (written < bytes.byteLength) { + const res = await handle.write(bytes, written, bytes.byteLength - written, written); + written += res.bytesWritten; + } + await handle.sync(); + } catch (err) { + await handle.close().catch(() => undefined); + await unlink(tempPath).catch(() => undefined); + throw err; + } + await handle.close(); + + try { + await chmod(tempPath, 0o400); + await rename(tempPath, finalPath); + } catch (err) { + await chmod(tempPath, 0o600).catch(() => undefined); + await unlink(tempPath).catch(() => undefined); + throw err; + } + + return { + digest: digestFromHex(hex), + byteLength: bytes.byteLength, + casPath: finalPath, + casRelPath, + }; + }); + } + + async #readCasBlobRawNoQueue(digestHex: string, maxBytes = 67_108_864): Promise { + if (!SHA256_HEX_RE.test(digestHex)) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', `invalid sha256 hex "${digestHex}"`); + } + await ensureNonSymlinkDirectory(this.campaignRoot, false); + await ensureNonSymlinkDirectory(join(this.campaignRoot, 'cas'), false); + await ensureNonSymlinkDirectory(join(this.campaignRoot, 'cas', 'sha256'), false); + + const blobPath = join(this.campaignRoot, 'cas', 'sha256', digestHex); + const st = await lstat(blobPath).catch((err: NodeJS.ErrnoException) => { + if (err.code === 'ENOENT') { + throw new EvolutionError('ARTIFACT_MISSING', `CAS blob not found: ${digestHex}`, blobPath); + } + if (err.code === 'ELOOP') { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `symlink forbidden along ${blobPath}`, blobPath); + } + throw err; + }); + if (st.isSymbolicLink()) { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `CAS blob cannot be a symlink: ${blobPath}`, blobPath); + } + if (!st.isFile() || st.nlink !== 1 || st.size > maxBytes) { + throw new EvolutionError('ARTIFACT_INVALID', `CAS blob failed stat checks: ${blobPath}`, blobPath); + } + + const noFollow = 'O_NOFOLLOW' in fsConstants ? fsConstants.O_NOFOLLOW : 0; + const handle = await open(blobPath, fsConstants.O_RDONLY | noFollow); + try { + const fdStat = await handle.stat(); + if (!fdStat.isFile() || fdStat.nlink !== 1 || fdStat.size !== st.size || fdStat.size > maxBytes) { + throw new EvolutionError('ARTIFACT_INVALID', `CAS blob changed during read: ${blobPath}`, blobPath); + } + 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 CAS blob read: ${blobPath}`, blobPath); + } + const observedHex = createHash('sha256').update(buf).digest('hex'); + if (observedHex !== digestHex) { + throw new EvolutionError('ARTIFACT_INVALID', `CAS blob SHA-256 mismatch for ${digestHex}`, blobPath); + } + return buf; + } finally { + await handle.close(); + } + } + + readCasBlob(digestHex: string, maxBytes = 67_108_864): Promise { + return this.enqueue(() => this.#readCasBlobRawNoQueue(digestHex, maxBytes)); + } + + recordScratchpadSnapshot( + lease: CampaignLease, + input: RecordScratchpadSnapshotInput, + ): Promise { + return this.enqueue(() => { + assertSafeId(input.snapshotId, 'snapshotId'); + assertSafeId(input.campaignId, 'campaignId'); + assertDigest(input.casDigest, 'casDigest'); + + return this.#inWriteTransaction(lease, now => { + 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 (?, ?, ?, ?, ?, ?, ?, ?, ?);`, + ) + .run( + input.snapshotId, + input.campaignId, + input.generation, + input.casDigest.hex, + input.byteLength, + input.casRelPath, + input.topGainsCount, + input.failurePatternsCount, + now.wallMs, + ); + const row = this.#db + .prepare('SELECT * FROM scratchpad_snapshots WHERE snapshot_id = ?;') + .get(input.snapshotId) as SqlRow; + return this.#hydrateScratchpadRow(row); + }); + }); + } + + #hydrateScratchpadRow(row: SqlRow): ScratchpadSnapshotRecord { + const out = createNullRecord<{ + snapshotId: string; + campaignId: string; + generation: number; + casDigest: Digest; + byteLength: number; + casRelPath: string; + topGainsCount: number; + failurePatternsCount: number; + createdAtWallMs: number; + }>(); + out.snapshotId = String(row['snapshot_id']); + out.campaignId = String(row['campaign_id']); + out.generation = Number(row['generation']); + out.casDigest = digestFromHex(String(row['cas_digest_hex'])); + out.byteLength = Number(row['byte_length']); + out.casRelPath = String(row['cas_rel_path']); + out.topGainsCount = Number(row['top_gains_count']); + out.failurePatternsCount = Number(row['failure_patterns_count']); + out.createdAtWallMs = Number(row['created_at_wall_ms']); + return out; + } + + getLatestScratchpadSnapshot(campaignId: string): Promise { + return this.enqueue(() => { + const row = this.#db + .prepare( + `SELECT * FROM scratchpad_snapshots + WHERE campaign_id = ? + ORDER BY generation DESC, created_at_wall_ms DESC, snapshot_id DESC + LIMIT 1;`, + ) + .get(campaignId) as SqlRow | undefined; + return row ? this.#hydrateScratchpadRow(row) : null; + }); + } + + listScratchpadSnapshots(campaignId: string): Promise { + return this.enqueue(() => { + const rows = this.#db + .prepare( + `SELECT * FROM scratchpad_snapshots + WHERE campaign_id = ? + ORDER BY generation ASC, created_at_wall_ms ASC, snapshot_id ASC;`, + ) + .all(campaignId) as SqlRow[]; + return rows.map(r => this.#hydrateScratchpadRow(r)); + }); + } + + close(): Promise { + const closing = this.#queue.then(() => { + if (!this.#closed) { + this.#closed = true; + this.#db.close(); + } + }); + this.#queue = closing.then( + () => undefined, + () => undefined, + ); + return closing; + } +} + +function compareNicheEliteBetter(a: IndividualRecord, b: IndividualRecord): number { + if (a.status !== b.status) { + if (a.status === 'passed') return -1; + if (b.status === 'passed') return 1; + } + const rankA = a.paretoRank ?? Number.MAX_SAFE_INTEGER; + const rankB = b.paretoRank ?? Number.MAX_SAFE_INTEGER; + if (rankA !== rankB) return rankA - rankB; + + const fitA = a.scalarFitness ?? Number.NEGATIVE_INFINITY; + const fitB = b.scalarFitness ?? Number.NEGATIVE_INFINITY; + if (fitA !== fitB) return fitB - fitA; + + const crowdA = a.crowdingDistance ?? -1; + const crowdB = b.crowdingDistance ?? -1; + if (crowdA !== crowdB) return crowdB > crowdA ? 1 : -1; + + return a.individualId < b.individualId ? -1 : a.individualId > b.individualId ? 1 : 0; +} diff --git a/packages/evolution/src/team-supervisor.ts b/packages/evolution/src/team-supervisor.ts new file mode 100644 index 0000000..d75da6b --- /dev/null +++ b/packages/evolution/src/team-supervisor.ts @@ -0,0 +1,1928 @@ +import { execFile } from 'node:child_process'; +import { createHash, randomBytes } from 'node:crypto'; +import { constants } from 'node:fs'; +import { chmod, lstat, mkdir, mkdtemp, open, readdir, readFile, realpath, rename, rm, unlink, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { dirname, isAbsolute, join, resolve } from 'node:path'; +import { promisify } from 'node:util'; +import { + LIMITS, + SecretScrubber, + validateDocument, + type Digest, + type StepHandoffSelector, + type TaskContract, +} from '@loopwright/core'; +import { + CONTROLLER_API_VERSION, + installedHandlerDigests, + loadTrustedConfiguration, + stepCancel, + stepNext, + stepSubmit, + type CheckpointCapacity, + type ControllerPolicyProfile, + type RunEvalReport, + type TrustedRegistry, +} from '@loopwright/controller'; +import type { TaskpackManifest, TaskpackToolName } from '@loopwright/taskpack'; +import { + canonicalizeJson, + parseNullProtoJson, + parseTeamPatchV1, + type NullProtoJson, +} from './schema.js'; +import type { EvolutionCampaignStore } from './store.js'; +import { + EvolutionError, + TEAM_PATCH_MAX_BYTES, + type CampaignLease, + type EvolutionBudgetsSpec, + type EvolutionTeamSpec, + type IndividualRecord, + type IslandRecord, + type TeamConfigRecord, + type TeamConfigStatus, + type TeamPatchV1, +} from './types.js'; + +const DEFAULT_SUPERVISOR_SCRUBBER = new SecretScrubber(); +const MAX_STAGED_DIAGNOSTIC_BYTES = 262_144; +const MUTATING_OR_EXEC_TOOLS: ReadonlySet = new Set(['write', 'edit', 'delete', 'bash']); + +const FORBIDDEN_PATCH_AUTHORITY_KEYS: ReadonlySet = new Set([ + 'scope', + 'writable', + 'protected', + 'acceptance', + 'checks', + 'evolveBlocks', + 'trustedContext', + 'discovery', + 'network', + 'mounts', + 'mcp', + 'mcpServers', + 'credentials', + 'capabilities', + 'allowWorkflowWrites', + 'heldOutWorkloadId', +]); + +export type TeamTriggerReason = 'pareto_stagnation' | 'run_eval_pathology'; + +export type TeamTriggerSuppressedReason = + | 'disabled' + | 'trial_in_progress' + | 'insufficient_evaluation_budget' + | 'insufficient_generation_budget' + | 'target_roofline_reached' + | 'steady_progress'; + +export interface EvaluateTeamTriggerInput { + readonly teamEvolution?: EvolutionTeamSpec | undefined; + readonly island: IslandRecord; + readonly budgets: EvolutionBudgetsSpec; + readonly evaluationsUsed: number; + readonly currentGeneration: number; + readonly recentRunEvals?: readonly RunEvalReport[] | undefined; + readonly activeTeamStatus?: TeamConfigStatus | undefined; +} + +export interface TeamEvolutionTriggerDecision { + readonly shouldInvoke: boolean; + readonly triggerReason?: TeamTriggerReason; + readonly suppressedReason?: TeamTriggerSuppressedReason; + readonly consecutiveNoGainGenerations: number; + readonly consecutivePathologyRuns: number; +} + +export interface IslandTrajectoryEntry { + readonly generation: number; + readonly hypervolume: number; + readonly bestScalarFitness: number | null; + readonly nichesOpen: number; +} + +export interface StagedSupervisorFile { + readonly name: string; + readonly filePath: string; + readonly resourceId: string; + readonly relativeResourcePath: string; + readonly digest: Digest; + readonly byteLength: number; +} + +export type PinnedContextResource = TaskContract['spec']['trustedContext']['resources'][number]; + +export interface StageSupervisorContextInput { + readonly stagingDir: string; + readonly campaignId: string; + readonly island: IslandRecord; + readonly triggerReason: TeamTriggerReason; + readonly teamEvolution: EvolutionTeamSpec; + readonly baseTaskContract: TaskContract; + readonly trajectory?: readonly IslandTrajectoryEntry[] | undefined; + readonly recentRunEvals?: readonly RunEvalReport[] | undefined; + readonly recentIndividuals?: readonly IndividualRecord[] | undefined; + readonly latestScratchpadMarkdown?: string | undefined; + readonly teamHistory?: readonly TeamConfigRecord[] | undefined; + readonly scrubber?: SecretScrubber | undefined; +} + +export interface StagedSupervisorContext { + readonly stagingDir: string; + readonly files: readonly StagedSupervisorFile[]; + readonly supervisorContract: TaskContract; + readonly writablePaths: readonly []; + readonly prompt: string; +} + +export interface ArchetypeRoleEnvelope { + readonly id: string; + readonly adapter: 'pi' | 'delegated'; + readonly purpose: 'task' | 'review'; + readonly tools: readonly TaskpackToolName[]; + readonly maxTimeoutSeconds: number; + readonly defaultModel?: string | undefined; + readonly provider?: string | undefined; + readonly thinking?: string | undefined; +} + +export interface ComputePatchCheckpointCapacityInput { + readonly maxAttempts: number; + readonly agentStepsCount: number; + readonly maxImplementationRepairs: number; + readonly verifierSlotCount: number; + readonly publicationEnabled?: boolean | undefined; + readonly reworkGenerations?: number | undefined; + readonly checkReworkGenerations?: number | undefined; +} + +export interface ValidateAndCompileTeamPatchInput { + readonly rawPatch: unknown; + readonly teamEvolution: EvolutionTeamSpec; + readonly baseTaskContract: TaskContract; + readonly taskpack?: TaskpackManifest | undefined; + readonly trustedRegistry?: TrustedRegistry | undefined; + readonly archetypes?: readonly ArchetypeRoleEnvelope[] | undefined; + readonly extraPinnedResources?: readonly PinnedContextResource[] | undefined; + readonly maxAttempts?: number | undefined; + readonly publicationEnabled?: boolean | undefined; + readonly scrubber?: SecretScrubber | undefined; +} + +export interface CompiledRoleModelBinding { + readonly provider: string; + readonly model: string; + readonly thinking: string; + readonly timeoutSeconds?: number; +} + +export interface CompiledTeamPatchResult { + readonly patch: TeamPatchV1; + readonly canonicalPatchJson: string; + readonly patchDigest: Digest; + readonly taskContract: TaskContract; + readonly capacity: CheckpointCapacity; + readonly resolvedRoleModels: Readonly>; + readonly compiledRegistry?: TrustedRegistry; +} + +export interface RecordTeamTrialOutcomeInput { + readonly campaignId: string; + readonly islandId: number; + readonly teamConfigId: string; + readonly advancedPareto: boolean; + readonly discoveredNiche: boolean; + readonly preempted?: boolean | undefined; +} + +export interface TeamTrialOutcomeResult { + readonly teamConfig: TeamConfigRecord; + readonly previousStatus: TeamConfigStatus; + readonly nextStatus: TeamConfigStatus; + readonly activeTeamConfigId: string; + readonly promoted: boolean; + readonly rolledBack: boolean; + readonly ignoredPreemption: boolean; +} + +export interface SupervisorExecutionContext { + readonly campaignId: string; + readonly island: IslandRecord; + readonly triggerReason: TeamTriggerReason; + readonly stagingDir: string; + readonly files: readonly StagedSupervisorFile[]; + readonly supervisorContract: TaskContract; + readonly writablePaths: readonly []; + readonly prompt: string; +} + +export type SupervisorRunnerPort = ( + context: SupervisorExecutionContext, +) => Promise>; + +export interface ReadOnlySupervisorTurnContext extends SupervisorExecutionContext { + readonly runRoot: string; + readonly runId: string; + readonly stepId: string; + readonly roleId: string; + readonly candidateDir: string; + readonly contextFiles: readonly string[]; + readonly leaseToken: string; + readonly tools: readonly ['read']; + readonly signal?: AbortSignal | undefined; +} + +export interface LocalRunStoreSupervisorRunnerOptions { + readonly executeReadOnlySupervisorTurn: ( + turn: ReadOnlySupervisorTurnContext, + ) => Promise>; + readonly environment?: ((name: string) => string | undefined) | undefined; + readonly policyProfile?: ControllerPolicyProfile | undefined; + readonly signal?: AbortSignal | undefined; + readonly scrubber?: SecretScrubber | undefined; +} + +export interface RunPlateauSupervisorTurnInput { + readonly store: EvolutionCampaignStore; + readonly lease: CampaignLease; + readonly campaignId: string; + readonly island: IslandRecord; + readonly teamEvolution?: EvolutionTeamSpec | undefined; + readonly budgets: EvolutionBudgetsSpec; + readonly evaluationsUsed: number; + readonly currentGeneration: number; + readonly baseTaskContract: TaskContract; + readonly taskpack?: TaskpackManifest | undefined; + readonly trustedRegistry?: TrustedRegistry | undefined; + readonly archetypes?: readonly ArchetypeRoleEnvelope[] | undefined; + readonly extraPinnedResources?: readonly PinnedContextResource[] | undefined; + readonly trajectory?: readonly IslandTrajectoryEntry[] | undefined; + readonly recentRunEvals?: readonly RunEvalReport[] | undefined; + readonly recentIndividuals?: readonly IndividualRecord[] | undefined; + readonly latestScratchpadMarkdown?: string | undefined; + readonly stagingDir: string; + readonly supervisorRunner: SupervisorRunnerPort; + readonly scrubber?: SecretScrubber | undefined; +} + +export interface PlateauSupervisorTurnResult { + readonly invoked: boolean; + readonly accepted: boolean; + readonly decision: TeamEvolutionTriggerDecision; + readonly activeTeamConfigId: string; + readonly teamConfig?: TeamConfigRecord; + readonly compiledPatch?: CompiledTeamPatchResult; + readonly stagedContext?: StagedSupervisorContext; + readonly error?: EvolutionError; +} + +function sha256Digest(bytes: Uint8Array | string): Digest { + return Object.freeze({ + algorithm: 'sha256' as const, + hex: createHash('sha256').update(bytes).digest('hex'), + }); +} + +function assertCleanSecrets(text: string, scrubber: SecretScrubber, diagPath: string): void { + const scrubbed = scrubber.scrub(text); + if (scrubbed !== text) { + throw new EvolutionError( + 'SECRET_LEAK_DETECTED', + `secret pattern detected while staging or validating ${diagPath}`, + diagPath, + ); + } +} + +function sanitizeIdentifier(raw: string, fallback: string): string { + const cleaned = raw + .toLowerCase() + .replace(/[^a-z0-9._-]+/g, '-') + .replace(/^[^a-z0-9]+/, '') + .slice(0, LIMITS.identifier); + return cleaned.length > 0 ? cleaned : fallback; +} + +/** + * Detect whether a single child `RunEvalReport` exhibits loop pathology (`pingPong` cycles or + * `toolRepeats` circuit-breaker trips `consecutive_tool_errors` / `no_progress`). + */ +export function hasRunEvalLoopPathology(report: RunEvalReport): boolean { + if (report.pingPong.detected === true) { + return true; + } + const cb = report.toolRepeats.circuitBreaker; + return cb === 'consecutive_tool_errors' || cb === 'no_progress'; +} + +function countTrailingPathologyRuns(reports: readonly RunEvalReport[] | undefined): number { + if (reports === undefined || reports.length === 0) return 0; + let count = 0; + for (let i = reports.length - 1; i >= 0; i -= 1) { + if (hasRunEvalLoopPathology(reports[i]!)) { + count += 1; + } else { + break; + } + } + return count; +} + +/** + * Pure event-driven plateau / pathology trigger check with zero steady-state overhead. + */ +export function evaluateTeamEvolutionTrigger(input: EvaluateTeamTriggerInput): TeamEvolutionTriggerDecision { + const { teamEvolution, island, budgets, evaluationsUsed, currentGeneration } = input; + const trailingFromReports = countTrailingPathologyRuns(input.recentRunEvals); + const consecutivePathologyRuns = Math.max(island.consecutivePathologyRuns, trailingFromReports); + const consecutiveNoGainGenerations = island.consecutiveNoGainGenerations; + + if (teamEvolution?.enabled !== true) { + return Object.freeze({ + shouldInvoke: false, + suppressedReason: 'disabled', + consecutiveNoGainGenerations, + consecutivePathologyRuns, + }); + } + + if (input.activeTeamStatus === 'trial') { + return Object.freeze({ + shouldInvoke: false, + suppressedReason: 'trial_in_progress', + consecutiveNoGainGenerations, + consecutivePathologyRuns, + }); + } + + // Must cover at least 1 supervisor turn + 1 child evaluation + if (budgets.maxEvaluations - evaluationsUsed < 2) { + return Object.freeze({ + shouldInvoke: false, + suppressedReason: 'insufficient_evaluation_budget', + consecutiveNoGainGenerations, + consecutivePathologyRuns, + }); + } + + if (budgets.maxGenerations - currentGeneration < 1) { + return Object.freeze({ + shouldInvoke: false, + suppressedReason: 'insufficient_generation_budget', + consecutiveNoGainGenerations, + consecutivePathologyRuns, + }); + } + + if ( + budgets.targetRooflineHeadroom !== undefined + && island.bestRooflineHeadroom !== null + && island.bestRooflineHeadroom <= budgets.targetRooflineHeadroom + ) { + return Object.freeze({ + shouldInvoke: false, + suppressedReason: 'target_roofline_reached', + consecutiveNoGainGenerations, + consecutivePathologyRuns, + }); + } + + if (teamEvolution.triggerOnRunEvalPathology && consecutivePathologyRuns >= 2) { + return Object.freeze({ + shouldInvoke: true, + triggerReason: 'run_eval_pathology', + consecutiveNoGainGenerations, + consecutivePathologyRuns, + }); + } + + if (consecutiveNoGainGenerations >= teamEvolution.stallGenerations) { + return Object.freeze({ + shouldInvoke: true, + triggerReason: 'pareto_stagnation', + consecutiveNoGainGenerations, + consecutivePathologyRuns, + }); + } + + return Object.freeze({ + shouldInvoke: false, + suppressedReason: 'steady_progress', + consecutiveNoGainGenerations, + consecutivePathologyRuns, + }); +} + +async function ensurePrivateNonSymlinkDir(dirPath: string): Promise { + if (!isAbsolute(dirPath) || dirPath.includes('\0')) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', `stagingDir must be an absolute path: "${dirPath}"`); + } + const resolved = resolve(dirPath); + const existing = await lstat(resolved).catch((err: NodeJS.ErrnoException) => { + if (err.code === 'ENOENT') return null; + throw err; + }); + if (existing !== null && existing.isSymbolicLink()) { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `symlink staging directory forbidden: "${resolved}"`); + } + + const parent = dirname(resolved); + const parentStat = await lstat(parent).catch((err: NodeJS.ErrnoException) => { + if (err.code === 'ENOENT') return null; + throw err; + }); + if (parentStat !== null && parentStat.isSymbolicLink()) { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `symlink parent directory forbidden: "${parent}"`); + } + + await mkdir(resolved, { recursive: true, mode: 0o700 }); + const afterStat = await lstat(resolved); + if (afterStat.isSymbolicLink() || !afterStat.isDirectory()) { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `staging directory must be a real directory: "${resolved}"`); + } + await chmod(resolved, 0o700); + const dirHandle = await open(resolved, constants.O_RDONLY | constants.O_NOFOLLOW); + await dirHandle.close(); + await realpath(resolved); + return resolved; +} + +async function writeReadOnlyFileNoFollow( + dirPath: string, + fileName: string, + content: string, + scrubber: SecretScrubber, +): Promise<{ readonly filePath: string; readonly digest: Digest; readonly byteLength: number }> { + const diagPath = `${dirPath}/${fileName}`; + assertCleanSecrets(content, scrubber, diagPath); + const bytes = Buffer.from(content, 'utf8'); + if (bytes.byteLength > MAX_STAGED_DIAGNOSTIC_BYTES) { + throw new EvolutionError( + 'EVOLUTION_SCHEMA_INVALID', + `staged supervisor artifact "${fileName}" exceeds ${MAX_STAGED_DIAGNOSTIC_BYTES} bytes`, + diagPath, + ); + } + const targetPath = join(dirPath, fileName); + const existing = await lstat(targetPath).catch((err: NodeJS.ErrnoException) => { + if (err.code === 'ENOENT') return null; + throw err; + }); + if (existing !== null) { + if (existing.isSymbolicLink()) { + throw new EvolutionError('EVOLUTION_SYMLINK_FORBIDDEN', `symlink staged file forbidden: "${targetPath}"`); + } + await chmod(targetPath, 0o600).catch(() => undefined); + await unlink(targetPath); + } + + const tmpPath = `${targetPath}.${randomBytes(6).toString('hex')}.tmp`; + const fh = await open( + tmpPath, + constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, + 0o400, + ); + try { + await fh.writeFile(bytes); + await fh.chmod(0o400); + await fh.sync(); + } finally { + await fh.close(); + } + await rename(tmpPath, targetPath); + + const verifyFh = await open(targetPath, constants.O_RDONLY | constants.O_NOFOLLOW); + try { + const st = await verifyFh.stat(); + if (!st.isFile() || st.nlink !== 1 || (st.mode & 0o777) !== 0o400) { + throw new EvolutionError('ARTIFACT_INVALID', `staged supervisor file failed 0o400 regular-file check: "${targetPath}"`); + } + } finally { + await verifyFh.close(); + } + + return Object.freeze({ + filePath: targetPath, + digest: sha256Digest(bytes), + byteLength: bytes.byteLength, + }); +} + +/** + * Stage read-only (`0o400`, `O_NOFOLLOW`, `SecretScrubber`-verified) diagnostic context artifacts + * and synthesize a strictly read-only (`tools: ['read']`, zero writable files, zero `held_out_workloads`) + * supervisor `TaskContract`. + */ +export async function stageSupervisorContext(input: StageSupervisorContextInput): Promise { + const scrubber = input.scrubber ?? DEFAULT_SUPERVISOR_SCRUBBER; + const resolvedDir = await ensurePrivateNonSymlinkDir(input.stagingDir); + + const trajectoryJson = canonicalizeJson({ + campaignId: input.campaignId, + islandId: input.island.islandId, + currentGeneration: input.island.currentGeneration, + consecutiveNoGainGenerations: input.island.consecutiveNoGainGenerations, + consecutivePathologyRuns: input.island.consecutivePathologyRuns, + lastHypervolume: input.island.lastHypervolume, + bestRooflineHeadroom: input.island.bestRooflineHeadroom, + triggerReason: input.triggerReason, + trajectory: (input.trajectory ?? []).slice(-32), + }); + + const runEvalSummariesJson = canonicalizeJson( + (input.recentRunEvals ?? []).slice(-8).map(rep => ({ + runId: rep.runId, + status: rep.status, + pingPong: rep.pingPong, + toolRepeats: { + totalFailingCalls: rep.toolRepeats.totalFailingCalls, + circuitBreaker: rep.toolRepeats.circuitBreaker, + items: rep.toolRepeats.items.slice(0, 8), + }, + repairConvergence: rep.repairConvergence, + suggestions: rep.suggestions.slice(0, 8), + })), + ); + + const hardwareDiagJson = canonicalizeJson( + (input.recentIndividuals ?? []).slice(-16).map(ind => ({ + individualId: ind.individualId, + generation: ind.generation, + status: ind.status, + failureReason: ind.failureReason, + nicheKey: ind.nicheKey, + paretoRank: ind.paretoRank, + scalarFitness: ind.scalarFitness, + metrics: ind.metrics, + ...(ind.hardwareDiagnostics !== undefined ? { hardwareDiagnostics: ind.hardwareDiagnostics } : {}), + ...(ind.findings !== undefined ? { findings: ind.findings.slice(0, 8) } : {}), + })), + ); + + const teamHistoryJson = canonicalizeJson( + (input.teamHistory ?? []).slice(-16).map(tc => ({ + teamConfigId: tc.teamConfigId, + parentTeamConfigId: tc.parentTeamConfigId, + status: tc.status, + createdGeneration: tc.createdGeneration, + trialBudgetGenerations: tc.trialBudgetGenerations, + trialUsedGenerations: tc.trialUsedGenerations, + paretoAdvances: tc.paretoAdvances, + nicheDiscoveries: tc.nicheDiscoveries, + diagnosis: tc.diagnosis, + patchCasDigest: tc.patchCasDigest, + })), + ); + + const scratchpadText = input.latestScratchpadMarkdown !== undefined && input.latestScratchpadMarkdown.trim().length > 0 + ? input.latestScratchpadMarkdown + : '# Campaign Scratchpad\nNo prior scratchpad entries recorded.\n'; + + const artifactEntries: readonly { + readonly name: string; + readonly resourceId: string; + readonly content: string; + }[] = [ + { name: 'island-trajectory.json', resourceId: 'sup-island-trajectory', content: `${trajectoryJson}\n` }, + { name: 'run-eval-summaries.json', resourceId: 'sup-run-eval-summaries', content: `${runEvalSummariesJson}\n` }, + { name: 'hardware-diagnostics.json', resourceId: 'sup-hardware-diagnostics', content: `${hardwareDiagJson}\n` }, + { name: 'team-history.json', resourceId: 'sup-team-history', content: `${teamHistoryJson}\n` }, + { name: 'scratchpad.md', resourceId: 'sup-scratchpad', content: scratchpadText }, + ]; + + const files: StagedSupervisorFile[] = []; + const supervisorResources: PinnedContextResource[] = []; + + for (const item of artifactEntries) { + const written = await writeReadOnlyFileNoFollow(resolvedDir, item.name, item.content, scrubber); + const relativeResourcePath = `.loopwright/supervisor-context/${item.name}`; + files.push( + Object.freeze({ + name: item.name, + filePath: written.filePath, + resourceId: item.resourceId, + relativeResourcePath, + digest: written.digest, + byteLength: written.byteLength, + }), + ); + supervisorResources.push({ + id: item.resourceId, + kind: 'document', + path: relativeResourcePath, + digest: written.digest, + }); + } + + const prompt = [ + `Diagnose island ${input.island.islandId} plateau (${input.triggerReason}) using ONLY read-only staged context.`, + `Do NOT write candidate code or repeat previously rolled_back topologies listed in team-history.json.`, + `Allowed archetype roles: ${input.teamEvolution.allowedArchetypeRoles.join(', ')}.`, + `Emit ONLY one raw UTF-8 JSON object matching schemaVersion "team-patch.v1" (kind "TeamPatch").`, + ].join(' '); + assertCleanSecrets(prompt, scrubber, '/supervisorPrompt'); + + // Protect '**' alongside base protected paths so every repository path is strictly non-writable (`isWritablePath === false`), + // and bind ONLY local `supervisor-no-change` check with zero `hardware_execution` / `held_out_workloads` bindings. + const protectedPatterns = Array.from(new Set(['**', ...input.baseTaskContract.spec.scope.protected])); + const baseRole = input.baseTaskContract.spec.roles[0]; + const rawSupervisorContract = { + apiVersion: 'loopwright.dev/v1alpha1' as const, + kind: 'TaskContract' as const, + spec: { + goal: prompt, + taskpack: sanitizeIdentifier( + `supervisor-${input.campaignId}-isl-${input.island.islandId}`, + input.baseTaskContract.spec.taskpack, + ), + target: { + repository: input.baseTaskContract.spec.target.repository, + baseRevision: input.baseTaskContract.spec.target.baseRevision, + sourceRevision: input.baseTaskContract.spec.target.sourceRevision, + matrix: null, + }, + scope: { + writable: [...input.baseTaskContract.spec.scope.writable], + protected: protectedPatterns, + }, + roles: [ + { + id: input.teamEvolution.supervisorRoleId, + adapter: 'delegated', + provider: baseRole?.provider ?? 'delegated', + model: baseRole?.model ?? 'default', + thinking: baseRole?.thinking ?? 'medium', + tools: ['read'], + resourceIds: supervisorResources.map(r => r.id), + }, + ], + trustedContext: { + revision: input.baseTaskContract.spec.trustedContext.revision, + discovery: 'disabled' as const, + resources: supervisorResources, + }, + budgets: { + ...input.baseTaskContract.spec.budgets, + wallTimeMs: Math.max(10_000, Math.min(input.baseTaskContract.spec.budgets.wallTimeMs, 120_000)), + totalTokens: Math.min(input.baseTaskContract.spec.budgets.totalTokens, 100_000), + maxModelCalls: 4, + maxConcurrency: 1, + maxFormatRepairs: 0, + maxImplementationRepairs: 0, + }, + steps: [ + { + id: 'step-supervisor', + kind: 'agent' as const, + uses: `handler.${input.teamEvolution.supervisorRoleId}`.slice(0, LIMITS.identifier), + roleId: input.teamEvolution.supervisorRoleId, + dependsOn: [], + }, + { + id: 'check-supervisor-readonly', + kind: 'check' as const, + uses: 'supervisor-no-change', + roleId: null, + dependsOn: ['step-supervisor'], + }, + ], + acceptance: { + required: ['supervisor-no-change'], + checks: [ + { + id: 'supervisor-no-change', + allowedEvidenceLevels: ['local_execution'], + }, + ], + }, + }, + }; + + const validated = validateDocument(rawSupervisorContract, 'TaskContract'); + if (!validated.ok) { + throw new EvolutionError( + 'EVOLUTION_SCHEMA_INVALID', + `failed to construct read-only supervisor TaskContract: ${validated.errors[0]?.code ?? 'invalid'} at ${validated.errors[0]?.path ?? '/'}`, + ); + } + + return Object.freeze({ + stagingDir: resolvedDir, + files: Object.freeze(files), + supervisorContract: validated.value, + writablePaths: Object.freeze([] as const), + prompt, + }); +} + +/** + * Exact controller checkpoint capacity precheck (`D <= 256`) matching `@loopwright/controller` `compile.ts`. + */ +export function computePatchCheckpointCapacity(input: ComputePatchCheckpointCapacityInput): CheckpointCapacity { + const A = input.maxAttempts; + const N = input.agentStepsCount; + const I = input.maxImplementationRepairs; + const C = input.verifierSlotCount; + const R = input.reworkGenerations ?? 0; + const K = input.checkReworkGenerations ?? 0; + const publication = input.publicationEnabled === true; + + const V = 1 + Math.min(A + K, N + I + R); + const J = C * V; + const D = 4 + 3 * A + 2 * J + (publication ? 3 : 0); + + return Object.freeze({ + A, + N, + I, + C, + V, + J, + D, + publication, + additionalRefs: 4, + requiredRefs: 6, + checkpointBytes: 40_960, + }); +} + +function inspectForbiddenAuthorityKeys(value: unknown, path: string): void { + if (value === null || typeof value !== 'object') return; + if (Array.isArray(value)) { + for (let i = 0; i < value.length; i += 1) { + inspectForbiddenAuthorityKeys(value[i], `${path}/${i}`); + } + return; + } + const obj = value as Record; + for (const key of Object.keys(obj)) { + // Allow `required` inside `/steps//handoffs//required` + if (key === 'required' && path.includes('/handoffs/')) { + continue; + } + if (FORBIDDEN_PATCH_AUTHORITY_KEYS.has(key)) { + throw new EvolutionError( + 'TEAM_ENVELOPE_VIOLATION', + `supervisor patch attempted forbidden authority or scope override "${key}" at ${path || '/'}`, + `${path}/${key}`, + ); + } + inspectForbiddenAuthorityKeys(obj[key], `${path}/${key}`); + } +} + +function resolveArchetypes(input: ValidateAndCompileTeamPatchInput): Map { + const map = new Map(); + const registryProfiles = new Map(); + if (input.trustedRegistry !== undefined) { + for (const p of input.trustedRegistry.spec.roleProfiles) { + registryProfiles.set(p.id, p); + if (p.id.startsWith('role.')) { + registryProfiles.set(p.id.slice(5), p); + } + if (p.id.startsWith('taskpack.profile.')) { + registryProfiles.set(p.id.slice('taskpack.profile.'.length), p); + } + if (p.id === 'taskpack-author-role') { + registryProfiles.set('author', p); + } + } + } + + const defaultWallSec = Math.max(1, Math.floor(input.baseTaskContract.spec.budgets.wallTimeMs / 1000)); + + if (input.archetypes !== undefined) { + for (const arch of input.archetypes) { + const regProf = registryProfiles.get(arch.id); + const regMaxSec = regProf?.limits?.toolWallMs !== undefined + ? Math.max(1, Math.floor(regProf.limits.toolWallMs / 1000)) + : arch.maxTimeoutSeconds; + map.set(arch.id, { + ...arch, + maxTimeoutSeconds: Math.min(arch.maxTimeoutSeconds, regMaxSec), + }); + } + } + + if (input.taskpack !== undefined) { + const firstModel = input.taskpack.spec.models?.[0]; + const taskpackToolSec = input.taskpack.spec.limits?.toolTimeoutSeconds; + const effectiveDefaultWallSec = taskpackToolSec !== undefined + ? Math.min(defaultWallSec, taskpackToolSec) + : defaultWallSec; + if (input.taskpack.spec.roles !== undefined && input.taskpack.spec.roles.length > 0) { + for (const role of input.taskpack.spec.roles) { + if (map.has(role.id)) continue; + const regProf = input.trustedRegistry !== undefined ? registryProfiles.get(role.id) : undefined; + if (input.trustedRegistry !== undefined && regProf === undefined) { + continue; + } + const purpose = role.purpose ?? 'task'; + const defaultTools: readonly TaskpackToolName[] = purpose === 'review' + ? ['read'] + : ['read', 'write', 'edit', 'bash']; + const tools = regProf?.tools !== undefined + ? (regProf.tools.filter(t => (role.tools ?? defaultTools).includes(t as TaskpackToolName)) as readonly TaskpackToolName[]) + : (role.tools ?? defaultTools); + const regMaxSec = regProf?.limits?.toolWallMs !== undefined + ? Math.max(1, Math.floor(regProf.limits.toolWallMs / 1000)) + : effectiveDefaultWallSec; + map.set(role.id, { + id: role.id, + adapter: regProf?.adapter === 'pi' ? 'pi' : 'delegated', + purpose, + tools: tools.length > 0 ? tools : (role.tools ?? defaultTools), + maxTimeoutSeconds: regMaxSec, + provider: role.provider ?? firstModel?.provider ?? 'delegated', + defaultModel: role.model ?? firstModel?.id ?? 'default', + thinking: role.thinking ?? firstModel?.thinking ?? 'medium', + }); + } + } else if (!map.has('author')) { + const regProf = input.trustedRegistry !== undefined ? registryProfiles.get('author') : undefined; + if (input.trustedRegistry === undefined || regProf !== undefined) { + const regMaxSec = regProf?.limits?.toolWallMs !== undefined + ? Math.max(1, Math.floor(regProf.limits.toolWallMs / 1000)) + : effectiveDefaultWallSec; + map.set('author', { + id: 'author', + adapter: 'delegated', + purpose: 'task', + tools: ['read', 'write', 'edit', 'bash', 'delete'], + maxTimeoutSeconds: regMaxSec, + provider: firstModel?.provider ?? 'delegated', + defaultModel: firstModel?.id ?? 'default', + thinking: firstModel?.thinking ?? 'medium', + }); + } + } + } + + if (input.taskpack === undefined && input.archetypes === undefined) { + for (const role of input.baseTaskContract.spec.roles) { + const regProf = input.trustedRegistry !== undefined ? registryProfiles.get(role.id) : undefined; + if (input.trustedRegistry !== undefined && regProf === undefined) continue; + const regMaxSec = regProf?.limits?.toolWallMs !== undefined + ? Math.max(1, Math.floor(regProf.limits.toolWallMs / 1000)) + : defaultWallSec; + map.set(role.id, { + id: role.id, + adapter: role.adapter === 'pi' ? 'pi' : 'delegated', + purpose: 'task', + tools: role.tools as readonly TaskpackToolName[], + maxTimeoutSeconds: regMaxSec, + provider: role.provider, + defaultModel: role.model, + thinking: role.thinking, + }); + } + } + + return map; +} + +function resolveDeclaredModels( + taskpack: TaskpackManifest | undefined, +): Map { + const allowed = new Map(); + if (taskpack?.spec.models !== undefined) { + for (const m of taskpack.spec.models) { + const entry = { provider: m.provider, model: m.id, thinking: m.thinking ?? 'medium' }; + allowed.set(m.id, entry); + allowed.set(`${m.provider}/${m.id}`, entry); + } + } + if (taskpack?.spec.roles !== undefined) { + for (const r of taskpack.spec.roles) { + if (r.model !== undefined && r.provider !== undefined) { + const entry = { provider: r.provider, model: r.model, thinking: r.thinking ?? 'medium' }; + allowed.set(r.model, entry); + allowed.set(`${r.provider}/${r.model}`, entry); + } + } + } + return allowed; +} + +function mapHandoffSourceForCore(h: StepHandoffSelector): StepHandoffSelector { + const rawKind = (h.source as { readonly kind: string }).kind; + const normalizedSource: StepHandoffSelector['source'] = rawKind === 'assistant_final' + ? { kind: 'submission' } + : h.source.kind === 'artifact' + ? { kind: 'artifact', path: h.source.path } + : { kind: h.source.kind }; + const normalizedSelect: StepHandoffSelector['select'] = h.select.kind === 'markdown_heading' + ? { + kind: 'markdown_heading', + heading: h.select.heading, + ...(h.select.includeSubheadings !== undefined ? { includeSubheadings: h.select.includeSubheadings } : {}), + } + : h.select.kind === 'json_pointer' + ? { kind: 'json_pointer', pointers: [...h.select.pointers] } + : { kind: 'full' }; + + return { + ...(h.id !== undefined ? { id: h.id } : {}), + fromStep: h.fromStep, + source: normalizedSource, + select: normalizedSelect, + ...(h.maxBytes !== undefined ? { maxBytes: h.maxBytes } : {}), + ...(h.required !== undefined ? { required: h.required } : {}), + }; +} + +/** + * Validate a supervisor `team-patch.v1` payload strictly against all 4 Archetype Capability Envelope + * invariants and compile it into a deterministic child `TaskContract` with pre-verified `D <= 256` capacity. + */ +export function validateAndCompileTeamPatch(input: ValidateAndCompileTeamPatchInput): CompiledTeamPatchResult { + const scrubber = input.scrubber ?? DEFAULT_SUPERVISOR_SCRUBBER; + + if (typeof input.rawPatch === 'object' && input.rawPatch !== null && !(input.rawPatch instanceof Uint8Array)) { + inspectForbiddenAuthorityKeys(input.rawPatch, ''); + } else if (typeof input.rawPatch === 'string' || input.rawPatch instanceof Uint8Array) { + const text = typeof input.rawPatch === 'string' + ? input.rawPatch + : new TextDecoder('utf-8', { fatal: false }).decode(input.rawPatch); + const trimmed = text.trim(); + if (trimmed.startsWith('{')) { + let maybeJson: NullProtoJson | null; + try { + maybeJson = parseNullProtoJson(trimmed, TEAM_PATCH_MAX_BYTES, ''); + } catch { + maybeJson = null; + } + if (maybeJson !== null) { + inspectForbiddenAuthorityKeys(maybeJson, ''); + } + } + } + + // Strict schema parse (zero Markdown regex scraping!) + const patch = parseTeamPatchV1(input.rawPatch, { scrubber }); + + if (patch.roles.length > input.teamEvolution.maxTeamSize) { + throw new EvolutionError( + 'TEAM_ENVELOPE_VIOLATION', + `team patch declares ${patch.roles.length} roles, exceeding maxTeamSize ${input.teamEvolution.maxTeamSize}`, + '/roles', + ); + } + if (patch.steps.length > input.teamEvolution.maxTeamSteps) { + throw new EvolutionError( + 'TEAM_ENVELOPE_VIOLATION', + `team patch declares ${patch.steps.length} steps, exceeding maxTeamSteps ${input.teamEvolution.maxTeamSteps}`, + '/steps', + ); + } + + const allowedArchetypeSet = new Set(input.teamEvolution.allowedArchetypeRoles); + const archetypes = resolveArchetypes(input); + const declaredModels = resolveDeclaredModels(input.taskpack); + + const mergedResourcesMap = new Map(); + for (const res of input.baseTaskContract.spec.trustedContext.resources) { + mergedResourcesMap.set(res.id, res); + } + for (const extra of input.extraPinnedResources ?? []) { + mergedResourcesMap.set(extra.id, extra); + } + const mergedResources = [...mergedResourcesMap.values()]; + + const resolvedRoleModels: Record = + Object.create(null) as Record; + const archetypeByPatchRoleId = new Map(); + + type CoreRoleSpec = TaskContract['spec']['roles'][number]; + const compiledRoles: CoreRoleSpec[] = []; + + for (let i = 0; i < patch.roles.length; i += 1) { + const role = patch.roles[i]!; + const rolePath = `/roles/${i}`; + + if (role.id === input.teamEvolution.supervisorRoleId || role.archetypeRoleId === input.teamEvolution.supervisorRoleId) { + throw new EvolutionError( + 'TEAM_ENVELOPE_VIOLATION', + `role "${role.id}" cannot impersonate or inherit supervisor role "${input.teamEvolution.supervisorRoleId}"`, + rolePath, + ); + } + + // Invariant 1: Approved archetype inheritance + if (!allowedArchetypeSet.has(role.archetypeRoleId)) { + throw new EvolutionError( + 'TEAM_ENVELOPE_VIOLATION', + `role "${role.id}" archetypeRoleId "${role.archetypeRoleId}" is not in teamEvolution.allowedArchetypeRoles`, + `${rolePath}/archetypeRoleId`, + ); + } + const archetype = archetypes.get(role.archetypeRoleId); + if (archetype === undefined) { + throw new EvolutionError( + 'TEAM_ENVELOPE_VIOLATION', + `role "${role.id}" archetypeRoleId "${role.archetypeRoleId}" does not resolve to an approved host archetype`, + `${rolePath}/archetypeRoleId`, + ); + } + archetypeByPatchRoleId.set(role.id, archetype.id); + + if (archetype.purpose === 'review' && role.purpose !== 'review') { + throw new EvolutionError( + 'TEAM_ENVELOPE_VIOLATION', + `role "${role.id}" cannot escalate review archetype "${archetype.id}" to purpose "${role.purpose}"`, + `${rolePath}/purpose`, + ); + } + + // Invariant 2: Monotonic tool narrowing (tools <= archetype.tools) & read-only / review protection + const archetypeToolSet = new Set(archetype.tools); + const archetypeIsReadOnly = !archetype.tools.some(t => MUTATING_OR_EXEC_TOOLS.has(t)); + for (const tool of role.tools) { + if (!archetypeToolSet.has(tool)) { + throw new EvolutionError( + 'TEAM_ENVELOPE_VIOLATION', + `role "${role.id}" widens tool "${tool}" beyond archetype "${archetype.id}" (${archetype.tools.join(', ')})`, + `${rolePath}/tools`, + ); + } + if ((role.purpose === 'review' || archetype.purpose === 'review' || archetypeIsReadOnly) && MUTATING_OR_EXEC_TOOLS.has(tool)) { + throw new EvolutionError( + 'TEAM_ENVELOPE_VIOLATION', + `role "${role.id}" cannot request mutating or exec tool "${tool}" on read-only/review envelope`, + `${rolePath}/tools`, + ); + } + } + + // Invariant 3: Pinned models, thinking, resources, and timeouts + let baseModelBinding: { readonly provider: string; readonly model: string; readonly thinking: string }; + if (role.model !== undefined) { + if (input.taskpack !== undefined) { + const found = declaredModels.get(role.model); + if (found === undefined) { + throw new EvolutionError( + 'TEAM_ENVELOPE_VIOLATION', + `role "${role.id}" model "${role.model}" is not declared in Taskpack.spec.models`, + `${rolePath}/model`, + ); + } + baseModelBinding = found; + } else { + baseModelBinding = { + provider: archetype.provider ?? 'delegated', + model: role.model, + thinking: archetype.thinking ?? 'medium', + }; + } + } else { + baseModelBinding = { + provider: archetype.provider ?? 'delegated', + model: archetype.defaultModel ?? 'default', + thinking: archetype.thinking ?? 'medium', + }; + } + + if (role.timeoutSeconds !== undefined && role.timeoutSeconds > archetype.maxTimeoutSeconds) { + throw new EvolutionError( + 'TEAM_ENVELOPE_VIOLATION', + `role "${role.id}" timeoutSeconds (${role.timeoutSeconds}) exceeds archetype "${archetype.id}" ceiling (${archetype.maxTimeoutSeconds}s)`, + `${rolePath}/timeoutSeconds`, + ); + } + + const effectiveThinking = role.thinking ?? baseModelBinding.thinking; + const modelBinding: CompiledRoleModelBinding = { + provider: baseModelBinding.provider, + model: baseModelBinding.model, + thinking: effectiveThinking, + ...(role.timeoutSeconds !== undefined ? { timeoutSeconds: role.timeoutSeconds } : {}), + }; + resolvedRoleModels[role.id] = modelBinding; + + if (role.resourceIds !== undefined) { + for (const resId of role.resourceIds) { + if (!mergedResourcesMap.has(resId)) { + throw new EvolutionError( + 'TEAM_ENVELOPE_VIOLATION', + `role "${role.id}" references unpinned resource "${resId}" absent from TaskContract.spec.trustedContext.resources`, + `${rolePath}/resourceIds`, + ); + } + } + } + + compiledRoles.push({ + id: role.id, + adapter: archetype.adapter, + provider: modelBinding.provider, + model: modelBinding.model, + thinking: modelBinding.thinking, + tools: [...role.tools] as TaskContract['spec']['roles'][number]['tools'][number][], + ...(role.resourceIds !== undefined ? { resourceIds: [...role.resourceIds] } : {}), + }); + } + + // Invariant 4: Isolated StepHandoffSelector relay, locked check steps, and D <= 256 precheck + type CoreStepSpec = TaskContract['spec']['steps'][number]; + const baseCheckSteps = input.baseTaskContract.spec.steps.filter(s => s.kind === 'check'); + const reservedCheckIds = new Set([ + ...baseCheckSteps.map(s => s.id), + ...input.baseTaskContract.spec.acceptance.checks.map(c => c.id), + ]); + + const roleById = new Map(compiledRoles.map(r => [r.id, r] as const)); + const usedRoles = new Set(); + const patchStepById = new Map(patch.steps.map(s => [s.id, s] as const)); + + for (let i = 0; i < patch.steps.length; i += 1) { + const step = patch.steps[i]!; + const stepPath = `/steps/${i}`; + if (reservedCheckIds.has(step.id)) { + throw new EvolutionError( + 'TEAM_ENVELOPE_VIOLATION', + `patch step "${step.id}" collides with locked acceptance check identifier`, + `${stepPath}/id`, + ); + } + if (!roleById.has(step.roleId)) { + throw new EvolutionError( + 'TEAM_ENVELOPE_VIOLATION', + `patch step "${step.id}" references unknown role "${step.roleId}"`, + `${stepPath}/roleId`, + ); + } + usedRoles.add(step.roleId); + for (const dep of step.dependsOn) { + if (!patchStepById.has(dep) || dep === step.id) { + throw new EvolutionError( + 'TEAM_ENVELOPE_VIOLATION', + `patch step "${step.id}" depends on unknown or self step "${dep}"`, + `${stepPath}/dependsOn`, + ); + } + } + } + + if (usedRoles.size !== compiledRoles.length) { + throw new EvolutionError( + 'TEAM_ENVELOPE_VIOLATION', + 'every declared role in team-patch.v1 must be bound to at least one step', + '/roles', + ); + } + + const inDegree = new Map(); + const children = new Map(); + for (const s of patch.steps) { + inDegree.set(s.id, s.dependsOn.length); + children.set(s.id, []); + } + for (const s of patch.steps) { + for (const dep of s.dependsOn) { + children.get(dep)!.push(s.id); + } + } + const queue = patch.steps.filter(s => s.dependsOn.length === 0).map(s => s.id); + const topoOrder: string[] = []; + const ancestors = new Map>(patch.steps.map(s => [s.id, new Set()] as const)); + + while (queue.length > 0) { + const cur = queue.shift()!; + topoOrder.push(cur); + const curAnc = ancestors.get(cur)!; + for (const next of children.get(cur) ?? []) { + const nextAnc = ancestors.get(next)!; + nextAnc.add(cur); + for (const a of curAnc) nextAnc.add(a); + const deg = inDegree.get(next)! - 1; + inDegree.set(next, deg); + if (deg === 0) queue.push(next); + } + } + + if (topoOrder.length !== patch.steps.length) { + throw new EvolutionError('TEAM_ENVELOPE_VIOLATION', 'team-patch.v1 steps contain a dependency cycle', '/steps'); + } + + const compiledAgentSteps: CoreStepSpec[] = []; + for (const stepId of topoOrder) { + const s = patchStepById.get(stepId)!; + const stepAnc = ancestors.get(stepId)!; + let mappedHandoffs: StepHandoffSelector[] | undefined; + if (s.handoffs !== undefined && s.handoffs.length > 0) { + mappedHandoffs = []; + for (const h of s.handoffs) { + if (!stepAnc.has(h.fromStep)) { + throw new EvolutionError( + 'TEAM_ENVELOPE_VIOLATION', + `step "${s.id}" handoff fromStep "${h.fromStep}" must be an upstream dependency`, + '/steps', + ); + } + mappedHandoffs.push(mapHandoffSourceForCore(h)); + } + } + if (s.onRework !== undefined && !stepAnc.has(s.onRework.rejectTo)) { + throw new EvolutionError( + 'TEAM_ENVELOPE_VIOLATION', + `step "${s.id}" onRework.rejectTo "${s.onRework.rejectTo}" must be a strict upstream dependency`, + '/steps', + ); + } + compiledAgentSteps.push({ + id: s.id, + kind: 'agent', + uses: sanitizeIdentifier(`handler.${s.roleId}`, `handler-${s.roleId}`), + roleId: s.roleId, + dependsOn: [...s.dependsOn], + ...(s.onRework !== undefined ? { onRework: { rejectTo: s.onRework.rejectTo, maxReworks: s.onRework.maxReworks } } : {}), + ...(mappedHandoffs !== undefined ? { handoffs: mappedHandoffs } : {}), + }); + } + + const sinkAgentIds = patch.steps + .filter(s => (children.get(s.id)?.length ?? 0) === 0) + .map(s => s.id); + + const baseCheckStepIds = new Set(baseCheckSteps.map(s => s.id)); + const compiledCheckSteps: CoreStepSpec[] = baseCheckSteps.length > 0 + ? baseCheckSteps.map(cs => { + const keptCheckDeps = cs.dependsOn.filter(dep => baseCheckStepIds.has(dep)); + const nextDeps = keptCheckDeps.length > 0 ? keptCheckDeps : [...sinkAgentIds]; + return { + id: cs.id, + kind: 'check' as const, + uses: cs.uses, + roleId: null, + dependsOn: nextDeps, + ...(cs.onRework !== undefined ? { onRework: cs.onRework } : {}), + }; + }) + : input.baseTaskContract.spec.acceptance.checks.map((chk, idx, arr) => ({ + id: sanitizeIdentifier(`check.${chk.id}`, `check-${idx}`), + kind: 'check' as const, + uses: chk.id, + roleId: null, + dependsOn: idx === 0 + ? [...sinkAgentIds] + : [sanitizeIdentifier(`check.${arr[idx - 1]!.id}`, `check-${idx - 1}`)], + })); + + const allOrderedSteps: readonly CoreStepSpec[] = [...compiledAgentSteps, ...compiledCheckSteps]; + const isMutatingRoleId = (rId: string | null): boolean => { + if (rId === null) return false; + const declared = roleById.get(rId); + return Boolean(declared?.tools.some(t => MUTATING_OR_EXEC_TOOLS.has(t))); + }; + const computeReworkSubgraphIds = (rejectToId: string): ReadonlySet => { + const found = new Set([rejectToId]); + let changed = true; + while (changed) { + changed = false; + for (const node of allOrderedSteps) { + if (!found.has(node.id) && node.dependsOn.some(parent => found.has(parent))) { + found.add(node.id); + changed = true; + } + } + } + return found; + }; + + let reworkGenerations = 0; + let checkReworkGenerations = 0; + for (const node of allOrderedSteps) { + if (node.onRework !== undefined) { + const subIds = computeReworkSubgraphIds(node.onRework.rejectTo); + const mutatingSubSteps = allOrderedSteps.filter( + item => subIds.has(item.id) && item.kind === 'agent' && isMutatingRoleId(item.roleId), + ).length; + reworkGenerations += node.onRework.maxReworks * (1 + mutatingSubSteps); + if (node.kind === 'check') { + checkReworkGenerations += node.onRework.maxReworks; + } + } + } + + const totalStepsCount = allOrderedSteps.length; + const N = compiledAgentSteps.length; + const I = input.baseTaskContract.spec.budgets.maxImplementationRepairs; + const C = input.baseTaskContract.spec.acceptance.checks.length + 2; + const K = checkReworkGenerations; + const A = input.maxAttempts ?? Math.min(64, Math.max(1, N + reworkGenerations + I + input.baseTaskContract.spec.budgets.maxFormatRepairs)); + const publicationEnabled = input.publicationEnabled === true; + + if (A < 1 || A > 64 || C < 2 || C > 34) { + throw new EvolutionError( + 'TEAM_ENVELOPE_VIOLATION', + `compiled team-patch.v1 violates controller bounds (A=${A}, C=${C})`, + '/steps', + ); + } + + const capacity = computePatchCheckpointCapacity({ + maxAttempts: A, + agentStepsCount: N, + maxImplementationRepairs: I, + verifierSlotCount: C, + publicationEnabled, + reworkGenerations, + checkReworkGenerations: K, + }); + + const proposedModelCalls = Math.max(input.baseTaskContract.spec.budgets.maxModelCalls, N + reworkGenerations); + + if ( + compiledRoles.length > 16 + || totalStepsCount > 16 + || capacity.D > 256 + || proposedModelCalls > 1024 + || proposedModelCalls + capacity.J + (publicationEnabled ? 2 : 0) + 3 * capacity.A > 2048 + ) { + throw new EvolutionError( + 'TEAM_ENVELOPE_VIOLATION', + `compiled team-patch.v1 exceeds controller checkpoint capacity envelope (D=${capacity.D}, steps=${totalStepsCount}, roles=${compiledRoles.length})`, + '/steps', + ); + } + + const rawCompiledContract = { + apiVersion: input.baseTaskContract.apiVersion, + kind: input.baseTaskContract.kind, + spec: { + goal: input.baseTaskContract.spec.goal, + taskpack: input.baseTaskContract.spec.taskpack, + target: input.baseTaskContract.spec.target, + scope: { + writable: [...input.baseTaskContract.spec.scope.writable], + protected: [...input.baseTaskContract.spec.scope.protected], + }, + roles: compiledRoles, + trustedContext: { + revision: input.baseTaskContract.spec.trustedContext.revision, + discovery: 'disabled' as const, + resources: mergedResources, + }, + budgets: { + ...input.baseTaskContract.spec.budgets, + maxModelCalls: proposedModelCalls, + }, + steps: [...compiledAgentSteps, ...compiledCheckSteps], + acceptance: { + required: [...input.baseTaskContract.spec.acceptance.required], + checks: [...input.baseTaskContract.spec.acceptance.checks], + }, + }, + }; + + const validated = validateDocument(rawCompiledContract, 'TaskContract'); + if (!validated.ok) { + throw new EvolutionError( + 'TEAM_ENVELOPE_VIOLATION', + `compiled team-patch.v1 failed TaskContract validation: ${validated.errors[0]?.code ?? 'invalid'} at ${validated.errors[0]?.path ?? '/spec'}`, + validated.errors[0]?.path ?? '/spec', + ); + } + + // Post-compile defense-in-depth lock verification + if ( + canonicalizeJson(validated.value.spec.scope) !== canonicalizeJson(input.baseTaskContract.spec.scope) + || canonicalizeJson(validated.value.spec.acceptance) !== canonicalizeJson(input.baseTaskContract.spec.acceptance) + || validated.value.spec.trustedContext.discovery !== 'disabled' + ) { + throw new EvolutionError( + 'TEAM_ENVELOPE_VIOLATION', + 'compiled team-patch.v1 diverged from locked scope or acceptance checks', + ); + } + + let compiledRegistry: TrustedRegistry | undefined; + if (input.trustedRegistry !== undefined) { + const baseProfiles = input.trustedRegistry.spec.roleProfiles; + const findBaseProfile = (archId: string) => + baseProfiles.find( + p => + p.id === archId + || p.id === `role.${archId}` + || p.id === `taskpack.profile.${archId}` + || (archId === 'author' && p.id === 'taskpack-author-role'), + ); + const updatedRoleProfiles: TrustedRegistry['spec']['roleProfiles'][number][] = patch.roles.map(pr => { + const baseProf = findBaseProfile(pr.archetypeRoleId) ?? baseProfiles[0]!; + const binding = resolvedRoleModels[pr.id]!; + const nextToolWallMs = pr.timeoutSeconds !== undefined + ? Math.min(baseProf.limits?.toolWallMs ?? pr.timeoutSeconds * 1000, pr.timeoutSeconds * 1000) + : baseProf.limits?.toolWallMs; + return { + ...baseProf, + id: `taskpack.profile.${pr.id}`, + selection: { + ...baseProf.selection, + provider: binding.provider, + model: binding.model, + thinking: binding.thinking, + }, + tools: [...pr.tools], + ...(baseProf.limits !== undefined || nextToolWallMs !== undefined + ? { + limits: { + ...baseProf.limits, + ...(nextToolWallMs !== undefined ? { toolWallMs: nextToolWallMs } : {}), + }, + } + : {}), + } as TrustedRegistry['spec']['roleProfiles'][number]; + }); + compiledRegistry = { + ...input.trustedRegistry, + spec: { + ...input.trustedRegistry.spec, + roleProfiles: updatedRoleProfiles, + }, + }; + } + + const canonicalPatchJson = canonicalizeJson(patch); + const patchDigest = sha256Digest(canonicalPatchJson); + + return Object.freeze({ + patch, + canonicalPatchJson, + patchDigest, + taskContract: validated.value, + capacity, + resolvedRoleModels: Object.freeze(resolvedRoleModels), + ...(compiledRegistry !== undefined ? { compiledRegistry } : {}), + }); +} + +/** + * Create a fenced, strictly read-only child `LocalRunStore` plateau supervisor executor + * (`/controller`) enforcing `tools: ['read']`, `scope.protected: ['**', ...]`, + * zero `held_out_workloads` mounts, and zero modified workspace files before accepting output. + */ +export function createLocalRunStoreSupervisorRunner( + options: LocalRunStoreSupervisorRunnerOptions, +): SupervisorRunnerPort { + const scrubber = options.scrubber ?? DEFAULT_SUPERVISOR_SCRUBBER; + const envLookup = options.environment ?? ((name: string) => process.env[name]); + + return async (context: SupervisorExecutionContext): Promise> => { + const resolvedStagingDir = await realpath(await ensurePrivateNonSymlinkDir(context.stagingDir)); + const controllerRunRoot = join(resolvedStagingDir, 'controller'); + const configDir = join(resolvedStagingDir, 'config'); + const workspaceDir = join(resolvedStagingDir, 'workspace'); + await mkdir(controllerRunRoot, { recursive: true, mode: 0o700 }); + await mkdir(configDir, { recursive: true, mode: 0o700 }); + await mkdir(workspaceDir, { recursive: true, mode: 0o700 }); + + const gitEnv = { + ...process.env, + GIT_AUTHOR_NAME: 'Loopwright Supervisor', + GIT_AUTHOR_EMAIL: 'supervisor@loopwright.dev', + GIT_COMMITTER_NAME: 'Loopwright Supervisor', + GIT_COMMITTER_EMAIL: 'supervisor@loopwright.dev', + }; + const execFileAsync = promisify(execFile); + if (!(await lstat(join(workspaceDir, '.git')).catch(() => null))) { + await execFileAsync('git', ['init', '-b', 'main'], { cwd: workspaceDir, env: gitEnv }); + await execFileAsync( + 'git', + ['commit', '--allow-empty', '-m', 'Read-only plateau supervisor workspace'], + { cwd: workspaceDir, env: gitEnv }, + ); + } + const { stdout: headStdout } = await execFileAsync('git', ['rev-parse', 'HEAD'], { + cwd: workspaceDir, + env: gitEnv, + encoding: 'utf8', + }); + const workspaceHeadRev = headStdout.trim().toLowerCase(); + + const rawContract = context.supervisorContract; + const contract: TaskContract = { + ...rawContract, + spec: { + ...rawContract.spec, + target: { + ...rawContract.spec.target, + baseRevision: workspaceHeadRev, + sourceRevision: workspaceHeadRev, + }, + }, + }; + if (contract.spec.roles.length !== 1) { + throw new EvolutionError('TEAM_ENVELOPE_VIOLATION', 'supervisor TaskContract must declare exactly 1 role'); + } + const supRole = contract.spec.roles[0]!; + if (supRole.tools.length !== 1 || supRole.tools[0] !== 'read') { + throw new EvolutionError('TEAM_ENVELOPE_VIOLATION', 'supervisor role must declare tools: ["read"] only'); + } + if (!contract.spec.scope.protected.includes('**')) { + throw new EvolutionError('TEAM_ENVELOPE_VIOLATION', 'supervisor TaskContract must protect "**" against mutations'); + } + if ( + contract.spec.acceptance.checks.some(chk => chk.allowedEvidenceLevels.includes('hardware_execution')) + || contract.spec.trustedContext.resources.some(r => r.path.includes('held_out_workloads')) + ) { + throw new EvolutionError('TEAM_ENVELOPE_VIOLATION', 'supervisor TaskContract must never bind hardware_execution or held_out_workloads'); + } + + const runId = sanitizeIdentifier( + `sup-${context.campaignId}-i${context.island.islandId}-g${context.island.currentGeneration}-${randomBytes(3).toString('hex')}`, + `sup-${randomBytes(4).toString('hex')}`, + ); + + const realTmpRoot = await realpath(tmpdir()); + const trustedTempDir = await mkdtemp(join(realTmpRoot, 'lw-evo-sup-reg-')); + await chmod(trustedTempDir, 0o700); + + try { + for (const stagedFile of context.files) { + const dstPath = join(trustedTempDir, stagedFile.relativeResourcePath); + await mkdir(dirname(dstPath), { recursive: true, mode: 0o700 }); + const rawBytes = await readFile(stagedFile.filePath); + const rawText = rawBytes.toString('utf8'); + assertCleanSecrets(rawText, scrubber, stagedFile.relativeResourcePath); + await writeFile(dstPath, rawBytes, { mode: 0o400 }); + await chmod(dstPath, 0o400); + } + + const installed = await installedHandlerDigests(); + const agentStep = contract.spec.steps.find(s => s.kind === 'agent'); + if (agentStep === undefined) { + throw new EvolutionError('EVOLUTION_SCHEMA_INVALID', 'supervisor TaskContract missing agent step'); + } + const profileId = sanitizeIdentifier(`profile.${supRole.id}`, 'profile-supervisor'); + const registryName = sanitizeIdentifier(`reg.${runId}`, 'reg-supervisor'); + + const registryObj = { + apiVersion: CONTROLLER_API_VERSION, + kind: 'TrustedRegistry' as const, + metadata: { name: registryName }, + spec: { + version: 1 as const, + resourceVersion: contract.spec.trustedContext.revision, + handlers: [ + { + id: agentStep.uses, + version: 1 as const, + digest: installed['pi.agent.v1'], + kind: 'agent' as const, + implementation: 'pi.agent.v1' as const, + parameters: { + prompt: contract.spec.goal, + purpose: 'task' as const, + }, + capabilities: ['pi'], + }, + { + id: 'supervisor-no-change', + version: 1 as const, + digest: installed['no-change.v1'], + kind: 'check' as const, + implementation: 'no-change.v1' as const, + parameters: { checkId: 'supervisor-no-change' }, + capabilities: ['inert_bytes', 'read_only'], + }, + { + id: 'implicit-scope', + version: 1 as const, + digest: installed['scope.v1'], + kind: 'check' as const, + implementation: 'scope.v1' as const, + parameters: { checkId: null }, + capabilities: ['inert_bytes', 'read_only'], + }, + { + id: 'implicit-no-change', + version: 1 as const, + digest: installed['no-change.v1'], + kind: 'check' as const, + implementation: 'no-change.v1' as const, + parameters: { checkId: null }, + capabilities: ['inert_bytes', 'read_only'], + }, + ], + roleProfiles: [ + { + id: profileId, + adapter: 'delegated' as const, + selection: { + provider: supRole.provider, + model: supRole.model, + thinking: supRole.thinking, + }, + tools: ['read'], + limits: { + toolWallMs: 60_000, + }, + runtimeRef: null, + providerCredentialRef: null, + mcp: null, + }, + ], + resources: contract.spec.trustedContext.resources.map(r => ({ + id: r.id, + kind: r.kind, + path: r.path, + digest: r.digest, + })), + runtimeProfiles: [], + credentialBindings: [], + environmentBindings: [], + gateEndpoints: [], + publicationEndpoints: [], + }, + }; + + const registryBytes = Buffer.from(`${JSON.stringify(registryObj, null, 2)}\n`, 'utf8'); + const registrySha256 = createHash('sha256').update(registryBytes).digest('hex'); + const registryPath = join(trustedTempDir, 'registry.json'); + await writeFile(registryPath, registryBytes, { mode: 0o600 }); + await chmod(registryPath, 0o600); + + const drainReserveMs = Math.max(5_000, Math.min(30_000, Math.floor(contract.spec.budgets.wallTimeMs / 4))); + const configObj = { + apiVersion: CONTROLLER_API_VERSION, + kind: 'ControllerConfig' as const, + spec: { + task: contract, + registry: { + name: registryName, + digest: { algorithm: 'sha256' as const, hex: registrySha256 }, + }, + profiles: { + roles: [{ roleId: supRole.id, profileRef: profileId }], + steps: [ + { stepId: agentStep.id, handlerRef: agentStep.uses }, + { stepId: 'check-supervisor-readonly', handlerRef: 'supervisor-no-change' }, + ], + }, + credentials: [], + controls: { + drainReserveMs, + maxAttempts: 1, + repeatFailureLimit: 2, + submission: { mode: 'artifact_or_assistant' as const, path: null }, + }, + publication: { mode: 'disabled' as const }, + }, + }; + + const configBytes = Buffer.from(`${JSON.stringify(configObj, null, 2)}\n`, 'utf8'); + const configPath = join(configDir, 'config.json'); + await writeFile(configPath, configBytes, { mode: 0o600 }); + await chmod(configPath, 0o600); + + const loadedRes = await loadTrustedConfiguration({ + configPath, + registryPath, + registrySha256, + untrustedRoots: [workspaceDir], + environment: envLookup, + }); + if (!loadedRes.ok) { + throw new EvolutionError( + 'EVOLUTION_STORE_ERROR', + `supervisor child loadTrustedConfiguration failed: ${loadedRes.error.code} (${loadedRes.error.path})`, + ); + } + + const tickRes = await stepNext({ + configuration: loadedRes.value, + repository: workspaceDir, + runRoot: controllerRunRoot, + runId, + mode: 'no-change', + policyProfile: options.policyProfile ?? 'local', + allowWorkflowWrites: false, + environment: envLookup, + ...(options.signal !== undefined ? { signal: options.signal } : {}), + }); + if (!tickRes.ok) { + throw new EvolutionError('EVOLUTION_STORE_ERROR', `supervisor child stepNext failed: ${tickRes.error.code}`); + } + if (tickRes.value.kind !== 'step') { + throw new EvolutionError('EVOLUTION_STORE_ERROR', 'supervisor child stepNext did not yield expected read-only step'); + } + + const tick = tickRes.value; + const rawOutput = await options.executeReadOnlySupervisorTurn({ + ...context, + runRoot: controllerRunRoot, + runId, + stepId: tick.stepId, + roleId: tick.roleId, + candidateDir: tick.candidateDir, + contextFiles: tick.contextFiles, + leaseToken: tick.leaseToken, + tools: Object.freeze(['read'] as const), + ...(options.signal !== undefined ? { signal: options.signal } : {}), + }); + + const candidateEntries = await readdir(tick.candidateDir); + if (candidateEntries.length > 0) { + await stepCancel({ runRoot: controllerRunRoot, runId, environment: envLookup }).catch(() => undefined); + throw new EvolutionError( + 'TEAM_ENVELOPE_VIOLATION', + `read-only supervisor turn illegally created or modified workspace files: ${candidateEntries.join(', ')}`, + '/scope/writable', + ); + } + + const submitRes = await stepSubmit({ + runRoot: controllerRunRoot, + runId, + leaseToken: tick.leaseToken, + status: 'no_change', + reason: 'read-only plateau supervisor diagnosis completed', + environment: envLookup, + ...(options.signal !== undefined ? { signal: options.signal } : {}), + }); + if (!submitRes.ok) { + await stepCancel({ runRoot: controllerRunRoot, runId, environment: envLookup }).catch(() => undefined); + throw new EvolutionError( + 'TEAM_ENVELOPE_VIOLATION', + `supervisor child stepSubmit refused (${submitRes.error.code} at ${submitRes.error.path})`, + ); + } + if ( + submitRes.value.kind !== 'result' + || (submitRes.value.result.spec.status !== 'no_change' && submitRes.value.result.spec.status !== 'completed') + ) { + await stepCancel({ runRoot: controllerRunRoot, runId, environment: envLookup }).catch(() => undefined); + throw new EvolutionError( + 'TEAM_ENVELOPE_VIOLATION', + `supervisor child run failed read-only no-change verification`, + ); + } + + return rawOutput; + } finally { + await rm(trustedTempDir, { recursive: true, force: true }).catch(() => undefined); + } + }; +} + +/** + * Record a child generation outcome against an island's `'trial'` `TeamConfigRecord`, promoting on + * Pareto/niche advance, auto-rolling back when `trialGenerations` expire without gain, and ignoring + * `BENCHMARK_PREEMPTED` runs (`preempted: true`). + */ +export async function recordTeamTrialOutcome( + store: EvolutionCampaignStore, + lease: CampaignLease, + input: RecordTeamTrialOutcomeInput, +): Promise { + const before = await store.getTeamConfig(input.teamConfigId); + if (before === null) { + throw new EvolutionError('EVOLUTION_NOT_FOUND', `team_config "${input.teamConfigId}" not found`); + } + const previousStatus = before.status; + const ignoredPreemption = input.preempted === true; + + const updated = await store.recordTeamTrialGeneration(lease, { + teamConfigId: input.teamConfigId, + advancedPareto: input.advancedPareto, + discoveredNiche: input.discoveredNiche, + ...(input.preempted !== undefined ? { preempted: input.preempted } : {}), + }); + + const island = await store.getIsland(input.campaignId, input.islandId); + const activeTeamConfigId = island?.activeTeamConfigId ?? updated.teamConfigId; + + return Object.freeze({ + teamConfig: updated, + previousStatus, + nextStatus: updated.status, + activeTeamConfigId, + promoted: previousStatus === 'trial' && updated.status === 'promoted', + rolledBack: previousStatus === 'trial' && updated.status === 'rolled_back', + ignoredPreemption, + }); +} + +/** + * Run an event-driven plateau / loop-pathology supervisor turn on an island. + * Keeps the incumbent `activeTeamConfigId` active without crashing the campaign if the supervisor + * output fails schema validation (`EVOLUTION_SCHEMA_INVALID`) or violates the Archetype Capability + * Envelope (`TEAM_ENVELOPE_VIOLATION`). + */ +export async function runPlateauSupervisorTurn( + input: RunPlateauSupervisorTurnInput, +): Promise { + const currentTeam = await input.store.getTeamConfig(input.island.activeTeamConfigId); + const decision = evaluateTeamEvolutionTrigger({ + ...(input.teamEvolution !== undefined ? { teamEvolution: input.teamEvolution } : {}), + island: input.island, + budgets: input.budgets, + evaluationsUsed: input.evaluationsUsed, + currentGeneration: input.currentGeneration, + ...(input.recentRunEvals !== undefined ? { recentRunEvals: input.recentRunEvals } : {}), + ...(currentTeam?.status !== undefined ? { activeTeamStatus: currentTeam.status } : {}), + }); + + if (!decision.shouldInvoke || input.teamEvolution === undefined || decision.triggerReason === undefined) { + return Object.freeze({ + invoked: false, + accepted: false, + decision, + activeTeamConfigId: input.island.activeTeamConfigId, + }); + } + + const teamHistory = await input.store.listTeamConfigs(input.campaignId, input.island.islandId); + const stagedContext = await stageSupervisorContext({ + stagingDir: input.stagingDir, + campaignId: input.campaignId, + island: input.island, + triggerReason: decision.triggerReason, + teamEvolution: input.teamEvolution, + baseTaskContract: input.baseTaskContract, + trajectory: input.trajectory, + recentRunEvals: input.recentRunEvals, + recentIndividuals: input.recentIndividuals, + latestScratchpadMarkdown: input.latestScratchpadMarkdown, + teamHistory, + scrubber: input.scrubber, + }); + + let compiledPatch: CompiledTeamPatchResult; + try { + const rawSupervisorOutput = await input.supervisorRunner({ + campaignId: input.campaignId, + island: input.island, + triggerReason: decision.triggerReason, + stagingDir: stagedContext.stagingDir, + files: stagedContext.files, + supervisorContract: stagedContext.supervisorContract, + writablePaths: stagedContext.writablePaths, + prompt: stagedContext.prompt, + }); + + compiledPatch = validateAndCompileTeamPatch({ + rawPatch: rawSupervisorOutput, + teamEvolution: input.teamEvolution, + baseTaskContract: input.baseTaskContract, + taskpack: input.taskpack, + trustedRegistry: input.trustedRegistry, + archetypes: input.archetypes, + extraPinnedResources: input.extraPinnedResources, + scrubber: input.scrubber, + }); + } catch (err: unknown) { + if ( + err instanceof EvolutionError + && (err.code === 'TEAM_ENVELOPE_VIOLATION' || err.code === 'EVOLUTION_SCHEMA_INVALID') + ) { + return Object.freeze({ + invoked: true, + accepted: false, + decision, + activeTeamConfigId: input.island.activeTeamConfigId, + stagedContext, + error: err, + }); + } + throw err; + } + + const casBlob = await input.store.writeCasBlob(Buffer.from(`${compiledPatch.canonicalPatchJson}\n`, 'utf8')); + const teamConfigId = `${input.campaignId}:isl-${input.island.islandId}:gen-${input.currentGeneration}:${casBlob.digest.hex.slice(0, 12)}`.slice( + 0, + 128, + ); + + const trialTeam = await input.store.createTrialTeamConfig(input.lease, { + teamConfigId, + campaignId: input.campaignId, + islandId: input.island.islandId, + parentTeamConfigId: input.island.activeTeamConfigId, + createdGeneration: input.currentGeneration, + trialBudgetGenerations: input.teamEvolution.trialGenerations, + diagnosis: compiledPatch.patch.diagnosis, + patchCasDigest: casBlob.digest, + }); + + await input.store.updateIslandProgress(input.lease, { + campaignId: input.campaignId, + islandId: input.island.islandId, + activeTeamConfigId: trialTeam.teamConfigId, + consecutiveNoGainGenerations: 0, + consecutivePathologyRuns: 0, + }); + + return Object.freeze({ + invoked: true, + accepted: true, + decision, + activeTeamConfigId: trialTeam.teamConfigId, + teamConfig: trialTeam, + compiledPatch, + stagedContext, + }); +} diff --git a/packages/evolution/src/types.ts b/packages/evolution/src/types.ts new file mode 100644 index 0000000..c6a1528 --- /dev/null +++ b/packages/evolution/src/types.ts @@ -0,0 +1,416 @@ +import type { + ArtifactRef, + BucketMetricEntry, + Digest, + HardwareDiagnostics, + HardwareProvenance, + ReworkPolicy, + StepHandoffSelector, + StructuredFinding, +} from '@loopwright/core'; + +export const EVOLUTION_API_VERSION = 'loopwright.dev/v1alpha1' as const; +export const EVOLUTION_CAMPAIGN_KIND = 'EvolutionCampaign' as const; +export const EVOLUTION_CAMPAIGN_MAX_BYTES = 65_536; + +export const TEAM_PATCH_KIND = 'TeamPatch' as const; +export const TEAM_PATCH_SCHEMA_VERSION = 'team-patch.v1' as const; +export const TEAM_PATCH_MAX_BYTES = 32_768; +export const TEAM_PATCH_DIAGNOSIS_MAX_BYTES = 4_096; + +export const DISPATCH_MANIFEST_MAX_BYTES = 65_536; +export const DISPATCH_MANIFEST_MAX_RULES = 64; + +export const SCRATCHPAD_MAX_BYTES = 16_384; +export const CONTEXT_SLICE_MAX_BYTES = 32_768; +export const CAMPAIGN_CLOCK_MAX_DRIFT_MS = 1_000; +export const CAMPAIGN_FORMAT_VERSION = 1 as const; +export const CAMPAIGN_APPLICATION_ID = 0x4c574556; + +export const EVOLUTION_ERROR_CODES = Object.freeze([ + 'EVOLUTION_SCHEMA_INVALID', + 'EVOLUTION_STORE_ERROR', + 'EVOLUTION_STORE_CLOSED', + 'EVOLUTION_STORE_BUSY', + 'EVOLUTION_STORE_CORRUPT', + 'EVOLUTION_LEASE_FENCED', + 'EVOLUTION_CLOCK_DRIFT', + 'EVOLUTION_SYMLINK_FORBIDDEN', + 'EVOLUTION_NOT_FOUND', + 'EVOLUTION_CONFLICT', + 'EVOLUTION_BUDGET_EXCEEDED', + 'TEAM_ENVELOPE_VIOLATION', + 'EXPORT_UNVERIFIED_FORBIDDEN', + 'ARTIFACT_INVALID', + 'ARTIFACT_MISSING', + 'SECRET_LEAK_DETECTED', +] as const); + +export type EvolutionErrorCode = (typeof EVOLUTION_ERROR_CODES)[number]; + +export class EvolutionError extends Error { + readonly code: EvolutionErrorCode; + readonly path?: string; + + constructor(code: EvolutionErrorCode, message: string, path?: string, options?: ErrorOptions) { + super(message, options); + this.name = 'EvolutionError'; + this.code = code; + if (path !== undefined) { + this.path = path; + } + } +} + +export interface ObjectiveDirectionSpec { + readonly metric: string; + readonly direction: 'minimize' | 'maximize'; +} + +export interface EvolutionSpecialistBucket { + readonly id: string; + readonly heldOutWorkloadId: string; +} + +export type EvolutionStagesSpec = + | { + readonly mode: 'single-target'; + readonly heldOutWorkloadId?: string; + } + | { + readonly mode: 'specialist-then-portfolio'; + readonly specialistBuckets: readonly EvolutionSpecialistBucket[]; + readonly portfolioHeldOutWorkloadId: string; + }; + +export interface EvolutionEnumNicheAxis { + readonly id: string; + readonly kind: 'enum'; + readonly field?: string; + readonly values: readonly string[]; +} + +export interface EvolutionNumericBinsNicheAxis { + readonly id: string; + readonly kind: 'numeric_bins'; + readonly field?: string; + readonly edges: readonly number[]; +} + +export type EvolutionNicheAxis = EvolutionEnumNicheAxis | EvolutionNumericBinsNicheAxis; + +export interface EvolutionPopulationSpec { + readonly islands: number; + readonly migrationIntervalGenerations: number; + readonly maxMigrationElites: number; + readonly nicheAxes: readonly EvolutionNicheAxis[]; +} + +export interface EvolutionMutationWeights { + readonly diff_tune: number; + readonly full_rewrite: number; + readonly crossover: number; +} + +export type EvolutionModelBanditStrategy = 'deterministic-round-robin' | 'ucb1'; + +export interface EvolutionSamplingSpec { + readonly noveltyDecayLambda: number; + readonly mutationWeights: EvolutionMutationWeights; + readonly modelBandit: EvolutionModelBanditStrategy; + readonly maxCrossoversPerPrompt: number; +} + +export interface EvolutionTeamSpec { + readonly enabled: boolean; + readonly supervisorRoleId: string; + readonly allowedArchetypeRoles: readonly string[]; + readonly stallGenerations: number; + readonly minHypervolumeDelta: number; + readonly triggerOnRunEvalPathology: boolean; + readonly trialGenerations: number; + readonly maxTeamSize: number; + readonly maxTeamSteps: number; +} + +export interface EvolutionBudgetsSpec { + readonly maxGenerations: number; + readonly maxEvaluations: number; + readonly maxConcurrentEvaluations: number; + readonly targetRooflineHeadroom?: number; + readonly scratchpadIntervalGenerations: number; +} + +export type EvolutionExportFormat = 'dir' | 'oci-layout'; + +export interface EvolutionExportSpec { + readonly format: EvolutionExportFormat; + readonly outputDir: string; +} + +export interface EvolutionCampaignMetadata { + readonly name: string; + readonly description?: string; +} + +export interface EvolutionCampaignSpec { + readonly taskpack: string; + readonly targetCellId: string; + readonly heldOutWorkloadId?: string; + readonly tracks?: readonly string[]; + readonly stages: EvolutionStagesSpec; + readonly population: EvolutionPopulationSpec; + readonly sampling: EvolutionSamplingSpec; + readonly teamEvolution?: EvolutionTeamSpec; + readonly objectives: readonly ObjectiveDirectionSpec[]; + readonly budgets: EvolutionBudgetsSpec; + readonly export?: EvolutionExportSpec; +} + +export interface EvolutionCampaignManifest { + readonly apiVersion: typeof EVOLUTION_API_VERSION; + readonly kind: typeof EVOLUTION_CAMPAIGN_KIND; + readonly metadata: EvolutionCampaignMetadata; + readonly spec: EvolutionCampaignSpec; +} + +export type TeamPlateauCategory = + | 'measurement_mismatch' + | 'coupled_responsibilities' + | 'local_optimum_anchor' + | 'resource_spill_trap' + | 'correctness_ping_pong' + | 'other'; + +export interface TeamPatchDiagnosis { + readonly summary: string; + readonly plateauCategory: TeamPlateauCategory; + readonly rationale: string; +} + +export interface TeamPatchRole { + readonly id: string; + readonly archetypeRoleId: string; + readonly purpose: 'task' | 'review'; + readonly prompt: string; + readonly model?: string; + readonly thinking?: string; + readonly tools: readonly string[]; + readonly resourceIds?: readonly string[]; + readonly timeoutSeconds?: number; +} + +export interface TeamPatchStep { + readonly id: string; + readonly roleId: string; + readonly dependsOn: readonly string[]; + readonly handoffs?: readonly StepHandoffSelector[]; + readonly onRework?: ReworkPolicy; +} + +export interface TeamPatchV1 { + readonly kind: typeof TEAM_PATCH_KIND; + readonly schemaVersion: typeof TEAM_PATCH_SCHEMA_VERSION; + readonly diagnosis: TeamPatchDiagnosis; + readonly roles: readonly TeamPatchRole[]; + readonly steps: readonly TeamPatchStep[]; +} + +export interface DispatchDimensionRange { + readonly min?: number; + readonly max?: number; +} + +export interface DispatchRuleV1 { + readonly bucketId: string; + readonly dimensionBounds?: Readonly>; + readonly dtypes?: readonly string[]; + readonly alignmentBytes?: number; + readonly blobDigest: Digest; + readonly blobPath?: string; + readonly entrypoint: string; +} + +export interface DispatchManifestV1 { + readonly version: 1; + readonly fallback: 'baseline'; + readonly rules: readonly DispatchRuleV1[]; +} + +export interface BundleCompatibilityTuple { + readonly accelerator: string; + readonly isolationMode: 'whole_device' | 'sliced'; + readonly deviceCount: number; + readonly driverVersion: string; + readonly driverConstraint?: string; + readonly runtimeVersion: string; + readonly topology?: string; + readonly workloadDigest: Digest; + readonly modelDigest?: Digest; + readonly parallelismTags?: readonly string[]; +} + +export interface BundleParetoEntry { + readonly individualId: string; + readonly paretoRank: number; + readonly nicheKey: string | null; + readonly metrics: Readonly>; + readonly bucketMetrics?: readonly BucketMetricEntry[]; + readonly hardwareDiagnostics?: HardwareDiagnostics; +} + +export interface BundleLineageProvenance { + readonly campaignId: string; + readonly individualIds: readonly string[]; + readonly baseRevision: string; + readonly lockHash: Digest; +} + +export interface BundleMemberDigest { + readonly path: string; + readonly digest: Digest; + readonly byteLength: number; + readonly mediaType?: string; +} + +export interface EvolutionBundleManifestV1 { + readonly kind: 'EvolutionBundle'; + readonly version: 1; + readonly compatibility: BundleCompatibilityTuple; + readonly paretoSummary: readonly BundleParetoEntry[]; + readonly lineage: BundleLineageProvenance; + readonly members: readonly BundleMemberDigest[]; +} + +export interface CampaignClockSource { + nowMonotonicMs(): number; + nowWallMs(): number; +} + +export interface CampaignLease { + readonly leaseId: string; + readonly fenceEpoch: number; +} + +export interface CampaignMetaRecord { + readonly formatVersion: number; + readonly leaseId: string | null; + readonly fenceEpoch: number; + readonly createdMonotonicMs: number; + readonly createdWallMs: number; + readonly lastMonotonicMs: number; + readonly lastWallMs: number; +} + +export type CampaignStatus = 'active' | 'paused' | 'completed' | 'failed'; +export type CampaignStagePhase = 'single-target' | 'specialist' | 'portfolio'; + +export interface CampaignRecord { + readonly campaignId: string; + readonly name: string; + readonly status: CampaignStatus; + readonly stagePhase: CampaignStagePhase; + readonly activeBucketId: string | null; + readonly manifest: EvolutionCampaignManifest; + readonly manifestDigest: Digest; + readonly baseRevision: string; + readonly lockHash: Digest; + readonly driverConstraint: string | null; + readonly currentGeneration: number; + readonly evaluationsUsed: number; + readonly preemptionsCount: number; + readonly createdAtWallMs: number; + readonly updatedAtWallMs: number; +} + +export interface IslandRecord { + readonly campaignId: string; + readonly islandId: number; + readonly activeTeamConfigId: string; + readonly currentGeneration: number; + readonly consecutiveNoGainGenerations: number; + readonly consecutivePathologyRuns: number; + readonly lastHypervolume: number; + readonly bestRooflineHeadroom: number | null; +} + +export type TeamConfigStatus = 'baseline' | 'trial' | 'promoted' | 'rolled_back'; + +export interface TeamConfigRecord { + readonly teamConfigId: string; + readonly campaignId: string; + readonly islandId: number; + readonly parentTeamConfigId: string | null; + readonly createdGeneration: number; + readonly status: TeamConfigStatus; + readonly trialBudgetGenerations: number; + readonly trialUsedGenerations: number; + readonly diagnosis: TeamPatchDiagnosis | null; + readonly patchCasDigest: Digest | null; + readonly paretoAdvances: number; + readonly nicheDiscoveries: number; +} + +export type IndividualStatus = 'passed' | 'soft_passed' | 'failed' | 'preempted'; +export type IndividualMutationKind = 'baseline' | 'diff_tune' | 'full_rewrite' | 'crossover' | 'portfolio'; + +export interface IndividualRecord { + 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 scalarFitness: number | null; + readonly offspringCount: number; + readonly codeSliceCasDigest: Digest | null; + readonly evidenceDigest: Digest | null; + readonly verdictReceiptCasDigest: Digest | null; + readonly outputArtifacts: readonly ArtifactRef[]; + readonly metrics: Readonly>; + readonly bucketMetrics?: readonly BucketMetricEntry[]; + readonly hardwareDiagnostics?: HardwareDiagnostics; + readonly hardwareProvenance?: HardwareProvenance; + readonly findings?: readonly StructuredFinding[]; + readonly createdAtWallMs: number; +} + +export type LineageRole = 'primary' | 'crossover_donor' | 'inspiration' | 'portfolio_member'; + +export interface LineageEdgeRecord { + readonly campaignId: string; + readonly childIndividualId: string; + readonly parentIndividualId: string; + readonly role: LineageRole; + readonly sourceIslandId: number; + readonly createdGeneration: number; +} + +export interface ModelBanditArmRecord { + readonly campaignId: string; + readonly modelId: string; + readonly pullCount: number; + readonly totalReward: number; + readonly meanReward: number; + readonly lastPulledGeneration: number | null; +} + +export interface ScratchpadSnapshotRecord { + readonly snapshotId: string; + readonly campaignId: string; + readonly generation: number; + readonly casDigest: Digest; + readonly byteLength: number; + readonly casRelPath: string; + readonly topGainsCount: number; + readonly failurePatternsCount: number; + readonly createdAtWallMs: number; +} diff --git a/packages/evolution/test/bundle.test.ts b/packages/evolution/test/bundle.test.ts new file mode 100644 index 0000000..59ab1be --- /dev/null +++ b/packages/evolution/test/bundle.test.ts @@ -0,0 +1,1622 @@ +import assert from 'node:assert/strict'; +import { createHash } from 'node:crypto'; +import { + chmodSync, + linkSync, + lstatSync, + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + rmSync, + symlinkSync, + unlinkSync, + writeFileSync, +} from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import test from 'node:test'; +import { + SecretScrubber, + type BucketMetricEntry, + type Digest, + type HardwareDiagnostics, + type HardwareProvenance, +} from '@loopwright/core'; +import { + signBenchmarkVerdict, + verifyBenchmarkVerdictSignature, + type BenchmarkOutputArtifact, + type BenchmarkVerdict, + type SignedBenchmarkVerdictReceipt, +} from '@loopwright/hardware-runner'; +import { + EVOLUTION_BUNDLE_KIND, + EVOLUTION_BUNDLE_VERSION, + OCI_IMAGE_INDEX_MEDIA_TYPE, + OCI_IMAGE_LAYOUT_VERSION, + OCI_IMAGE_MANIFEST_MEDIA_TYPE, + exportEvolutionBundle, + verifyEvolutionBundle, +} from '../src/bundle.js'; +import { parseDispatchManifestV1, parseEvolutionCampaignDocument } from '../src/schema.js'; +import { EvolutionCampaignStore } from '../src/store.js'; +import { + EvolutionError, + type DispatchManifestV1, + type EvolutionBundleManifestV1, + type EvolutionErrorCode, +} from '../src/types.js'; + +const TEST_HMAC_SECRET = 'test-bundle-hmac-signing-secret-2026'; + +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 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 + export: + format: oci-layout + outputDir: .loopwright-out/bundles/flash-decode-sm90a +`; + +const PORTFOLIO_CAMPAIGN_YAML = `apiVersion: loopwright.dev/v1alpha1 +kind: EvolutionCampaign +metadata: + name: flash-decode-portfolio +spec: + taskpack: .loopwright/taskpack.yaml + targetCellId: cuda-h100-whole + stages: + mode: specialist-then-portfolio + specialistBuckets: + - id: bs1-isl4k + heldOutWorkloadId: decode-bs1-4k + - id: bs16-isl8k + heldOutWorkloadId: decode-bs16-8k + portfolioHeldOutWorkloadId: decode-portfolio-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 +`; + +interface ReceiptFixtureOptions { + readonly lockHash: Digest; + readonly operationId: string; + readonly status?: 'approved' | 'denied' | 'expired'; + readonly reason?: string | null; + readonly detail?: string | null; + readonly probeKind?: 'physical' | 'synthetic_fixture'; + readonly accelerator?: string; + readonly driverVersion?: string; + readonly workloadDigest?: Digest; + readonly outputArtifacts?: readonly BenchmarkOutputArtifact[]; + readonly metrics?: Readonly>; + readonly signingSecret?: string; + readonly prettyPrint?: boolean; + readonly extraFields?: Readonly>; +} + +function makeSignedReceiptBytes(opts: ReceiptFixtureOptions): { + readonly receipt: SignedBenchmarkVerdictReceipt; + readonly rawBytes: Buffer; + readonly provenance: HardwareProvenance; +} { + const provenance: HardwareProvenance = { + targetCellId: 'cuda-h100-whole', + probeKind: opts.probeKind ?? 'physical', + vendor: 'nvidia', + deviceModel: 'NVIDIA H100 80GB HBM3', + accelerator: opts.accelerator ?? 'sm_90a', + isolationMode: 'whole_device', + deviceCount: 1, + driverVersion: opts.driverVersion ?? '560.35.03', + runtimeVersion: 'cuda-12.6', + topology: 'single_gpu', + workloadDigest: opts.workloadDigest ?? makeDigest('workload-default'), + clockLockMode: 'locked', + }; + + 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, + ...(opts.detail !== undefined ? { detail: opts.detail } : {}), + metrics: opts.metrics ?? { latency_us_p50: 42.5, goodput_rps: 2400 }, + hardwareProvenance: provenance, + ...(opts.outputArtifacts !== undefined ? { outputArtifacts: opts.outputArtifacts } : {}), + ...(opts.extraFields ?? {}), + }; + + const signature = signBenchmarkVerdict( + opts.signingSecret ?? TEST_HMAC_SECRET, + verdictBase as unknown as BenchmarkVerdict, + ); + const receipt = { + ...verdictBase, + signature, + } as unknown as SignedBenchmarkVerdictReceipt; + + // Optionally pretty-print with non-canonical key order and whitespace to verify unmodified receipt bytes are preserved! + const rawJson = opts.prettyPrint + ? `${JSON.stringify(receipt, null, 2)}\n` + : JSON.stringify(receipt); + return { + receipt, + rawBytes: Buffer.from(rawJson, 'utf8'), + provenance, + }; +} + +async function seedSingleTargetCampaign( + campaignRoot: string, + options: { + readonly probeKind?: 'physical' | 'synthetic_fixture'; + readonly receiptStatus?: 'approved' | 'denied'; + readonly missingReceipt?: boolean; + readonly receiptDetail?: string; + readonly policyJsonContent?: string; + } = {}, +): Promise<{ + readonly store: EvolutionCampaignStore; + readonly campaignId: string; + readonly lockHash: Digest; + readonly cubinBytes: Buffer; + readonly cubinDigest: Digest; + readonly policyDigest: Digest; + readonly rawReceiptBytes: Buffer; + readonly dispatchManifest: DispatchManifestV1; +}> { + const store = await EvolutionCampaignStore.open({ campaignRoot }); + const lease = await store.acquireLease('bundle-test-owner'); + const manifest = parseEvolutionCampaignDocument(SINGLE_TARGET_CAMPAIGN_YAML); + const lockHash = makeDigest('lock-single-target'); + const campaignId = 'camp-bundle-1'; + + await store.createCampaign(lease, { + campaignId, + manifest, + manifestDigest: makeDigest(SINGLE_TARGET_CAMPAIGN_YAML), + baseRevision: 'a'.repeat(40), + lockHash, + modelIds: ['claude-sonnet-4-6'], + }); + await store.updateCampaignProgress(lease, { campaignId, status: 'completed', currentGeneration: 4 }); + + const islands = await store.listIslands(campaignId); + const team0 = islands[0]!.activeTeamConfigId; + + const cubinBytes = Buffer.from('\x7fELF\x02\x01\x01\x00FLASH_DECODE_SM90A_CUBIN_PAYLOAD_V1', 'binary'); + const cubinCas = await store.writeCasBlob(cubinBytes); + const policyBytes = Buffer.from( + options.policyJsonContent ?? '{"tileM":128,"tileN":64,"warps":8}\n', + 'utf8', + ); + const policyCas = await store.writeCasBlob(policyBytes); + + const outputArtifacts: readonly BenchmarkOutputArtifact[] = [ + { + name: 'flash_decode_sm90a.cubin', + digest: cubinCas.digest, + byteLength: cubinCas.byteLength, + mediaType: 'application/x-nvidia-cubin', + }, + { + name: 'policy.json', + digest: policyCas.digest, + byteLength: policyCas.byteLength, + mediaType: 'application/json', + }, + ]; + + 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 }, + }, + { + bucketId: 'bs16-isl8k', + dimensions: { batch: 16, isl: 8192, dtype: 'bf16' }, + metrics: { latency_us_p50: 95.0, goodput_rps: 5100, max_ulp: 0.5 }, + }, + ]; + + const hardwareDiagnostics: HardwareDiagnostics = { + boundPipeline: 'tensor_cube', + rooflineHeadroom: 1.12, + achievedSolPct: 84.5, + occupancyPct: 75, + localSpillBytes: 0, + }; + + const { rawBytes: rawReceiptBytes, provenance } = makeSignedReceiptBytes({ + lockHash, + operationId: 'op-ind-win-1', + status: options.receiptStatus ?? 'approved', + probeKind: options.probeKind ?? 'physical', + ...(options.receiptDetail !== undefined ? { detail: options.receiptDetail } : {}), + outputArtifacts, + metrics: { latency_us_p50: 42.5, goodput_rps: 2400 }, + prettyPrint: true, + }); + + const receiptCas = await store.writeCasBlob(rawReceiptBytes); + + await store.recordIndividual(lease, { + individualId: 'ind-win-1', + campaignId, + islandId: 0, + generation: 4, + bucketId: null, + teamConfigId: team0, + modelId: 'claude-sonnet-4-6', + trackId: 'cute', + mutationKind: 'full_rewrite', + status: 'passed', + failureReason: null, + nicheKey: 'bound_pipeline=tensor_cube', + paretoRank: 1, + crowdingDistance: Number.POSITIVE_INFINITY, + scalarFitness: 0.96, + codeSliceCasDigest: makeDigest('code-win-1'), + evidenceDigest: makeDigest('ev-win-1'), + verdictReceiptCasDigest: options.missingReceipt ? null : 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: { latency_us_p50: 42.5, goodput_rps: 2400 }, + bucketMetrics, + hardwareDiagnostics, + hardwareProvenance: provenance, + }); + + const dispatchManifest: DispatchManifestV1 = { + version: 1, + fallback: 'baseline', + rules: [ + { + bucketId: 'bs1-isl4k', + dimensionBounds: { batch: { min: 1, max: 4 }, isl: { min: 1, max: 4096 } }, + dtypes: ['bf16', 'fp16'], + alignmentBytes: 16, + blobDigest: cubinCas.digest, + blobPath: `blobs/sha256/${cubinCas.digest.hex}`, + entrypoint: 'flash_decode_sm90a_bs1', + }, + { + bucketId: 'bs16-isl8k', + dimensionBounds: { batch: { min: 5, max: 32 }, isl: { min: 4097, max: 16384 } }, + dtypes: ['bf16'], + alignmentBytes: 16, + blobDigest: cubinCas.digest, + blobPath: `blobs/sha256/${cubinCas.digest.hex}`, + entrypoint: 'flash_decode_sm90a_bs16', + }, + ], + }; + + return { + store, + campaignId, + lockHash, + cubinBytes, + cubinDigest: cubinCas.digest, + policyDigest: policyCas.digest, + rawReceiptBytes, + dispatchManifest, + }; +} + +test('bundle (dir): repeated exports produce byte-identical manifest, dispatch-manifest, unmodified HMAC receipt, and verified blobs', async () => { + const tempDir = mkdtempSync(join(tmpdir(), 'evo-bundle-dir-')); + try { + const campaignRoot = join(tempDir, 'campaign'); + const seeded = await seedSingleTargetCampaign(campaignRoot); + try { + const outA = join(tempDir, 'out-dir-a'); + const outB = join(tempDir, 'out-dir-b'); + const modelDigest = makeDigest('model-llama3-70b'); + + const resA = await exportEvolutionBundle({ + store: seeded.store, + campaignId: seeded.campaignId, + outputDir: outA, + format: 'dir', + dispatchManifest: seeded.dispatchManifest, + receiptSigningSecret: TEST_HMAC_SECRET, + driverConstraint: '>=560.35', + modelDigest, + parallelismTags: ['tp4', 'pp1'], + }); + + const resB = await exportEvolutionBundle({ + store: seeded.store, + campaignId: seeded.campaignId, + outputDir: outB, + format: 'dir', + dispatchManifest: seeded.dispatchManifest, + receiptSigningSecret: TEST_HMAC_SECRET, + driverConstraint: '>=560.35', + modelDigest, + parallelismTags: ['pp1', 'tp4'], // Reversed order must still yield identical canonical bytes + }); + + assert.equal(resA.format, 'dir'); + assert.equal(resA.ociIndexDigest, undefined); + assert.equal(resA.manifestDigest.hex, resB.manifestDigest.hex); + assert.equal(resA.dispatchManifestDigest.hex, resB.dispatchManifestDigest.hex); + assert.deepEqual(resA.exportedIndividualIds, ['ind-win-1']); + assert.equal(resA.blobCount, 2); + + // Compare full directory trees byte-for-byte + const filesA = collectRelativeFilesRecursive(outA); + const filesB = collectRelativeFilesRecursive(outB); + assert.deepEqual(filesA, filesB); + assert.equal(filesA.includes('oci-layout'), false); + assert.equal(filesA.includes('index.json'), false); + + for (const rel of filesA) { + assert.deepEqual(readFileSync(join(outA, rel)), readFileSync(join(outB, rel)), `byte mismatch on ${rel}`); + } + + // Check manifest.json structure and member digests + const manifestRaw = readFileSync(join(outA, 'manifest.json')); + assert.equal(sha256Hex(manifestRaw), resA.manifestDigest.hex); + const bundleManifest = JSON.parse(manifestRaw.toString('utf8')) as EvolutionBundleManifestV1; + assert.equal(bundleManifest.kind, EVOLUTION_BUNDLE_KIND); + assert.equal(bundleManifest.version, EVOLUTION_BUNDLE_VERSION); + assert.equal(bundleManifest.compatibility.accelerator, 'sm_90a'); + assert.equal(bundleManifest.compatibility.isolationMode, 'whole_device'); + assert.equal(bundleManifest.compatibility.deviceCount, 1); + assert.equal(bundleManifest.compatibility.driverVersion, '560.35.03'); + assert.equal(bundleManifest.compatibility.driverConstraint, '>=560.35'); + assert.equal(bundleManifest.compatibility.runtimeVersion, 'cuda-12.6'); + assert.equal(bundleManifest.compatibility.topology, 'single_gpu'); + assert.equal(bundleManifest.compatibility.modelDigest?.hex, modelDigest.hex); + assert.deepEqual(bundleManifest.compatibility.parallelismTags, ['pp1', 'tp4']); + assert.equal(bundleManifest.lineage.campaignId, seeded.campaignId); + assert.deepEqual(bundleManifest.lineage.individualIds, ['ind-win-1']); + assert.equal(bundleManifest.lineage.baseRevision, 'a'.repeat(40)); + assert.equal(bundleManifest.lineage.lockHash.hex, seeded.lockHash.hex); + assert.equal(bundleManifest.paretoSummary.length, 1); + assert.equal(bundleManifest.paretoSummary[0]!.paretoRank, 1); + assert.equal(bundleManifest.paretoSummary[0]!.bucketMetrics?.length, 2); + + // Check dispatch-manifest.json parses cleanly and mandates fallback: 'baseline' + const dispatchRaw = readFileSync(join(outA, 'dispatch-manifest.json')); + assert.equal(sha256Hex(dispatchRaw), resA.dispatchManifestDigest.hex); + const parsedDispatch = parseDispatchManifestV1(dispatchRaw); + assert.equal(parsedDispatch.version, 1); + assert.equal(parsedDispatch.fallback, 'baseline'); + assert.equal(parsedDispatch.rules.length, 2); + + // Check receipt is byte-for-byte UNMODIFIED from CAS and passes HMAC verification + const receiptBytesOnDisk = readFileSync(join(outA, 'receipts', 'ind-win-1.verdict.json')); + assert.deepEqual(receiptBytesOnDisk, seeded.rawReceiptBytes); + const parsedReceipt = JSON.parse(receiptBytesOnDisk.toString('utf8')) as SignedBenchmarkVerdictReceipt; + assert.equal( + verifyBenchmarkVerdictSignature( + TEST_HMAC_SECRET, + parsedReceipt as unknown as Record, + parsedReceipt.signature, + ), + true, + ); + + // Check .cubin blob matches byte-for-byte + const exportedCubin = readFileSync(join(outA, 'blobs', 'sha256', seeded.cubinDigest.hex)); + assert.deepEqual(exportedCubin, seeded.cubinBytes); + + // Re-exporting over an existing outputDir atomically succeeds and leaves zero staging temp dirs + const resOverwrite = await exportEvolutionBundle({ + store: seeded.store, + campaignId: seeded.campaignId, + outputDir: outA, + format: 'dir', + dispatchManifest: seeded.dispatchManifest, + receiptSigningSecret: TEST_HMAC_SECRET, + driverConstraint: '>=560.35', + modelDigest, + parallelismTags: ['tp4', 'pp1'], + }); + assert.equal(resOverwrite.manifestDigest.hex, resA.manifestDigest.hex); + const siblings = readdirSync(tempDir).filter(name => name.startsWith('.evolution-bundle-')); + assert.deepEqual(siblings, []); + + // verifyEvolutionBundle passes on exported dir bundle + const verified = await verifyEvolutionBundle({ + bundleDir: outA, + receiptSigningSecret: TEST_HMAC_SECRET, + }); + assert.equal(verified.format, 'dir'); + assert.equal(verified.manifestDigest.hex, resA.manifestDigest.hex); + assert.equal(verified.dispatchManifestDigest.hex, resA.dispatchManifestDigest.hex); + assert.equal(verified.receiptCount, 1); + assert.equal(verified.blobCount, 2); + } finally { + chmodSync(join(campaignRoot, 'cas', 'sha256'), 0o700); + await seeded.store.close(); + } + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } +}); + +test('bundle (oci-layout): emits valid byte-identical OCI Image Layout (oci-layout, index.json, OCI manifest, layers) and auto-synthesizes dispatch-manifest', async () => { + const tempDir = mkdtempSync(join(tmpdir(), 'evo-bundle-oci-')); + try { + const campaignRoot = join(tempDir, 'campaign'); + const seeded = await seedSingleTargetCampaign(campaignRoot); + try { + const outA = join(tempDir, 'out-oci-a'); + const outB = join(tempDir, 'out-oci-b'); + + // Omit explicit dispatchManifest and format (should pick up campaign.spec.export.format === 'oci-layout') + const resA = await exportEvolutionBundle({ + store: seeded.store, + campaignId: seeded.campaignId, + outputDir: outA, + receiptSigningSecret: TEST_HMAC_SECRET, + }); + const resB = await exportEvolutionBundle({ + store: seeded.store, + campaignId: seeded.campaignId, + outputDir: outB, + format: 'oci-layout', + receiptSigningSecret: TEST_HMAC_SECRET, + }); + + assert.equal(resA.format, 'oci-layout'); + assert.ok(resA.ociIndexDigest !== undefined); + assert.equal(resA.ociIndexDigest.hex, resB.ociIndexDigest?.hex); + assert.equal(resA.manifestDigest.hex, resB.manifestDigest.hex); + assert.equal(resA.dispatchManifestDigest.hex, resB.dispatchManifestDigest.hex); + + const filesA = collectRelativeFilesRecursive(outA); + const filesB = collectRelativeFilesRecursive(outB); + assert.deepEqual(filesA, filesB); + for (const rel of filesA) { + assert.deepEqual(readFileSync(join(outA, rel)), readFileSync(join(outB, rel)), `OCI byte mismatch on ${rel}`); + } + + // Verify oci-layout file + const ociLayoutRaw = readFileSync(join(outA, 'oci-layout'), 'utf8'); + assert.deepEqual(JSON.parse(ociLayoutRaw), { imageLayoutVersion: OCI_IMAGE_LAYOUT_VERSION }); + + // Verify index.json and referenced OCI manifest blob + const indexRaw = readFileSync(join(outA, 'index.json')); + assert.equal(sha256Hex(indexRaw), resA.ociIndexDigest.hex); + const indexDoc = JSON.parse(indexRaw.toString('utf8')) as { + schemaVersion: number; + mediaType: string; + manifests: Array<{ mediaType: string; digest: string; size: number }>; + }; + assert.equal(indexDoc.schemaVersion, 2); + assert.equal(indexDoc.mediaType, OCI_IMAGE_INDEX_MEDIA_TYPE); + assert.equal(indexDoc.manifests.length, 1); + + const manifestDesc = indexDoc.manifests[0]!; + assert.equal(manifestDesc.mediaType, OCI_IMAGE_MANIFEST_MEDIA_TYPE); + assert.ok(manifestDesc.digest.startsWith('sha256:')); + const ociManifestHex = manifestDesc.digest.slice(7); + const ociManifestBytes = readFileSync(join(outA, 'blobs', 'sha256', ociManifestHex)); + assert.equal(ociManifestBytes.byteLength, manifestDesc.size); + assert.equal(sha256Hex(ociManifestBytes), ociManifestHex); + + const ociManifest = JSON.parse(ociManifestBytes.toString('utf8')) as { + schemaVersion: number; + mediaType: string; + config: { digest: string; size: number }; + layers: Array<{ digest: string; size: number; annotations?: Record }>; + }; + assert.equal(ociManifest.schemaVersion, 2); + assert.equal(ociManifest.mediaType, OCI_IMAGE_MANIFEST_MEDIA_TYPE); + + // Every layer descriptor must match an existing blob under blobs/sha256/ with exact digest + size + const layerTitles = ociManifest.layers.map(l => l.annotations?.['org.opencontainers.image.title']); + assert.ok(layerTitles.includes('manifest.json')); + assert.ok(layerTitles.includes('dispatch-manifest.json')); + assert.ok(layerTitles.includes('receipts/ind-win-1.verdict.json')); + assert.ok(layerTitles.includes(`blobs/sha256/${seeded.cubinDigest.hex}`)); + assert.ok(layerTitles.includes(`blobs/sha256/${seeded.policyDigest.hex}`)); + + for (const layer of ociManifest.layers) { + const hex = layer.digest.slice(7); + const blobBytes = readFileSync(join(outA, 'blobs', 'sha256', hex)); + assert.equal(blobBytes.byteLength, layer.size); + assert.equal(sha256Hex(blobBytes), hex); + } + + // Auto-synthesized dispatch manifest must be valid with fallback: 'baseline' + const autoDispatch = parseDispatchManifestV1(readFileSync(join(outA, 'dispatch-manifest.json'))); + assert.equal(autoDispatch.fallback, 'baseline'); + assert.equal(autoDispatch.rules.length, 2); + assert.equal(autoDispatch.rules[0]!.bucketId, 'bs1-isl4k'); + assert.equal(autoDispatch.rules[1]!.bucketId, 'bs16-isl8k'); + + // Full bundle verification passes + const verified = await verifyEvolutionBundle({ + bundleDir: outA, + receiptSigningSecret: TEST_HMAC_SECRET, + }); + assert.equal(verified.format, 'oci-layout'); + assert.equal(verified.ociIndexDigest?.hex, resA.ociIndexDigest.hex); + + // Tampering with 1 byte of the exported .cubin blob in the OCI bundle fails verifyEvolutionBundle + const exportedCubinPath = join(outA, 'blobs', 'sha256', seeded.cubinDigest.hex); + const tampered = Buffer.from(readFileSync(exportedCubinPath)); + tampered[0] = tampered[0]! ^ 0xff; + writeFileSync(exportedCubinPath, tampered); + await assertEvolutionErrorAsync( + () => verifyEvolutionBundle({ bundleDir: outA, receiptSigningSecret: TEST_HMAC_SECRET }), + 'ARTIFACT_INVALID', + ); + } finally { + chmodSync(join(campaignRoot, 'cas', 'sha256'), 0o700); + await seeded.store.close(); + } + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } +}); + +test('bundle: refuses missing receipt, denied receipt, synthetic_fixture without opt-in, and forged HMAC with EXPORT_UNVERIFIED_FORBIDDEN; allows synthetic_fixture with allowSyntheticProbe: true', async () => { + const tempDir = mkdtempSync(join(tmpdir(), 'evo-bundle-unverified-')); + try { + // 1. Missing hardware_execution receipt + const missingRoot = join(tempDir, 'camp-missing'); + const seededMissing = await seedSingleTargetCampaign(missingRoot, { missingReceipt: true }); + try { + await assertEvolutionErrorAsync( + () => exportEvolutionBundle({ + store: seededMissing.store, + campaignId: seededMissing.campaignId, + outputDir: join(tempDir, 'out-missing'), + receiptSigningSecret: TEST_HMAC_SECRET, + }), + 'EXPORT_UNVERIFIED_FORBIDDEN', + ); + } finally { + chmodSync(join(missingRoot, 'cas', 'sha256'), 0o700); + await seededMissing.store.close(); + } + + // 2. Denied receipt status + const deniedRoot = join(tempDir, 'camp-denied'); + const seededDenied = await seedSingleTargetCampaign(deniedRoot, { receiptStatus: 'denied' }); + try { + await assertEvolutionErrorAsync( + () => exportEvolutionBundle({ + store: seededDenied.store, + campaignId: seededDenied.campaignId, + outputDir: join(tempDir, 'out-denied'), + receiptSigningSecret: TEST_HMAC_SECRET, + }), + 'EXPORT_UNVERIFIED_FORBIDDEN', + ); + } finally { + chmodSync(join(deniedRoot, 'cas', 'sha256'), 0o700); + await seededDenied.store.close(); + } + + // 3. synthetic_fixture without allowSyntheticProbe -> refused; with allowSyntheticProbe: true -> succeeds + const synthRoot = join(tempDir, 'camp-synth'); + const seededSynth = await seedSingleTargetCampaign(synthRoot, { probeKind: 'synthetic_fixture' }); + try { + await assertEvolutionErrorAsync( + () => exportEvolutionBundle({ + store: seededSynth.store, + campaignId: seededSynth.campaignId, + outputDir: join(tempDir, 'out-synth-denied'), + receiptSigningSecret: TEST_HMAC_SECRET, + }), + 'EXPORT_UNVERIFIED_FORBIDDEN', + ); + + const synthOut = join(tempDir, 'out-synth-ok'); + const okRes = await exportEvolutionBundle({ + store: seededSynth.store, + campaignId: seededSynth.campaignId, + outputDir: synthOut, + format: 'dir', + allowSyntheticProbe: true, + receiptSigningSecret: TEST_HMAC_SECRET, + }); + assert.equal(okRes.format, 'dir'); + assert.deepEqual(okRes.exportedIndividualIds, ['ind-win-1']); + + // verifyEvolutionBundle also refuses synthetic_fixture unless allowSyntheticProbe: true + await assertEvolutionErrorAsync( + () => verifyEvolutionBundle({ bundleDir: synthOut, receiptSigningSecret: TEST_HMAC_SECRET }), + 'EXPORT_UNVERIFIED_FORBIDDEN', + ); + const verifiedSynth = await verifyEvolutionBundle({ + bundleDir: synthOut, + allowSyntheticProbe: true, + receiptSigningSecret: TEST_HMAC_SECRET, + }); + assert.equal(verifiedSynth.receiptCount, 1); + } finally { + chmodSync(join(synthRoot, 'cas', 'sha256'), 0o700); + await seededSynth.store.close(); + } + + // 4. Tampered / wrong HMAC secret or custom verifier callback returning false -> EXPORT_UNVERIFIED_FORBIDDEN + const hmacRoot = join(tempDir, 'camp-hmac'); + const seededHmac = await seedSingleTargetCampaign(hmacRoot); + try { + await assertEvolutionErrorAsync( + () => exportEvolutionBundle({ + store: seededHmac.store, + campaignId: seededHmac.campaignId, + outputDir: join(tempDir, 'out-bad-hmac'), + receiptSigningSecret: 'wrong-secret-key-for-verification', + }), + 'EXPORT_UNVERIFIED_FORBIDDEN', + ); + + await assertEvolutionErrorAsync( + () => exportEvolutionBundle({ + store: seededHmac.store, + campaignId: seededHmac.campaignId, + outputDir: join(tempDir, 'out-bad-cb'), + verifyReceiptSignature: () => false, + }), + 'EXPORT_UNVERIFIED_FORBIDDEN', + ); + } finally { + chmodSync(join(hmacRoot, 'cas', 'sha256'), 0o700); + await seededHmac.store.close(); + } + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } +}); + +test('bundle: refuses 1-byte tampered .cubin blob, symlink blob, hardlink (nlink > 1) blob, and unverified dispatch blob with ARTIFACT_INVALID', async () => { + const tempDir = mkdtempSync(join(tmpdir(), 'evo-bundle-tamper-')); + try { + // 1. 1-byte tampered .cubin blob in CAS + const tamperRoot = join(tempDir, 'camp-tamper'); + const seededTamper = await seedSingleTargetCampaign(tamperRoot); + try { + const cubinPath = join(tamperRoot, 'cas', 'sha256', seededTamper.cubinDigest.hex); + chmodSync(cubinPath, 0o600); + const mutated = Buffer.from(seededTamper.cubinBytes); + mutated[mutated.byteLength - 1] = mutated[mutated.byteLength - 1]! ^ 0x01; + writeFileSync(cubinPath, mutated); + chmodSync(cubinPath, 0o400); + + const outTamper = join(tempDir, 'out-tamper'); + await assertEvolutionErrorAsync( + () => exportEvolutionBundle({ + store: seededTamper.store, + campaignId: seededTamper.campaignId, + outputDir: outTamper, + receiptSigningSecret: TEST_HMAC_SECRET, + }), + 'ARTIFACT_INVALID', + ); + // Output directory must not be created on pre-export failure + assert.equal( + lstatSync(outTamper, { throwIfNoEntry: false }), + undefined, + ); + } finally { + chmodSync(join(tamperRoot, 'cas', 'sha256'), 0o700); + await seededTamper.store.close(); + } + + // 2. Symlink replacing .cubin blob in CAS -> ARTIFACT_INVALID + const symlinkRoot = join(tempDir, 'camp-symlink'); + const seededSym = await seedSingleTargetCampaign(symlinkRoot); + try { + const externalFile = join(tempDir, 'external.cubin'); + writeFileSync(externalFile, seededSym.cubinBytes); + const cubinPath = join(symlinkRoot, 'cas', 'sha256', seededSym.cubinDigest.hex); + chmodSync(cubinPath, 0o600); + unlinkSync(cubinPath); + symlinkSync(externalFile, cubinPath); + + await assertEvolutionErrorAsync( + () => exportEvolutionBundle({ + store: seededSym.store, + campaignId: seededSym.campaignId, + outputDir: join(tempDir, 'out-symlink'), + receiptSigningSecret: TEST_HMAC_SECRET, + }), + 'ARTIFACT_INVALID', + ); + } finally { + chmodSync(join(symlinkRoot, 'cas', 'sha256'), 0o700); + await seededSym.store.close(); + } + + // 3. Hardlink (nlink > 1) on .cubin blob in CAS -> ARTIFACT_INVALID + const hardlinkRoot = join(tempDir, 'camp-hardlink'); + const seededHard = await seedSingleTargetCampaign(hardlinkRoot); + try { + const cubinPath = join(hardlinkRoot, 'cas', 'sha256', seededHard.cubinDigest.hex); + const extraLink = join(tempDir, 'hardlinked-cubin-alias'); + linkSync(cubinPath, extraLink); + assert.equal(lstatSync(cubinPath).nlink, 2); + + await assertEvolutionErrorAsync( + () => exportEvolutionBundle({ + store: seededHard.store, + campaignId: seededHard.campaignId, + outputDir: join(tempDir, 'out-hardlink'), + receiptSigningSecret: TEST_HMAC_SECRET, + }), + 'ARTIFACT_INVALID', + ); + } finally { + chmodSync(join(hardlinkRoot, 'cas', 'sha256'), 0o700); + await seededHard.store.close(); + } + + // 4. Dispatch rule pointing to an unverified blob digest not in any selected receipt -> ARTIFACT_INVALID + const unrefRoot = join(tempDir, 'camp-unref'); + const seededUnref = await seedSingleTargetCampaign(unrefRoot); + try { + const fakeDigest = makeDigest('unverified-blob'); + await seededUnref.store.writeCasBlob(Buffer.from('unverified-blob', 'utf8')); + await assertEvolutionErrorAsync( + () => exportEvolutionBundle({ + store: seededUnref.store, + campaignId: seededUnref.campaignId, + outputDir: join(tempDir, 'out-unref'), + receiptSigningSecret: TEST_HMAC_SECRET, + dispatchManifest: { + version: 1, + fallback: 'baseline', + rules: [ + { + bucketId: 'bs1-isl4k', + blobDigest: fakeDigest, + blobPath: `blobs/sha256/${fakeDigest.hex}`, + entrypoint: 'rogue_kernel', + }, + ], + }, + }), + 'ARTIFACT_INVALID', + ); + // 5. ByteLength mismatch between receipt outputArtifacts and CAS blob -> ARTIFACT_INVALID + const badLenRoot = join(tempDir, 'camp-bad-len'); + const storeBadLen = await EvolutionCampaignStore.open({ campaignRoot: badLenRoot }); + try { + const lease = await storeBadLen.acquireLease('bad-len-owner'); + const manifest = parseEvolutionCampaignDocument(SINGLE_TARGET_CAMPAIGN_YAML); + const lockHash = makeDigest('lock-bad-len'); + await storeBadLen.createCampaign(lease, { + campaignId: 'camp-bad-len', + manifest, + manifestDigest: makeDigest(SINGLE_TARGET_CAMPAIGN_YAML), + baseRevision: 'c'.repeat(40), + lockHash, + modelIds: ['claude-sonnet-4-6'], + }); + const islands = await storeBadLen.listIslands('camp-bad-len'); + const blob = await storeBadLen.writeCasBlob(Buffer.from('EXACT_BYTES', 'utf8')); + const rec = makeSignedReceiptBytes({ + lockHash, + operationId: 'op-bad-len', + outputArtifacts: [ + { name: 'kernel.cubin', digest: blob.digest, byteLength: blob.byteLength + 1 }, + ], + }); + const recCas = await storeBadLen.writeCasBlob(rec.rawBytes); + await storeBadLen.recordIndividual(lease, { + individualId: 'ind-bad-len', + campaignId: 'camp-bad-len', + islandId: 0, + generation: 1, + bucketId: null, + teamConfigId: islands[0]!.activeTeamConfigId, + modelId: 'claude-sonnet-4-6', + trackId: 'cute', + mutationKind: 'diff_tune', + status: 'passed', + failureReason: null, + nicheKey: 'bound_pipeline=tensor_cube', + paretoRank: 1, + crowdingDistance: Number.POSITIVE_INFINITY, + scalarFitness: 0.9, + codeSliceCasDigest: makeDigest('code-bl'), + evidenceDigest: makeDigest('ev-bl'), + verdictReceiptCasDigest: recCas.digest, + outputArtifacts: [{ name: 'kernel.cubin', digest: blob.digest, byteLength: blob.byteLength + 1 }], + metrics: { latency_us_p50: 40, goodput_rps: 2000 }, + hardwareProvenance: rec.provenance, + }); + + await assertEvolutionErrorAsync( + () => exportEvolutionBundle({ + store: storeBadLen, + campaignId: 'camp-bad-len', + outputDir: join(tempDir, 'out-bad-len'), + receiptSigningSecret: TEST_HMAC_SECRET, + }), + 'ARTIFACT_INVALID', + ); + } finally { + chmodSync(join(badLenRoot, 'cas', 'sha256'), 0o700); + await storeBadLen.close(); + } + } finally { + chmodSync(join(unrefRoot, 'cas', 'sha256'), 0o700); + await seededUnref.store.close(); + } + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } +}); + +test('bundle (specialist-then-portfolio): refuses export when portfolioHeldOutWorkloadId has not passed, and succeeds once verified portfolio passes', async () => { + const tempDir = mkdtempSync(join(tmpdir(), 'evo-bundle-portfolio-')); + try { + const campaignRoot = join(tempDir, 'campaign'); + const store = await EvolutionCampaignStore.open({ campaignRoot }); + try { + const lease = await store.acquireLease('portfolio-owner'); + const manifest = parseEvolutionCampaignDocument(PORTFOLIO_CAMPAIGN_YAML); + const lockHash = makeDigest('lock-portfolio'); + const campaignId = 'camp-portfolio-1'; + + await store.createCampaign(lease, { + campaignId, + manifest, + manifestDigest: makeDigest(PORTFOLIO_CAMPAIGN_YAML), + baseRevision: 'b'.repeat(40), + lockHash, + modelIds: ['claude-sonnet-4-6'], + }); + + const islands = await store.listIslands(campaignId); + const team0 = islands[0]!.activeTeamConfigId; + + const spec1Bytes = Buffer.from('SPEC_BS1_CUBIN', 'utf8'); + const spec2Bytes = Buffer.from('SPEC_BS16_CUBIN', 'utf8'); + const routerBytes = Buffer.from('PORTFOLIO_ROUTER_SO', 'utf8'); + const spec1Cas = await store.writeCasBlob(spec1Bytes); + const spec2Cas = await store.writeCasBlob(spec2Bytes); + const routerCas = await store.writeCasBlob(routerBytes); + + const rec1 = makeSignedReceiptBytes({ + lockHash, + operationId: 'op-spec-1', + workloadDigest: makeDigest('decode-bs1-4k'), + outputArtifacts: [{ name: 'spec_bs1.cubin', digest: spec1Cas.digest, byteLength: spec1Cas.byteLength }], + metrics: { latency_us_p50: 30, goodput_rps: 2000 }, + }); + const rec2 = makeSignedReceiptBytes({ + lockHash, + operationId: 'op-spec-2', + workloadDigest: makeDigest('decode-bs16-8k'), + outputArtifacts: [{ name: 'spec_bs16.cubin', digest: spec2Cas.digest, byteLength: spec2Cas.byteLength }], + metrics: { latency_us_p50: 80, goodput_rps: 5000 }, + }); + const rec1Cas = await store.writeCasBlob(rec1.rawBytes); + const rec2Cas = await store.writeCasBlob(rec2.rawBytes); + + await store.recordIndividual(lease, { + individualId: 'ind-spec-1', + campaignId, + islandId: 0, + generation: 1, + bucketId: 'bs1-isl4k', + teamConfigId: team0, + modelId: 'claude-sonnet-4-6', + trackId: 'cute', + mutationKind: 'full_rewrite', + status: 'passed', + failureReason: null, + nicheKey: 'bound_pipeline=tensor_cube', + paretoRank: 1, + crowdingDistance: Number.POSITIVE_INFINITY, + scalarFitness: 0.9, + codeSliceCasDigest: makeDigest('code-s1'), + evidenceDigest: makeDigest('ev-s1'), + verdictReceiptCasDigest: rec1Cas.digest, + outputArtifacts: [{ name: 'spec_bs1.cubin', digest: spec1Cas.digest, byteLength: spec1Cas.byteLength }], + metrics: { latency_us_p50: 30, goodput_rps: 2000 }, + hardwareProvenance: rec1.provenance, + }); + + await store.recordIndividual(lease, { + individualId: 'ind-spec-2', + campaignId, + islandId: 0, + generation: 1, + bucketId: 'bs16-isl8k', + teamConfigId: team0, + modelId: 'claude-sonnet-4-6', + trackId: 'cute', + mutationKind: 'full_rewrite', + status: 'passed', + failureReason: null, + nicheKey: 'bound_pipeline=hbm', + paretoRank: 1, + crowdingDistance: Number.POSITIVE_INFINITY, + scalarFitness: 0.92, + codeSliceCasDigest: makeDigest('code-s2'), + evidenceDigest: makeDigest('ev-s2'), + verdictReceiptCasDigest: rec2Cas.digest, + outputArtifacts: [{ name: 'spec_bs16.cubin', digest: spec2Cas.digest, byteLength: spec2Cas.byteLength }], + metrics: { latency_us_p50: 80, goodput_rps: 5000 }, + hardwareProvenance: rec2.provenance, + }); + + // Record a FAILED portfolio evaluation on portfolioHeldOutWorkloadId + await store.recordIndividual(lease, { + individualId: 'ind-port-fail', + campaignId, + islandId: 0, + generation: 2, + bucketId: 'decode-portfolio-holdout', + teamConfigId: team0, + modelId: 'claude-sonnet-4-6', + trackId: 'cute', + mutationKind: 'portfolio', + status: 'failed', + failureReason: 'METRIC_THRESHOLD_FAILED', + nicheKey: null, + paretoRank: null, + crowdingDistance: null, + scalarFitness: null, + codeSliceCasDigest: makeDigest('code-pf'), + evidenceDigest: null, + verdictReceiptCasDigest: null, + outputArtifacts: [], + metrics: { latency_us_p50: 500, goodput_rps: 100 }, + }); + + // Must refuse both automatic export AND explicit specialist export before portfolio passes! + await assertEvolutionErrorAsync( + () => exportEvolutionBundle({ + store, + campaignId, + outputDir: join(tempDir, 'out-port-denied-1'), + receiptSigningSecret: TEST_HMAC_SECRET, + }), + 'EXPORT_UNVERIFIED_FORBIDDEN', + ); + await assertEvolutionErrorAsync( + () => exportEvolutionBundle({ + store, + campaignId, + outputDir: join(tempDir, 'out-port-denied-2'), + individualIds: ['ind-spec-1', 'ind-spec-2'], + receiptSigningSecret: TEST_HMAC_SECRET, + }), + 'EXPORT_UNVERIFIED_FORBIDDEN', + ); + + // Now record a PASSING portfolio individual verified on decode-portfolio-holdout + const portfolioWorkloadDigest = makeDigest('decode-portfolio-holdout'); + const recPort = makeSignedReceiptBytes({ + lockHash, + operationId: 'op-port-pass', + workloadDigest: portfolioWorkloadDigest, + outputArtifacts: [ + { name: 'portfolio_router.so', digest: routerCas.digest, byteLength: routerCas.byteLength, mediaType: 'application/x-sharedlib' }, + ], + metrics: { latency_us_p50: 52, goodput_rps: 3800 }, + }); + const recPortCas = await store.writeCasBlob(recPort.rawBytes); + + await store.recordIndividual(lease, { + individualId: 'ind-port-pass', + campaignId, + islandId: 0, + generation: 3, + bucketId: 'decode-portfolio-holdout', + teamConfigId: team0, + modelId: 'claude-sonnet-4-6', + trackId: 'cute', + mutationKind: 'portfolio', + status: 'passed', + failureReason: null, + nicheKey: 'bound_pipeline=tensor_cube', + paretoRank: 1, + crowdingDistance: Number.POSITIVE_INFINITY, + scalarFitness: 0.99, + codeSliceCasDigest: makeDigest('code-pp'), + evidenceDigest: makeDigest('ev-pp'), + verdictReceiptCasDigest: recPortCas.digest, + outputArtifacts: [ + { name: 'portfolio_router.so', digest: routerCas.digest, byteLength: routerCas.byteLength, mediaType: 'application/x-sharedlib' }, + ], + metrics: { latency_us_p50: 52, goodput_rps: 3800 }, + hardwareProvenance: recPort.provenance, + lineageEdges: [ + { + campaignId, + childIndividualId: 'ind-port-pass', + parentIndividualId: 'ind-spec-1', + role: 'portfolio_member', + sourceIslandId: 0, + createdGeneration: 3, + }, + { + campaignId, + childIndividualId: 'ind-port-pass', + parentIndividualId: 'ind-spec-2', + role: 'portfolio_member', + sourceIslandId: 0, + createdGeneration: 3, + }, + ], + }); + await store.updateCampaignProgress(lease, { + campaignId, + status: 'completed', + stagePhase: 'portfolio', + currentGeneration: 3, + }); + + const outPort = join(tempDir, 'out-port-ok'); + const res = await exportEvolutionBundle({ + store, + campaignId, + outputDir: outPort, + format: 'oci-layout', + receiptSigningSecret: TEST_HMAC_SECRET, + dispatchManifest: { + version: 1, + fallback: 'baseline', + rules: [ + { + bucketId: 'bs1-isl4k', + dimensionBounds: { batch: { min: 1, max: 4 } }, + blobDigest: spec1Cas.digest, + entrypoint: 'kernel_bs1', + }, + { + bucketId: 'bs16-isl8k', + dimensionBounds: { batch: { min: 5, max: 32 } }, + blobDigest: spec2Cas.digest, + entrypoint: 'kernel_bs16', + }, + ], + }, + }); + + assert.equal(res.format, 'oci-layout'); + assert.deepEqual(res.exportedIndividualIds, ['ind-port-pass', 'ind-spec-1', 'ind-spec-2']); + assert.equal(res.blobCount, 3); + + const bundleManifest = JSON.parse( + readFileSync(join(outPort, 'manifest.json'), 'utf8'), + ) as EvolutionBundleManifestV1; + assert.equal(bundleManifest.compatibility.workloadDigest.hex, portfolioWorkloadDigest.hex); + + const verified = await verifyEvolutionBundle({ + bundleDir: outPort, + receiptSigningSecret: TEST_HMAC_SECRET, + }); + assert.equal(verified.receiptCount, 3); + assert.equal(verified.blobCount, 3); + } finally { + chmodSync(join(campaignRoot, 'cas', 'sha256'), 0o700); + await store.close(); + } + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } +}); + +test('bundle: refuses secrets via SecretScrubber, symlink outputDir, overwrite: false conflict, and incompatible hardware provenance', async () => { + const tempDir = mkdtempSync(join(tmpdir(), 'evo-bundle-guards-')); + try { + // 1. SecretScrubber catches secret in receipt detail + const secretRoot = join(tempDir, 'camp-secret'); + const seededSecret = await seedSingleTargetCampaign(secretRoot, { + receiptDetail: 'leaked token ghp_1234567890abcdefghijklmnopqrstuvwxyz', + }); + try { + await assertEvolutionErrorAsync( + () => exportEvolutionBundle({ + store: seededSecret.store, + campaignId: seededSecret.campaignId, + outputDir: join(tempDir, 'out-secret'), + receiptSigningSecret: TEST_HMAC_SECRET, + }), + 'SECRET_LEAK_DETECTED', + ); + } finally { + chmodSync(join(secretRoot, 'cas', 'sha256'), 0o700); + await seededSecret.store.close(); + } + + // 2. Custom registered secret in policy.json artifact + const customSecRoot = join(tempDir, 'camp-custom-secret'); + const seededCustomSec = await seedSingleTargetCampaign(customSecRoot, { + policyJsonContent: '{"token":"my-super-secret-value-998877"}\n', + }); + try { + const scrubber = new SecretScrubber(); + scrubber.register('my-super-secret-value-998877'); + await assertEvolutionErrorAsync( + () => exportEvolutionBundle({ + store: seededCustomSec.store, + campaignId: seededCustomSec.campaignId, + outputDir: join(tempDir, 'out-custom-secret'), + receiptSigningSecret: TEST_HMAC_SECRET, + scrubber, + }), + 'SECRET_LEAK_DETECTED', + ); + } finally { + chmodSync(join(customSecRoot, 'cas', 'sha256'), 0o700); + await seededCustomSec.store.close(); + } + + // 3. Symlink outputDir & overwrite: false conflict + const cleanRoot = join(tempDir, 'camp-clean'); + const seededClean = await seedSingleTargetCampaign(cleanRoot); + try { + const realTarget = join(tempDir, 'real-dir'); + mkdirSync(realTarget); + const symOut = join(tempDir, 'sym-out'); + symlinkSync(realTarget, symOut); + + await assertEvolutionErrorAsync( + () => exportEvolutionBundle({ + store: seededClean.store, + campaignId: seededClean.campaignId, + outputDir: symOut, + receiptSigningSecret: TEST_HMAC_SECRET, + }), + 'EVOLUTION_SYMLINK_FORBIDDEN', + ); + + // Existing non-symlink directory with overwrite: false -> EVOLUTION_CONFLICT + await assertEvolutionErrorAsync( + () => exportEvolutionBundle({ + store: seededClean.store, + campaignId: seededClean.campaignId, + outputDir: realTarget, + overwrite: false, + receiptSigningSecret: TEST_HMAC_SECRET, + }), + 'EVOLUTION_CONFLICT', + ); + } finally { + chmodSync(join(cleanRoot, 'cas', 'sha256'), 0o700); + await seededClean.store.close(); + } + + // 4. Incompatible hardware provenance across selected individuals -> ARTIFACT_INVALID + const mismatchRoot = join(tempDir, 'camp-mismatch'); + const seededMismatch = await seedSingleTargetCampaign(mismatchRoot); + try { + const lease = await seededMismatch.store.acquireLease('mismatch-owner'); + const islands = await seededMismatch.store.listIslands(seededMismatch.campaignId); + const altBlob = await seededMismatch.store.writeCasBlob(Buffer.from('SM89_CUBIN', 'utf8')); + const altReceipt = makeSignedReceiptBytes({ + lockHash: seededMismatch.lockHash, + operationId: 'op-alt-sm89', + accelerator: 'sm_89', + outputArtifacts: [{ name: 'alt.cubin', digest: altBlob.digest, byteLength: altBlob.byteLength }], + }); + const altReceiptCas = await seededMismatch.store.writeCasBlob(altReceipt.rawBytes); + await seededMismatch.store.recordIndividual(lease, { + individualId: 'ind-win-2-sm89', + campaignId: seededMismatch.campaignId, + islandId: 1, + generation: 4, + bucketId: null, + teamConfigId: islands[1]!.activeTeamConfigId, + modelId: 'claude-sonnet-4-6', + trackId: 'cute', + mutationKind: 'diff_tune', + status: 'passed', + failureReason: null, + nicheKey: 'bound_pipeline=hbm', + paretoRank: 1, + crowdingDistance: Number.POSITIVE_INFINITY, + scalarFitness: 0.9, + codeSliceCasDigest: makeDigest('code-alt'), + evidenceDigest: makeDigest('ev-alt'), + verdictReceiptCasDigest: altReceiptCas.digest, + outputArtifacts: [{ name: 'alt.cubin', digest: altBlob.digest, byteLength: altBlob.byteLength }], + metrics: { latency_us_p50: 45, goodput_rps: 2500 }, + hardwareProvenance: altReceipt.provenance, + }); + + await assertEvolutionErrorAsync( + () => exportEvolutionBundle({ + store: seededMismatch.store, + campaignId: seededMismatch.campaignId, + outputDir: join(tempDir, 'out-mismatch'), + individualIds: ['ind-win-1', 'ind-win-2-sm89'], + receiptSigningSecret: TEST_HMAC_SECRET, + }), + 'ARTIFACT_INVALID', + ); + } finally { + chmodSync(join(mismatchRoot, 'cas', 'sha256'), 0o700); + await seededMismatch.store.close(); + } + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } +}); + +test('bundle: requires receiptSigningSecret or verifyReceiptSignature by default, supports explicit allowUnverifiedSignature opt-in, and auto-populates persisted campaign.driverConstraint', async () => { + const tempDir = mkdtempSync(join(tmpdir(), 'evo-bundle-hmac-driver-')); + try { + const campRoot = join(tempDir, 'camp'); + const seeded = await seedSingleTargetCampaign(campRoot); + try { + const lease = await seeded.store.acquireLease('driver-constraint-owner'); + await seeded.store.updateCampaignProgress(lease, { + campaignId: seeded.campaignId, + driverConstraint: '>=560.35,<570.0', + }); + + // 1. Omitting receiptSigningSecret & verifyReceiptSignature on exportEvolutionBundle fails closed + const unverifiedErr = await assertEvolutionErrorAsync( + () => exportEvolutionBundle({ + store: seeded.store, + campaignId: seeded.campaignId, + outputDir: join(tempDir, 'denied-no-secret'), + }), + 'EXPORT_UNVERIFIED_FORBIDDEN', + ); + assert.match(unverifiedErr.message, /receiptSigningSecret or verifyReceiptSignature is required/); + + // 2. Explicit allowUnverifiedSignature: true succeeds and populates persisted campaign.driverConstraint + const offlineOut = join(tempDir, 'offline-bundle'); + const exported = await exportEvolutionBundle({ + store: seeded.store, + campaignId: seeded.campaignId, + outputDir: offlineOut, + format: 'dir', + allowUnverifiedSignature: true, + }); + assert.equal(exported.format, 'dir'); + + const bundleManifest = JSON.parse( + readFileSync(join(offlineOut, 'manifest.json'), 'utf8'), + ) as EvolutionBundleManifestV1; + assert.equal(bundleManifest.compatibility.driverConstraint, '>=560.35,<570.0'); + + // 3. verifyEvolutionBundle WITHOUT secret also fails closed unless allowUnverifiedSignature: true + await assertEvolutionErrorAsync( + () => verifyEvolutionBundle({ bundleDir: offlineOut }), + 'EXPORT_UNVERIFIED_FORBIDDEN', + ); + + const verifiedOffline = await verifyEvolutionBundle({ + bundleDir: offlineOut, + allowUnverifiedSignature: true, + }); + assert.equal(verifiedOffline.manifest.compatibility.driverConstraint, '>=560.35,<570.0'); + + // 4. And real HMAC verification succeeds with TEST_HMAC_SECRET + const verifiedHmac = await verifyEvolutionBundle({ + bundleDir: offlineOut, + receiptSigningSecret: TEST_HMAC_SECRET, + }); + assert.equal(verifiedHmac.receiptCount, 1); + } finally { + chmodSync(join(campRoot, 'cas', 'sha256'), 0o700); + await seeded.store.close(); + } + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } +}); + +test('bundle: exports 64-bucket specialist-then-portfolio campaign without overflowing 64 dispatch rules', async () => { + const tempDir = mkdtempSync(join(tmpdir(), 'evo-bundle-64-buckets-')); + try { + const campRoot = join(tempDir, 'camp-64'); + const store = await EvolutionCampaignStore.open({ campaignRoot: campRoot }); + try { + const lease = await store.acquireLease('bundle-64-owner'); + const bucketDefs: string[] = []; + for (let i = 0; i < 64; i += 1) { + const id = `bucket-${String(i).padStart(2, '0')}`; + bucketDefs.push(` - id: ${id}\n heldOutWorkloadId: wl-${id}`); + } + const yaml64 = `apiVersion: loopwright.dev/v1alpha1 +kind: EvolutionCampaign +metadata: + name: flash-decode-64-buckets +spec: + taskpack: .loopwright/taskpack.yaml + targetCellId: cuda-h100-whole + stages: + mode: specialist-then-portfolio + specialistBuckets: +${bucketDefs.join('\n')} + portfolioHeldOutWorkloadId: decode-portfolio-64 + 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 + maxCrossoversPerPrompt: 1 + objectives: + - metric: latency_us_p50 + direction: minimize + budgets: + maxGenerations: 65 + maxEvaluations: 65 + maxConcurrentEvaluations: 1 + scratchpadIntervalGenerations: 10 +`; + const manifest = parseEvolutionCampaignDocument(yaml64); + const campaignId = 'camp-64-portfolio'; + const lockHash = makeDigest('lock-64-portfolio'); + await store.createCampaign(lease, { + campaignId, + manifest, + manifestDigest: makeDigest(yaml64), + baseRevision: 'b'.repeat(40), + lockHash, + modelIds: ['claude-sonnet-4-6'], + }); + await store.updateCampaignProgress(lease, { + campaignId, + status: 'completed', + currentGeneration: 65, + driverConstraint: '>=550.54', + }); + const teamConfigId = (await store.listIslands(campaignId))[0]!.activeTeamConfigId; + + const specialistIds: string[] = []; + for (let i = 0; i < 64; i += 1) { + const bucketId = `bucket-${String(i).padStart(2, '0')}`; + const indId = `ind-spec-${String(i).padStart(2, '0')}`; + specialistIds.push(indId); + const cubin = await store.writeCasBlob(Buffer.from(`ELF64_SPEC_${i}`, 'utf8')); + const codeCas = await store.writeCasBlob(Buffer.from(`int k_${i}() { return ${i}; }\n`, 'utf8')); + const art: readonly BenchmarkOutputArtifact[] = [ + { name: `kernel_${i}.cubin`, digest: cubin.digest, byteLength: cubin.byteLength, mediaType: 'application/octet-stream' }, + ]; + const receipt = makeSignedReceiptBytes({ + lockHash, + operationId: `op-${indId}`, + status: 'approved', + probeKind: 'physical', + outputArtifacts: art, + metrics: { latency_us_p50: 20 + i * 0.1 }, + }); + const recCas = await store.writeCasBlob(receipt.rawBytes); + await store.recordIndividual(lease, { + individualId: indId, + campaignId, + islandId: 0, + generation: 1, + bucketId, + teamConfigId, + modelId: 'claude-sonnet-4-6', + trackId: 'triton', + mutationKind: 'diff_tune', + status: 'passed', + failureReason: null, + nicheKey: 'bound_pipeline=tensor_cube', + paretoRank: 1, + crowdingDistance: Number.POSITIVE_INFINITY, + scalarFitness: 1.0, + codeSliceCasDigest: codeCas.digest, + evidenceDigest: makeDigest(`ev-${indId}`), + verdictReceiptCasDigest: recCas.digest, + outputArtifacts: art.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: { latency_us_p50: 20 + i * 0.1 }, + bucketMetrics: [{ bucketId, dimensions: { batch: i + 1 }, metrics: { latency_us_p50: 20 + i * 0.1 } }], + hardwareProvenance: receipt.provenance, + }); + } + + // Portfolio individual referencing all 64 specialist winners via portfolio_member edges + const portCubin = await store.writeCasBlob(Buffer.from('ELF64_PORTFOLIO_DISPATCH', 'utf8')); + const portCodeCas = await store.writeCasBlob(Buffer.from('int dispatch_portfolio() { return 0; }\n', 'utf8')); + const portArt: readonly BenchmarkOutputArtifact[] = [ + { name: 'portfolio.cubin', digest: portCubin.digest, byteLength: portCubin.byteLength, mediaType: 'application/octet-stream' }, + ]; + const portReceipt = makeSignedReceiptBytes({ + lockHash, + operationId: 'op-ind-portfolio-64', + status: 'approved', + probeKind: 'physical', + outputArtifacts: portArt, + metrics: { latency_us_p50: 22.0 }, + }); + const portRecCas = await store.writeCasBlob(portReceipt.rawBytes); + await store.recordIndividual(lease, { + individualId: 'ind-portfolio-64', + campaignId, + islandId: 0, + generation: 65, + bucketId: 'decode-portfolio-64', + teamConfigId, + modelId: 'claude-sonnet-4-6', + trackId: 'triton', + mutationKind: 'portfolio', + status: 'passed', + failureReason: null, + nicheKey: 'bound_pipeline=tensor_cube', + paretoRank: 1, + crowdingDistance: Number.POSITIVE_INFINITY, + scalarFitness: 1.0, + codeSliceCasDigest: portCodeCas.digest, + evidenceDigest: makeDigest('ev-portfolio-64'), + verdictReceiptCasDigest: portRecCas.digest, + outputArtifacts: portArt.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: { latency_us_p50: 22.0 }, + hardwareProvenance: portReceipt.provenance, + }); + await store.recordLineageEdges( + lease, + specialistIds.map(specId => ({ + campaignId, + parentIndividualId: specId, + childIndividualId: 'ind-portfolio-64', + role: 'portfolio_member' as const, + sourceIslandId: 0, + createdGeneration: 65, + })), + ); + + const outDir = join(tempDir, 'out-64'); + const exported = await exportEvolutionBundle({ + store, + campaignId, + outputDir: outDir, + format: 'dir', + receiptSigningSecret: TEST_HMAC_SECRET, + }); + assert.equal(exported.format, 'dir'); + + const verified = await verifyEvolutionBundle({ + bundleDir: outDir, + receiptSigningSecret: TEST_HMAC_SECRET, + }); + assert.equal(verified.dispatchManifest.rules.length, 64); + assert.ok(verified.dispatchManifest.rules.every(r => r.bucketId.startsWith('bucket-'))); + assert.equal(verified.receiptCount, 65); + } finally { + chmodSync(join(campRoot, 'cas', 'sha256'), 0o700); + await store.close(); + } + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } +}); diff --git a/packages/evolution/test/campaign-e2e.test.ts b/packages/evolution/test/campaign-e2e.test.ts new file mode 100644 index 0000000..c865307 --- /dev/null +++ b/packages/evolution/test/campaign-e2e.test.ts @@ -0,0 +1,1194 @@ +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { + chmodSync, + existsSync, + lstatSync, + mkdirSync, + mkdtempSync, + readFileSync, + realpathSync, + rmSync, + writeFileSync, +} from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import test from 'node:test'; +import { expectedSchema } from '../../state/src/schema.js'; +import { + runHardwareWorker, + startRelayServer, + type WorkerConfig, +} from '@loopwright/hardware-runner'; +import { + checkEvolutionCampaign, + createControllerChildRunEvaluator, + exportEvolutionBundle, + getEvolutionCampaignStatus, + inspectEvolutionCampaign, + resumeEvolutionCampaign, + runEvolutionCampaign, + verifyEvolutionBundle, + EvolutionError, + type CandidateEvaluationProposal, + type CandidateEvaluationResult, +} from '../src/index.js'; + +const BENCH_HMAC_SECRET = 'e2e-campaign-relay-hmac-secret-0123456789abcdef'; +const WORKER_BEARER_TOKEN = 'e2e-campaign-worker-token-0123456789abcdef'; + +function sha256Hex(data: Uint8Array | string): string { + return createHash('sha256').update(data).digest('hex'); +} + +function makeDigest(seed: string): { readonly algorithm: 'sha256'; readonly hex: string } { + return { algorithm: 'sha256', hex: sha256Hex(seed) }; +} + +function initGitRepo(repoDir: string, files: Readonly>): string { + mkdirSync(repoDir, { recursive: true, mode: 0o700 }); + for (const [relPath, entry] of Object.entries(files)) { + const absPath = join(repoDir, relPath); + mkdirSync(join(absPath, '..'), { recursive: true, mode: 0o700 }); + writeFileSync(absPath, entry.content, { mode: entry.executable ? 0o755 : 0o644 }); + if (entry.executable) chmodSync(absPath, 0o755); + } + const gitEnv = { + ...process.env, + GIT_AUTHOR_NAME: 'Loopwright Test', + GIT_AUTHOR_EMAIL: 'test@loopwright.dev', + GIT_COMMITTER_NAME: 'Loopwright Test', + GIT_COMMITTER_EMAIL: 'test@loopwright.dev', + }; + execFileSync('git', ['init', '-b', 'main'], { cwd: repoDir, env: gitEnv, stdio: 'ignore' }); + execFileSync('git', ['add', '.'], { cwd: repoDir, env: gitEnv, stdio: 'ignore' }); + execFileSync('git', ['commit', '-m', 'Initial baseline kernel'], { cwd: repoDir, env: gitEnv, stdio: 'ignore' }); + return execFileSync('git', ['rev-parse', 'HEAD'], { cwd: repoDir, env: gitEnv, encoding: 'utf8' }).trim(); +} + +/** + * Deterministic pure-TypeScript ELF64 builder for Stage A static symbol audit testing. + */ +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; // ELFCLASS64 + ehdr[5] = 1; // ELFDATA2LSB + ehdr[6] = 1; + ehdr.writeUInt16LE(2, 16); // ET_EXEC (.cubin) + ehdr.writeUInt16LE(190, 18); // EM_CUDA + 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); +} + +const BASELINE_KERNEL_SOURCE = [ + '#include ', + '// Locked prologue header outside EVOLVE-BLOCK', + '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 SINGLE_TARGET_TASKPACK_YAML = ` +apiVersion: loopwright.dev/v1alpha1 +kind: Taskpack +metadata: + name: flash-decode-e2e +spec: + goal: + candidate: Evolve flash decode kernel inside EVOLVE-BLOCK markers. + noChange: No kernel change needed. + target: + matrix: + - id: cuda-h100-whole + platform: linux/amd64 + variant: cuda12 + hardware: + accelerator: sm_90a + isolationMode: whole_device + deviceCount: 1 + forbiddenSymbolPatterns: + - cublas + - cudnn + scope: + writable: + - src/kernels/** + protected: + - scripts/** + models: + - provider: anthropic + id: claude-sonnet-4-6 + thinking: medium + - provider: openai + id: gpt-5.4 + thinking: high + roles: + - id: probe-readonly + provider: anthropic + model: claude-sonnet-4-6 + purpose: task + tools: [read] + prompt: Inspect kernel Roofline bottleneck. + - id: mutator-sandboxed + provider: anthropic + model: claude-sonnet-4-6 + purpose: task + tools: [read, write, edit, bash] + prompt: Mutate flash_decode.cu strictly 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-h100-whole + heldOutWorkloadId: decode-bs1-4k + allowSyntheticHardwareProbe: true + metricThresholds: + - kind: bounds + metric: max_ulp + max: 2 + bucketScope: all_buckets + publication: + mode: disabled + triggers: + schedule: false + workflowDispatch: true + releasePublished: false + commentCommands: [] +`; + +const STEPPING_STONE_CAMPAIGN_YAML = ` +apiVersion: loopwright.dev/v1alpha1 +kind: EvolutionCampaign +metadata: + name: stepping-stone-campaign +spec: + taskpack: .loopwright/taskpack.yaml + targetCellId: cuda-h100-whole + stages: + mode: single-target + population: + islands: 2 + migrationIntervalGenerations: 2 + maxMigrationElites: 1 + nicheAxes: + - id: bound_pipeline + kind: enum + values: [hbm, l2, smem_lds_ub, tensor_cube] + - id: occupancy_band + kind: numeric_bins + edges: [0, 50, 100] + sampling: + noveltyDecayLambda: 1.0 + mutationWeights: + diff_tune: 0.2 + full_rewrite: 0.2 + crossover: 0.6 + modelBandit: ucb1 + maxCrossoversPerPrompt: 2 + objectives: + - metric: latency_us_p50 + direction: minimize + - metric: goodput_rps + direction: maximize + budgets: + maxGenerations: 3 + maxEvaluations: 6 + maxConcurrentEvaluations: 2 + scratchpadIntervalGenerations: 2 +`; + +test('campaign: checkEvolutionCampaign validates Taskpack links and rejects broken targetCellId, unapproved team archetype, or colliding portfolio workload', async () => { + const tempDir = mkdtempSync(join(tmpdir(), 'evo-check-campaign-')); + try { + const repoDir = join(tempDir, 'repo'); + initGitRepo(repoDir, { + '.loopwright/taskpack.yaml': { content: SINGLE_TARGET_TASKPACK_YAML }, + '.loopwright/campaign.yaml': { content: STEPPING_STONE_CAMPAIGN_YAML }, + 'src/kernels/flash_decode.cu': { content: BASELINE_KERNEL_SOURCE }, + }); + + const checked = await checkEvolutionCampaign({ + manifestPath: join(repoDir, '.loopwright', 'campaign.yaml'), + repositoryRoot: repoDir, + }); + assert.equal(checked.valid, true); + assert.equal(checked.targetCellId, 'cuda-h100-whole'); + assert.deepEqual(checked.modelIds, ['claude-sonnet-4-6', 'gpt-5.4']); + + // Unknown targetCellId -> fails closed + await assert.rejects( + () => checkEvolutionCampaign({ + manifest: STEPPING_STONE_CAMPAIGN_YAML.replace('targetCellId: cuda-h100-whole', 'targetCellId: missing-cell'), + repositoryRoot: repoDir, + }), + (err: unknown) => err instanceof EvolutionError && err.code === 'EVOLUTION_SCHEMA_INVALID', + ); + + // Unapproved archetype in teamEvolution -> TEAM_ENVELOPE_VIOLATION + const badArchetypeYaml = `${STEPPING_STONE_CAMPAIGN_YAML} + teamEvolution: + enabled: true + supervisorRoleId: supervisor + allowedArchetypeRoles: [nonexistent-archetype] + stallGenerations: 4 + minHypervolumeDelta: 0.001 + triggerOnRunEvalPathology: true + trialGenerations: 2 + maxTeamSize: 2 + maxTeamSteps: 2 +`; + await assert.rejects( + () => checkEvolutionCampaign({ + manifest: badArchetypeYaml, + repositoryRoot: repoDir, + }), + (err: unknown) => err instanceof EvolutionError && err.code === 'TEAM_ENVELOPE_VIOLATION', + ); + + // Portfolio workload colliding with specialist bucket workload -> EVOLUTION_SCHEMA_INVALID + const collidingPortfolioYaml = STEPPING_STONE_CAMPAIGN_YAML.replace( + ` stages:\n mode: single-target`, + [ + ' stages:', + ' mode: specialist-then-portfolio', + ' specialistBuckets:', + ' - id: bs1-isl4k', + ' heldOutWorkloadId: decode-bs1-4k', + ' portfolioHeldOutWorkloadId: decode-bs1-4k', + ].join('\n'), + ); + await assert.rejects( + () => checkEvolutionCampaign({ + manifest: collidingPortfolioYaml, + repositoryRoot: repoDir, + }), + (err: unknown) => err instanceof EvolutionError && err.code === 'EVOLUTION_SCHEMA_INVALID', + ); + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } +}); + +test('campaign: retains slower MAP-Elites stepping stone in distinct bound_pipeline niche, migrates inspiration across islands, and promotes crossover child to rank-1 Pareto dominance', async () => { + const tempDir = mkdtempSync(join(tmpdir(), 'evo-stepping-stone-')); + try { + const repoDir = join(tempDir, 'repo'); + const baseRevision = initGitRepo(repoDir, { + '.loopwright/taskpack.yaml': { content: SINGLE_TARGET_TASKPACK_YAML }, + 'src/kernels/flash_decode.cu': { content: BASELINE_KERNEL_SOURCE }, + }); + const campaignRoot = join(tempDir, 'campaign-state'); + + const observedStagedParentPerms: number[] = []; + + const evaluator = async (proposal: CandidateEvaluationProposal): Promise => { + for (const file of proposal.stagedParentFiles) { + const st = lstatSync(file.filePath); + assert.equal(st.isSymbolicLink(), false); + assert.equal(st.nlink, 1); + observedStagedParentPerms.push(st.mode & 0o777); + } + if (proposal.stagedScratchpadPath !== undefined) { + const scStat = lstatSync(proposal.stagedScratchpadPath); + assert.equal(scStat.mode & 0o777, 0o400); + } + + // Generation 1: + // Island 0 discovers a fast HBM-bound local elite (latency 70, goodput 1900) + // Island 1 discovers a SLOWER structural tensor_cube stepping stone (latency 96, goodput 1450) + if (proposal.generation === 1) { + if (proposal.islandId === 0) { + return { + status: 'passed', + codeSlice: `// EVOLVE-BLOCK-START: flash_decode\nint flash_decode_mode() { return 10; /* fast_hbm_vec4 */ }\n// EVOLVE-BLOCK-END: flash_decode\n`, + metrics: { latency_us_p50: 70, goodput_rps: 1900 }, + hardwareDiagnostics: { boundPipeline: 'hbm', occupancyPct: 75, rooflineHeadroom: 1.45 }, + evidenceDigest: makeDigest(`ev-${proposal.individualId}`), + }; + } + return { + status: 'passed', + codeSlice: `// EVOLVE-BLOCK-START: flash_decode\nint flash_decode_mode() { return 20; /* async_tma_tensor_cube_stone */ }\n// EVOLVE-BLOCK-END: flash_decode\n`, + metrics: { latency_us_p50: 96, goodput_rps: 1450 }, + hardwareDiagnostics: { boundPipeline: 'tensor_cube', occupancyPct: 35, rooflineHeadroom: 1.65 }, + evidenceDigest: makeDigest(`ev-${proposal.individualId}`), + }; + } + + // Generation 2: Island 0 ALSO discovers a local smem_lds_ub stepping stone so Island 0 has 2 distinct niches! + if (proposal.generation === 2) { + if (proposal.islandId === 0) { + return { + status: 'passed', + codeSlice: `// EVOLVE-BLOCK-START: flash_decode\nint flash_decode_mode() { return 15; /* double_buffered_smem_stone */ }\n// EVOLVE-BLOCK-END: flash_decode\n`, + metrics: { latency_us_p50: 88, goodput_rps: 1600 }, + hardwareDiagnostics: { boundPipeline: 'smem_lds_ub', occupancyPct: 40, rooflineHeadroom: 1.52 }, + evidenceDigest: makeDigest(`ev-${proposal.individualId}`), + }; + } + return { + status: 'passed', + codeSlice: `// EVOLVE-BLOCK-START: flash_decode\nint flash_decode_mode() { return 22; /* l2_prefetch_stone */ }\n// EVOLVE-BLOCK-END: flash_decode\n`, + metrics: { latency_us_p50: 84, goodput_rps: 1650 }, + hardwareDiagnostics: { boundPipeline: 'l2', occupancyPct: 60, rooflineHeadroom: 1.48 }, + evidenceDigest: makeDigest(`ev-${proposal.individualId}`), + }; + } + + // Generation 3 (after gen-2 ring migration + scratchpad synthesis): + // Multi-parent crossover combines primary + stepping-stone donor/inspiration -> rank-1 Pareto breakthrough! + const hasSteppingStoneParent = proposal.parents.some(p => + p.individual.nicheKey?.includes('tensor_cube') + || p.individual.nicheKey?.includes('smem_lds_ub') + || p.role === 'inspiration' + || p.role === 'crossover_donor', + ); + if (proposal.islandId === 0 && hasSteppingStoneParent) { + return { + status: 'passed', + codeSlice: `// EVOLVE-BLOCK-START: flash_decode\nint flash_decode_mode() { return 99; /* fused_tma_double_buffer_winner */ }\n// EVOLVE-BLOCK-END: flash_decode\n`, + metrics: { latency_us_p50: 42, goodput_rps: 2850 }, + hardwareDiagnostics: { boundPipeline: 'tensor_cube', occupancyPct: 80, rooflineHeadroom: 1.11 }, + evidenceDigest: makeDigest(`ev-${proposal.individualId}`), + }; + } + return { + status: 'passed', + codeSlice: `// EVOLVE-BLOCK-START: flash_decode\nint flash_decode_mode() { return ${30 + proposal.islandId}; }\n// EVOLVE-BLOCK-END: flash_decode\n`, + metrics: { latency_us_p50: 68, goodput_rps: 1950 }, + hardwareDiagnostics: { boundPipeline: 'hbm', occupancyPct: 70, rooflineHeadroom: 1.38 }, + evidenceDigest: makeDigest(`ev-${proposal.individualId}`), + }; + }; + + const result = await runEvolutionCampaign({ + campaignRoot, + campaignId: 'camp-stepping-stone', + manifest: STEPPING_STONE_CAMPAIGN_YAML, + repositoryRoot: repoDir, + baseRevision, + evaluator, + }); + + assert.equal(result.campaign.status, 'completed'); + assert.equal(result.campaign.evaluationsUsed, 6); + assert.ok(observedStagedParentPerms.length > 0); + assert.ok(observedStagedParentPerms.every(mode => mode === 0o400)); + + const inspected = await inspectEvolutionCampaign({ + campaignRoot, + campaignId: 'camp-stepping-stone', + }); + + // Slower stepping stones in smem_lds_ub / tensor_cube niches survived in island niche archives! + const island0Archive = inspected.nicheArchives.find(a => a.islandId === 0); + assert.ok(island0Archive !== undefined); + assert.ok(island0Archive.elites.length >= 2, 'MAP-Elites must retain distinct hardware-behavior niches on Island 0'); + + // Rank-1 Pareto winner achieved (latency 42, goodput 2850) and has multi-parent lineage edges + assert.equal(inspected.paretoFrontier.length, 1); + const winner = inspected.paretoFrontier[0]!; + assert.equal(winner.metrics['latency_us_p50'], 42); + assert.equal(winner.metrics['goodput_rps'], 2850); + + const winnerEdges = inspected.lineageEdges.filter(e => e.childIndividualId === winner.individualId); + assert.ok(winnerEdges.length >= 2, 'crossover winner must record multi-parent lineage_edges'); + assert.equal(winnerEdges.some(e => e.role === 'primary'), true); + assert.equal( + winnerEdges.some(e => e.role === 'crossover_donor' || e.role === 'inspiration'), + true, + ); + + // Scratchpad snapshot was synthesized at generation 2 and model bandit arms recorded rewards + assert.ok(inspected.scratchpadSnapshots.length >= 1); + assert.equal(inspected.modelBanditArms.length, 2); + assert.ok(inspected.modelBanditArms.some(arm => arm.totalReward > 0)); + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } +}); + +test('campaign: cosmetic EVOLVE-BLOCK clone is rejected by @loopwright/decisions with 0 benchmark-gate.v1 dispatches and verificationCertified: false', async () => { + const tempDir = mkdtempSync(join(tmpdir(), 'evo-novelty-clone-')); + try { + const repoDir = join(tempDir, 'repo'); + const baseRevision = initGitRepo(repoDir, { + '.loopwright/taskpack.yaml': { content: SINGLE_TARGET_TASKPACK_YAML }, + 'src/kernels/flash_decode.cu': { content: BASELINE_KERNEL_SOURCE }, + }); + const campaignRoot = join(tempDir, 'campaign-state'); + + const twoGenYaml = STEPPING_STONE_CAMPAIGN_YAML + .replace('islands: 2', 'islands: 1') + .replace('maxGenerations: 3', 'maxGenerations: 2') + .replace('maxEvaluations: 6', 'maxEvaluations: 4'); + + let benchmarkGateDispatches = 0; + + const result = await runEvolutionCampaign({ + campaignRoot, + campaignId: 'camp-novelty-filter', + manifest: twoGenYaml, + repositoryRoot: repoDir, + baseRevision, + proposeCandidateSlice: async ctx => { + if (ctx.generation === 1) { + return '// EVOLVE-BLOCK-START: flash_decode\nint flash_decode_mode() {\n return 7;\n}\n// EVOLVE-BLOCK-END: flash_decode\n'; + } + // Generation 2: cosmetic whitespace + comment-only clone of Generation 1! + return '// EVOLVE-BLOCK-START: flash_decode\n/* pure cosmetic comment */\nint flash_decode_mode( ) {\n return 7; // identical AST token stream\n}\n// EVOLVE-BLOCK-END: flash_decode\n'; + }, + evaluator: async proposal => { + benchmarkGateDispatches += 1; + return { + status: 'passed', + codeSlice: proposal.proposedCodeSlice ?? '', + metrics: { latency_us_p50: 60, goodput_rps: 2100 }, + hardwareDiagnostics: { boundPipeline: 'tensor_cube', occupancyPct: 75, rooflineHeadroom: 1.25 }, + evidenceDigest: makeDigest(`ev-${proposal.individualId}`), + }; + }, + }); + + // Generation 1 dispatched benchmark-gate.v1 (1 time); Generation 2 cosmetic clone was rejected BEFORE evaluator (0 dispatches for clone!) + assert.equal(benchmarkGateDispatches, 1); + assert.equal(result.noveltyRejectionsCount, 1); + assert.equal(result.campaign.evaluationsUsed, 1); + assert.ok(result.advisoryDecisions.length >= 2); + assert.equal(result.advisoryDecisions.every(d => d.verificationCertified === false && d.advisoryOnly === true), true); + + const inspected = await inspectEvolutionCampaign({ campaignRoot, campaignId: 'camp-novelty-filter' }); + const rejectedClone = inspected.individuals.find(i => i.failureReason === 'NOVELTY_CLONE_REJECTED'); + assert.ok(rejectedClone !== undefined); + assert.equal(rejectedClone.status, 'failed'); + assert.equal(rejectedClone.verdictReceiptCasDigest, null); + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } +}); + +test('campaign (real LocalRunStore + RelayServer + Worker): enforces evolve-block-guard.v1 pre-lease, Stage A cublasGemmEx static audit with 0 Stage B runs, and all_buckets max_ulp threshold', async () => { + const stateSchemaBefore = expectedSchema(); + const tempDir = mkdtempSync(join(realpathSync(tmpdir()), 'evo-real-gates-')); + + const relayCasDir = join(tempDir, 'relay-cas'); + const workerWorkDir = join(tempDir, 'worker-work'); + const workloadsDir = join(tempDir, 'workloads'); + mkdirSync(workerWorkDir, { recursive: true, mode: 0o700 }); + mkdirSync(join(workloadsDir, 'decode-bs1-4k'), { recursive: true, mode: 0o700 }); + + // Stage B blind workload script: reads compiled mode marker inside sealed Stage A metadata and emits bucketed metrics + const evaluateScript = [ + `#!${process.execPath}`, + 'const fs = require("node:fs");', + 'const path = require("node:path");', + 'const modePath = path.join(process.env.LOOPWRIGHT_STAGE_A_OUT || ".", "mode.txt");', + 'const mode = fs.existsSync(modePath) ? fs.readFileSync(modePath, "utf8").trim() : "clean";', + 'const badUlp = mode === "bad_ulp";', + 'const payload = {', + ' status: "approved",', + ' metrics: { latency_us_p50: badUlp ? 45 : 52, goodput_rps: 2400, max_ulp: badUlp ? 5 : 1 },', + ' bucketMetrics: [', + ' { bucketId: "b0", dimensions: { bs: 1 }, metrics: { latency_us_p50: 48, goodput_rps: 2500, max_ulp: 1 } },', + ' { bucketId: "b1", dimensions: { bs: 4 }, metrics: { latency_us_p50: 56, goodput_rps: 2300, max_ulp: badUlp ? 5 : 1 } }', + ' ],', + ' hardwareDiagnostics: { boundPipeline: "tensor_cube", occupancyPct: 75, rooflineHeadroom: 1.15 }', + '};', + 'process.stdout.write("LOOPWRIGHT_STAGE_B_RESULT:" + JSON.stringify(payload) + "\\n");', + '', + ].join('\n'); + writeFileSync(join(workloadsDir, 'decode-bs1-4k', 'evaluate.sh'), evaluateScript, { mode: 0o755 }); + chmodSync(join(workloadsDir, 'decode-bs1-4k', 'evaluate.sh'), 0o755); + + const cleanCubinHex = buildElf64Cubin(['flash_decode_sm90a']).toString('hex'); + const cublasCubinHex = buildElf64Cubin(['cublasGemmEx']).toString('hex'); + + // Stage A build script inside repo: compiles src/kernels/flash_decode.cu into Stage A .cubin + mode.txt + const buildScript = [ + `#!${process.execPath}`, + 'const fs = require("node:fs");', + 'const path = require("node:path");', + 'const src = fs.readFileSync("src/kernels/flash_decode.cu", "utf8");', + 'const outDir = process.env.LOOPWRIGHT_STAGE_A_OUT;', + 'if (src.includes("USE_CUBLAS_FALLBACK")) {', + ` fs.writeFileSync(path.join(outDir, "kernel.cubin"), Buffer.from(${JSON.stringify(cublasCubinHex)}, "hex"));`, + '} else {', + ` fs.writeFileSync(path.join(outDir, "kernel.cubin"), Buffer.from(${JSON.stringify(cleanCubinHex)}, "hex"));`, + ' fs.writeFileSync(path.join(outDir, "mode.txt"), src.includes("TRIGGER_BAD_ULP") ? "bad_ulp" : "clean");', + '}', + '', + ].join('\n'); + + const relay = await startRelayServer({ + port: 0, + casDir: relayCasDir, + controllerSigningSecret: BENCH_HMAC_SECRET, + workerTokens: [WORKER_BEARER_TOKEN], + leaseTtlMs: 15_000, + sweepIntervalMs: 250, + }); + + const workerAbort = new AbortController(); + let workerLeasesAcquired = 0; + let stageBExecutionsObserved = 0; + const workerConfig: WorkerConfig = { + workerId: 'worker-e2e-gates', + 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-bs1-4k'], + }, + pollWaitMs: 200, + heartbeatIntervalMs: 50, + requestTimeoutMs: 5_000, + stageATimeoutMs: 15_000, + stageBTimeoutMs: 15_000, + toolchainPaths: [join(process.execPath, '..')], + probeMode: 'synthetic_fixture', + }; + + let workerFatalError: unknown = null; + const workerPromise = runHardwareWorker({ + config: workerConfig, + once: false, + signal: workerAbort.signal, + registerProcessSignalHandlers: false, + onLeaseAcquired: () => { + workerLeasesAcquired += 1; + }, + }).catch((err: unknown) => { + if (!workerAbort.signal.aborted) { + workerFatalError = err; + } + }); + + try { + const repoDir = join(tempDir, 'repo'); + const baseRevision = initGitRepo(repoDir, { + '.loopwright/taskpack.yaml': { content: SINGLE_TARGET_TASKPACK_YAML }, + 'src/kernels/flash_decode.cu': { content: BASELINE_KERNEL_SOURCE }, + 'scripts/build.sh': { content: buildScript, executable: true }, + }); + + const fourGenCampaignYaml = STEPPING_STONE_CAMPAIGN_YAML + .replace('islands: 2', 'islands: 1') + .replace('maxGenerations: 3', 'maxGenerations: 4') + .replace('maxEvaluations: 6', 'maxEvaluations: 4'); + + const envMap: Readonly> = { + BENCH_SIGNING_SECRET: BENCH_HMAC_SECRET, + }; + + const leaseCountsAfterGen: number[] = []; + const stageBCountsAfterGen: number[] = []; + + const evaluator = createControllerChildRunEvaluator({ + repositoryRoot: repoDir, + allowLoopbackHttp: true, + gateEndpoints: [ + { + id: 'hw-relay', + url: `${relay.url}/v1/benchmark/jobs`, + signingCredentialRef: 'bench-sign', + implementation: 'benchmark-gate.v1', + timeoutMs: 10_000, + maxPollMs: 120_000, + pollInitialMs: 100, + pollMaxMs: 250, + jitter: 10, + }, + ], + credentialEnvMap: { + byCredentialRef: { 'bench-sign': 'BENCH_SIGNING_SECRET' }, + }, + environment: name => envMap[name], + agentDriver: async stepCtx => { + const kernelPath = join(stepCtx.workspacePath, 'src/kernels/flash_decode.cu'); + if (stepCtx.generation === 1) { + // 1. Mutate 1 character OUTSIDE EVOLVE-BLOCK -> must fail evolve-block-guard.v1 BEFORE Relay/Worker lease! + const illegalOutsideEdit = BASELINE_KERNEL_SOURCE.replace( + 'LOCKED_ABI_VERSION = 1;', + 'LOCKED_ABI_VERSION = 2;', + ); + writeFileSync(kernelPath, illegalOutsideEdit, 'utf8'); + } else if (stepCtx.generation === 2) { + // 2. Legal inside-block edit, but Stage A links forbidden cublasGemmEx -> STAGE_A_STATIC_AUDIT_FAILED (0 Stage B runs!) + const cublasEdit = BASELINE_KERNEL_SOURCE.replace( + 'return 0; // baseline', + 'return 1; // USE_CUBLAS_FALLBACK', + ); + writeFileSync(kernelPath, cublasEdit, 'utf8'); + } else if (stepCtx.generation === 3) { + // 3. Clean Stage A ELF, but Stage B bucket b1 has max_ulp = 5 > 2 -> METRIC_THRESHOLD_FAILED! + const badUlpEdit = BASELINE_KERNEL_SOURCE.replace( + 'return 0; // baseline', + 'return 2; // TRIGGER_BAD_ULP', + ); + writeFileSync(kernelPath, badUlpEdit, 'utf8'); + } else { + // 4. Clean Stage A ELF + clean all-bucket Stage B -> PASSED! + const cleanEdit = BASELINE_KERNEL_SOURCE.replace( + 'return 0; // baseline', + 'return 3; // CLEAN_TENSOR_CUBE_WINNER', + ); + writeFileSync(kernelPath, cleanEdit, 'utf8'); + } + }, + onAfterChildEvaluation: async (_proposal, evalResult) => { + if (evalResult.bucketMetrics !== undefined && evalResult.bucketMetrics.length > 0) { + stageBExecutionsObserved += 1; + } + leaseCountsAfterGen.push(workerLeasesAcquired); + stageBCountsAfterGen.push(stageBExecutionsObserved); + }, + }); + + const campaignRoot = join(tempDir, 'campaign-real'); + const runRes = await runEvolutionCampaign({ + campaignRoot, + campaignId: 'camp-real-gates', + manifest: fourGenCampaignYaml, + repositoryRoot: repoDir, + baseRevision, + evaluator, + }); + + assert.equal(runRes.campaign.status, 'completed'); + assert.equal(runRes.campaign.evaluationsUsed, 4); + + // Gen 1 (outside EVOLVE-BLOCK): 0 worker leases, 0 Stage B runs! + assert.equal(leaseCountsAfterGen[0], 0); + assert.equal(stageBCountsAfterGen[0], 0); + + // Gen 2 (Stage A cublasGemmEx): 1 worker lease, STILL 0 Stage B runs! + assert.equal(leaseCountsAfterGen[1], 1); + assert.equal(stageBCountsAfterGen[1], 0); + + // Gen 3 (all_buckets max_ulp failure): 2 worker leases, 1 Stage B run + assert.equal(leaseCountsAfterGen[2], 2); + assert.equal(stageBCountsAfterGen[2], 1); + + // Gen 4 (clean pass): 3 worker leases, 2 Stage B runs + assert.equal(leaseCountsAfterGen[3], 3); + assert.equal(stageBCountsAfterGen[3], 2); + + const inspected = await inspectEvolutionCampaign({ campaignRoot, campaignId: 'camp-real-gates' }); + const byGen = [...inspected.individuals].sort((a, b) => a.generation - b.generation); + assert.equal(byGen.length, 4); + + // Verify child LocalRunStore directories exist under /runs//controller//state + for (const ind of byGen) { + const childStateDir = join(campaignRoot, 'runs', ind.individualId, 'controller', ind.individualId, 'state'); + assert.equal(existsSync(childStateDir), true); + } + + assert.equal(byGen[0]?.status, 'failed'); + assert.ok(byGen[0]?.failureReason !== null); + + assert.equal(byGen[1]?.status, 'failed'); + assert.equal(byGen[1]?.failureReason, 'STAGE_A_STATIC_AUDIT_FAILED'); + + assert.equal(byGen[2]?.status, 'failed'); + assert.equal(byGen[2]?.failureReason, 'METRIC_THRESHOLD_FAILED'); + + assert.equal(byGen[3]?.status, 'passed'); + assert.ok(byGen[3]?.verdictReceiptCasDigest !== null); + assert.ok(byGen[3]?.outputArtifacts.some(a => a.name === 'kernel.cubin')); + + assert.equal(expectedSchema(), stateSchemaBefore); + } finally { + workerAbort.abort(); + await workerPromise; + await relay.close(); + rmSync(tempDir, { recursive: true, force: true }); + } + assert.equal(workerFatalError, null); +}); + +test('campaign: graceful SIGTERM / BENCHMARK_PREEMPTED interruption and resumeEvolutionCampaign preserve archives without double-counting maxEvaluations or mutating @loopwright/state schema', async () => { + const stateSchemaBefore = expectedSchema(); + const tempDir = mkdtempSync(join(tmpdir(), 'evo-resume-preempt-')); + try { + const repoDir = join(tempDir, 'repo'); + const baseRevision = initGitRepo(repoDir, { + '.loopwright/taskpack.yaml': { content: SINGLE_TARGET_TASKPACK_YAML }, + 'src/kernels/flash_decode.cu': { content: BASELINE_KERNEL_SOURCE }, + }); + const campaignRoot = join(tempDir, 'campaign-resume'); + + const resumeYaml = STEPPING_STONE_CAMPAIGN_YAML + .replace('islands: 2', 'islands: 1') + .replace('maxGenerations: 3', 'maxGenerations: 4') + .replace('maxEvaluations: 6', 'maxEvaluations: 3'); + + const abortController = new AbortController(); + let callCount = 0; + + // Run 1: + // Call 1 (Gen 1): passed (evaluationsUsed = 1) + // Call 2 (Gen 2): BENCHMARK_PREEMPTED (preemptionsCount = 1, evaluationsUsed MUST stay 1!) -> then SIGTERM abort triggers! + const firstRun = await runEvolutionCampaign({ + campaignRoot, + campaignId: 'camp-resume-1', + manifest: resumeYaml, + repositoryRoot: repoDir, + baseRevision, + signal: abortController.signal, + evaluator: async proposal => { + callCount += 1; + if (callCount === 1) { + return { + status: 'passed', + codeSlice: '// EVOLVE-BLOCK-START: flash_decode\nint flash_decode_mode() { return 101; }\n// EVOLVE-BLOCK-END: flash_decode\n', + metrics: { latency_us_p50: 80, goodput_rps: 1700 }, + hardwareDiagnostics: { boundPipeline: 'hbm', occupancyPct: 60, rooflineHeadroom: 1.4 }, + evidenceDigest: makeDigest(`ev-${proposal.individualId}`), + }; + } + abortController.abort(); + return { + status: 'preempted', + failureReason: 'BENCHMARK_PREEMPTED', + codeSlice: '// EVOLVE-BLOCK-START: flash_decode\nint flash_decode_mode() { return 102; }\n// EVOLVE-BLOCK-END: flash_decode\n', + metrics: {}, + }; + }, + }); + + assert.equal(firstRun.campaign.status, 'paused'); + assert.equal(firstRun.campaign.evaluationsUsed, 1, 'preempted evaluation must NOT consume maxEvaluations'); + assert.equal(firstRun.campaign.preemptionsCount, 1); + + const midStatus = await getEvolutionCampaignStatus({ campaignRoot, campaignId: 'camp-resume-1' }); + assert.equal(midStatus.campaign.status, 'paused'); + assert.equal(midStatus.countsByStatus.passed, 1); + assert.equal(midStatus.countsByStatus.preempted, 1); + + // Resume from campaign.sqlite with fresh coordinator lease and complete remaining 2 evaluations (total = 3 === maxEvaluations) + let resumedCalls = 0; + const resumedRun = await resumeEvolutionCampaign({ + campaignRoot, + campaignId: 'camp-resume-1', + repositoryRoot: repoDir, + evaluator: async proposal => { + resumedCalls += 1; + return { + status: 'passed', + codeSlice: `// EVOLVE-BLOCK-START: flash_decode\nint flash_decode_mode() { return ${200 + resumedCalls}; }\n// EVOLVE-BLOCK-END: flash_decode\n`, + metrics: { latency_us_p50: 70 - resumedCalls * 10, goodput_rps: 1900 + resumedCalls * 300 }, + hardwareDiagnostics: { boundPipeline: 'tensor_cube', occupancyPct: 75, rooflineHeadroom: 1.15 }, + evidenceDigest: makeDigest(`ev-resumed-${proposal.individualId}`), + }; + }, + }); + + assert.equal(resumedRun.campaign.status, 'completed'); + assert.equal(resumedCalls, 2); + assert.equal(resumedRun.campaign.evaluationsUsed, 3); + assert.equal(resumedRun.campaign.preemptionsCount, 1); + assert.equal(expectedSchema(), stateSchemaBefore); + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } +}); + +test('campaign (e2e specialist-then-portfolio -> OCI bundle): evolves 2 specialist buckets without exposing portfolioHeldOutWorkloadId, verifies portfolio, exports OCI bundle, and rejects 1-byte tampered .cubin', async () => { + const tempDir = mkdtempSync(join(realpathSync(tmpdir()), 'evo-portfolio-e2e-')); + + const relayCasDir = join(tempDir, 'relay-cas'); + const workerWorkDir = join(tempDir, 'worker-work'); + const workloadsDir = join(tempDir, 'workloads'); + mkdirSync(workerWorkDir, { recursive: true, mode: 0o700 }); + + for (const [workloadId, baseLat, baseRps] of [ + ['decode-bs1-4k', 28, 2200] as const, + ['decode-bs16-8k', 64, 5400] as const, + ['decode-portfolio-holdout', 44, 4100] as const, + ]) { + mkdirSync(join(workloadsDir, workloadId), { recursive: true, mode: 0o700 }); + const script = [ + `#!${process.execPath}`, + `const payload = {`, + ` status: "approved",`, + ` metrics: { latency_us_p50: ${baseLat}, goodput_rps: ${baseRps}, max_ulp: 1 },`, + ` bucketMetrics: [`, + ` { bucketId: ${JSON.stringify(workloadId)}, dimensions: { bs: ${workloadId.includes('bs16') ? 16 : 1} }, metrics: { latency_us_p50: ${baseLat}, goodput_rps: ${baseRps}, max_ulp: 1 } }`, + ` ],`, + ` hardwareDiagnostics: { boundPipeline: "tensor_cube", occupancyPct: 78, rooflineHeadroom: 1.12 }`, + `};`, + `process.stdout.write("LOOPWRIGHT_STAGE_B_RESULT:" + JSON.stringify(payload) + "\\n");`, + '', + ].join('\n'); + const scriptPath = join(workloadsDir, workloadId, 'evaluate.sh'); + writeFileSync(scriptPath, script, { mode: 0o755 }); + chmodSync(scriptPath, 0o755); + } + + const bs1CubinHex = buildElf64Cubin(['flash_decode_bs1_sm90a']).toString('hex'); + const bs16CubinHex = buildElf64Cubin(['flash_decode_bs16_sm90a']).toString('hex'); + const routerCubinHex = buildElf64Cubin(['flash_decode_portfolio_router_sm90a']).toString('hex'); + + const portfolioBuildScript = [ + `#!${process.execPath}`, + 'const fs = require("node:fs");', + 'const path = require("node:path");', + 'const src = fs.readFileSync("src/kernels/flash_decode.cu", "utf8");', + 'const outDir = process.env.LOOPWRIGHT_STAGE_A_OUT;', + 'if (src.includes("PORTFOLIO_ROUTER_DISPATCH")) {', + ` fs.writeFileSync(path.join(outDir, "portfolio_router.cubin"), Buffer.from(${JSON.stringify(routerCubinHex)}, "hex"));`, + '} else if (src.includes("SPECIALIST_BS16")) {', + ` fs.writeFileSync(path.join(outDir, "spec_bs16.cubin"), Buffer.from(${JSON.stringify(bs16CubinHex)}, "hex"));`, + '} else {', + ` fs.writeFileSync(path.join(outDir, "spec_bs1.cubin"), Buffer.from(${JSON.stringify(bs1CubinHex)}, "hex"));`, + '}', + '', + ].join('\n'); + + const relay = await startRelayServer({ + port: 0, + casDir: relayCasDir, + controllerSigningSecret: BENCH_HMAC_SECRET, + workerTokens: [WORKER_BEARER_TOKEN], + leaseTtlMs: 15_000, + sweepIntervalMs: 250, + }); + + const observedWorkloadsByPhase: Array<{ readonly phase: string; readonly workloadId: string }> = []; + let portfolioWorkerError: unknown = null; + const workerAbort = new AbortController(); + const workerPromise = runHardwareWorker({ + config: { + workerId: 'worker-portfolio-e2e', + 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-bs1-4k', 'decode-bs16-8k', 'decode-portfolio-holdout'], + }, + pollWaitMs: 40, + heartbeatIntervalMs: 50, + requestTimeoutMs: 5_000, + stageATimeoutMs: 15_000, + stageBTimeoutMs: 15_000, + toolchainPaths: [join(process.execPath, '..')], + probeMode: 'synthetic_fixture', + }, + once: false, + signal: workerAbort.signal, + registerProcessSignalHandlers: false, + onLeaseAcquired: grant => { + observedWorkloadsByPhase.push({ + phase: grant.job.heldOutWorkloadId === 'decode-portfolio-holdout' ? 'portfolio' : 'specialist', + workloadId: grant.job.heldOutWorkloadId, + }); + }, + }).catch((err: unknown) => { + if (!workerAbort.signal.aborted) { + portfolioWorkerError = err; + } + }); + + try { + const repoDir = join(tempDir, 'repo'); + const baseRevision = initGitRepo(repoDir, { + '.loopwright/taskpack.yaml': { content: SINGLE_TARGET_TASKPACK_YAML }, + 'src/kernels/flash_decode.cu': { content: BASELINE_KERNEL_SOURCE }, + 'scripts/build.sh': { content: portfolioBuildScript, executable: true }, + }); + + const bundleRelDir = '.loopwright-out/bundles/portfolio'; + const bundleOutputDir = join(repoDir, bundleRelDir); + const portfolioCampaignYaml = ` +apiVersion: loopwright.dev/v1alpha1 +kind: EvolutionCampaign +metadata: + name: portfolio-flash-decode +spec: + taskpack: .loopwright/taskpack.yaml + targetCellId: cuda-h100-whole + stages: + mode: specialist-then-portfolio + specialistBuckets: + - id: bs1-isl4k + heldOutWorkloadId: decode-bs1-4k + - id: bs16-isl8k + heldOutWorkloadId: decode-bs16-8k + portfolioHeldOutWorkloadId: decode-portfolio-holdout + population: + islands: 1 + 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.5 + crossover: 0.0 + modelBandit: deterministic-round-robin + maxCrossoversPerPrompt: 1 + objectives: + - metric: latency_us_p50 + direction: minimize + - metric: goodput_rps + direction: maximize + budgets: + maxGenerations: 3 + maxEvaluations: 6 + maxConcurrentEvaluations: 1 + scratchpadIntervalGenerations: 5 + export: + format: oci-layout + outputDir: ${bundleRelDir} +`; + + const envMap: Readonly> = { + BENCH_SIGNING_SECRET: BENCH_HMAC_SECRET, + }; + + const specialistContextSnapshots: string[] = []; + + const evaluator = createControllerChildRunEvaluator({ + repositoryRoot: repoDir, + allowLoopbackHttp: true, + gateEndpoints: [ + { + id: 'hw-relay', + url: `${relay.url}/v1/benchmark/jobs`, + signingCredentialRef: 'bench-sign', + implementation: 'benchmark-gate.v1', + timeoutMs: 10_000, + maxPollMs: 120_000, + pollInitialMs: 100, + pollMaxMs: 250, + jitter: 10, + }, + ], + credentialEnvMap: { + byCredentialRef: { 'bench-sign': 'BENCH_SIGNING_SECRET' }, + }, + environment: name => envMap[name], + agentDriver: async stepCtx => { + if (stepCtx.stagePhase === 'specialist') { + // Confirm portfolioHeldOutWorkloadId ('decode-portfolio-holdout') is NEVER exposed anywhere in specialist prompt or context! + specialistContextSnapshots.push(stepCtx.prompt); + for (const cf of stepCtx.contextFiles) { + specialistContextSnapshots.push(readFileSync(cf, 'utf8')); + } + const registryText = readFileSync(join(stepCtx.childRunDir, 'registry', 'registry.json'), 'utf8'); + const configText = readFileSync(join(stepCtx.childRunDir, 'registry', 'config.json'), 'utf8'); + specialistContextSnapshots.push(registryText, configText); + } + + const kernelPath = join(stepCtx.workspacePath, 'src/kernels/flash_decode.cu'); + if (stepCtx.stagePhase === 'portfolio') { + writeFileSync( + kernelPath, + BASELINE_KERNEL_SOURCE.replace('return 0; // baseline', 'return 77; // PORTFOLIO_ROUTER_DISPATCH'), + 'utf8', + ); + } else if (stepCtx.bucketId === 'bs16-isl8k') { + writeFileSync( + kernelPath, + BASELINE_KERNEL_SOURCE.replace('return 0; // baseline', 'return 16; // SPECIALIST_BS16'), + 'utf8', + ); + } else { + writeFileSync( + kernelPath, + BASELINE_KERNEL_SOURCE.replace('return 0; // baseline', 'return 1; // SPECIALIST_BS1'), + 'utf8', + ); + } + }, + }); + + const campaignRoot = join(tempDir, 'campaign-portfolio'); + const runRes = await runEvolutionCampaign({ + campaignRoot, + campaignId: 'camp-portfolio-e2e', + manifest: portfolioCampaignYaml, + repositoryRoot: repoDir, + baseRevision, + evaluator, + allowSyntheticProbe: true, + receiptSigningSecret: BENCH_HMAC_SECRET, + }); + + assert.equal(runRes.campaign.status, 'completed'); + assert.equal(runRes.campaign.stagePhase, 'portfolio'); + + // Confirm portfolioHeldOutWorkloadId ('decode-portfolio-holdout') was NEVER exposed in any specialist run! + assert.ok(specialistContextSnapshots.length > 0); + for (const snap of specialistContextSnapshots) { + assert.equal( + snap.includes('decode-portfolio-holdout'), + false, + 'portfolioHeldOutWorkloadId must NEVER leak into specialist runs', + ); + } + + // Confirm Relay/Worker ran specialist workloads first, then decode-portfolio-holdout last + assert.deepEqual( + observedWorkloadsByPhase.map(item => item.workloadId), + ['decode-bs1-4k', 'decode-bs16-8k', 'decode-portfolio-holdout'], + ); + + // Auto-export produced a valid OCI-layout evolution-bundle.v1 + assert.ok(runRes.exportedBundle !== undefined); + assert.equal(runRes.exportedBundle.format, 'oci-layout'); + assert.equal(runRes.exportedBundle.exportedIndividualIds.length, 3); + assert.equal(runRes.exportedBundle.blobCount, 3); + + // Verify status & inspect APIs + const status = await getEvolutionCampaignStatus({ campaignRoot, campaignId: 'camp-portfolio-e2e' }); + assert.equal(status.campaign.status, 'completed'); + assert.equal(status.countsByStatus.passed, 3); + + const inspected = await inspectEvolutionCampaign({ campaignRoot, campaignId: 'camp-portfolio-e2e' }); + const portfolioEdges = inspected.lineageEdges.filter(e => e.role === 'portfolio_member'); + assert.equal(portfolioEdges.length, 2, 'portfolio individual must link both specialist winners as portfolio_member'); + + // Verify exported OCI bundle passes verifyEvolutionBundle with HMAC signature check + const verifiedBundle = await verifyEvolutionBundle({ + bundleDir: bundleOutputDir, + allowSyntheticProbe: true, + receiptSigningSecret: BENCH_HMAC_SECRET, + }); + assert.equal(verifiedBundle.format, 'oci-layout'); + assert.equal(verifiedBundle.receiptCount, 3); + assert.equal(verifiedBundle.blobCount, 3); + + // Also verify manual re-export to a second directory is deterministic + const manualExportDir = join(tempDir, 'manual-oci-bundle'); + await exportEvolutionBundle({ + store: runRes.store, + campaignId: 'camp-portfolio-e2e', + outputDir: manualExportDir, + format: 'oci-layout', + allowSyntheticProbe: true, + receiptSigningSecret: BENCH_HMAC_SECRET, + }); + await runRes.store.close(); + + // Tamper 1 byte of an exported .cubin blob in bundleOutputDir -> verifyEvolutionBundle MUST fail closed with ARTIFACT_INVALID + const expectedBs1Digest = sha256Hex(Buffer.from(bs1CubinHex, 'hex')); + const cubinBlobPath = join(bundleOutputDir, 'blobs', 'sha256', expectedBs1Digest); + assert.equal(existsSync(cubinBlobPath), true); + const tampered = Buffer.from(readFileSync(cubinBlobPath)); + tampered[0] = tampered[0]! ^ 0xff; + writeFileSync(cubinBlobPath, tampered); + + await assert.rejects( + () => verifyEvolutionBundle({ + bundleDir: bundleOutputDir, + allowSyntheticProbe: true, + receiptSigningSecret: BENCH_HMAC_SECRET, + }), + (err: unknown) => err instanceof EvolutionError && err.code === 'ARTIFACT_INVALID', + ); + } finally { + workerAbort.abort(); + await workerPromise; + await relay.close(); + rmSync(tempDir, { recursive: true, force: true }); + } + assert.equal(portfolioWorkerError, null); +}); diff --git a/packages/evolution/test/campaign-hardening.test.ts b/packages/evolution/test/campaign-hardening.test.ts new file mode 100644 index 0000000..cf3ae34 --- /dev/null +++ b/packages/evolution/test/campaign-hardening.test.ts @@ -0,0 +1,1390 @@ +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { + chmodSync, + existsSync, + linkSync, + lstatSync, + mkdirSync, + mkdtempSync, + readFileSync, + realpathSync, + rmSync, + symlinkSync, + writeFileSync, +} from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import test from 'node:test'; +import type { DecisionTransport } from '@loopwright/decisions'; +import { runHardwareWorker, startRelayServer } from '@loopwright/hardware-runner'; +import { loadDeclarativeTaskpack } from '@loopwright/taskpack'; +import { + buildStageScopedTaskpack, + collectChildBenchmarkArtifacts, + createControllerChildRunEvaluator, + EvolutionCampaignStore, + EvolutionError, + exportEvolutionBundle, + inspectEvolutionCampaign, + materializeGitCheckoutNoFollow, + parseEvolutionCampaignDocument, + resumeEvolutionCampaign, + runEvolutionCampaign, + sanitizeRunId, + stageMultiParentContextFiles, + type EvolutionBundleManifestV1, + type TeamPatchV1, +} from '../src/index.js'; + +const HMAC_SECRET = 'hardening-relay-hmac-secret-0123456789abcdef'; +const WORKER_TOKEN = 'hardening-worker-bearer-token-0123456789abcdef'; + +function sha256Hex(data: Uint8Array | string): string { + return createHash('sha256').update(data).digest('hex'); +} + +function makeDigest(seed: string): { readonly algorithm: 'sha256'; readonly hex: string } { + return { algorithm: 'sha256', hex: sha256Hex(seed) }; +} + +function initGitRepo( + repoDir: string, + files: Readonly>, +): string { + mkdirSync(repoDir, { recursive: true, mode: 0o700 }); + for (const [relPath, entry] of Object.entries(files)) { + const absPath = join(repoDir, relPath); + mkdirSync(join(absPath, '..'), { recursive: true, mode: 0o700 }); + writeFileSync(absPath, entry.content, { mode: entry.executable ? 0o755 : 0o644 }); + if (entry.executable) chmodSync(absPath, 0o755); + } + const gitEnv = { + ...process.env, + GIT_AUTHOR_NAME: 'Loopwright Test', + GIT_AUTHOR_EMAIL: 'test@loopwright.dev', + GIT_COMMITTER_NAME: 'Loopwright Test', + GIT_COMMITTER_EMAIL: 'test@loopwright.dev', + }; + execFileSync('git', ['init', '-b', 'main'], { cwd: repoDir, env: gitEnv, stdio: 'ignore' }); + execFileSync('git', ['add', '.'], { cwd: repoDir, env: gitEnv, stdio: 'ignore' }); + execFileSync('git', ['commit', '-m', 'Initial baseline'], { cwd: repoDir, env: gitEnv, stdio: 'ignore' }); + return execFileSync('git', ['rev-parse', 'HEAD'], { cwd: repoDir, env: gitEnv, encoding: 'utf8' }).trim(); +} + +function buildMinimalElf64(symbolName: string): Buffer { + const strTab = Buffer.concat([Buffer.from([0]), Buffer.from(`${symbolName}\0`, 'utf8')]); + const symTab = Buffer.alloc(48, 0); + symTab.writeUInt32LE(1, 24); + symTab.writeUInt8(0x12, 28); + const shStrTab = Buffer.from('\0.strtab\0.symtab\0.shstrtab\0', 'utf8'); + const shStrOffsets = [1, 9, 17]; + 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(4, 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); +} + +const KERNEL_SRC = [ + '// header', + '// EVOLVE-BLOCK-START: decode', + 'int decode_kernel() { return 0; }', + '// EVOLVE-BLOCK-END: decode', + '', +].join('\n'); + +const MULTI_CELL_TASKPACK_YAML = ` +apiVersion: loopwright.dev/v1alpha1 +kind: Taskpack +metadata: + name: hardening-taskpack +spec: + goal: + candidate: Optimize decode kernel inside EVOLVE-BLOCK. + noChange: No kernel change. + target: + matrix: + - id: cuda-h100-whole + platform: linux/amd64 + variant: cuda12 + hardware: + accelerator: sm_90a + isolationMode: whole_device + deviceCount: 1 + driverConstraint: ">=550.54" + forbiddenSymbolPatterns: [cublas] + - id: rocm-mi300x-whole + platform: linux/amd64 + variant: rocm6 + hardware: + accelerator: gfx942 + isolationMode: whole_device + deviceCount: 1 + scope: + writable: + - src/kernels/** + protected: + - scripts/** + models: + - provider: anthropic + id: claude-sonnet-4-6 + thinking: medium + - provider: openai + id: gpt-5.4 + thinking: high + roles: + - id: mutator + provider: anthropic + model: claude-sonnet-4-6 + purpose: task + tools: [read, write, edit, bash] + instructions: + - docs/role-guide.md + prompt: Edit kernel inside EVOLVE-BLOCK. + - id: reviewer + provider: anthropic + model: claude-sonnet-4-6 + purpose: review + dependsOn: [mutator] + tools: [read] + prompt: Review kernel diff. + verification: + localChecks: + - id: evolve-guard + implementation: evolve-block-guard.v1 + parameters: + files: + - src/kernels/decode.cu + externalGates: + - id: gpu-bench-cuda + implementation: benchmark-gate.v1 + endpointId: hw-relay + gateId: decode-cuda-bench + required: true + targetCellId: cuda-h100-whole + heldOutWorkloadId: cuda-default-workload + allowSyntheticHardwareProbe: true + - id: gpu-bench-rocm + implementation: benchmark-gate.v1 + endpointId: hw-relay + gateId: decode-rocm-bench + required: false + targetCellId: rocm-mi300x-whole + heldOutWorkloadId: rocm-untouched-workload + allowSyntheticHardwareProbe: true + publication: + mode: disabled + triggers: + schedule: false + workflowDispatch: true + releasePublished: false + commentCommands: [] +`; + +const BASE_CAMPAIGN_YAML = ` +apiVersion: loopwright.dev/v1alpha1 +kind: EvolutionCampaign +metadata: + name: hardening-campaign +spec: + taskpack: .loopwright/taskpack.yaml + targetCellId: cuda-h100-whole + tracks: [triton, tilelang] + stages: + mode: single-target + population: + islands: 2 + migrationIntervalGenerations: 2 + maxMigrationElites: 1 + nicheAxes: + - id: bound_pipeline + kind: enum + values: [hbm, l2, smem_lds_ub, tensor_cube] + sampling: + noveltyDecayLambda: 1.0 + mutationWeights: + diff_tune: 0.4 + full_rewrite: 0.2 + crossover: 0.4 + modelBandit: deterministic-round-robin + maxCrossoversPerPrompt: 2 + objectives: + - metric: latency_us_p50 + direction: minimize + - metric: goodput_rps + direction: maximize + budgets: + maxGenerations: 2 + maxEvaluations: 4 + maxConcurrentEvaluations: 2 + scratchpadIntervalGenerations: 1 +`; + +test('sanitizeRunId emits controller-valid lowercase <= 64-char IDs and preserves trailing hex nonces', () => { + const controllerRe = /^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/; + + const upperColon = sanitizeRunId('ind-g1-i0-Decode_BS16:4k-a1b2c3'); + assert.match(upperColon, controllerRe); + assert.equal(upperColon, upperColon.toLowerCase()); + assert.ok(upperColon.endsWith('-a1b2c3')); + + const leadingDigit = sanitizeRunId('99-Bucket:Upper'); + assert.match(leadingDigit, controllerRe); + + const reserved = sanitizeRunId('__proto__'); + assert.match(reserved, controllerRe); + assert.notEqual(reserved, '__proto__'); + + const longBucket = 'Decode_BS128_ISL32768_FP8_PagedKV_SplitK_Persistent_Cluster_90a'; + const idA = sanitizeRunId(`ind-g12-i3-${longBucket}-deadbeef`); + const idB = sanitizeRunId(`ind-g12-i3-${longBucket}-cafebabe`); + assert.ok(idA.length <= 64); + assert.ok(idB.length <= 64); + assert.match(idA, controllerRe); + assert.match(idB, controllerRe); + assert.ok(idA.endsWith('-deadbeef')); + assert.ok(idB.endsWith('-cafebabe')); + assert.notEqual(idA, idB); +}); + +test('buildStageScopedTaskpack scopes heldOutWorkloadId strictly to targetCellId, resolves cross-provider models, and tampered team_configs fail closed on reload', async () => { + const tempDir = mkdtempSync(join(tmpdir(), 'evo-hardening-scoped-')); + try { + const taskpack = await loadDeclarativeTaskpack({ + bytes: Buffer.from(MULTI_CELL_TASKPACK_YAML, 'utf8'), + format: 'yaml', + executionMode: 'delegated', + allowLoopbackHttp: true, + }); + + const patch: TeamPatchV1 = { + kind: 'TeamPatch', + schemaVersion: 'team-patch.v1', + diagnosis: { + summary: 'Test scoped taskpack', + plateauCategory: 'coupled_responsibilities', + rationale: 'Verify thinking, timeoutSeconds, onRework, and targetCellId scoping', + }, + roles: [ + { + id: 'mutator-fast', + archetypeRoleId: 'mutator', + purpose: 'task', + tools: ['read', 'edit'], + model: 'gpt-5.4', + thinking: 'low', + timeoutSeconds: 75, + prompt: 'Edit kernel.', + }, + { + id: 'rev-gate', + archetypeRoleId: 'reviewer', + purpose: 'review', + tools: ['read'], + model: 'claude-sonnet-4-6', + thinking: 'high', + timeoutSeconds: 30, + prompt: 'Check diff.', + }, + ], + steps: [ + { id: 'step-mut', roleId: 'mutator-fast', dependsOn: [] }, + { + id: 'step-rev', + roleId: 'rev-gate', + dependsOn: ['step-mut'], + onRework: { rejectTo: 'step-mut', maxReworks: 2 }, + }, + ], + }; + + const scoped = buildStageScopedTaskpack({ + taskpack, + heldOutWorkloadId: 'specialist-cuda-bs1', + targetCellId: 'cuda-h100-whole', + teamPatch: patch, + }); + + const cudaGate = scoped.spec.verification.externalGates.find(g => g.id === 'gpu-bench-cuda'); + const rocmGate = scoped.spec.verification.externalGates.find(g => g.id === 'gpu-bench-rocm'); + assert.equal(cudaGate?.heldOutWorkloadId, 'specialist-cuda-bs1'); + assert.equal(rocmGate?.heldOutWorkloadId, 'rocm-untouched-workload', 'non-target cell gate must NEVER be overwritten'); + + const mutatorFast = scoped.spec.roles?.find(r => r.id === 'mutator-fast'); + const revGate = scoped.spec.roles?.find(r => r.id === 'rev-gate'); + assert.equal(mutatorFast?.provider, 'openai', 'cross-provider role.model must resolve provider from Taskpack.spec.models'); + assert.equal(mutatorFast?.model, 'gpt-5.4'); + assert.equal(mutatorFast?.thinking, 'low'); + assert.equal(revGate?.provider, 'anthropic'); + assert.equal(revGate?.model, 'claude-sonnet-4-6'); + assert.equal(revGate?.thinking, 'high'); + assert.equal(scoped.spec.limits?.toolTimeoutSeconds, 75); + assert.deepEqual( + scoped.spec.steps?.find(s => s.id === 'step-rev')?.onRework, + { rejectTo: 'step-mut', maxReworks: 2 }, + ); + + // Explicit provider/model syntax in TeamPatch also resolves to bare model ID + matched provider + const scopedQualified = buildStageScopedTaskpack({ + taskpack, + heldOutWorkloadId: 'specialist-cuda-bs1', + targetCellId: 'cuda-h100-whole', + teamPatch: { + ...patch, + roles: [ + { ...patch.roles[0]!, model: 'openai/gpt-5.4' }, + patch.roles[1]!, + ], + }, + }); + const qualifiedMutator = scopedQualified.spec.roles?.find(r => r.id === 'mutator-fast'); + assert.equal(qualifiedMutator?.provider, 'openai'); + assert.equal(qualifiedMutator?.model, 'gpt-5.4'); + + // Reloading a tampered team_configs patch from campaign.sqlite MUST fail closed with TEAM_ENVELOPE_VIOLATION! + const repoDir = join(tempDir, 'repo'); + const baseRevision = initGitRepo(repoDir, { + '.loopwright/taskpack.yaml': { content: MULTI_CELL_TASKPACK_YAML }, + 'docs/role-guide.md': { content: '# Role Guide\nKeep coalesced loads.\n' }, + 'src/kernels/decode.cu': { content: KERNEL_SRC }, + }); + const campaignRoot = join(tempDir, 'camp-tamper-team'); + const abortAfter1 = new AbortController(); + + await runEvolutionCampaign({ + campaignRoot, + campaignId: 'camp-tamper-team', + manifest: BASE_CAMPAIGN_YAML.replace('islands: 2', 'islands: 1'), + repositoryRoot: repoDir, + baseRevision, + signal: abortAfter1.signal, + evaluator: async () => { + abortAfter1.abort(); + return { + status: 'passed', + codeSlice: '// EVOLVE-BLOCK-START: decode\nint decode_kernel() { return 1; }\n// EVOLVE-BLOCK-END: decode\n', + metrics: { latency_us_p50: 50, goodput_rps: 2000 }, + evidenceDigest: makeDigest('ev-1'), + }; + }, + }); + + // Inject a rogue TeamPatch into campaign.sqlite CAS and activate it on Island 0 while teamEvolution is NOT enabled! + const store = await EvolutionCampaignStore.open({ campaignRoot }); + const lease = await store.acquireLease('tamper-writer'); + const incumbentIsl0 = (await store.getIsland('camp-tamper-team', 0))!; + const roguePatchBytes = Buffer.from( + JSON.stringify({ + ...patch, + roles: [ + { + id: 'rogue-role', + archetypeRoleId: 'reviewer', + purpose: 'task', + tools: ['read', 'write', 'delete'], + prompt: 'Escalate tools beyond reviewer archetype.', + }, + ], + steps: [{ id: 'step-rogue', roleId: 'rogue-role', dependsOn: [] }], + }), + 'utf8', + ); + const rogueCas = await store.writeCasBlob(roguePatchBytes); + await store.createTrialTeamConfig(lease, { + teamConfigId: 'rogue-team-cfg', + campaignId: 'camp-tamper-team', + islandId: 0, + parentTeamConfigId: incumbentIsl0.activeTeamConfigId, + createdGeneration: 1, + trialBudgetGenerations: 2, + diagnosis: { + summary: 'Tampered team config injected into SQLite', + plateauCategory: 'other', + rationale: 'Must be rejected on campaign reload', + }, + patchCasDigest: rogueCas.digest, + }); + await store.close(); + + // 1. Fails when teamEvolution.enabled !== true + await assert.rejects( + () => resumeEvolutionCampaign({ + campaignRoot, + campaignId: 'camp-tamper-team', + repositoryRoot: repoDir, + evaluator: async () => ({ + status: 'passed', + codeSlice: '// never reached\n', + metrics: { latency_us_p50: 40, goodput_rps: 2200 }, + }), + }), + (err: unknown) => err instanceof EvolutionError && err.code === 'TEAM_ENVELOPE_VIOLATION', + ); + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } +}); + +test('refuses overlapping campaignRoot/repositoryRoot and materializes Git checkouts cleanly around untracked node_modules/.bin symlinks while refusing tracked symlinks', async () => { + const tempDir = mkdtempSync(join(realpathSync(tmpdir()), 'evo-hardening-checkout-')); + try { + const repoDir = join(tempDir, 'repo'); + initGitRepo(repoDir, { + '.loopwright/taskpack.yaml': { content: MULTI_CELL_TASKPACK_YAML }, + 'docs/role-guide.md': { content: '# Guide\n' }, + 'src/kernels/decode.cu': { content: KERNEL_SRC }, + 'scripts/build.sh': { content: '#!/bin/sh\nexit 0\n', executable: true }, + }); + + // Add untracked node_modules/.bin/tsc symlink inside repoDir! + mkdirSync(join(repoDir, 'node_modules', 'typescript', 'bin'), { recursive: true }); + mkdirSync(join(repoDir, 'node_modules', '.bin'), { recursive: true }); + writeFileSync(join(repoDir, 'node_modules', 'typescript', 'bin', 'tsc'), '#!/usr/bin/env node\n'); + symlinkSync('../typescript/bin/tsc', join(repoDir, 'node_modules', '.bin', 'tsc')); + + // 1. Overlapping campaignRoot inside repositoryRoot -> EVOLUTION_SCHEMA_INVALID before creating campaign.sqlite + const nestedCampaignRoot = join(repoDir, '.loopwright-campaign'); + await assert.rejects( + () => runEvolutionCampaign({ + campaignRoot: nestedCampaignRoot, + manifest: BASE_CAMPAIGN_YAML, + repositoryRoot: repoDir, + evaluator: async () => ({ status: 'passed', codeSlice: '', metrics: {} }), + }), + (err: unknown) => + err instanceof EvolutionError + && err.code === 'EVOLUTION_SCHEMA_INVALID' + && /campaignRoot must live outside repositoryRoot/.test(err.message), + ); + assert.equal(existsSync(nestedCampaignRoot), false); + + // Also reject repositoryRoot inside campaignRoot and equal roots on resumeEvolutionCampaign + await assert.rejects( + () => resumeEvolutionCampaign({ + campaignRoot: tempDir, + repositoryRoot: repoDir, + evaluator: async () => ({ status: 'passed', codeSlice: '', metrics: {} }), + }), + (err: unknown) => err instanceof EvolutionError && err.code === 'EVOLUTION_SCHEMA_INVALID', + ); + + // 2. materializeGitCheckoutNoFollow succeeds cleanly despite node_modules/.bin/tsc symlink and preserves 0o755 mode + const checkoutDst = join(tempDir, 'materialized-checkout'); + await materializeGitCheckoutNoFollow(repoDir, checkoutDst); + assert.equal(existsSync(join(checkoutDst, 'src', 'kernels', 'decode.cu')), true); + assert.equal(existsSync(join(checkoutDst, 'node_modules')), false); + assert.equal(lstatSync(join(checkoutDst, 'scripts', 'build.sh')).mode & 0o111, 0o111); + + // 3. Tracked symlink committed to Git MUST be refused with EVOLUTION_SYMLINK_FORBIDDEN + const badRepoDir = join(tempDir, 'bad-symlink-repo'); + initGitRepo(badRepoDir, { + 'README.md': { content: 'hi\n' }, + }); + symlinkSync('README.md', join(badRepoDir, 'tracked-link.md')); + const gitEnv = { + ...process.env, + GIT_AUTHOR_NAME: 'Loopwright Test', + GIT_AUTHOR_EMAIL: 'test@loopwright.dev', + GIT_COMMITTER_NAME: 'Loopwright Test', + GIT_COMMITTER_EMAIL: 'test@loopwright.dev', + }; + execFileSync('git', ['add', 'tracked-link.md'], { cwd: badRepoDir, env: gitEnv, stdio: 'ignore' }); + execFileSync('git', ['commit', '-m', 'Add tracked symlink'], { cwd: badRepoDir, env: gitEnv, stdio: 'ignore' }); + + await assert.rejects( + () => materializeGitCheckoutNoFollow(badRepoDir, join(tempDir, 'bad-checkout')), + (err: unknown) => err instanceof EvolutionError && err.code === 'EVOLUTION_SYMLINK_FORBIDDEN', + ); + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } +}); + +test('concurrent child evaluator never mutates process.env, preserves evo-parent-* & evo-scratchpad in role.resourceIds, rejects cosmetic clone BEFORE benchmark-gate.v1 dispatch, and forwards driverConstraint', async () => { + const tempDir = mkdtempSync(join(realpathSync(tmpdir()), 'evo-hardening-child-')); + const relayCasDir = join(tempDir, 'relay-cas'); + const workerWorkDir = join(tempDir, 'worker-work'); + const workloadsDir = join(tempDir, 'workloads'); + mkdirSync(workerWorkDir, { recursive: true, mode: 0o700 }); + mkdirSync(join(workloadsDir, 'cuda-default-workload'), { recursive: true, mode: 0o700 }); + + const evalScript = [ + `#!${process.execPath}`, + 'const payload = {', + ' status: "approved",', + ' metrics: { latency_us_p50: 40, goodput_rps: 2500 },', + ' hardwareDiagnostics: { boundPipeline: "tensor_cube", occupancyPct: 75, rooflineHeadroom: 1.15 }', + '};', + 'process.stdout.write("LOOPWRIGHT_STAGE_B_RESULT:" + JSON.stringify(payload) + "\\n");', + ].join('\n'); + const evalScriptPath = join(workloadsDir, 'cuda-default-workload', 'evaluate.sh'); + writeFileSync(evalScriptPath, evalScript, { mode: 0o755 }); + chmodSync(evalScriptPath, 0o755); + + const cubinHex = buildMinimalElf64('decode_sm90a_kernel').toString('hex'); + const buildScript = [ + `#!${process.execPath}`, + 'const fs = require("node:fs");', + 'const path = require("node:path");', + `fs.writeFileSync(path.join(process.env.LOOPWRIGHT_STAGE_A_OUT, "decode.cubin"), Buffer.from(${JSON.stringify(cubinHex)}, "hex"));`, + ].join('\n'); + + const relay = await startRelayServer({ + port: 0, + casDir: relayCasDir, + controllerSigningSecret: HMAC_SECRET, + workerTokens: [WORKER_TOKEN], + leaseTtlMs: 30_000, + sweepIntervalMs: 200, + }); + + let workerLeases = 0; + const workerAbort = new AbortController(); + const workerPromise = runHardwareWorker({ + config: { + workerId: 'worker-hardening', + relayUrl: relay.url, + workerToken: WORKER_TOKEN, + workDir: workerWorkDir, + heldOutWorkloadsDir: workloadsDir, + sandboxBackend: 'native_os', + capabilities: { + accelerator: 'sm_90a', + isolationModes: ['whole_device'], + deviceCount: 1, + driverVersion: '555.42.02', + workloadIds: ['cuda-default-workload'], + }, + pollWaitMs: 50, + heartbeatIntervalMs: 50, + requestTimeoutMs: 10_000, + stageATimeoutMs: 45_000, + stageBTimeoutMs: 45_000, + toolchainPaths: [join(process.execPath, '..')], + probeMode: 'synthetic_fixture', + }, + once: false, + signal: workerAbort.signal, + registerProcessSignalHandlers: false, + onLeaseAcquired: () => { + workerLeases += 1; + }, + }).catch(() => undefined); + + const secretEnvVarName = 'LW_ISOLATED_TEST_SIGNING_KEY_SC2'; + assert.equal(process.env[secretEnvVarName], undefined); + + try { + const repoDir = join(tempDir, 'repo'); + const singleGateTaskpack = MULTI_CELL_TASKPACK_YAML.slice( + 0, + MULTI_CELL_TASKPACK_YAML.indexOf(' - id: gpu-bench-rocm'), + ) + MULTI_CELL_TASKPACK_YAML.slice(MULTI_CELL_TASKPACK_YAML.indexOf(' publication:')); + + const baseRevision = initGitRepo(repoDir, { + '.loopwright/taskpack.yaml': { content: singleGateTaskpack }, + 'docs/role-guide.md': { content: '# Role Guide\nUse vectorized loads.\n' }, + 'src/kernels/decode.cu': { content: KERNEL_SRC }, + 'scripts/build.sh': { content: buildScript, executable: true }, + }); + // Also place an untracked node_modules/.bin symlink inside repoDir to prove createControllerChildRunEvaluator handles it! + mkdirSync(join(repoDir, 'node_modules', '.bin'), { recursive: true }); + symlinkSync('../../scripts/build.sh', join(repoDir, 'node_modules', '.bin', 'fake-bin')); + + const bundleRelDir = '.loopwright-out/bundles/hardening'; + const bundleOutDir = join(repoDir, bundleRelDir); + const campaignYaml = `${BASE_CAMPAIGN_YAML} export:\n format: dir\n outputDir: ${bundleRelDir}\n`; + + let sawParentContextInAgent = false; + let sawScratchpadInAgent = false; + let sawProcessEnvMutation = false; + + const evaluator = createControllerChildRunEvaluator({ + repositoryRoot: repoDir, + allowLoopbackHttp: true, + gateEndpoints: [ + { + id: 'hw-relay', + url: `${relay.url}/v1/benchmark/jobs`, + signingCredentialRef: 'bench-sign', + implementation: 'benchmark-gate.v1', + timeoutMs: 10_000, + maxPollMs: 120_000, + pollInitialMs: 100, + pollMaxMs: 250, + jitter: 10, + }, + ], + credentialEnvMap: { + byCredentialRef: { 'bench-sign': secretEnvVarName }, + }, + environment: name => (name === secretEnvVarName ? HMAC_SECRET : undefined), + agentDriver: async ctx => { + if (process.env[secretEnvVarName] !== undefined) { + sawProcessEnvMutation = true; + } + for (const cf of ctx.contextFiles) { + if (cf.includes('parent-0.json')) sawParentContextInAgent = true; + if (cf.includes('latest.md')) sawScratchpadInAgent = true; + } + const kernelPath = join(ctx.workspacePath, 'src/kernels/decode.cu'); + if (ctx.generation === 1) { + writeFileSync( + kernelPath, + KERNEL_SRC.replace('return 0;', `return ${10 + ctx.islandId};`), + 'utf8', + ); + } else if (ctx.islandId === 0) { + // Gen 2 Island 0: cosmetic comment/whitespace clone of Gen 1 Island 0 (return 10;) -> MUST be rejected BEFORE benchmark-gate.v1! + writeFileSync( + kernelPath, + '// header\n// EVOLVE-BLOCK-START: decode\n/* cosmetic comment */\nint decode_kernel( ) {\n return 10; // exact token clone\n}\n// EVOLVE-BLOCK-END: decode\n', + 'utf8', + ); + } else { + // Gen 2 Island 1: genuinely novel mutation -> dispatches benchmark-gate.v1 + writeFileSync( + kernelPath, + KERNEL_SRC.replace('return 0;', 'return 99; /* novel_gen2 */'), + 'utf8', + ); + } + }, + }); + + const campaignRoot = join(tempDir, 'campaign-run'); + const res = await runEvolutionCampaign({ + campaignRoot, + campaignId: 'camp-sc2-sh3-pm2', + manifest: campaignYaml, + repositoryRoot: repoDir, + baseRevision, + evaluator, + allowSyntheticProbe: true, + receiptSigningSecret: HMAC_SECRET, + }); + + // Zero process.env mutation during or after concurrent child runs + assert.equal(sawProcessEnvMutation, false); + assert.equal(process.env[secretEnvVarName], undefined); + + // evo-parent-0 and evo-scratchpad are preserved in role.resourceIds despite role-level instructions + assert.equal(sawParentContextInAgent, true, 'evo-parent-0 must be exposed in contextFiles when role.instructions is set'); + assert.equal(sawScratchpadInAgent, true, 'evo-scratchpad must be exposed in contextFiles when role.instructions is set'); + + // Gen 1 ran 2 worker leases (Island 0 + Island 1); Gen 2 Island 0 clone was rejected pre-gate (0 leases), Gen 2 Island 1 ran 1 lease -> total 3 leases + assert.equal(res.noveltyRejectionsCount, 1); + assert.equal(workerLeases, 3, 'cosmetic clone must be rejected BEFORE benchmark-gate.v1 acquires any worker lease'); + assert.equal(res.campaign.evaluationsUsed, 3); + + // Auto-exported bundle carries hardware.driverConstraint (">=550.54") in compatibility + assert.ok(res.exportedBundle !== undefined); + const bundleManifest = JSON.parse( + readFileSync(join(bundleOutDir, 'manifest.json'), 'utf8'), + ) as EvolutionBundleManifestV1; + assert.equal(bundleManifest.compatibility.driverConstraint, '>=550.54'); + + await res.store.close(); + } finally { + workerAbort.abort(); + await workerPromise; + await relay.close(); + rmSync(tempDir, { recursive: true, force: true }); + } +}); + +test('specialist-then-portfolio supports 5..64 specialist buckets and resets per-island roofline/stall state across buckets', async () => { + const tempDir = mkdtempSync(join(tmpdir(), 'evo-hardening-buckets-')); + try { + // Verify stageMultiParentContextFiles still enforces <= 4 crossover donors + await assert.rejects( + () => stageMultiParentContextFiles({ + stagingDir: join(tempDir, 'bad-crossover'), + maxCrossoversPerPrompt: 5, + parents: [], + }), + (err: unknown) => err instanceof EvolutionError && err.code === 'EVOLUTION_SCHEMA_INVALID', + ); + + const repoDir = join(tempDir, 'repo'); + const baseRevision = initGitRepo(repoDir, { + '.loopwright/taskpack.yaml': { content: MULTI_CELL_TASKPACK_YAML }, + 'docs/role-guide.md': { content: '# Guide\n' }, + 'src/kernels/decode.cu': { content: KERNEL_SRC }, + }); + + // 5 specialist buckets + teamEvolution + targetRooflineHeadroom = 1.10 + // Bucket 0 hits headroom 1.05 (<= 1.10); Bucket 1 stalls for 2 generations with headroom 1.45 -> supervisor MUST fire in Bucket 1! + const fiveBucketYaml = ` +apiVersion: loopwright.dev/v1alpha1 +kind: EvolutionCampaign +metadata: + name: five-bucket-portfolio +spec: + taskpack: .loopwright/taskpack.yaml + targetCellId: cuda-h100-whole + stages: + mode: specialist-then-portfolio + specialistBuckets: + - id: bucket-0 + heldOutWorkloadId: wl-0 + - id: bucket-1 + heldOutWorkloadId: wl-1 + - id: bucket-2 + heldOutWorkloadId: wl-2 + - id: bucket-3 + heldOutWorkloadId: wl-3 + - id: bucket-4 + heldOutWorkloadId: wl-4 + portfolioHeldOutWorkloadId: wl-portfolio + 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 + maxCrossoversPerPrompt: 1 + teamEvolution: + enabled: true + supervisorRoleId: reviewer + allowedArchetypeRoles: [mutator, reviewer] + stallGenerations: 2 + minHypervolumeDelta: 0.01 + triggerOnRunEvalPathology: false + trialGenerations: 2 + maxTeamSize: 2 + maxTeamSteps: 2 + objectives: + - metric: latency_us_p50 + direction: minimize + budgets: + maxGenerations: 16 + maxEvaluations: 25 + maxConcurrentEvaluations: 1 + targetRooflineHeadroom: 1.10 + scratchpadIntervalGenerations: 10 +`; + + const supervisorBucketsObserved: Array = []; + let observedPortfolioParentFiles = 0; + + const res = await runEvolutionCampaign({ + campaignRoot: join(tempDir, 'camp-5buckets'), + campaignId: 'camp-5buckets', + manifest: fiveBucketYaml, + repositoryRoot: repoDir, + baseRevision, + supervisorRunner: async ctx => { + supervisorBucketsObserved.push(ctx.island.bestRooflineHeadroom !== null ? String(ctx.island.bestRooflineHeadroom) : 'null'); + return JSON.stringify({ + kind: 'TeamPatch', + schemaVersion: 'team-patch.v1', + diagnosis: { + summary: 'Bucket 1 stalled after Bucket 0 hit roofline', + plateauCategory: 'coupled_responsibilities', + rationale: 'Verify per-bucket reset allowed supervisor invocation in Bucket 1', + }, + roles: [ + { + id: 'mut-tuned', + archetypeRoleId: 'mutator', + purpose: 'task', + tools: ['read', 'edit'], + prompt: 'Tune bucket.', + }, + ], + steps: [{ id: 'step-mut-tuned', roleId: 'mut-tuned', dependsOn: [] }], + }); + }, + evaluator: async proposal => { + if (proposal.stagePhase === 'portfolio') { + observedPortfolioParentFiles = proposal.stagedParentFiles.length; + return { + status: 'passed', + codeSlice: '// EVOLVE-BLOCK-START: decode\nint decode_kernel() { return 555; }\n// EVOLVE-BLOCK-END: decode\n', + metrics: { latency_us_p50: 35 }, + hardwareDiagnostics: { boundPipeline: 'tensor_cube', rooflineHeadroom: 1.06 }, + evidenceDigest: makeDigest(`ev-${proposal.individualId}`), + }; + } + if (proposal.bucketId === 'bucket-0') { + // Hits targetRooflineHeadroom 1.05 <= 1.10 immediately in bucket-0! + return { + status: 'passed', + codeSlice: `// EVOLVE-BLOCK-START: decode\nint decode_kernel() { return ${100 + proposal.generation}; }\n// EVOLVE-BLOCK-END: decode\n`, + metrics: { latency_us_p50: 30 }, + hardwareDiagnostics: { boundPipeline: 'tensor_cube', rooflineHeadroom: 1.05 }, + evidenceDigest: makeDigest(`ev-${proposal.individualId}`), + }; + } + if (proposal.bucketId === 'bucket-1') { + // Stalls across its 2 generations (same latency 90, headroom 1.45 > 1.10) -> triggers supervisor on 2nd no-gain gen! + return { + status: 'passed', + codeSlice: `// EVOLVE-BLOCK-START: decode\nint decode_kernel() { return ${200 + proposal.generation}; }\n// EVOLVE-BLOCK-END: decode\n`, + metrics: { latency_us_p50: 90 }, + hardwareDiagnostics: { boundPipeline: 'hbm', rooflineHeadroom: 1.45 }, + evidenceDigest: makeDigest(`ev-${proposal.individualId}`), + }; + } + return { + status: 'passed', + codeSlice: `// EVOLVE-BLOCK-START: decode\nint decode_kernel() { return ${300 + proposal.generation}; }\n// EVOLVE-BLOCK-END: decode\n`, + metrics: { latency_us_p50: 45 }, + hardwareDiagnostics: { boundPipeline: 'tensor_cube', rooflineHeadroom: 1.05 }, + evidenceDigest: makeDigest(`ev-${proposal.individualId}`), + }; + }, + }); + + assert.equal(res.campaign.status, 'completed'); + assert.equal(observedPortfolioParentFiles, 5, 'stagePortfolioSpecialistContextFiles must stage all 5 specialist winners'); + assert.ok(supervisorBucketsObserved.length >= 1, 'bucket-0 roofline must NOT suppress plateau supervision in bucket-1'); + await res.store.close(); + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } +}); + +test('wires decisionPolicy/transport mutationKind & declaredTracks, caps >64 island history slices without crashing, and retains soft_passed stepping stones in MAP-Elites niches without exporting them', async () => { + const tempDir = mkdtempSync(join(tmpdir(), 'evo-hardening-decisions-')); + try { + const repoDir = join(tempDir, 'repo'); + const taskpackWithDecisions = MULTI_CELL_TASKPACK_YAML.replace( + ' publication:', + ' decisions:\n enabled: true\n provider: typesafe-jev\n disclosurePolicy: repo-approved-redacted-evidence\n publication:', + ); + const baseRevision = initGitRepo(repoDir, { + '.loopwright/taskpack.yaml': { content: taskpackWithDecisions }, + 'docs/role-guide.md': { content: '# Guide\n' }, + 'src/kernels/decode.cu': { content: KERNEL_SRC }, + }); + + const campaignRoot = join(tempDir, 'camp-decisions'); + let transportStrategyCalls = 0; + + // Mock System-One DecisionTransport returning 'tilelang' + 'crossover' when available + const mockTransport: DecisionTransport = { + send: async req => { + const body = JSON.parse(req.body) as { + questions: Record }>; + }; + const answers: Record = {}; + for (const [qId, q] of Object.entries(body.questions)) { + if (q.type === 'choice' && q.criteria !== undefined) { + transportStrategyCalls += 1; + const keys = Object.keys(q.criteria); + const pick = keys.includes('tilelang') + ? 'tilelang' + : (keys.includes('crossover') ? 'crossover' : keys[0]!); + const probabilities: Record = {}; + for (const k of keys) { + probabilities[k] = k === pick ? 1 : 0; + } + answers[qId] = { type: 'choice', choice: pick, confidence: 0.95, probabilities }; + } else if (q.type === 'noul') { + answers[qId] = { type: 'noul', noul: 0.05 }; + } + } + return { + status: 200, + body: JSON.stringify({ answers }), + }; + }, + }; + + const threeGenOneIslandYaml = BASE_CAMPAIGN_YAML + .replace('islands: 2', 'islands: 1') + .replace('maxGenerations: 2', 'maxGenerations: 3') + .replace('maxEvaluations: 4', 'maxEvaluations: 3'); + + const observedTracks: string[] = []; + const observedMutations: string[] = []; + + const res = await runEvolutionCampaign({ + campaignRoot, + campaignId: 'camp-pw1-pw2', + manifest: threeGenOneIslandYaml, + repositoryRoot: repoDir, + baseRevision, + decisionTransport: mockTransport, + decisionApiKey: 'test-jev-api-key-pw1', + evaluator: async proposal => { + observedTracks.push(proposal.trackId); + observedMutations.push(proposal.mutationKind); + if (proposal.generation === 1) { + // Gen 1: passed in hbm niche (latency 50) + return { + status: 'passed', + codeSlice: '// EVOLVE-BLOCK-START: decode\nint decode_kernel() { return 1; }\n// EVOLVE-BLOCK-END: decode\n', + metrics: { latency_us_p50: 50, goodput_rps: 2000 }, + hardwareDiagnostics: { boundPipeline: 'hbm', rooflineHeadroom: 1.4 }, + evidenceDigest: makeDigest('ev-g1'), + }; + } + if (proposal.generation === 2) { + // Gen 2: smokeMetrics severely regressed (500 vs parent 50) -> cascade prunes to soft_passed in smem_lds_ub niche! + return { + status: 'passed', + codeSlice: '// EVOLVE-BLOCK-START: decode\nint decode_kernel() { return 2; }\n// EVOLVE-BLOCK-END: decode\n', + metrics: { latency_us_p50: 85, goodput_rps: 1600 }, + smokeMetrics: { latency_us_p50: 500 }, + hardwareDiagnostics: { boundPipeline: 'smem_lds_ub', rooflineHeadroom: 1.5 }, + evidenceDigest: makeDigest('ev-g2'), + }; + } + // Gen 3: Island 0 now has 2 niches (hbm passed + smem_lds_ub soft_passed!) -> mockTransport picks crossover! + return { + status: 'passed', + codeSlice: '// EVOLVE-BLOCK-START: decode\nint decode_kernel() { return 3; }\n// EVOLVE-BLOCK-END: decode\n', + metrics: { latency_us_p50: 38, goodput_rps: 2600 }, + hardwareDiagnostics: { boundPipeline: 'tensor_cube', rooflineHeadroom: 1.12 }, + evidenceDigest: makeDigest('ev-g3'), + }; + }, + }); + + assert.ok(transportStrategyCalls >= 2, 'taskpack.spec.decisions + decisionTransport must invoke System-One router'); + assert.ok(observedTracks.every(t => t === 'triton' || t === 'tilelang'), 'tracks must be restricted to manifest.spec.tracks'); + assert.ok(observedTracks.includes('tilelang')); + assert.equal(res.cascadeSoftStopsCount, 1); + assert.equal(observedMutations[2], 'crossover', 'Gen 3 must honor strategyDecision.mutationKind === crossover using soft_passed second niche!'); + + const inspected = await inspectEvolutionCampaign({ campaignRoot, campaignId: 'camp-pw1-pw2' }); + const isl0Elites = inspected.nicheArchives.find(a => a.islandId === 0)!.elites; + assert.equal(isl0Elites.some(e => e.status === 'soft_passed' && e.nicheKey === 'bound_pipeline=smem_lds_ub'), true); + assert.equal(inspected.paretoFrontier.every(e => e.status === 'passed'), true); + + // Seed 70 passed individuals on Island 0 (> 64 DECISION_NOVELTY_MAX_HISTORY_SLICES) and resume without overflowing novelty history cap + await res.store.close(); + + const seventyRoot = join(tempDir, 'camp-70-slices'); + const seventyYaml = BASE_CAMPAIGN_YAML + .replace('islands: 2', 'islands: 1') + .replace('maxGenerations: 2', 'maxGenerations: 2') + .replace('maxEvaluations: 4', 'maxEvaluations: 2'); + const abortGen1 = new AbortController(); + const first70 = await runEvolutionCampaign({ + campaignRoot: seventyRoot, + campaignId: 'camp-70', + manifest: seventyYaml, + repositoryRoot: repoDir, + baseRevision, + signal: abortGen1.signal, + proposeCandidateSlice: async () => + '// EVOLVE-BLOCK-START: decode\nint decode_kernel() { return 1; }\n// EVOLVE-BLOCK-END: decode\n', + evaluator: async p => { + abortGen1.abort(); + return { + status: 'passed', + codeSlice: p.proposedCodeSlice ?? '', + metrics: { latency_us_p50: 50, goodput_rps: 2000 }, + evidenceDigest: makeDigest('ev-70-1'), + }; + }, + }); + const l70 = await first70.store.acquireLease('seed-70-b'); + const team70Id = (await first70.store.getIsland('camp-70', 0))!.activeTeamConfigId; + for (let k = 0; k < 70; k += 1) { + const sc = await first70.store.writeCasBlob( + Buffer.from(`// EVOLVE-BLOCK-START: decode\nint decode_kernel() { return ${5000 + k}; }\n// EVOLVE-BLOCK-END: decode\n`, 'utf8'), + ); + await first70.store.recordIndividual(l70, { + individualId: `ind-seed70-${k}`, + campaignId: 'camp-70', + islandId: 0, + generation: 1, + bucketId: null, + teamConfigId: team70Id, + modelId: 'claude-sonnet-4-6', + trackId: 'triton', + mutationKind: 'diff_tune', + status: 'passed', + failureReason: null, + nicheKey: 'bound_pipeline=hbm', + paretoRank: 2, + crowdingDistance: 0, + scalarFitness: 0.5, + countEvaluation: false, + codeSliceCasDigest: sc.digest, + evidenceDigest: makeDigest(`ev-s70-${k}`), + verdictReceiptCasDigest: null, + outputArtifacts: [], + metrics: { latency_us_p50: 60, goodput_rps: 1900 }, + }); + } + await first70.store.close(); + + const resumed70 = await resumeEvolutionCampaign({ + campaignRoot: seventyRoot, + campaignId: 'camp-70', + repositoryRoot: repoDir, + proposeCandidateSlice: async () => + '// EVOLVE-BLOCK-START: decode\nint decode_kernel() { return 9999; }\n// EVOLVE-BLOCK-END: decode\n', + evaluator: async p => ({ + status: 'passed', + codeSlice: p.proposedCodeSlice ?? '', + metrics: { latency_us_p50: 40, goodput_rps: 2400 }, + evidenceDigest: makeDigest('ev-70-2'), + }), + }); + assert.equal(resumed70.campaign.status, 'completed'); + + // Verify soft_passed-only campaign refuses exportEvolutionBundle with EXPORT_UNVERIFIED_FORBIDDEN + const softOnlyRoot = join(tempDir, 'camp-soft-only'); + const softRes = await runEvolutionCampaign({ + campaignRoot: softOnlyRoot, + campaignId: 'camp-soft-only', + manifest: BASE_CAMPAIGN_YAML + .replace('islands: 2', 'islands: 1') + .replace('maxGenerations: 2', 'maxGenerations: 1') + .replace('maxEvaluations: 4', 'maxEvaluations: 1') + .replace('maxConcurrentEvaluations: 2', 'maxConcurrentEvaluations: 1'), + repositoryRoot: repoDir, + baseRevision, + evaluator: async () => ({ + status: 'soft_passed', + failureReason: 'CASCADE_NOT_ESCALATED', + codeSlice: '// EVOLVE-BLOCK-START: decode\nint decode_kernel() { return 7; }\n// EVOLVE-BLOCK-END: decode\n', + metrics: { latency_us_p50: 80, goodput_rps: 1500 }, + }), + }); + await assert.rejects( + () => exportEvolutionBundle({ + store: softRes.store, + campaignId: 'camp-soft-only', + outputDir: join(tempDir, 'out-soft-denied'), + allowUnverifiedSignature: true, + }), + (err: unknown) => err instanceof EvolutionError && err.code === 'EXPORT_UNVERIFIED_FORBIDDEN', + ); + await softRes.store.close(); + await resumed70.store.close(); + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } +}); + +test('mid-generation SIGTERM resumes unfinished islands in same generation, evaluator throws close SQLite store cleanly, and collectChildBenchmarkArtifacts rejects symlinks/hardlinks/prototype keys', async () => { + const tempDir = mkdtempSync(join(tmpdir(), 'evo-hardening-resume-')); + try { + const repoDir = join(tempDir, 'repo'); + const baseRevision = initGitRepo(repoDir, { + '.loopwright/taskpack.yaml': { content: MULTI_CELL_TASKPACK_YAML }, + 'docs/role-guide.md': { content: '# Guide\n' }, + 'src/kernels/decode.cu': { content: KERNEL_SRC }, + }); + + // 1. Two islands, maxConcurrentEvaluations = 1; SIGTERM after Gen 1 Island 0 -> resume completes Gen 1 Island 1 without skipping Gen 1 or re-running Island 0 + const midGenRoot = join(tempDir, 'camp-midgen'); + const midGenYaml = BASE_CAMPAIGN_YAML.replace('maxConcurrentEvaluations: 2', 'maxConcurrentEvaluations: 1'); + const abortMid = new AbortController(); + const seenSlotsRun1: string[] = []; + + const firstHalf = await runEvolutionCampaign({ + campaignRoot: midGenRoot, + campaignId: 'camp-midgen', + manifest: midGenYaml, + repositoryRoot: repoDir, + baseRevision, + signal: abortMid.signal, + evaluator: async p => { + seenSlotsRun1.push(`g${p.generation}-i${p.islandId}`); + abortMid.abort(); + return { + status: 'passed', + codeSlice: `// EVOLVE-BLOCK-START: decode\nint decode_kernel() { return ${p.generation * 10 + p.islandId}; }\n// EVOLVE-BLOCK-END: decode\n`, + metrics: { latency_us_p50: 60, goodput_rps: 2000 }, + evidenceDigest: makeDigest(`ev-${p.individualId}`), + }; + }, + }); + assert.deepEqual(seenSlotsRun1, ['g1-i0']); + assert.equal(firstHalf.campaign.status, 'paused'); + assert.equal(firstHalf.campaign.currentGeneration, 0, 'interrupted Gen 1 must NOT advance currentGeneration to 1'); + await firstHalf.store.close(); + + const seenSlotsRun2: string[] = []; + const secondHalf = await resumeEvolutionCampaign({ + campaignRoot: midGenRoot, + campaignId: 'camp-midgen', + repositoryRoot: repoDir, + evaluator: async p => { + seenSlotsRun2.push(`g${p.generation}-i${p.islandId}`); + return { + status: 'passed', + codeSlice: `// EVOLVE-BLOCK-START: decode\nint decode_kernel() { return ${100 + p.generation * 10 + p.islandId}; }\n// EVOLVE-BLOCK-END: decode\n`, + metrics: { latency_us_p50: 50 - p.generation, goodput_rps: 2200 }, + evidenceDigest: makeDigest(`ev2-${p.individualId}`), + }; + }, + }); + assert.deepEqual(seenSlotsRun2, ['g1-i1', 'g2-i0', 'g2-i1']); + assert.equal(secondHalf.campaign.status, 'completed'); + assert.equal(secondHalf.campaign.evaluationsUsed, 4); + await secondHalf.store.close(); + + // 2. Throwing inside evaluator closes EvolutionCampaignStore cleanly so immediate reopen succeeds + const throwRoot = join(tempDir, 'camp-throw-close'); + await assert.rejects( + () => runEvolutionCampaign({ + campaignRoot: throwRoot, + campaignId: 'camp-throw', + manifest: midGenYaml, + repositoryRoot: repoDir, + baseRevision, + evaluator: async () => { + throw new Error('simulated evaluator crash'); + }, + }), + /simulated evaluator crash/, + ); + const reopenedAfterCrash = await EvolutionCampaignStore.open({ campaignRoot: throwRoot, createIfMissing: false }); + assert.equal((await reopenedAfterCrash.getCampaign('camp-throw'))?.campaignId, 'camp-throw'); + await reopenedAfterCrash.close(); + + // 3. collectChildBenchmarkArtifacts rejects symlink proof, hardlinked proof, and __proto__ keys + const artSymDir = join(tempDir, 'artifacts-symlink'); + mkdirSync(artSymDir, { recursive: true }); + const extProof = join(tempDir, 'external-proof.json'); + writeFileSync(extProof, '{"output":{"name":"out.json"}}\n'); + symlinkSync(extProof, join(artSymDir, 'benchmark-producer-01.proof.json')); + await assert.rejects( + () => collectChildBenchmarkArtifacts(artSymDir, true), + (err: unknown) => err instanceof EvolutionError && err.code === 'EVOLUTION_SYMLINK_FORBIDDEN', + ); + + const artHardDir = join(tempDir, 'artifacts-hardlink'); + mkdirSync(artHardDir, { recursive: true }); + const proofFile = join(artHardDir, 'benchmark-producer-01.proof.json'); + writeFileSync(proofFile, '{"output":null}\n'); + linkSync(proofFile, join(tempDir, 'hardlinked-proof.json')); + await assert.rejects( + () => collectChildBenchmarkArtifacts(artHardDir, true), + (err: unknown) => err instanceof EvolutionError && err.code === 'EVOLUTION_SYMLINK_FORBIDDEN', + ); + + const artProtoDir = join(tempDir, 'artifacts-proto'); + mkdirSync(artProtoDir, { recursive: true }); + writeFileSync( + join(artProtoDir, 'benchmark-producer-01.proof.json'), + '{"output":{"name":"bench-out.json"}}\n', + ); + writeFileSync( + join(artProtoDir, 'bench-out.json'), + '{"__proto__":{"polluted":true},"verdict":{"metrics":{"latency_us_p50":10}}}\n', + ); + await assert.rejects( + () => collectChildBenchmarkArtifacts(artProtoDir, true), + (err: unknown) => err instanceof EvolutionError && err.code === 'EVOLUTION_SCHEMA_INVALID', + ); + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } +}); + +test('heldOutWorkloadId enforces strict identifier schema, forwards single-target override to evaluator, and gates bundle export', async () => { + const tempDir = mkdtempSync(join(tmpdir(), 'evo-hardening-workload-id-')); + try { + // 1. Invalid heldOutWorkloadId values (leading digit, uppercase, colon) fail closed at parse time + for (const badId of ['16x4096', 'Decode_BS16', 'bs16:fp16']) { + assert.throws( + () => parseEvolutionCampaignDocument( + BASE_CAMPAIGN_YAML.replace('targetCellId: cuda-h100-whole', `targetCellId: cuda-h100-whole\n heldOutWorkloadId: "${badId}"`), + ), + (err: unknown) => err instanceof EvolutionError && err.code === 'EVOLUTION_SCHEMA_INVALID', + ); + assert.throws( + () => parseEvolutionCampaignDocument( + BASE_CAMPAIGN_YAML.replace( + ' stages:\n mode: single-target', + ` stages:\n mode: specialist-then-portfolio\n specialistBuckets:\n - id: bs16:fp16\n heldOutWorkloadId: valid-wl\n portfolioHeldOutWorkloadId: "${badId}"`, + ), + ), + (err: unknown) => err instanceof EvolutionError && err.code === 'EVOLUTION_SCHEMA_INVALID', + ); + } + + // 2. Top-level spec.heldOutWorkloadId is rejected under specialist-then-portfolio mode + assert.throws( + () => parseEvolutionCampaignDocument( + BASE_CAMPAIGN_YAML + .replace('targetCellId: cuda-h100-whole', 'targetCellId: cuda-h100-whole\n heldOutWorkloadId: single-override') + .replace( + ' stages:\n mode: single-target', + ' stages:\n mode: specialist-then-portfolio\n specialistBuckets:\n - id: bs16:fp16\n heldOutWorkloadId: valid-wl\n portfolioHeldOutWorkloadId: portfolio-wl', + ), + ), + (err: unknown) => err instanceof EvolutionError && err.code === 'EVOLUTION_SCHEMA_INVALID', + ); + + // 3. Bucket IDs with colons remain accepted while heldOutWorkloadId must be an identifier + const validPortfolio = parseEvolutionCampaignDocument( + BASE_CAMPAIGN_YAML.replace( + ' stages:\n mode: single-target', + ' stages:\n mode: specialist-then-portfolio\n specialistBuckets:\n - id: bs16:fp16\n heldOutWorkloadId: valid-wl-1\n portfolioHeldOutWorkloadId: portfolio-wl', + ), + ); + assert.equal(validPortfolio.spec.stages.mode, 'specialist-then-portfolio'); + + // 4. single-target spec.heldOutWorkloadId override is forwarded to evaluator and enforced at export + const repoDir = join(tempDir, 'repo'); + const baseRevision = initGitRepo(repoDir, { + '.loopwright/taskpack.yaml': { content: MULTI_CELL_TASKPACK_YAML }, + 'docs/role-guide.md': { content: '# Guide\n' }, + 'src/kernels/decode.cu': { content: KERNEL_SRC }, + }); + + const singleOverrideYaml = BASE_CAMPAIGN_YAML + .replace('targetCellId: cuda-h100-whole', 'targetCellId: cuda-h100-whole\n heldOutWorkloadId: full-sm90a-holdout') + .replace('islands: 2', 'islands: 1') + .replace('maxGenerations: 2', 'maxGenerations: 1') + .replace('maxEvaluations: 4', 'maxEvaluations: 1') + .replace('maxConcurrentEvaluations: 2', 'maxConcurrentEvaluations: 1'); + + const seenWorkloads: string[] = []; + const cubinBytes = buildMinimalElf64('decode_override_kernel'); + const cubinDigest = { algorithm: 'sha256' as const, hex: sha256Hex(cubinBytes) }; + const wrongWorkloadReceipt = Buffer.from( + JSON.stringify({ + version: 1, + kind: 'benchmark_verdict', + storeId: 'store-wl-override', + runId: 'run-wl-override', + lockHash: makeDigest('lock-wl'), + operationId: 'op-wrong-wl', + dispatchId: 'disp-wrong-wl', + dispatchGeneration: 1, + gateId: 'decode-cuda-bench', + checkId: 'gpu-bench-cuda', + candidateDigest: sha256Hex('cand-wl'), + status: 'approved', + reason: null, + expiresAtMs: '1900000000000', + preemptionCount: 0, + heldOutWorkloadId: 'cuda-default-workload', + metrics: { latency_us_p50: 32, goodput_rps: 2600 }, + hardwareProvenance: { + targetCellId: 'cuda-h100-whole', + probeKind: 'physical', + vendor: 'nvidia', + deviceModel: 'NVIDIA H100 80GB HBM3', + accelerator: 'sm_90a', + isolationMode: 'whole_device', + deviceCount: 1, + driverVersion: '555.42.02', + runtimeVersion: 'cuda-12.5', + topology: 'single_gpu', + workloadDigest: makeDigest('wl-wrong'), + clockLockMode: 'locked', + }, + outputArtifacts: [ + { + name: 'decode.cubin', + digest: cubinDigest, + byteLength: cubinBytes.byteLength, + mediaType: 'application/octet-stream', + }, + ], + signature: '0'.repeat(64), + }), + 'utf8', + ); + + const res = await runEvolutionCampaign({ + campaignRoot: join(tempDir, 'camp-wl-override'), + campaignId: 'camp-wl-override', + manifest: singleOverrideYaml, + repositoryRoot: repoDir, + baseRevision, + evaluator: async proposal => { + seenWorkloads.push(proposal.heldOutWorkloadId); + return { + status: 'passed', + codeSlice: '// EVOLVE-BLOCK-START: decode\nint decode_kernel() { return 42; }\n// EVOLVE-BLOCK-END: decode\n', + metrics: { latency_us_p50: 32, goodput_rps: 2600 }, + evidenceDigest: makeDigest('ev-wl-override'), + rawVerdictReceiptBytes: wrongWorkloadReceipt, + stageABlobs: [{ name: 'decode.cubin', bytes: cubinBytes, digest: cubinDigest, byteLength: cubinBytes.byteLength }], + outputArtifacts: [{ name: 'decode.cubin', digest: cubinDigest, byteLength: cubinBytes.byteLength, uri: `cas://sha256/${cubinDigest.hex}` }], + }; + }, + }); + assert.deepEqual(seenWorkloads, ['full-sm90a-holdout']); + + await assert.rejects( + () => exportEvolutionBundle({ + store: res.store, + campaignId: 'camp-wl-override', + outputDir: join(tempDir, 'out-wrong-wl'), + allowUnverifiedSignature: true, + }), + (err: unknown) => + err instanceof EvolutionError + && err.code === 'EXPORT_UNVERIFIED_FORBIDDEN' + && /expected "full-sm90a-holdout"/.test(err.message), + ); + await res.store.close(); + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } +}); diff --git a/packages/evolution/test/live-gpu-smoke.test.ts b/packages/evolution/test/live-gpu-smoke.test.ts new file mode 100644 index 0000000..ab0f091 --- /dev/null +++ b/packages/evolution/test/live-gpu-smoke.test.ts @@ -0,0 +1,462 @@ +import assert from 'node:assert/strict'; +import { execFile, execFileSync } from 'node:child_process'; +import { createHash, randomBytes } from 'node:crypto'; +import { mkdirSync, mkdtempSync, readFileSync, realpathSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import test from 'node:test'; +import { promisify } from 'node:util'; +import { SecretScrubber, type ArtifactRef } from '@loopwright/core'; +import { + auditSealedStageAOutputs, + canonicalJson, + collectHardwareProvenance, + probeAcceleratorHealth, + removeTreeFailClosed, + sealStageAOutputs, + signRelayPayload, + type ProbeCommandRunner, +} from '@loopwright/hardware-runner'; +import { + exportEvolutionBundle, + runEvolutionCampaign, + verifyEvolutionBundle, +} from '../src/index.js'; + +const execFileAsync = promisify(execFile); + +function sha256(bytes: Uint8Array | string) { + return { algorithm: 'sha256' as const, hex: createHash('sha256').update(bytes).digest('hex') }; +} + +function makeSshProbeRunner(sshTarget: string): ProbeCommandRunner { + return async (binaryPath, args, opts) => { + const remoteCmd = [binaryPath, ...args] + .map(tok => `'${tok.replace(/'/g, `'\\''`)}'`) + .join(' '); + try { + const { stdout, stderr } = await execFileAsync( + 'ssh', + ['-o', 'BatchMode=yes', '-o', 'ConnectTimeout=10', sshTarget, remoteCmd], + { + timeout: opts.timeoutMs, + maxBuffer: 4 * 1024 * 1024, + ...(opts.signal !== undefined ? { signal: opts.signal } : {}), + }, + ); + return { stdout, stderr, exitCode: 0 }; + } catch (err: unknown) { + const e = err as { code?: unknown; stdout?: string; stderr?: string; message?: string }; + return { + exitCode: typeof e.code === 'number' ? e.code : 1, + stdout: e.stdout ?? '', + stderr: e.stderr ?? e.message ?? 'ssh probe failed', + }; + } + }; +} + +async function remoteWhichOptional(sshHost: string, bin: string): Promise { + try { + const { stdout } = await execFileAsync( + 'ssh', + ['-o', 'BatchMode=yes', '-o', 'ConnectTimeout=10', sshHost, `command -v ${bin}`], + { timeout: 10_000 }, + ); + const trimmed = stdout.trim(); + return trimmed.length > 0 ? trimmed : null; + } catch { + return null; + } +} + +async function runHostLivePhysicalCampaign(options: { + readonly vendor: 'nvidia' | 'amd'; + readonly sshHost: string; + readonly expectedAccelerator: string; +}): Promise { + const { vendor, sshHost, expectedAccelerator } = options; + const isCuda = vendor === 'nvidia'; + const sshRunner = makeSshProbeRunner(sshHost); + const scrubber = new SecretScrubber(); + const hmacSecret = `live-gpu-hmac-${randomBytes(16).toString('hex')}`; + scrubber.register(hmacSecret); + + const smiPath = await remoteWhichOptional(sshHost, isCuda ? 'nvidia-smi' : 'rocm-smi'); + assert.ok(smiPath !== null, `expected ${isCuda ? 'nvidia-smi' : 'rocm-smi'} on ${sshHost}`); + + const workloadDigest = sha256(`live-gpu-workload:${vendor}:${sshHost}`); + const capabilities = { + accelerator: expectedAccelerator, + isolationModes: ['whole_device'] as const, + deviceCount: 1, + driverVersion: '0.0.0', + workloadIds: ['live-vec-scale-holdout'], + }; + + // 1. Live physical hardware provenance + post-crash health probe over SSH + const provenance = await collectHardwareProvenance({ + probeMode: 'physical', + targetCellId: `live-${vendor}-cell`, + capabilities, + workloadDigest, + executableOverrides: isCuda ? { nvidiaSmiPath: smiPath } : { rocmSmiPath: smiPath }, + commandRunner: sshRunner, + verifyExecutable: async p => p, + }); + assert.equal(provenance.probeKind, 'physical'); + assert.equal(provenance.vendor, vendor); + + const health = await probeAcceleratorHealth({ + probeMode: 'physical', + capabilities: { + ...capabilities, + driverVersion: provenance.driverVersion, + }, + executableOverrides: isCuda ? { nvidiaSmiPath: smiPath } : { rocmSmiPath: smiPath }, + commandRunner: sshRunner, + verifyExecutable: async p => p, + scrubber, + }); + assert.equal(health.healthy, true, `unhealthy ${vendor} host ${sshHost}: ${health.summary}`); + assert.equal(health.quarantineRequired, false); + + const tempDir = mkdtempSync(join(realpathSync(tmpdir()), `evo-live-${vendor}-`)); + try { + // 2. Produce real Stage A binary/PTX artifact (using remote nvcc/hipcc if present, else valid PTX), + // seal it (0o400/0o500), and verify Stage A static symbol audit! + const nvccPath = isCuda ? await remoteWhichOptional(sshHost, 'nvcc') : null; + const hipccPath = !isCuda ? await remoteWhichOptional(sshHost, 'hipcc') : null; + + let stageABlobName = 'vec_scale.ptx'; + let stageABlobBytes: Buffer; + if (isCuda && nvccPath !== null) { + const { stdout: ptxText } = await execFileAsync( + 'ssh', + [ + '-o', + 'BatchMode=yes', + sshHost, + 'tmp=$(mktemp -d) && printf \'extern "C" __global__ void vec_scale(float* x, float s) { int i = blockIdx.x * blockDim.x + threadIdx.x; x[i] *= s; }\\n\' > "$tmp/k.cu" && nvcc -ptx "$tmp/k.cu" -o "$tmp/k.ptx" && cat "$tmp/k.ptx" && rm -rf "$tmp"', + ], + { timeout: 30_000, maxBuffer: 8 * 1024 * 1024 }, + ); + stageABlobName = 'vec_scale.ptx'; + stageABlobBytes = Buffer.from(ptxText, 'utf8'); + } else if (!isCuda && hipccPath !== null) { + const { stdout: hsacoB64 } = await execFileAsync( + 'ssh', + [ + '-o', + 'BatchMode=yes', + sshHost, + 'tmp=$(mktemp -d) && printf \'#include \\nextern "C" __global__ void vec_scale(float* x, float s) { int i = blockIdx.x * blockDim.x + threadIdx.x; x[i] *= s; }\\n\' > "$tmp/k.cpp" && hipcc --genco "$tmp/k.cpp" -o "$tmp/k.hsaco" && base64 < "$tmp/k.hsaco" && rm -rf "$tmp"', + ], + { timeout: 45_000, maxBuffer: 8 * 1024 * 1024 }, + ); + stageABlobName = 'vec_scale.hsaco'; + stageABlobBytes = Buffer.from(hsacoB64.replace(/\s+/g, ''), 'base64'); + } else { + stageABlobName = 'vec_scale.ptx'; + stageABlobBytes = Buffer.from( + [ + '.version 7.0', + '.target sm_80', + '.address_size 64', + '.visible .entry vec_scale() {', + ' .reg .b32 %r<16>;', + ' ret;', + '}', + '', + ].join('\n'), + 'utf8', + ); + } + + const stageACheckDir = join(tempDir, 'stage-a-audit-check'); + mkdirSync(stageACheckDir, { recursive: true, mode: 0o700 }); + writeFileSync(join(stageACheckDir, stageABlobName), stageABlobBytes); + const sealed = await sealStageAOutputs({ + stageAOutDir: stageACheckDir, + scrubber, + secretOverlapBytes: 64, + }); + assert.equal(sealed.length, 1); + const auditRes = await auditSealedStageAOutputs({ + sealedOutputs: sealed, + auditSpec: { + forbiddenSymbolPatterns: isCuda ? ['cublas', 'cudnn'] : ['rocblas', 'miopen'], + maxRegisterCount: 64, + maxLocalSpillBytes: 0, + }, + scrubber, + }); + assert.equal(auditRes.passed, true, `Stage A static audit failed: ${JSON.stringify(auditRes.findings)}`); + + // 3. Run 2-generation evolutionary campaign with real physical provenance & HMAC receipts, + // then export & verify evolution-bundle.v1 (oci-layout) WITHOUT allowSyntheticProbe! + const repoDir = join(tempDir, 'repo'); + mkdirSync(join(repoDir, '.loopwright'), { recursive: true, mode: 0o700 }); + mkdirSync(join(repoDir, 'src', 'kernels'), { recursive: true, mode: 0o700 }); + + const baselineKernel = [ + 'extern "C" __global__ void vec_scale(float* x, float s) {', + '// EVOLVE-BLOCK-START: body', + ' int i = blockIdx.x * blockDim.x + threadIdx.x;', + ' x[i] = x[i] * s;', + '// EVOLVE-BLOCK-END: body', + '}', + '', + ].join('\n'); + + const taskpackYaml = [ + 'apiVersion: loopwright.dev/v1alpha1', + 'kind: Taskpack', + 'metadata:', + ` name: live-${vendor}-smoke`, + 'spec:', + ' goal:', + ' candidate: Optimize vec_scale kernel inside EVOLVE-BLOCK.', + ' noChange: No change.', + ' target:', + ' matrix:', + ` - id: live-${vendor}-cell`, + ' platform: linux/amd64', + ` variant: ${vendor}`, + ' hardware:', + ` accelerator: ${provenance.accelerator}`, + ' isolationMode: whole_device', + ' deviceCount: 1', + ` driverConstraint: ">=${provenance.driverVersion}"`, + ' forbiddenSymbolPatterns:', + ` - ${isCuda ? 'cublas' : 'rocblas'}`, + ' scope:', + ' writable: [src/kernels/**]', + ' protected: [scripts/**]', + ' models:', + ' - provider: anthropic', + ' id: claude-sonnet-4-6', + ' thinking: medium', + ' roles:', + ' - id: mutator', + ' provider: anthropic', + ' model: claude-sonnet-4-6', + ' purpose: task', + ' tools: [read, write, edit, bash]', + ' prompt: Optimize vec_scale.cu inside EVOLVE-BLOCK.', + ' verification:', + ' localChecks:', + ' - id: evolve-guard', + ' implementation: evolve-block-guard.v1', + ' parameters:', + ' files: [src/kernels/vec_scale.cu]', + ' externalGates:', + ' - id: gpu-bench', + ' implementation: benchmark-gate.v1', + ' endpointId: hw-relay', + ' gateId: live-gpu-bench', + ' required: true', + ` targetCellId: live-${vendor}-cell`, + ' heldOutWorkloadId: live-vec-scale-holdout', + ' allowSyntheticHardwareProbe: false', + ' metricThresholds:', + ' - kind: bounds', + ' metric: max_ulp', + ' max: 1', + ' publication:', + ' mode: disabled', + '', + ].join('\n'); + + const campaignYaml = [ + 'apiVersion: loopwright.dev/v1alpha1', + 'kind: EvolutionCampaign', + 'metadata:', + ` name: live-${vendor}-campaign`, + 'spec:', + ' taskpack: .loopwright/taskpack.yaml', + ` targetCellId: live-${vendor}-cell`, + ' stages:', + ' mode: single-target', + ' population:', + ' islands: 1', + ' migrationIntervalGenerations: 2', + ' 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', + ' maxCrossoversPerPrompt: 1', + ' objectives:', + ' - metric: latency_us_p50', + ' direction: minimize', + ' budgets:', + ' maxGenerations: 2', + ' maxEvaluations: 2', + ' maxConcurrentEvaluations: 1', + ' scratchpadIntervalGenerations: 2', + '', + ].join('\n'); + + writeFileSync(join(repoDir, '.loopwright', 'taskpack.yaml'), taskpackYaml, 'utf8'); + writeFileSync(join(repoDir, 'src', 'kernels', 'vec_scale.cu'), baselineKernel, 'utf8'); + + const gitEnv = { + PATH: '/usr/bin:/bin', + GIT_CONFIG_NOSYSTEM: '1', + GIT_CONFIG_GLOBAL: '/dev/null', + GIT_AUTHOR_NAME: 'Loopwright Live GPU', + GIT_AUTHOR_EMAIL: 'gpu@loopwright.dev', + GIT_COMMITTER_NAME: 'Loopwright Live GPU', + GIT_COMMITTER_EMAIL: 'gpu@loopwright.dev', + }; + execFileSync('/usr/bin/git', ['init', '-b', 'main'], { cwd: repoDir, env: gitEnv, stdio: 'ignore' }); + execFileSync('/usr/bin/git', ['add', '.'], { cwd: repoDir, env: gitEnv, stdio: 'ignore' }); + execFileSync('/usr/bin/git', ['commit', '-m', 'Baseline live GPU kernel'], { cwd: repoDir, env: gitEnv, stdio: 'ignore' }); + const baseRevision = execFileSync('/usr/bin/git', ['rev-parse', 'HEAD'], { cwd: repoDir, env: gitEnv, encoding: 'utf8' }).trim(); + + const campaignRoot = join(tempDir, 'campaign'); + const bundleOutDir = join(tempDir, 'live-bundle-oci'); + const blobDigest = sha256(readFileSync(join(stageACheckDir, stageABlobName))); + let evalSeq = 0; + + const campaignRes = await runEvolutionCampaign({ + campaignRoot, + campaignId: `camp-live-${vendor}`, + manifest: campaignYaml, + repositoryRoot: repoDir, + baseRevision, + autoExport: false, + allowSyntheticProbe: false, + receiptSigningSecret: hmacSecret, + scrubber, + evaluator: async proposal => { + evalSeq += 1; + const latencyUs = evalSeq === 1 ? 26.0 : 18.5; + const outputArtifacts: readonly ArtifactRef[] = [{ + name: stageABlobName, + digest: blobDigest, + byteLength: stageABlobBytes.byteLength, + mediaType: 'application/octet-stream', + }]; + const lockHash = sha256(`live-lock:${proposal.individualId}`); + const verdictBody = { + version: 1, + kind: 'benchmark_verdict', + storeId: `live-${vendor}-store`, + runId: proposal.individualId, + operationId: `verify.0.check.gpu-bench.${evalSeq}`, + dispatchId: `disp-${evalSeq}`, + dispatchGeneration: 1, + gateId: 'live-gpu-bench', + checkId: 'gpu-bench', + candidateDigest: blobDigest.hex, + expiresAtMs: String(Date.now() + 3_600_000), + preemptionCount: 0, + lockHash, + status: 'approved', + reason: null, + metrics: { latency_us_p50: latencyUs, max_ulp: 0 }, + bucketMetrics: [{ + bucketId: 'live-vec-scale-holdout', + dimensions: { unroll: evalSeq === 1 ? 1 : 4 }, + metrics: { latency_us_p50: latencyUs, max_ulp: 0 }, + }], + hardwareDiagnostics: { + boundPipeline: 'hbm' as const, + occupancyPct: 75, + rooflineHeadroom: evalSeq === 1 ? 1.35 : 1.12, + }, + hardwareProvenance: provenance, + outputArtifacts, + }; + const sig = signRelayPayload(hmacSecret, canonicalJson(verdictBody)).replace(/^sha256=/, ''); + const rawVerdictReceiptBytes = Buffer.from(`${canonicalJson({ ...verdictBody, signature: sig })}\n`, 'utf8'); + + return { + status: 'passed', + failureReason: null, + codeSlice: `// EVOLVE-BLOCK-START: body\n // gen=${evalSeq}\n// EVOLVE-BLOCK-END: body\n`, + metrics: { latency_us_p50: latencyUs, max_ulp: 0 }, + bucketMetrics: verdictBody.bucketMetrics, + hardwareDiagnostics: verdictBody.hardwareDiagnostics, + hardwareProvenance: provenance, + outputArtifacts, + stageABlobs: [{ + name: stageABlobName, + bytes: stageABlobBytes, + digest: blobDigest, + byteLength: stageABlobBytes.byteLength, + mediaType: 'application/octet-stream', + }], + rawVerdictReceiptBytes, + evidenceDigest: sha256(`ev:${proposal.individualId}`), + childRunRelPath: `runs/${proposal.individualId}`, + }; + }, + }); + + try { + assert.equal(campaignRes.campaign.status, 'completed'); + assert.ok(campaignRes.paretoFrontier.length >= 1); + + const exported = await exportEvolutionBundle({ + store: campaignRes.store, + campaignId: campaignRes.campaign.campaignId, + outputDir: bundleOutDir, + format: 'oci-layout', + allowSyntheticProbe: false, + receiptSigningSecret: hmacSecret, + scrubber, + }); + assert.ok(exported.exportedIndividualIds.length >= 1); + + const verified = await verifyEvolutionBundle({ + bundleDir: bundleOutDir, + allowSyntheticProbe: false, + receiptSigningSecret: hmacSecret, + scrubber, + }); + assert.equal(verified.format, 'oci-layout'); + assert.equal(verified.manifest.compatibility.accelerator, provenance.accelerator); + assert.equal(verified.manifest.compatibility.driverConstraint, `>=${provenance.driverVersion}`); + assert.ok(verified.receiptCount >= 1); + } finally { + await campaignRes.store.close(); + } + } finally { + await removeTreeFailClosed(tempDir); + } +} + +test('live-gpu-smoke: physical CUDA/ROCm SSH probe, Stage A PTX/ELF static audit, 2-gen campaign, and physical bundle export', async t => { + const cudaHost = process.env['LOOPWRIGHT_CUDA_SSH_HOST']?.trim(); + const rocmHost = process.env['LOOPWRIGHT_ROCM_SSH_HOST']?.trim(); + + if (!cudaHost && !rocmHost) { + t.skip('Skipping live physical GPU smoke test: set LOOPWRIGHT_CUDA_SSH_HOST or LOOPWRIGHT_ROCM_SSH_HOST to enable.'); + return; + } + + if (cudaHost) { + await runHostLivePhysicalCampaign({ + vendor: 'nvidia', + sshHost: cudaHost, + expectedAccelerator: process.env['LOOPWRIGHT_CUDA_ACCELERATOR']?.trim() || 'sm_89', + }); + } + + if (rocmHost) { + await runHostLivePhysicalCampaign({ + vendor: 'amd', + sshHost: rocmHost, + expectedAccelerator: process.env['LOOPWRIGHT_ROCM_ACCELERATOR']?.trim() || 'gfx1101', + }); + } +}); diff --git a/packages/evolution/test/pareto-and-sampler.test.ts b/packages/evolution/test/pareto-and-sampler.test.ts new file mode 100644 index 0000000..d7580cf --- /dev/null +++ b/packages/evolution/test/pareto-and-sampler.test.ts @@ -0,0 +1,449 @@ +import assert from 'node:assert/strict'; +import { createHash } from 'node:crypto'; +import { lstatSync, mkdtempSync, readFileSync, rmSync, symlinkSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import test from 'node:test'; +import { SecretScrubber } from '@loopwright/core'; +import { + computeHypervolume, + computeHypervolumeDelta, + computeMedianFitness, + computeNicheKey, + computeNsga2Ranking, + computeObjectiveReferenceStats, + dominatesObjectives, + scalarizeFitness, +} from '../src/pareto.js'; +import { + computeSteppingStoneSamplingWeight, + computeTruncatedImprovementReward, + createSeededPrng, + sampleParents, + selectModelCandidate, + selectRingMigrationElites, + stageMultiParentContextFiles, +} from '../src/sampler.js'; +import { + EvolutionError, + type EvolutionNicheAxis, + type IndividualRecord, + type ModelBanditArmRecord, + type ObjectiveDirectionSpec, +} from '../src/types.js'; + +function makeDigest(seed: string): { readonly algorithm: 'sha256'; readonly hex: string } { + return { algorithm: 'sha256', hex: createHash('sha256').update(seed, 'utf8').digest('hex') }; +} + +function makeIndividual(overrides: Partial & { readonly individualId: string }): IndividualRecord { + return { + individualId: overrides.individualId, + campaignId: overrides.campaignId ?? 'camp-1', + islandId: overrides.islandId ?? 0, + generation: overrides.generation ?? 1, + bucketId: overrides.bucketId ?? null, + teamConfigId: overrides.teamConfigId ?? 'team-0', + modelId: overrides.modelId ?? 'model-a', + trackId: overrides.trackId ?? 'cuda_raw', + mutationKind: overrides.mutationKind ?? 'diff_tune', + status: overrides.status ?? 'passed', + failureReason: overrides.failureReason ?? null, + nicheKey: overrides.nicheKey !== undefined ? overrides.nicheKey : 'bound_pipeline=hbm', + paretoRank: overrides.paretoRank !== undefined ? overrides.paretoRank : 1, + crowdingDistance: overrides.crowdingDistance !== undefined ? overrides.crowdingDistance : 1.0, + scalarFitness: overrides.scalarFitness !== undefined ? overrides.scalarFitness : 0.5, + offspringCount: overrides.offspringCount ?? 0, + codeSliceCasDigest: overrides.codeSliceCasDigest ?? makeDigest(overrides.individualId), + evidenceDigest: overrides.evidenceDigest ?? makeDigest(`ev-${overrides.individualId}`), + verdictReceiptCasDigest: overrides.verdictReceiptCasDigest ?? makeDigest(`vr-${overrides.individualId}`), + outputArtifacts: overrides.outputArtifacts ?? [], + metrics: overrides.metrics ?? { latency_us_p50: 100, goodput_rps: 1000 }, + ...(overrides.bucketMetrics !== undefined ? { bucketMetrics: overrides.bucketMetrics } : {}), + ...(overrides.hardwareDiagnostics !== undefined ? { hardwareDiagnostics: overrides.hardwareDiagnostics } : {}), + ...(overrides.hardwareProvenance !== undefined ? { hardwareProvenance: overrides.hardwareProvenance } : {}), + ...(overrides.findings !== undefined ? { findings: overrides.findings } : {}), + createdAtWallMs: overrides.createdAtWallMs ?? 1_700_000_000_000, + }; +} + +test('pareto: dominatesObjectives and computeNsga2Ranking are permutation-invariant and deterministic', () => { + const objectives: readonly ObjectiveDirectionSpec[] = [ + { metric: 'latency_us_p50', direction: 'minimize' }, + { metric: 'goodput_rps', direction: 'maximize' }, + ]; + + assert.equal( + dominatesObjectives( + { latency_us_p50: 80, goodput_rps: 1200 }, + { latency_us_p50: 90, goodput_rps: 1200 }, + objectives, + ), + true, + ); + // Equal objective vectors never strictly dominate each other + assert.equal( + dominatesObjectives( + { latency_us_p50: 80, goodput_rps: 1200 }, + { latency_us_p50: 80, goodput_rps: 1200 }, + objectives, + ), + false, + ); + // Trade-off vectors are mutually non-dominated + assert.equal( + dominatesObjectives( + { latency_us_p50: 70, goodput_rps: 1000 }, + { latency_us_p50: 90, goodput_rps: 1400 }, + objectives, + ), + false, + ); + + const candidates = [ + { individualId: 'ind-f1-left', metrics: { latency_us_p50: 50, goodput_rps: 1000 } }, + { individualId: 'ind-f1-mid-b', metrics: { latency_us_p50: 70, goodput_rps: 1300 } }, + { individualId: 'ind-f1-mid-a', metrics: { latency_us_p50: 60, goodput_rps: 1100 } }, + { individualId: 'ind-f1-right', metrics: { latency_us_p50: 90, goodput_rps: 1500 } }, + { individualId: 'ind-f2-b', metrics: { latency_us_p50: 100, goodput_rps: 1100 } }, + { individualId: 'ind-f2-a', metrics: { latency_us_p50: 100, goodput_rps: 1100 } }, // Exact tie broken by individualId + { individualId: 'ind-f3', metrics: { latency_us_p50: 130, goodput_rps: 900 } }, + ]; + + const ranked1 = computeNsga2Ranking(candidates, objectives); + const reversed = [...candidates].reverse(); + const shuffled = [candidates[4]!, candidates[1]!, candidates[6]!, candidates[0]!, candidates[5]!, candidates[2]!, candidates[3]!]; + const ranked2 = computeNsga2Ranking(reversed, objectives); + const ranked3 = computeNsga2Ranking(shuffled, objectives); + + assert.deepEqual(ranked1, ranked2); + assert.deepEqual(ranked1, ranked3); + + // Verify front assignments + const rankById = new Map(ranked1.map(r => [r.individualId, r])); + assert.equal(rankById.get('ind-f1-left')?.paretoRank, 1); + assert.equal(rankById.get('ind-f1-right')?.paretoRank, 1); + assert.equal(rankById.get('ind-f1-left')?.crowdingDistance, Number.POSITIVE_INFINITY); + assert.equal(rankById.get('ind-f1-right')?.crowdingDistance, Number.POSITIVE_INFINITY); + assert.ok(Number.isFinite(rankById.get('ind-f1-mid-a')!.crowdingDistance)); + assert.ok(Number.isFinite(rankById.get('ind-f1-mid-b')!.crowdingDistance)); + assert.equal(rankById.get('ind-f2-a')?.paretoRank, 2); + assert.equal(rankById.get('ind-f2-b')?.paretoRank, 2); + assert.equal(rankById.get('ind-f3')?.paretoRank, 3); + + // Tie-break order: ind-f2-a precedes ind-f2-b + const idxF2A = ranked1.findIndex(r => r.individualId === 'ind-f2-a'); + const idxF2B = ranked1.findIndex(r => r.individualId === 'ind-f2-b'); + assert.ok(idxF2A < idxF2B); +}); + +test('pareto: computeHypervolume and computeHypervolumeDelta are exact in 1D, 2D, and 3D', () => { + // 2D exact test: minimize latency (ref 100), maximize goodput (ref 500) + const obj2d: readonly ObjectiveDirectionSpec[] = [ + { metric: 'latency', direction: 'minimize' }, + { metric: 'goodput', direction: 'maximize' }, + ]; + const ref2d = { latency: 100, goodput: 500 }; + // p1 = (60, 900) -> box [40 x 400] = 16,000 + // p2 = (80, 1100) -> box [20 x 600] = 12,000 + // intersection = [20 x 400] = 8,000 -> union = 20,000 + const hv2d = computeHypervolume( + [ + { latency: 60, goodput: 900 }, + { latency: 80, goodput: 1100 }, + { latency: 90, goodput: 800 }, // Dominated -> contributes 0 + { latency: 120, goodput: 2000 }, // Worse than reference on latency -> contributes 0 + ], + obj2d, + ref2d, + ); + assert.equal(hv2d, 20_000); + + // 3D exact inclusion-exclusion verification: minimize a, b, c relative to (10, 10, 10) + const obj3d: readonly ObjectiveDirectionSpec[] = [ + { metric: 'a', direction: 'minimize' }, + { metric: 'b', direction: 'minimize' }, + { metric: 'c', direction: 'minimize' }, + ]; + const ref3d = { a: 10, b: 10, c: 10 }; + // P1=(2,5,5) -> box (8,5,5)=200; P2=(5,2,6) -> box (5,8,4)=160; intersection (5,5,4)=100 -> union = 260 + const hv3d = computeHypervolume( + [ + { a: 2, b: 5, c: 5 }, + { a: 5, b: 2, c: 6 }, + ], + obj3d, + ref3d, + ); + assert.equal(hv3d, 260); + + const delta = computeHypervolumeDelta( + [{ a: 2, b: 5, c: 5 }], + [ + { a: 2, b: 5, c: 5 }, + { a: 5, b: 2, c: 6 }, + ], + obj3d, + ref3d, + ); + assert.equal(delta, 60); +}); + +test('pareto: computeNicheKey and scalarizeFitness map hardware diagnostics and metrics canonically', () => { + const axes: readonly EvolutionNicheAxis[] = [ + { id: 'bound_pipeline', kind: 'enum', values: ['hbm', 'l2', 'smem_lds_ub', 'tensor_cube', 'vector_valu'] }, + { id: 'occupancy_band', kind: 'numeric_bins', edges: [0, 25, 50, 75, 100] }, + ]; + + assert.equal( + computeNicheKey(axes, { latency_us_p50: 85 }, { boundPipeline: 'tensor_cube', occupancyPct: 50 }), + 'bound_pipeline=tensor_cube|occupancy_band=[50,75)', + ); + // Upper boundary 100 falls into closed final bin [75,100] + assert.equal( + computeNicheKey(axes, { latency_us_p50: 85 }, { boundPipeline: 'hbm', occupancyPct: 100 }), + 'bound_pipeline=hbm|occupancy_band=[75,100]', + ); + // Underflow, overflow, and unclassified enum fall into dedicated non-colliding bins + assert.equal( + computeNicheKey(axes, { occupancy_band: -5 }, { boundPipeline: 'unknown' }), + 'bound_pipeline=~unclassified|occupancy_band=<-inf,0)', + ); + assert.equal( + computeNicheKey(axes, { occupancy_band: 125 }), + 'bound_pipeline=~unclassified|occupancy_band=(100,+inf)', + ); + + const objectives: readonly ObjectiveDirectionSpec[] = [ + { metric: 'latency_us_p50', direction: 'minimize' }, + { metric: 'goodput_rps', direction: 'maximize' }, + ]; + const entries = [ + { latency_us_p50: 50, goodput_rps: 2000 }, + { latency_us_p50: 100, goodput_rps: 1500 }, + { latency_us_p50: 150, goodput_rps: 1000 }, + ]; + const stats = computeObjectiveReferenceStats(entries, objectives); + const scores = entries.map(m => scalarizeFitness(m, objectives, stats)); + assert.equal(scores[0], 1); + assert.equal(scores[1], 0.5); + assert.equal(scores[2], 0); + assert.equal(computeMedianFitness(scores), 0.5); +}); + +test('sampler: stepping-stone weight decay, deterministic parent crossover, and Island Elitism ring migration', () => { + // Exact formula check: at fitness === median, sigmoid(0) = 0.5 + assert.equal(computeSteppingStoneSamplingWeight(0.5, 0.5, 0, 1.0), 0.5); + assert.equal(computeSteppingStoneSamplingWeight(0.5, 0.5, 3, 1.0), 0.125); // 0.5 / (1 + 3) + + // Novelty decay: over-sampled leader gets lower weight than fresh stepping stone + const overSampledLeaderWeight = computeSteppingStoneSamplingWeight(0.9, 0.5, 20, 1.0); + const freshSteppingStoneWeight = computeSteppingStoneSamplingWeight(0.45, 0.5, 0, 1.0); + assert.ok(freshSteppingStoneWeight > overSampledLeaderWeight); + + // Island Elitism ring migration: rank-1 leaders stay strictly local; rank >= 2 niche elites migrate to (i + 1) % islands + const islandIndividuals: readonly IndividualRecord[] = [ + makeIndividual({ + individualId: 'isl0-leader-r1', + islandId: 0, + nicheKey: 'bound_pipeline=hbm', + paretoRank: 1, + scalarFitness: 0.95, + }), + makeIndividual({ + individualId: 'isl0-stone-r2', + islandId: 0, + nicheKey: 'bound_pipeline=tensor_cube', + paretoRank: 2, + scalarFitness: 0.6, + }), + makeIndividual({ + individualId: 'isl1-leader-r1', + islandId: 1, + nicheKey: 'bound_pipeline=l2', + paretoRank: 1, + scalarFitness: 0.92, + }), + makeIndividual({ + individualId: 'isl1-stone-r3', + islandId: 1, + nicheKey: 'bound_pipeline=smem_lds_ub', + paretoRank: 3, + scalarFitness: 0.55, + }), + ]; + + // Off-interval generation produces zero migrations + assert.equal( + selectRingMigrationElites({ + generation: 7, + islands: 2, + migrationIntervalGenerations: 8, + maxMigrationElites: 1, + individuals: islandIndividuals, + }).length, + 0, + ); + + // On-interval generation migrates non-rank-1 niche elites across ring (0 -> 1, 1 -> 0) as inspiration + const migrations = selectRingMigrationElites({ + generation: 8, + islands: 2, + migrationIntervalGenerations: 8, + maxMigrationElites: 1, + individuals: islandIndividuals, + }); + assert.equal(migrations.length, 2); + assert.equal(migrations.some(m => m.individual.paretoRank === 1), false); + assert.equal(migrations[0]?.sourceIslandId, 0); + assert.equal(migrations[0]?.targetIslandId, 1); + assert.equal(migrations[0]?.individual.individualId, 'isl0-stone-r2'); + assert.equal(migrations[0]?.role, 'inspiration'); + assert.equal(migrations[1]?.sourceIslandId, 1); + assert.equal(migrations[1]?.targetIslandId, 0); + assert.equal(migrations[1]?.individual.individualId, 'isl1-stone-r3'); + + // Seeded PRNG and multi-parent sampling determinism + const rngA = createSeededPrng('campaign-seed-42'); + const rngB = createSeededPrng('campaign-seed-42'); + assert.deepEqual( + Array.from({ length: 8 }, () => rngA()), + Array.from({ length: 8 }, () => rngB()), + ); + + const selection1 = sampleParents({ + islandId: 1, + localCandidates: [ + islandIndividuals[2]!, + islandIndividuals[3]!, + makeIndividual({ individualId: 'isl1-donor-b', islandId: 1, nicheKey: 'bound_pipeline=vector_valu', paretoRank: 2, scalarFitness: 0.7 }), + ], + inspirationCandidates: [migrations[0]!.individual], + maxCrossoversPerPrompt: 2, + noveltyDecayLambda: 1.0, + seed: 'gen-8-isl-1-slot-0', + }); + const selection2 = sampleParents({ + islandId: 1, + localCandidates: [ + islandIndividuals[2]!, + islandIndividuals[3]!, + makeIndividual({ individualId: 'isl1-donor-b', islandId: 1, nicheKey: 'bound_pipeline=vector_valu', paretoRank: 2, scalarFitness: 0.7 }), + ], + inspirationCandidates: [migrations[0]!.individual], + maxCrossoversPerPrompt: 2, + noveltyDecayLambda: 1.0, + seed: 'gen-8-isl-1-slot-0', + }); + assert.deepEqual(selection1, selection2); + assert.equal(selection1.primary.role, 'primary'); + assert.equal(selection1.primary.individual.islandId, 1); + assert.equal(selection1.secondary.length, 2); + const selectedIds = new Set([selection1.primary.individual.individualId, ...selection1.secondary.map(s => s.individual.individualId)]); + assert.equal(selectedIds.size, 3); +}); + +test('sampler: stageMultiParentContextFiles enforces 0o400 permissions, O_NOFOLLOW, and SecretScrubber', async () => { + const tempDir = mkdtempSync(join(tmpdir(), 'evo-context-test-')); + const scrubber = new SecretScrubber(); + scrubber.register('private-token-abcdef123456'); + + try { + const contextDir = join(tempDir, 'parent-context'); + const primary = makeIndividual({ + individualId: 'parent-primary', + islandId: 0, + bucketMetrics: [{ bucketId: 'bs1-isl4k', metrics: { latency_us_p50: 82 } }], + hardwareDiagnostics: { boundPipeline: 'tensor_cube', occupancyPct: 62.5 }, + }); + const donor = makeIndividual({ + individualId: 'parent-insp', + islandId: 3, + hardwareDiagnostics: { boundPipeline: 'smem_lds_ub', bankConflictPct: 1.5 }, + }); + + const staged = await stageMultiParentContextFiles({ + stagingDir: contextDir, + parents: [ + { individual: primary, role: 'primary', codeSlice: '// EVOLVE-BLOCK-START: k\n__syncthreads();\n// EVOLVE-BLOCK-END: k\n' }, + { individual: donor, role: 'inspiration', codeSlice: '// Donor double-buffered smem pipeline\n' }, + ], + maxCrossoversPerPrompt: 2, + scrubber, + }); + + assert.equal(staged.files.length, 2); + for (const file of staged.files) { + const stat = lstatSync(file.filePath); + assert.equal(stat.isSymbolicLink(), false); + assert.equal(stat.nlink, 1); + assert.equal(stat.mode & 0o777, 0o400); + const parsed = JSON.parse(readFileSync(file.filePath, 'utf8')) as Record; + assert.ok(typeof parsed['codeSlice'] === 'string'); + } + + // Secret leak inside codeSlice fails closed with SECRET_LEAK_DETECTED + await assert.rejects( + () => stageMultiParentContextFiles({ + stagingDir: join(tempDir, 'leak-context'), + parents: [ + { individual: primary, role: 'primary', codeSlice: 'const key = "private-token-abcdef123456";' }, + ], + maxCrossoversPerPrompt: 2, + scrubber, + }), + (err: unknown) => err instanceof EvolutionError && err.code === 'SECRET_LEAK_DETECTED', + ); + + // Symlink staging directory fails closed with EVOLUTION_SYMLINK_FORBIDDEN + const symlinkContextDir = join(tempDir, 'symlink-context'); + symlinkSync(contextDir, symlinkContextDir); + await assert.rejects( + () => stageMultiParentContextFiles({ + stagingDir: symlinkContextDir, + parents: [{ individual: primary, role: 'primary', codeSlice: '// clean' }], + maxCrossoversPerPrompt: 2, + scrubber, + }), + (err: unknown) => err instanceof EvolutionError && err.code === 'EVOLUTION_SYMLINK_FORBIDDEN', + ); + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } +}); + +test('sampler: UCB1 bandit and truncated parent-relative improvement reward follow exact spec formulas', () => { + // r_u = exp(max(r - r_parent, 0)) - 1 + assert.equal(computeTruncatedImprovementReward(0.4, 0.6), 0); // regression -> 0 + assert.equal(computeTruncatedImprovementReward(0.6, 0.6), 0); // tie -> 0 + const posReward = computeTruncatedImprovementReward(0.8, 0.5); + assert.ok(Math.abs(posReward - (Math.exp(0.3) - 1)) < 1e-12); + + const models = ['model-alpha', 'model-beta', 'model-gamma'] as const; + + // Round-robin deterministic cycling + assert.equal( + selectModelCandidate({ strategy: 'deterministic-round-robin', modelIds: models, arms: [], sequenceIndex: 0 }).modelId, + 'model-alpha', + ); + assert.equal( + selectModelCandidate({ strategy: 'deterministic-round-robin', modelIds: models, arms: [], sequenceIndex: 4 }).modelId, + 'model-beta', + ); + + // UCB1 pulls unpulled arms first in declaration order + const partialArms: readonly ModelBanditArmRecord[] = [ + { campaignId: 'c1', modelId: 'model-alpha', pullCount: 1, totalReward: 0.5, meanReward: 0.5, lastPulledGeneration: 0 }, + ]; + const explorePick = selectModelCandidate({ strategy: 'ucb1', modelIds: models, arms: partialArms, sequenceIndex: 1 }); + assert.equal(explorePick.modelId, 'model-beta'); + + // UCB1 exploits higher-reward arm once all arms are pulled sufficiently + const matureArms: readonly ModelBanditArmRecord[] = [ + { campaignId: 'c1', modelId: 'model-alpha', pullCount: 10, totalReward: 0.2, meanReward: 0.02, lastPulledGeneration: 9 }, + { campaignId: 'c1', modelId: 'model-beta', pullCount: 10, totalReward: 8.5, meanReward: 0.85, lastPulledGeneration: 9 }, + { campaignId: 'c1', modelId: 'model-gamma', pullCount: 10, totalReward: 1.0, meanReward: 0.10, lastPulledGeneration: 9 }, + ]; + const exploitPick = selectModelCandidate({ strategy: 'ucb1', modelIds: models, arms: matureArms, sequenceIndex: 30 }); + assert.equal(exploitPick.modelId, 'model-beta'); +}); diff --git a/packages/evolution/test/scaffold.test.ts b/packages/evolution/test/scaffold.test.ts new file mode 100644 index 0000000..8845663 --- /dev/null +++ b/packages/evolution/test/scaffold.test.ts @@ -0,0 +1,67 @@ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; +import test from 'node:test'; +import { fileURLToPath } from 'node:url'; +import { + EVOLUTION_PACKAGE_NAME, + EVOLUTION_SCAFFOLD_VERSION, + getEvolutionPackageDescriptor, + probeNodeSqliteSupport, +} from '../src/index.js'; +import { expectedSchema } from '../../state/src/schema.js'; + +const PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..'); +const ALLOWED_EVOLUTION_DEPS = new Set([ + '@loopwright/core', + '@loopwright/state', + '@loopwright/controller', + '@loopwright/decisions', + '@loopwright/memory', + '@loopwright/taskpack', + '@loopwright/hardware-runner', +]); + +test('evolution scaffold: exports package descriptor and verifies built-in node:sqlite STRICT support', () => { + assert.equal(EVOLUTION_PACKAGE_NAME, '@loopwright/evolution'); + assert.equal(EVOLUTION_SCAFFOLD_VERSION, 1); + + const descriptor = getEvolutionPackageDescriptor(); + assert.equal(Object.isFrozen(descriptor), true); + assert.equal(descriptor.name, '@loopwright/evolution'); + assert.equal(descriptor.version, 1); + assert.equal(descriptor.sqliteBuiltin, true); + assert.match(descriptor.sqliteVersion, /^3\.\d+\.\d+/); + + const probe = probeNodeSqliteSupport(); + assert.equal(probe.strictTablesSupported, true); + assert.equal(probe.journalMode, 'memory'); +}); + +test('evolution scaffold: enforces zero third-party runtime dependencies and strict package layering', () => { + const pkgPath = PACKAGE_ROOT.includes('.test-build') + ? resolve(PACKAGE_ROOT, '..', '..', '..', 'packages', 'evolution', 'package.json') + : join(PACKAGE_ROOT, 'package.json'); + const manifest = JSON.parse(readFileSync(pkgPath, 'utf8')) as { + name: string; + private: boolean; + dependencies?: Record; + }; + + assert.equal(manifest.name, '@loopwright/evolution'); + assert.equal(manifest.private, true); + + const depNames = Object.keys(manifest.dependencies ?? {}); + assert.ok(depNames.length > 0, 'must declare workspace dependencies'); + for (const dep of depNames) { + assert.ok(dep.startsWith('@loopwright/'), `forbidden third-party runtime dependency: ${dep}`); + assert.ok(ALLOWED_EVOLUTION_DEPS.has(dep), `disallowed workspace dependency for @loopwright/evolution: ${dep}`); + } + assert.equal(depNames.includes('@loopwright/github-app'), false); + assert.equal(depNames.includes('@loopwright/cli'), false); +}); + +test('evolution scaffold: preserves @loopwright/state expectedSchema() digest format', () => { + const digest = expectedSchema(); + assert.match(digest, /^[0-9a-f]{64}$/); +}); diff --git a/packages/evolution/test/schema-and-store.test.ts b/packages/evolution/test/schema-and-store.test.ts new file mode 100644 index 0000000..4663569 --- /dev/null +++ b/packages/evolution/test/schema-and-store.test.ts @@ -0,0 +1,734 @@ +import assert from 'node:assert/strict'; +import { createHash } from 'node:crypto'; +import { mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import test from 'node:test'; +import { SecretScrubber } from '@loopwright/core'; +import { expectedSchema } from '../../state/src/schema.js'; +import { + loadEvolutionCampaignFile, + parseDispatchManifestV1, + parseEvolutionCampaignDocument, + parseNullProtoJson, + parseTeamPatchV1, +} from '../src/schema.js'; +import { EvolutionCampaignStore } from '../src/store.js'; +import { + EVOLUTION_CAMPAIGN_MAX_BYTES, + EvolutionError, + TEAM_PATCH_DIAGNOSIS_MAX_BYTES, + TEAM_PATCH_MAX_BYTES, + type CampaignClockSource, + type EvolutionErrorCode, +} from '../src/types.js'; + +function sha256Hex(text: string): string { + return createHash('sha256').update(text, 'utf8').digest('hex'); +} + +function makeDigest(seed: string): { readonly algorithm: 'sha256'; readonly hex: string } { + return { algorithm: 'sha256', hex: sha256Hex(seed) }; +} + +function assertEvolutionError(fn: () => unknown, expectedCode: EvolutionErrorCode): void { + assert.throws(fn, (err: unknown) => { + assert.ok(err instanceof EvolutionError, `expected EvolutionError, got ${String(err)}`); + assert.equal(err.code, expectedCode); + return true; + }); +} + +async function assertEvolutionErrorAsync( + fn: () => Promise, + expectedCode: EvolutionErrorCode, +): Promise { + await assert.rejects(fn, (err: unknown) => { + assert.ok(err instanceof EvolutionError, `expected EvolutionError, got ${String(err)}`); + assert.equal(err.code, expectedCode); + return true; + }); +} + +const VALID_CAMPAIGN_YAML = `apiVersion: loopwright.dev/v1alpha1 +kind: EvolutionCampaign +metadata: + name: flash-decode-sm90a +spec: + taskpack: .loopwright/taskpack.yaml + targetCellId: cuda-h100-whole + stages: + mode: specialist-then-portfolio + specialistBuckets: + - id: bs1-isl4k + heldOutWorkloadId: decode-bs1-4k + - id: bs16-isl8k + heldOutWorkloadId: decode-bs16-8k + portfolioHeldOutWorkloadId: decode-portfolio-holdout + population: + islands: 4 + migrationIntervalGenerations: 8 + maxMigrationElites: 1 + nicheAxes: + - id: bound_pipeline + kind: enum + values: [hbm, l2, smem_lds_ub, tensor_cube, vector_valu] + - id: occupancy_band + kind: numeric_bins + edges: [0, 25, 50, 75, 100] + sampling: + noveltyDecayLambda: 1.0 + mutationWeights: + diff_tune: 0.5 + full_rewrite: 0.3 + crossover: 0.2 + modelBandit: ucb1 + maxCrossoversPerPrompt: 2 + teamEvolution: + enabled: true + supervisorRoleId: supervisor + allowedArchetypeRoles: [probe-readonly, mutator-sandboxed, reviewer] + stallGenerations: 4 + minHypervolumeDelta: 0.001 + triggerOnRunEvalPathology: true + trialGenerations: 2 + maxTeamSize: 3 + maxTeamSteps: 4 + objectives: + - metric: latency_us_p50 + direction: minimize + - metric: goodput_rps + direction: maximize + - metric: peak_mem_bytes + direction: minimize + budgets: + maxGenerations: 40 + maxEvaluations: 160 + maxConcurrentEvaluations: 4 + targetRooflineHeadroom: 1.08 + scratchpadIntervalGenerations: 5 + export: + format: oci-layout + outputDir: .loopwright-out/bundles/flash-decode-sm90a +`; + +test('schema: parseEvolutionCampaignDocument produces null-prototype records and enforces bounds', async () => { + const manifest = parseEvolutionCampaignDocument(VALID_CAMPAIGN_YAML); + assert.equal(Object.getPrototypeOf(manifest), null); + assert.equal(Object.getPrototypeOf(manifest.metadata), null); + assert.equal(Object.getPrototypeOf(manifest.spec), null); + assert.equal(manifest.metadata.name, 'flash-decode-sm90a'); + assert.equal(manifest.spec.stages.mode, 'specialist-then-portfolio'); + if (manifest.spec.stages.mode === 'specialist-then-portfolio') { + assert.equal(manifest.spec.stages.specialistBuckets.length, 2); + assert.equal(manifest.spec.stages.portfolioHeldOutWorkloadId, 'decode-portfolio-holdout'); + } + assert.equal(manifest.spec.population.islands, 4); + assert.equal(manifest.spec.sampling.modelBandit, 'ucb1'); + assert.equal(manifest.spec.teamEvolution?.maxTeamSize, 3); + assert.equal(manifest.spec.objectives.length, 3); + assert.equal(manifest.spec.export?.format, 'oci-layout'); + + // Oversized YAML document (> 65,536 bytes) rejected + const oversized = `${VALID_CAMPAIGN_YAML}# ${'x'.repeat(EVOLUTION_CAMPAIGN_MAX_BYTES)}\n`; + assertEvolutionError(() => parseEvolutionCampaignDocument(oversized), 'EVOLUTION_SCHEMA_INVALID'); + + // Negative zero, NaN, Infinity, prototype keys, unknown keys, lone surrogates rejected + assertEvolutionError( + () => parseEvolutionCampaignDocument(VALID_CAMPAIGN_YAML.replace('noveltyDecayLambda: 1.0', 'noveltyDecayLambda: -0.0')), + 'EVOLUTION_SCHEMA_INVALID', + ); + assertEvolutionError( + () => parseEvolutionCampaignDocument(`${VALID_CAMPAIGN_YAML} unknownExtraField: true\n`), + 'EVOLUTION_SCHEMA_INVALID', + ); + assertEvolutionError( + () => parseEvolutionCampaignDocument(VALID_CAMPAIGN_YAML.replace('flash-decode-sm90a', 'bad\uD800name')), + 'EVOLUTION_SCHEMA_INVALID', + ); + assertEvolutionError( + () => parseNullProtoJson('{"__proto__": {"polluted": true}}'), + 'EVOLUTION_SCHEMA_INVALID', + ); + assertEvolutionError( + () => parseNullProtoJson('{"value": -0}'), + 'EVOLUTION_SCHEMA_INVALID', + ); + assertEvolutionError( + () => parseNullProtoJson('{"dup": 1, "dup": 2}'), + 'EVOLUTION_SCHEMA_INVALID', + ); + + // Out-of-bounds population, sampling, teamEvolution, and budget fields rejected + assertEvolutionError( + () => parseEvolutionCampaignDocument(VALID_CAMPAIGN_YAML.replace('islands: 4', 'islands: 17')), + 'EVOLUTION_SCHEMA_INVALID', + ); + assertEvolutionError( + () => parseEvolutionCampaignDocument(VALID_CAMPAIGN_YAML.replace('edges: [0, 25, 50, 75, 100]', 'edges: [0, 50, 25, 100]')), + 'EVOLUTION_SCHEMA_INVALID', + ); + assertEvolutionError( + () => parseEvolutionCampaignDocument(VALID_CAMPAIGN_YAML.replace('maxCrossoversPerPrompt: 2', 'maxCrossoversPerPrompt: 5')), + 'EVOLUTION_SCHEMA_INVALID', + ); + assertEvolutionError( + () => parseEvolutionCampaignDocument(VALID_CAMPAIGN_YAML.replace('targetRooflineHeadroom: 1.08', 'targetRooflineHeadroom: 0.95')), + 'EVOLUTION_SCHEMA_INVALID', + ); + assertEvolutionError( + () => parseEvolutionCampaignDocument(VALID_CAMPAIGN_YAML.replace('outputDir: .loopwright-out/bundles/flash-decode-sm90a', 'outputDir: ../escape')), + 'EVOLUTION_SCHEMA_INVALID', + ); + + // File loading with O_NOFOLLOW rejects symlinks + const tempDir = mkdtempSync(join(tmpdir(), 'evo-schema-test-')); + try { + const campaignPath = join(tempDir, 'campaign.yaml'); + const symlinkPath = join(tempDir, 'campaign-link.yaml'); + writeFileSync(campaignPath, VALID_CAMPAIGN_YAML, 'utf8'); + symlinkSync(campaignPath, symlinkPath); + + const loaded = await loadEvolutionCampaignFile(campaignPath); + assert.equal(loaded.metadata.name, 'flash-decode-sm90a'); + await assertEvolutionErrorAsync(() => loadEvolutionCampaignFile(symlinkPath), 'EVOLUTION_SYMLINK_FORBIDDEN'); + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } +}); + +test('schema: parseTeamPatchV1 validates DAG acyclicity, handoffs, diagnosis byte caps, and secrets', () => { + const scrubber = new SecretScrubber(); + scrubber.register('super-secret-credential-9999'); + + const validPatch = parseTeamPatchV1({ + kind: 'TeamPatch', + schemaVersion: 'team-patch.v1', + diagnosis: { + summary: 'Optimizer conflates Roofline bank-conflict diagnosis with tile-size mutation.', + plateauCategory: 'coupled_responsibilities', + rationale: 'Splitting read-only Roofline diagnosis from sandboxed mutation isolates shared-memory layout analysis.', + }, + roles: [ + { + id: 'diag-probe', + archetypeRoleId: 'probe-readonly', + purpose: 'review', + prompt: 'Analyze Stage B Roofline stall counters and propose tile layout changes.', + tools: ['read'], + timeoutSeconds: 120, + }, + { + id: 'kernel-mutator', + archetypeRoleId: 'mutator-sandboxed', + purpose: 'task', + prompt: 'Apply the proposed shared-memory swizzle inside EVOLVE-BLOCK.', + model: 'claude-sonnet-4-6', + tools: ['read', 'edit'], + }, + ], + steps: [ + { + id: 'analyze', + roleId: 'diag-probe', + dependsOn: [], + }, + { + id: 'mutate', + roleId: 'kernel-mutator', + dependsOn: ['analyze'], + handoffs: [ + { + id: 'diag-summary', + fromStep: 'analyze', + source: { kind: 'submission' }, + select: { kind: 'markdown_heading', heading: '## Tile Plan' }, + }, + ], + onRework: { + rejectTo: 'analyze', + maxReworks: 2, + }, + }, + ], + }, { scrubber }); + + assert.equal(Object.getPrototypeOf(validPatch), null); + assert.equal(validPatch.roles.length, 2); + assert.equal(validPatch.steps.length, 2); + + // Cycle in steps[] (A -> B -> A) rejected + assertEvolutionError( + () => parseTeamPatchV1({ + kind: 'TeamPatch', + schemaVersion: 'team-patch.v1', + diagnosis: { + summary: 'Cycle test', + plateauCategory: 'other', + rationale: 'Cycle test rationale', + }, + roles: [ + { id: 'r1', archetypeRoleId: 'probe-readonly', purpose: 'review', prompt: 'p1', tools: ['read'] }, + ], + steps: [ + { id: 's1', roleId: 'r1', dependsOn: ['s2'] }, + { id: 's2', roleId: 'r1', dependsOn: ['s1'] }, + ], + }), + 'EVOLUTION_SCHEMA_INVALID', + ); + + // Unknown roleId and non-ancestor handoff.fromStep rejected + assertEvolutionError( + () => parseTeamPatchV1({ + kind: 'TeamPatch', + schemaVersion: 'team-patch.v1', + diagnosis: { + summary: 'Bad role ref', + plateauCategory: 'other', + rationale: 'Missing role', + }, + roles: [ + { id: 'r1', archetypeRoleId: 'probe-readonly', purpose: 'review', prompt: 'p1', tools: ['read'] }, + ], + steps: [ + { id: 's1', roleId: 'nonexistent', dependsOn: [] }, + ], + }), + 'EVOLUTION_SCHEMA_INVALID', + ); + + assertEvolutionError( + () => parseTeamPatchV1({ + kind: 'TeamPatch', + schemaVersion: 'team-patch.v1', + diagnosis: { + summary: 'Bad handoff ancestor', + plateauCategory: 'other', + rationale: 'Parallel non-ancestor handoff', + }, + roles: [ + { id: 'r1', archetypeRoleId: 'probe-readonly', purpose: 'review', prompt: 'p1', tools: ['read'] }, + ], + steps: [ + { id: 's1', roleId: 'r1', dependsOn: [] }, + { + id: 's2', + roleId: 'r1', + dependsOn: [], + handoffs: [{ fromStep: 's1', source: { kind: 'submission' }, select: { kind: 'full' } }], + }, + ], + }), + 'EVOLUTION_SCHEMA_INVALID', + ); + + // Diagnosis > 4,096 bytes and total payload > 32,768 bytes rejected + assertEvolutionError( + () => parseTeamPatchV1({ + kind: 'TeamPatch', + schemaVersion: 'team-patch.v1', + diagnosis: { + summary: 'x'.repeat(TEAM_PATCH_DIAGNOSIS_MAX_BYTES), + plateauCategory: 'other', + rationale: 'overflow', + }, + roles: [{ id: 'r1', archetypeRoleId: 'probe-readonly', purpose: 'review', prompt: 'p1', tools: ['read'] }], + steps: [{ id: 's1', roleId: 'r1', dependsOn: [] }], + }), + 'EVOLUTION_SCHEMA_INVALID', + ); + + assertEvolutionError( + () => parseTeamPatchV1(' '.repeat(TEAM_PATCH_MAX_BYTES + 10)), + 'EVOLUTION_SCHEMA_INVALID', + ); + + // Registered secret inside prompt or diagnosis rejected + assertEvolutionError( + () => parseTeamPatchV1({ + kind: 'TeamPatch', + schemaVersion: 'team-patch.v1', + diagnosis: { + summary: 'Clean summary', + plateauCategory: 'other', + rationale: 'Leaked super-secret-credential-9999 in diagnosis', + }, + roles: [{ id: 'r1', archetypeRoleId: 'probe-readonly', purpose: 'review', prompt: 'p1', tools: ['read'] }], + steps: [{ id: 's1', roleId: 'r1', dependsOn: [] }], + }, { scrubber }), + 'SECRET_LEAK_DETECTED', + ); +}); + +test('schema: parseDispatchManifestV1 enforces 1..64 rules and mandatory baseline fallback', () => { + const digest = makeDigest('kernel-cubin-v1'); + const parsed = parseDispatchManifestV1({ + version: 1, + fallback: 'baseline', + rules: [ + { + bucketId: 'bs1-isl4k', + dimensionBounds: { + batch_size: { min: 1, max: 4 }, + seq_len: { min: 1024, max: 4096 }, + }, + dtypes: ['fp16', 'bf16'], + alignmentBytes: 16, + blobDigest: digest, + blobPath: `blobs/sha256/${digest.hex}`, + entrypoint: 'flash_decode_bs1_sm90a', + }, + ], + }); + + assert.equal(Object.getPrototypeOf(parsed), null); + assert.equal(parsed.fallback, 'baseline'); + assert.equal(parsed.rules.length, 1); + assert.equal(parsed.rules[0]?.entrypoint, 'flash_decode_bs1_sm90a'); + + // Missing or non-baseline fallback rejected + assertEvolutionError( + () => parseDispatchManifestV1({ version: 1, rules: parsed.rules }), + 'EVOLUTION_SCHEMA_INVALID', + ); + assertEvolutionError( + () => parseDispatchManifestV1({ version: 1, fallback: 'error', rules: parsed.rules }), + 'EVOLUTION_SCHEMA_INVALID', + ); + + // Empty rules or min > max rejected + assertEvolutionError( + () => parseDispatchManifestV1({ version: 1, fallback: 'baseline', rules: [] }), + 'EVOLUTION_SCHEMA_INVALID', + ); + assertEvolutionError( + () => parseDispatchManifestV1({ + version: 1, + fallback: 'baseline', + rules: [ + { + bucketId: 'bs1-isl4k', + dimensionBounds: { batch_size: { min: 8, max: 2 } }, + blobDigest: digest, + entrypoint: 'flash_decode_bs1_sm90a', + }, + ], + }), + 'EVOLUTION_SCHEMA_INVALID', + ); +}); + +test('store: enforces O_NOFOLLOW symlinks, DELETE/FULL STRICT pragmas, lease fencing, 1000ms clock drift, team trial rollback, preemption accounting, and serialized concurrent writes', async () => { + const stateSchemaBefore = expectedSchema(); + const baseTemp = mkdtempSync(join(tmpdir(), 'evo-store-test-')); + + try { + // 1. Symlink campaignRoot rejected fail-closed with EVOLUTION_SYMLINK_FORBIDDEN + const realRoot = join(baseTemp, 'real-campaign'); + const symlinkRoot = join(baseTemp, 'symlink-campaign'); + symlinkSync(realRoot, symlinkRoot); + await assertEvolutionErrorAsync( + () => EvolutionCampaignStore.open({ campaignRoot: symlinkRoot }), + 'EVOLUTION_SYMLINK_FORBIDDEN', + ); + + // 2. Controllable monotonic/wall clock + let monoMs = 10_000; + let wallMs = 1_700_000_000_000; + const clock: CampaignClockSource = { + nowMonotonicMs: () => monoMs, + nowWallMs: () => wallMs, + }; + const advanceClock = (deltaMono: number, deltaWall = deltaMono): void => { + monoMs += deltaMono; + wallMs += deltaWall; + }; + + const store = await EvolutionCampaignStore.open({ campaignRoot: realRoot, clock }); + try { + const pragmas = await store.inspectPragmas(); + assert.equal(pragmas.journalMode, 'delete'); + assert.equal(pragmas.synchronous, 2); // FULL = 2 + assert.equal(pragmas.foreignKeys, 1); + for (const requiredTable of [ + 'campaign_meta', + 'campaigns', + 'islands', + 'team_configs', + 'individuals', + 'lineage_edges', + 'model_bandit_arms', + 'scratchpad_snapshots', + ]) { + assert.ok(pragmas.tables.includes(requiredTable), `missing STRICT table ${requiredTable}`); + } + + // 3. Lease fencing + advanceClock(50); + const lease1 = await store.acquireLease('controller-1'); + assert.equal(lease1.fenceEpoch, 1); + + const manifest = parseEvolutionCampaignDocument(VALID_CAMPAIGN_YAML); + advanceClock(25); + const campaign = await store.createCampaign(lease1, { + campaignId: 'camp-001', + manifest, + manifestDigest: makeDigest(VALID_CAMPAIGN_YAML), + baseRevision: 'a'.repeat(40), + lockHash: makeDigest('lock-001'), + modelIds: ['claude-sonnet-4-6', 'gpt-5.4'], + }); + assert.equal(campaign.evaluationsUsed, 0); + assert.equal(campaign.preemptionsCount, 0); + + const islands = await store.listIslands('camp-001'); + assert.equal(islands.length, 4); + const island0BaselineTeamId = islands[0]!.activeTeamConfigId; + + // Second lease immediately fences lease1 + advanceClock(25); + const lease2 = await store.acquireLease('controller-2'); + assert.equal(lease2.fenceEpoch, 2); + await assertEvolutionErrorAsync( + () => store.updateCampaignProgress(lease1, { campaignId: 'camp-001', currentGeneration: 1 }), + 'EVOLUTION_LEASE_FENCED', + ); + + // 4.Foreign key enforcement on individuals.team_config_id + advanceClock(10); + await assertEvolutionErrorAsync( + () => store.recordIndividual(lease2, { + individualId: 'ind-bad-fk', + campaignId: 'camp-001', + islandId: 0, + generation: 0, + bucketId: 'bs1-isl4k', + teamConfigId: 'nonexistent-team-id', + modelId: 'claude-sonnet-4-6', + trackId: 'cuda_raw', + mutationKind: 'baseline', + status: 'passed', + failureReason: null, + nicheKey: 'bound_pipeline=hbm|occupancy_band=[50,75)', + paretoRank: 1, + crowdingDistance: Number.POSITIVE_INFINITY, + scalarFitness: 0.5, + codeSliceCasDigest: makeDigest('code-0'), + evidenceDigest: makeDigest('ev-0'), + verdictReceiptCasDigest: makeDigest('verdict-0'), + outputArtifacts: [], + metrics: { latency_us_p50: 120, goodput_rps: 900, peak_mem_bytes: 4096 }, + }), + 'EVOLUTION_STORE_ERROR', + ); + + // 5. Team trial promotion vs auto-rollback + preemption non-consumption + advanceClock(10); + const trialTeam1 = await store.createTrialTeamConfig(lease2, { + teamConfigId: 'team-trial-1', + campaignId: 'camp-001', + islandId: 0, + parentTeamConfigId: island0BaselineTeamId, + createdGeneration: 4, + trialBudgetGenerations: 2, + diagnosis: { + summary: 'Stalled on HBM bandwidth', + plateauCategory: 'resource_spill_trap', + rationale: 'Separate spill auditor from mutator', + }, + patchCasDigest: makeDigest('patch-1'), + }); + assert.equal(trialTeam1.status, 'trial'); + assert.equal((await store.getIsland('camp-001', 0))?.activeTeamConfigId, 'team-trial-1'); + + // Preempted generation must NOT consume trial_used_generations + advanceClock(10); + const afterPreemptTrial = await store.recordTeamTrialGeneration(lease2, { + teamConfigId: 'team-trial-1', + advancedPareto: false, + discoveredNiche: false, + preempted: true, + }); + assert.equal(afterPreemptTrial.trialUsedGenerations, 0); + assert.equal(afterPreemptTrial.status, 'trial'); + + // Two non-advancing generations auto-roll back to baseline team + advanceClock(10); + const gen1Trial = await store.recordTeamTrialGeneration(lease2, { + teamConfigId: 'team-trial-1', + advancedPareto: false, + discoveredNiche: false, + }); + assert.equal(gen1Trial.trialUsedGenerations, 1); + assert.equal(gen1Trial.status, 'trial'); + + advanceClock(10); + const gen2Trial = await store.recordTeamTrialGeneration(lease2, { + teamConfigId: 'team-trial-1', + advancedPareto: false, + discoveredNiche: false, + }); + assert.equal(gen2Trial.trialUsedGenerations, 2); + assert.equal(gen2Trial.status, 'rolled_back'); + assert.equal((await store.getIsland('camp-001', 0))?.activeTeamConfigId, island0BaselineTeamId); + + // Trial team that advances Pareto promotes immediately + advanceClock(10); + await store.createTrialTeamConfig(lease2, { + teamConfigId: 'team-trial-2', + campaignId: 'camp-001', + islandId: 1, + parentTeamConfigId: islands[1]!.activeTeamConfigId, + createdGeneration: 5, + trialBudgetGenerations: 2, + diagnosis: { + summary: 'Coupled concerns', + plateauCategory: 'coupled_responsibilities', + rationale: 'Split probe and mutator', + }, + patchCasDigest: makeDigest('patch-2'), + }); + advanceClock(10); + const promoted = await store.recordTeamTrialGeneration(lease2, { + teamConfigId: 'team-trial-2', + advancedPareto: true, + discoveredNiche: true, + }); + assert.equal(promoted.status, 'promoted'); + assert.equal(promoted.paretoAdvances, 1); + assert.equal(promoted.nicheDiscoveries, 1); + assert.equal((await store.getIsland('camp-001', 1))?.activeTeamConfigId, 'team-trial-2'); + + // 6. Concurrent serialized writes via enqueue (16 parallel operations + preemptions) + advanceClock(20); + await store.recordIndividual(lease2, { + individualId: 'ind-seed-0', + campaignId: 'camp-001', + islandId: 0, + generation: 0, + bucketId: 'bs1-isl4k', + teamConfigId: island0BaselineTeamId, + modelId: 'claude-sonnet-4-6', + trackId: 'cuda_raw', + mutationKind: 'baseline', + status: 'passed', + failureReason: null, + nicheKey: 'bound_pipeline=hbm|occupancy_band=[25,50)', + paretoRank: 1, + crowdingDistance: Number.POSITIVE_INFINITY, + scalarFitness: 0.4, + countEvaluation: false, + codeSliceCasDigest: makeDigest('seed-slice'), + evidenceDigest: makeDigest('seed-ev'), + verdictReceiptCasDigest: makeDigest('seed-verdict'), + outputArtifacts: [], + metrics: { latency_us_p50: 100, goodput_rps: 1000, peak_mem_bytes: 2048 }, + }); + + const concurrentTasks = Array.from({ length: 16 }, (_, idx) => { + const isPreempted = idx % 5 === 0; // idx = 0, 5, 10, 15 -> 4 preempted (1 per island), 12 counted evaluations + return store.recordIndividual(lease2, { + individualId: `ind-conc-${idx}`, + campaignId: 'camp-001', + islandId: idx % 4, + generation: 1, + bucketId: 'bs1-isl4k', + teamConfigId: islands[idx % 4]!.activeTeamConfigId === 'team-trial-2' && idx % 4 === 1 + ? 'team-trial-2' + : islands[idx % 4]!.activeTeamConfigId, + modelId: idx % 2 === 0 ? 'claude-sonnet-4-6' : 'gpt-5.4', + trackId: 'triton', + mutationKind: 'diff_tune', + status: isPreempted ? 'preempted' : 'passed', + failureReason: isPreempted ? 'BENCHMARK_PREEMPTED' : null, + nicheKey: isPreempted ? null : `bound_pipeline=tensor_cube|occupancy_band=[50,75)`, + paretoRank: isPreempted ? null : 1, + crowdingDistance: isPreempted ? null : 0.75, + scalarFitness: isPreempted ? null : 0.5 + idx * 0.01, + codeSliceCasDigest: makeDigest(`slice-${idx}`), + evidenceDigest: isPreempted ? null : makeDigest(`ev-${idx}`), + verdictReceiptCasDigest: isPreempted ? null : makeDigest(`verdict-${idx}`), + outputArtifacts: [], + metrics: { latency_us_p50: 95 - idx, goodput_rps: 1050 + idx * 10, peak_mem_bytes: 2048 }, + lineageEdges: [ + { + campaignId: 'camp-001', + childIndividualId: `ind-conc-${idx}`, + parentIndividualId: 'ind-seed-0', + role: 'primary', + sourceIslandId: 0, + createdGeneration: 1, + }, + ], + }); + }); + + await Promise.all(concurrentTasks); + + const updatedCampaign = await store.getCampaign('camp-001'); + assert.equal(updatedCampaign?.evaluationsUsed, 12); + assert.equal(updatedCampaign?.preemptionsCount, 4); + + const island0Elites = await store.getIslandNicheElites('camp-001', 0, 'bs1-isl4k'); + assert.equal(island0Elites.size, 2); + assert.equal( + island0Elites.get('bound_pipeline=tensor_cube|occupancy_band=[50,75)')?.individualId, + 'ind-conc-12', + ); + const seedReloaded = await store.getIndividual('ind-seed-0'); + assert.equal(seedReloaded?.crowdingDistance, Number.POSITIVE_INFINITY); + + // 7. Clock drift > 1,000ms rejected fail-closed with EVOLUTION_CLOCK_DRIFT + advanceClock(100, 1_250); // +1,150ms drift (> 1,000ms limit) + await assertEvolutionErrorAsync( + () => store.updateCampaignProgress(lease2, { campaignId: 'camp-001', currentGeneration: 2 }), + 'EVOLUTION_CLOCK_DRIFT', + ); + } finally { + await store.close(); + } + + // 8. Reopening existing store after process stop/resume works when monotonic+wall advance, and rejects regressed clocks + const reopened = await EvolutionCampaignStore.open({ + campaignRoot: realRoot, + createIfMissing: false, + clock: { + nowMonotonicMs: () => monoMs + 5_000, + nowWallMs: () => wallMs + 30_000, + }, + }); + const resumedCampaign = await reopened.getCampaign('camp-001'); + assert.equal(resumedCampaign?.evaluationsUsed, 12); + assert.equal(resumedCampaign?.preemptionsCount, 4); + await reopened.close(); + + await assertEvolutionErrorAsync( + () => EvolutionCampaignStore.open({ + campaignRoot: realRoot, + createIfMissing: false, + clock: { + nowMonotonicMs: () => 500, // Regressed behind persisted last_monotonic_ms + nowWallMs: () => wallMs + 30_000, + }, + }), + 'EVOLUTION_CLOCK_DRIFT', + ); + + // 8. Symlink campaign.sqlite rejected on reopen + const symlinkDbDir = join(baseTemp, 'symlink-db-campaign'); + const store2 = await EvolutionCampaignStore.open({ campaignRoot: symlinkDbDir }); + await store2.close(); + rmSync(join(symlinkDbDir, 'campaign.sqlite')); + symlinkSync(join(realRoot, 'campaign.sqlite'), join(symlinkDbDir, 'campaign.sqlite')); + await assertEvolutionErrorAsync( + () => EvolutionCampaignStore.open({ campaignRoot: symlinkDbDir }), + 'EVOLUTION_SYMLINK_FORBIDDEN', + ); + } finally { + rmSync(baseTemp, { recursive: true, force: true }); + } + + // Verify @loopwright/state schema digest is byte-for-byte untouched + assert.equal(expectedSchema(), stateSchemaBefore); +}); diff --git a/packages/evolution/test/scratchpad.test.ts b/packages/evolution/test/scratchpad.test.ts new file mode 100644 index 0000000..e138d1d --- /dev/null +++ b/packages/evolution/test/scratchpad.test.ts @@ -0,0 +1,285 @@ +import assert from 'node:assert/strict'; +import { createHash } from 'node:crypto'; +import { chmodSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import test from 'node:test'; +import { SecretScrubber } from '@loopwright/core'; +import { parseEvolutionCampaignDocument } from '../src/schema.js'; +import { synthesizeCampaignScratchpad } from '../src/scratchpad.js'; +import { EvolutionCampaignStore } from '../src/store.js'; +import { EvolutionError, SCRATCHPAD_MAX_BYTES } from '../src/types.js'; + +function makeDigest(seed: string): { readonly algorithm: 'sha256'; readonly hex: string } { + return { algorithm: 'sha256', hex: createHash('sha256').update(seed, 'utf8').digest('hex') }; +} + +const CAMPAIGN_YAML = `apiVersion: loopwright.dev/v1alpha1 +kind: EvolutionCampaign +metadata: + name: scratchpad-campaign +spec: + taskpack: .loopwright/taskpack.yaml + targetCellId: cuda-h100-whole + 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: 20 + maxEvaluations: 200 + maxConcurrentEvaluations: 2 + scratchpadIntervalGenerations: 5 +`; + +test('scratchpad: synthesizes deterministic <= 16 KiB CAS snapshot with speedup deltas, boundPipeline shifts, failure patterns, 0o400 permissions, and secret scrubbing', async () => { + const tempDir = mkdtempSync(join(tmpdir(), 'evo-scratchpad-test-')); + const scrubber = new SecretScrubber(); + scrubber.register('custom-api-secret-xyz987654'); + + try { + const campaignRoot = join(tempDir, 'campaign'); + const store = await EvolutionCampaignStore.open({ campaignRoot }); + try { + const lease = await store.acquireLease('scratchpad-owner'); + const manifest = parseEvolutionCampaignDocument(CAMPAIGN_YAML); + await store.createCampaign(lease, { + campaignId: 'camp-sp', + manifest, + manifestDigest: makeDigest(CAMPAIGN_YAML), + baseRevision: 'b'.repeat(40), + lockHash: makeDigest('lock-sp'), + modelIds: ['claude-sonnet-4-6'], + }); + + const islands = await store.listIslands('camp-sp'); + const team0 = islands[0]!.activeTeamConfigId; + + // Seed baseline individual (HBM-bound, 120us) + await store.recordIndividual(lease, { + individualId: 'ind-base', + campaignId: 'camp-sp', + islandId: 0, + generation: 0, + bucketId: null, + teamConfigId: team0, + modelId: 'claude-sonnet-4-6', + trackId: 'cuda_raw', + mutationKind: 'baseline', + status: 'passed', + failureReason: null, + nicheKey: 'bound_pipeline=hbm', + paretoRank: 2, + crowdingDistance: 1.0, + scalarFitness: 0.4, + countEvaluation: false, + codeSliceCasDigest: makeDigest('base-code'), + evidenceDigest: makeDigest('base-ev'), + verdictReceiptCasDigest: makeDigest('base-vr'), + outputArtifacts: [], + metrics: { latency_us_p50: 120, goodput_rps: 800 }, + hardwareDiagnostics: { boundPipeline: 'hbm', occupancyPct: 40, localSpillBytes: 0 }, + }); + + // Advancing child (shifts hbm -> tensor_cube, 120us -> 60us = 2.00x speedup!) + await store.recordIndividual(lease, { + individualId: 'ind-fast', + campaignId: 'camp-sp', + islandId: 0, + generation: 1, + bucketId: null, + teamConfigId: team0, + modelId: 'claude-sonnet-4-6', + trackId: 'cute', + mutationKind: 'full_rewrite', + status: 'passed', + failureReason: null, + nicheKey: 'bound_pipeline=tensor_cube', + paretoRank: 1, + crowdingDistance: Number.POSITIVE_INFINITY, + scalarFitness: 0.95, + codeSliceCasDigest: makeDigest('fast-code'), + evidenceDigest: makeDigest('fast-ev'), + verdictReceiptCasDigest: makeDigest('fast-vr'), + outputArtifacts: [], + metrics: { latency_us_p50: 60, goodput_rps: 1600 }, + hardwareDiagnostics: { boundPipeline: 'tensor_cube', occupancyPct: 65, localSpillBytes: 0 }, + lineageEdges: [ + { + campaignId: 'camp-sp', + childIndividualId: 'ind-fast', + parentIndividualId: 'ind-base', + role: 'primary', + sourceIslandId: 0, + createdGeneration: 1, + }, + ], + }); + + // Populate recurring failure patterns (including secret strings and verbose payload to stress 16 KiB cap) + for (let i = 0; i < 45; i++) { + const reason = i % 3 === 0 + ? 'STAGE_A_STATIC_AUDIT_FAILED' + : i % 3 === 1 + ? 'METRIC_THRESHOLD_FAILED' + : 'STAGE_A_SPILL_CEILING'; + await store.recordIndividual(lease, { + individualId: `ind-fail-${i}`, + campaignId: 'camp-sp', + islandId: 0, + generation: 2 + Math.floor(i / 5), + bucketId: null, + teamConfigId: team0, + modelId: 'claude-sonnet-4-6', + trackId: 'triton', + mutationKind: 'diff_tune', + status: 'failed', + failureReason: reason, + nicheKey: null, + paretoRank: null, + crowdingDistance: null, + scalarFitness: null, + codeSliceCasDigest: makeDigest(`fail-code-${i}`), + evidenceDigest: null, + verdictReceiptCasDigest: null, + outputArtifacts: [], + metrics: { max_ulp: i % 3 === 1 ? 8 : 0 }, + findings: [ + { + title: reason === 'STAGE_A_STATIC_AUDIT_FAILED' ? 'Forbidden cublas symbol' : 'ULP / spill violation', + severity: 'high', + evidence: `Failure detail ${i} with token ghp_1234567890abcdefghijklmnop and custom-api-secret-xyz987654 ${'padding-'.repeat(40)}`, + }, + ], + lineageEdges: [ + { + campaignId: 'camp-sp', + childIndividualId: `ind-fail-${i}`, + parentIndividualId: 'ind-fast', + role: 'primary', + sourceIslandId: 0, + createdGeneration: 2, + }, + ], + }); + } + + // Also add many distinct synthetic niche improvements to test <= 16 KiB bounding + for (let n = 0; n < 40; n++) { + await store.recordIndividual(lease, { + individualId: `ind-niche-${n}`, + campaignId: 'camp-sp', + islandId: 1, + generation: 3, + bucketId: null, + teamConfigId: islands[1]!.activeTeamConfigId, + modelId: 'claude-sonnet-4-6', + trackId: 'cute', + mutationKind: 'diff_tune', + status: 'passed', + failureReason: null, + nicheKey: `bound_pipeline=smem_lds_ub|synthetic_bin=${n}-${'wide'.repeat(12)}`, + paretoRank: 2, + crowdingDistance: 0.5, + scalarFitness: 0.7, + codeSliceCasDigest: makeDigest(`niche-${n}`), + evidenceDigest: makeDigest(`niche-ev-${n}`), + verdictReceiptCasDigest: makeDigest(`niche-vr-${n}`), + outputArtifacts: [], + metrics: { latency_us_p50: 80 - (n % 20), goodput_rps: 1200 + n * 5 }, + hardwareDiagnostics: { boundPipeline: 'smem_lds_ub', localSpillBytes: 64 }, + lineageEdges: [ + { + campaignId: 'camp-sp', + childIndividualId: `ind-niche-${n}`, + parentIndividualId: 'ind-base', + role: 'primary', + sourceIslandId: 0, + createdGeneration: 3, + }, + ], + }); + } + + const synth1 = await synthesizeCampaignScratchpad({ + store, + lease, + campaignId: 'camp-sp', + generation: 5, + scrubber, + }); + + assert.ok(synth1.snapshot.byteLength <= SCRATCHPAD_MAX_BYTES); + assert.equal(Buffer.byteLength(synth1.content, 'utf8'), synth1.snapshot.byteLength); + assert.match(synth1.content, /2\.00x/); + assert.match(synth1.content, /hbm -> tensor_cube/); + assert.match(synth1.content, /STAGE_A_STATIC_AUDIT_FAILED/); + + // Zero secrets in persisted or returned scratchpad + assert.equal(scrubber.containsSecret(synth1.content), false); + assert.equal(synth1.content.includes('ghp_1234567890abcdefghijklmnop'), false); + assert.equal(synth1.content.includes('custom-api-secret-xyz987654'), false); + + // Verify CAS file on disk has 0o400 permissions, nlink === 1, and exact SHA-256 + const casStat = lstatSync(synth1.casFilePath); + assert.equal(casStat.isSymbolicLink(), false); + assert.equal(casStat.nlink, 1); + assert.equal(casStat.mode & 0o777, 0o400); + const diskBytes = readFileSync(synth1.casFilePath); + assert.equal(createHash('sha256').update(diskBytes).digest('hex'), synth1.snapshot.casDigest.hex); + + // Deterministic repeatability: synthesizing at the same state produces identical CAS digest + const synth2 = await synthesizeCampaignScratchpad({ + store, + lease, + campaignId: 'camp-sp', + generation: 5, + snapshotId: 'snap-repeat', + scrubber, + }); + assert.equal(synth2.snapshot.casDigest.hex, synth1.snapshot.casDigest.hex); + assert.equal(synth2.content, synth1.content); + + const latest = await store.getLatestScratchpadSnapshot('camp-sp'); + assert.equal(latest?.casDigest.hex, synth1.snapshot.casDigest.hex); + } finally { + // Restore write permission before temp cleanup so rmSync works across all platforms + chmodSync(join(campaignRoot, 'cas', 'sha256'), 0o700); + await store.close(); + } + + // Symlink CAS directory fails closed with EVOLUTION_SYMLINK_FORBIDDEN + const badRoot = join(tempDir, 'bad-cas-campaign'); + const storeBad = await EvolutionCampaignStore.open({ campaignRoot: badRoot }); + try { + const externalDir = join(tempDir, 'ext-dir'); + mkdirSync(externalDir); + rmSync(join(badRoot, 'cas'), { recursive: true, force: true }); + symlinkSync(externalDir, join(badRoot, 'cas')); + await assert.rejects( + () => storeBad.writeCasBlob('hello'), + (err: unknown) => err instanceof EvolutionError && err.code === 'EVOLUTION_SYMLINK_FORBIDDEN', + ); + } finally { + await storeBad.close(); + } + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } +}); diff --git a/packages/evolution/test/team-supervisor.test.ts b/packages/evolution/test/team-supervisor.test.ts new file mode 100644 index 0000000..c10e55b --- /dev/null +++ b/packages/evolution/test/team-supervisor.test.ts @@ -0,0 +1,1440 @@ +import assert from 'node:assert/strict'; +import { createHash } from 'node:crypto'; +import { + chmodSync, + existsSync, + lstatSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + symlinkSync, + writeFileSync, +} from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import test from 'node:test'; +import { + SecretScrubber, + isWritablePath, + validateDocument, + type Digest, + type TaskContract, +} from '@loopwright/core'; +import { + RUN_EVAL_SCHEMA_VERSION, + type RunEvalReport, + type TrustedRegistry, +} from '@loopwright/controller'; +import { + compileDeclarativeTaskpack, + loadDeclarativeTaskpack, + type TaskpackManifest, +} from '@loopwright/taskpack'; +import { parseEvolutionCampaignDocument } from '../src/schema.js'; +import { EvolutionCampaignStore } from '../src/store.js'; +import { + createLocalRunStoreSupervisorRunner, + evaluateTeamEvolutionTrigger, + hasRunEvalLoopPathology, + recordTeamTrialOutcome, + runPlateauSupervisorTurn, + stageSupervisorContext, + validateAndCompileTeamPatch, +} from '../src/team-supervisor.js'; +import { + EvolutionError, + type EvolutionBudgetsSpec, + type EvolutionErrorCode, + type EvolutionTeamSpec, + type IslandRecord, + type TeamPatchV1, +} from '../src/types.js'; + +function makeDigest(seed: string): Digest { + return { algorithm: 'sha256', hex: createHash('sha256').update(seed, 'utf8').digest('hex') }; +} + +function assertEvolutionError(fn: () => unknown, expectedCode: EvolutionErrorCode): void { + assert.throws(fn, (err: unknown) => { + assert.ok(err instanceof EvolutionError, `expected EvolutionError, got ${String(err)}`); + assert.equal(err.code, expectedCode); + return true; + }); +} + +const TEAM_EVOLUTION_SPEC: EvolutionTeamSpec = Object.freeze({ + enabled: true, + supervisorRoleId: 'supervisor', + allowedArchetypeRoles: ['probe-readonly', 'mutator-sandboxed', 'reviewer'], + stallGenerations: 4, + minHypervolumeDelta: 0.001, + triggerOnRunEvalPathology: true, + trialGenerations: 2, + maxTeamSize: 3, + maxTeamSteps: 4, +}); + +const DEFAULT_BUDGETS: EvolutionBudgetsSpec = Object.freeze({ + maxGenerations: 20, + maxEvaluations: 80, + maxConcurrentEvaluations: 2, + targetRooflineHeadroom: 1.08, + scratchpadIntervalGenerations: 5, +}); + +const BASE_TASKPACK_YAML = ` +apiVersion: loopwright.dev/v1alpha1 +kind: Taskpack +metadata: + name: flash-decode-team-test +spec: + goal: + candidate: Optimize flash decode kernel inside EVOLVE-BLOCK markers. + noChange: No kernel change needed. + target: + matrix: + - id: cuda-h100-whole + platform: linux/amd64 + variant: cuda12 + hardware: + accelerator: sm_90a + isolationMode: whole_device + deviceCount: 1 + scope: + writable: + - src/kernels/** + protected: + - src/kernels/locked.cu + models: + - provider: anthropic + id: claude-sonnet-4-6 + thinking: medium + - provider: openai + id: gpt-5.4 + thinking: high + roles: + - id: probe-readonly + provider: anthropic + model: claude-sonnet-4-6 + purpose: task + tools: [read] + prompt: Inspect kernel Roofline bottleneck without mutating files. + - id: mutator-sandboxed + provider: anthropic + model: claude-sonnet-4-6 + purpose: task + dependsOn: [probe-readonly] + tools: [read, write, edit, bash] + prompt: Apply bounded kernel changes inside EVOLVE-BLOCK markers. + - id: reviewer + provider: anthropic + model: claude-sonnet-4-6 + purpose: review + dependsOn: [mutator-sandboxed] + tools: [read] + prompt: Review candidate diff against scope and numerical bounds. + 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-h100-whole + heldOutWorkloadId: decode-bs1-4k + allowSyntheticHardwareProbe: true + metricThresholds: + - kind: bounds + metric: max_ulp + max: 2 + bucketScope: all_buckets + publication: + mode: disabled + triggers: + schedule: false + workflowDispatch: true + releasePublished: false + commentCommands: [] +`; + +const CAMPAIGN_WITH_TEAM_YAML = ` +apiVersion: loopwright.dev/v1alpha1 +kind: EvolutionCampaign +metadata: + name: team-evo-campaign +spec: + taskpack: .loopwright/taskpack.yaml + targetCellId: cuda-h100-whole + stages: + mode: single-target + 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 + modelBandit: ucb1 + maxCrossoversPerPrompt: 2 + teamEvolution: + enabled: true + supervisorRoleId: supervisor + allowedArchetypeRoles: [probe-readonly, mutator-sandboxed, reviewer] + stallGenerations: 4 + minHypervolumeDelta: 0.001 + triggerOnRunEvalPathology: true + trialGenerations: 2 + maxTeamSize: 3 + maxTeamSteps: 4 + objectives: + - metric: latency_us_p50 + direction: minimize + - metric: goodput_rps + direction: maximize + budgets: + maxGenerations: 20 + maxEvaluations: 80 + maxConcurrentEvaluations: 2 + targetRooflineHeadroom: 1.08 + scratchpadIntervalGenerations: 5 +`; + +async function makeCompiledBaseFixtures(): Promise<{ + readonly taskpack: TaskpackManifest; + readonly baseTaskContract: TaskContract; + readonly trustedRegistry: TrustedRegistry; +}> { + const taskpack = await loadDeclarativeTaskpack({ + bytes: Buffer.from(BASE_TASKPACK_YAML, 'utf8'), + format: 'yaml', + executionMode: 'delegated', + allowLoopbackHttp: true, + policyProfile: 'local', + }); + const compiled = await compileDeclarativeTaskpack(taskpack, { + mode: 'candidate', + executionMode: 'delegated', + repository: 'local/evolution', + hostPolicy: { policyProfile: 'local', allowWorkflowWrites: false }, + baseRevision: 'a'.repeat(40), + sourceRevision: 'a'.repeat(40), + gateEndpoints: [ + { + id: 'hw-relay', + url: 'http://127.0.0.1:9999', + signingCredentialRef: 'bench-sign', + implementation: 'benchmark-gate.v1', + }, + ], + credentialEnvMap: { + byCredentialRef: { 'bench-sign': 'LOOPWRIGHT_GATE_SIGNING_SECRET' }, + }, + budgets: { + wallTimeMs: 600_000, + totalTokens: 250_000, + perCallOutputTokens: 16_384, + maxModelCalls: 16, + maxConcurrency: 1, + maxFormatRepairs: 0, + maxImplementationRepairs: 0, + maxTransportRetries: 1, + enforcement: { + wallTime: 'hard_admission', + tokens: 'soft_accounting', + modelCalls: 'hard_admission', + concurrency: 'hard_admission', + formatRepairs: 'hard_admission', + implementationRepairs: 'hard_admission', + transportRetries: 'hard_admission', + }, + }, + }); + + const extraResources = [ + { + id: 'res-arch-guide', + kind: 'document' as const, + path: '.loopwright/instructions/sm90a.md', + digest: makeDigest('res-arch-guide'), + }, + { + id: 'res-scratchpad', + kind: 'document' as const, + path: '.loopwright/scratchpad/latest.md', + digest: makeDigest('res-scratchpad'), + }, + ]; + + const baseTaskContract: TaskContract = { + ...compiled.config.spec.task, + spec: { + ...compiled.config.spec.task.spec, + trustedContext: { + ...compiled.config.spec.task.spec.trustedContext, + resources: [...compiled.config.spec.task.spec.trustedContext.resources, ...extraResources], + }, + }, + }; + + // Enforce 60s toolWallMs on probe-readonly profile to test timeout ceiling enforcement + const trustedRegistry: TrustedRegistry = { + ...compiled.registry, + spec: { + ...compiled.registry.spec, + resources: [...compiled.registry.spec.resources, ...extraResources], + roleProfiles: compiled.registry.spec.roleProfiles.map(prof => + prof.id.includes('probe-readonly') + ? { ...prof, limits: { ...prof.limits, toolWallMs: 60_000 } } + : { ...prof, limits: { ...prof.limits, toolWallMs: 180_000 } }, + ), + }, + }; + + return { taskpack, baseTaskContract, trustedRegistry }; +} + +function makeIsland(overrides: Partial = {}): IslandRecord { + return { + campaignId: overrides.campaignId ?? 'camp-team-1', + islandId: overrides.islandId ?? 0, + activeTeamConfigId: overrides.activeTeamConfigId ?? 'camp-team-1:island-0:baseline', + currentGeneration: overrides.currentGeneration ?? 3, + consecutiveNoGainGenerations: overrides.consecutiveNoGainGenerations ?? 0, + consecutivePathologyRuns: overrides.consecutivePathologyRuns ?? 0, + lastHypervolume: overrides.lastHypervolume ?? 120.5, + bestRooflineHeadroom: overrides.bestRooflineHeadroom !== undefined ? overrides.bestRooflineHeadroom : 1.35, + }; +} + +function makeRunEvalReport(overrides: { + readonly runId?: string; + readonly pingPongDetected?: boolean; + readonly circuitBreaker?: 'none' | 'max_turns' | 'consecutive_tool_errors' | 'no_progress' | 'unavailable'; +} = {}): RunEvalReport { + return { + schemaVersion: RUN_EVAL_SCHEMA_VERSION, + runId: overrides.runId ?? 'run-eval-1', + status: 'failed', + journalRevision: 6, + toolTelemetry: 'available', + toolRepeats: { + items: [], + totalFailingCalls: overrides.circuitBreaker === 'consecutive_tool_errors' ? 4 : 0, + circuitBreaker: overrides.circuitBreaker ?? 'none', + }, + pingPong: { + detected: overrides.pingPongDetected === true, + checkOscillations: overrides.pingPongDetected ? 2 : 0, + repeatedFailureSignatures: overrides.pingPongDetected ? 2 : 0, + digestCycles: 0, + repeatedReworks: 0, + totalReworks: 0, + }, + repairConvergence: { + attempts: { ordinary: 1, format: 0, implementation: 1, rework: 0 }, + unchangedDigestRepairs: 0, + initialFailingChecks: 1, + finalFailingChecks: 1, + failingCheckDelta: 0, + converged: false, + }, + breakdown: { + byStep: [], + byRole: [], + totals: { + tokens: { input: 100, output: 50, total: 150 }, + costMicrousd: null, + costCompleteness: 'unavailable', + modelCalls: 1, + toolCalls: 2, + elapsedMs: 250, + }, + }, + suggestions: [], + }; +} + +test('team-supervisor: steady-progress island, disabled spec, reached roofline, or exhausted budget invokes 0 supervisor turns', async () => { + const tempDir = mkdtempSync(join(tmpdir(), 'evo-supervisor-steady-')); + try { + const { taskpack, baseTaskContract, trustedRegistry } = await makeCompiledBaseFixtures(); + const store = await EvolutionCampaignStore.open({ campaignRoot: join(tempDir, 'campaign') }); + try { + const lease = await store.acquireLease('steady-owner'); + const manifest = parseEvolutionCampaignDocument(CAMPAIGN_WITH_TEAM_YAML); + await store.createCampaign(lease, { + campaignId: 'camp-steady', + manifest, + manifestDigest: makeDigest(CAMPAIGN_WITH_TEAM_YAML), + baseRevision: 'a'.repeat(40), + lockHash: makeDigest('lock-steady'), + modelIds: ['claude-sonnet-4-6'], + }); + const island = (await store.getIsland('camp-steady', 0))!; + + // 1. Steady-progress island (consecutiveNoGainGenerations = 2 < stallGenerations = 4, 1 pathology < 2) + const steadyDecision = evaluateTeamEvolutionTrigger({ + teamEvolution: TEAM_EVOLUTION_SPEC, + island: makeIsland({ ...island, consecutiveNoGainGenerations: 2, consecutivePathologyRuns: 1 }), + budgets: DEFAULT_BUDGETS, + evaluationsUsed: 10, + currentGeneration: 3, + recentRunEvals: [makeRunEvalReport({ pingPongDetected: false }), makeRunEvalReport({ pingPongDetected: true })], + }); + assert.equal(steadyDecision.shouldInvoke, false); + assert.equal(steadyDecision.suppressedReason, 'steady_progress'); + + // 2. teamEvolution disabled + assert.equal( + evaluateTeamEvolutionTrigger({ + teamEvolution: { ...TEAM_EVOLUTION_SPEC, enabled: false }, + island: makeIsland({ consecutiveNoGainGenerations: 10 }), + budgets: DEFAULT_BUDGETS, + evaluationsUsed: 10, + currentGeneration: 5, + }).shouldInvoke, + false, + ); + + // 3. Remaining evaluation budget < 2 (cannot cover 1 supervisor turn + 1 child evaluation) + const noEvalBudget = evaluateTeamEvolutionTrigger({ + teamEvolution: TEAM_EVOLUTION_SPEC, + island: makeIsland({ consecutiveNoGainGenerations: 6 }), + budgets: DEFAULT_BUDGETS, + evaluationsUsed: 79, + currentGeneration: 5, + }); + assert.equal(noEvalBudget.shouldInvoke, false); + assert.equal(noEvalBudget.suppressedReason, 'insufficient_evaluation_budget'); + + // 4. Remaining generation budget < 1 + const noGenBudget = evaluateTeamEvolutionTrigger({ + teamEvolution: TEAM_EVOLUTION_SPEC, + island: makeIsland({ consecutiveNoGainGenerations: 6 }), + budgets: DEFAULT_BUDGETS, + evaluationsUsed: 20, + currentGeneration: 20, + }); + assert.equal(noGenBudget.shouldInvoke, false); + assert.equal(noGenBudget.suppressedReason, 'insufficient_generation_budget'); + + // 5. Island already reached targetRooflineHeadroom (1.05 <= 1.08) + const rooflineMet = evaluateTeamEvolutionTrigger({ + teamEvolution: TEAM_EVOLUTION_SPEC, + island: makeIsland({ consecutiveNoGainGenerations: 8, bestRooflineHeadroom: 1.05 }), + budgets: DEFAULT_BUDGETS, + evaluationsUsed: 20, + currentGeneration: 5, + }); + assert.equal(rooflineMet.shouldInvoke, false); + assert.equal(rooflineMet.suppressedReason, 'target_roofline_reached'); + + // Verify runPlateauSupervisorTurn invokes supervisorRunner 0 times on steady island + let supervisorCalls = 0; + const turnRes = await runPlateauSupervisorTurn({ + store, + lease, + campaignId: 'camp-steady', + island, + teamEvolution: TEAM_EVOLUTION_SPEC, + budgets: DEFAULT_BUDGETS, + evaluationsUsed: 10, + currentGeneration: 2, + baseTaskContract, + taskpack, + trustedRegistry, + stagingDir: join(tempDir, 'unused-stage'), + supervisorRunner: async () => { + supervisorCalls += 1; + return '{}'; + }, + }); + assert.equal(turnRes.invoked, false); + assert.equal(supervisorCalls, 0); + } finally { + await store.close(); + } + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } +}); + +test('team-supervisor: stalled island and >= 2 RunEval pathologies invoke strictly read-only tools: ["read"] supervisor with 0o400 O_NOFOLLOW scrubbed context', async () => { + const tempDir = mkdtempSync(join(tmpdir(), 'evo-supervisor-isolation-')); + try { + const { baseTaskContract } = await makeCompiledBaseFixtures(); + + assert.equal(hasRunEvalLoopPathology(makeRunEvalReport({ pingPongDetected: false, circuitBreaker: 'none' })), false); + assert.equal(hasRunEvalLoopPathology(makeRunEvalReport({ pingPongDetected: true })), true); + assert.equal(hasRunEvalLoopPathology(makeRunEvalReport({ circuitBreaker: 'consecutive_tool_errors' })), true); + assert.equal(hasRunEvalLoopPathology(makeRunEvalReport({ circuitBreaker: 'no_progress' })), true); + + const stallTrigger = evaluateTeamEvolutionTrigger({ + teamEvolution: TEAM_EVOLUTION_SPEC, + island: makeIsland({ consecutiveNoGainGenerations: 4, consecutivePathologyRuns: 0 }), + budgets: DEFAULT_BUDGETS, + evaluationsUsed: 16, + currentGeneration: 4, + }); + assert.equal(stallTrigger.shouldInvoke, true); + assert.equal(stallTrigger.triggerReason, 'pareto_stagnation'); + + const pathologyTrigger = evaluateTeamEvolutionTrigger({ + teamEvolution: TEAM_EVOLUTION_SPEC, + island: makeIsland({ consecutiveNoGainGenerations: 1, consecutivePathologyRuns: 0 }), + budgets: DEFAULT_BUDGETS, + evaluationsUsed: 8, + currentGeneration: 2, + recentRunEvals: [ + makeRunEvalReport({ runId: 'r-ok', pingPongDetected: false }), + makeRunEvalReport({ runId: 'r-p1', pingPongDetected: true }), + makeRunEvalReport({ runId: 'r-p2', circuitBreaker: 'no_progress' }), + ], + }); + assert.equal(pathologyTrigger.shouldInvoke, true); + assert.equal(pathologyTrigger.triggerReason, 'run_eval_pathology'); + assert.equal(pathologyTrigger.consecutivePathologyRuns, 2); + + const stagingDir = join(tempDir, 'sup-ctx'); + const scrubber = new SecretScrubber(); + scrubber.register('super-secret-relay-hmac-key-999'); + + const staged = await stageSupervisorContext({ + stagingDir, + campaignId: 'camp-iso-1', + island: makeIsland({ campaignId: 'camp-iso-1', consecutiveNoGainGenerations: 4 }), + triggerReason: 'pareto_stagnation', + teamEvolution: TEAM_EVOLUTION_SPEC, + baseTaskContract, + trajectory: [ + { generation: 1, hypervolume: 100, bestScalarFitness: 0.5, nichesOpen: 2 }, + { generation: 2, hypervolume: 100.0002, bestScalarFitness: 0.5, nichesOpen: 2 }, + ], + recentRunEvals: [ + makeRunEvalReport({ runId: 'r-p1', pingPongDetected: true }), + makeRunEvalReport({ runId: 'r-p2', circuitBreaker: 'consecutive_tool_errors' }), + ], + recentIndividuals: [], + latestScratchpadMarkdown: '# Campaign Scratchpad\n- Avoid shared memory bank conflicts.\n', + teamHistory: [ + { + teamConfigId: 'team-failed-prev', + campaignId: 'camp-iso-1', + islandId: 0, + parentTeamConfigId: 'camp-iso-1:island-0:baseline', + status: 'rolled_back', + createdGeneration: 2, + trialBudgetGenerations: 2, + trialUsedGenerations: 2, + paretoAdvances: 0, + nicheDiscoveries: 0, + diagnosis: { + summary: 'Over-split pipeline degraded context coherence', + plateauCategory: 'coupled_responsibilities', + rationale: 'Three-hop chain lost tile size invariants', + }, + patchCasDigest: makeDigest('old-patch'), + }, + ], + scrubber, + }); + + assert.equal(staged.supervisorContract.spec.roles.length, 1); + const supRole = staged.supervisorContract.spec.roles[0]!; + assert.equal(supRole.id, 'supervisor'); + assert.deepEqual(supRole.tools, ['read']); + assert.deepEqual(staged.writablePaths, []); + const writableCheck = isWritablePath(staged.supervisorContract, 'src/kernels/flash_decode.cu'); + assert.equal(writableCheck.ok, true); + if (writableCheck.ok) { + assert.equal(writableCheck.value, false); + } + assert.equal( + staged.supervisorContract.spec.acceptance.checks.some(c => c.allowedEvidenceLevels.includes('hardware_execution')), + false, + ); + assert.equal(JSON.stringify(staged.supervisorContract).includes('decode-bs1-4k'), false); + + assert.ok(staged.files.length >= 5); + for (const file of staged.files) { + const st = lstatSync(file.filePath); + assert.equal(st.isSymbolicLink(), false); + assert.equal(st.nlink, 1); + assert.equal(st.mode & 0o777, 0o400); + } + const historyFile = staged.files.find(f => f.name === 'team-history.json'); + assert.ok(historyFile !== undefined); + const historyJson = readFileSync(historyFile.filePath, 'utf8'); + assert.ok(historyJson.includes('rolled_back')); + assert.ok(historyJson.includes('Over-split pipeline degraded context coherence')); + + const symDir = join(tempDir, 'sym-sup-ctx'); + symlinkSync(stagingDir, symDir); + await assert.rejects( + () => stageSupervisorContext({ + stagingDir: symDir, + campaignId: 'camp-iso-1', + island: makeIsland(), + triggerReason: 'pareto_stagnation', + teamEvolution: TEAM_EVOLUTION_SPEC, + baseTaskContract, + scrubber, + }), + (err: unknown) => err instanceof EvolutionError && err.code === 'EVOLUTION_SYMLINK_FORBIDDEN', + ); + + await assert.rejects( + () => stageSupervisorContext({ + stagingDir: join(tempDir, 'leak-sup-ctx'), + campaignId: 'camp-iso-1', + island: makeIsland(), + triggerReason: 'pareto_stagnation', + teamEvolution: TEAM_EVOLUTION_SPEC, + baseTaskContract, + latestScratchpadMarkdown: 'Leaked credential super-secret-relay-hmac-key-999', + scrubber, + }), + (err: unknown) => err instanceof EvolutionError && err.code === 'SECRET_LEAK_DETECTED', + ); + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } +}); + +test('team-supervisor: TEAM_ENVELOPE_VIOLATION rejects tool widening, unapproved archetype, undeclared model, unpinned resource, scope/acceptance tampering, and D > 256 overflow while retaining incumbent team', async () => { + const tempDir = mkdtempSync(join(tmpdir(), 'evo-supervisor-envelope-')); + try { + const { taskpack, baseTaskContract, trustedRegistry } = await makeCompiledBaseFixtures(); + + const makeValidRawPatch = (): Record => ({ + kind: 'TeamPatch', + schemaVersion: 'team-patch.v1', + diagnosis: { + summary: 'Mutator couples bottleneck measurement with tile tuning', + plateauCategory: 'coupled_responsibilities', + rationale: 'Isolate read-only bottleneck analysis from sandboxed mutator', + }, + roles: [ + { + id: 'bottleneck-auditor', + archetypeRoleId: 'probe-readonly', + purpose: 'task', + tools: ['read'], + model: 'claude-sonnet-4-6', + resourceIds: ['res-arch-guide'], + timeoutSeconds: 45, + prompt: 'Analyze warp stall breakdown and emit ## Bottleneck Summary.', + }, + { + id: 'tile-mutator', + archetypeRoleId: 'mutator-sandboxed', + purpose: 'task', + tools: ['read', 'edit'], + model: 'gpt-5.4', + resourceIds: ['res-arch-guide', 'res-scratchpad'], + timeoutSeconds: 120, + prompt: 'Apply async TMA tile schedule inside EVOLVE-BLOCK.', + }, + ], + steps: [ + { + id: 'step-audit', + roleId: 'bottleneck-auditor', + dependsOn: [], + }, + { + id: 'step-mutate', + roleId: 'tile-mutator', + dependsOn: ['step-audit'], + handoffs: [ + { + id: 'bottleneck-handoff', + fromStep: 'step-audit', + source: { kind: 'submission' }, + select: { kind: 'markdown_heading', heading: 'Bottleneck Summary' }, + maxBytes: 4096, + required: true, + }, + ], + }, + ], + }); + + // 0. Free-form Markdown wrapper rejected (strict parseTeamPatchV1, zero regex scraping) + assertEvolutionError( + () => validateAndCompileTeamPatch({ + rawPatch: '```json\n' + JSON.stringify(makeValidRawPatch()) + '\n```', + teamEvolution: TEAM_EVOLUTION_SPEC, + baseTaskContract, + taskpack, + trustedRegistry, + }), + 'EVOLUTION_SCHEMA_INVALID', + ); + + // 1. Unapproved archetypeRoleId + const badArchetype = makeValidRawPatch(); + (badArchetype['roles'] as Array>)[0]!['archetypeRoleId'] = 'root-shell-admin'; + assertEvolutionError( + () => validateAndCompileTeamPatch({ + rawPatch: badArchetype, + teamEvolution: TEAM_EVOLUTION_SPEC, + baseTaskContract, + taskpack, + trustedRegistry, + }), + 'TEAM_ENVELOPE_VIOLATION', + ); + + // 2a. Tool widening beyond read-only archetype (probe-readonly requesting 'write') + const widenedReadonly = makeValidRawPatch(); + (widenedReadonly['roles'] as Array>)[0]!['tools'] = ['read', 'write']; + assertEvolutionError( + () => validateAndCompileTeamPatch({ + rawPatch: widenedReadonly, + teamEvolution: TEAM_EVOLUTION_SPEC, + baseTaskContract, + taskpack, + trustedRegistry, + }), + 'TEAM_ENVELOPE_VIOLATION', + ); + + // 2b. Tool widening beyond mutator archetype ('delete' not in mutator-sandboxed.tools) + const widenedMutator = makeValidRawPatch(); + (widenedMutator['roles'] as Array>)[1]!['tools'] = ['read', 'edit', 'delete']; + assertEvolutionError( + () => validateAndCompileTeamPatch({ + rawPatch: widenedMutator, + teamEvolution: TEAM_EVOLUTION_SPEC, + baseTaskContract, + taskpack, + trustedRegistry, + }), + 'TEAM_ENVELOPE_VIOLATION', + ); + + // 2c. Mutating tool on purpose: 'review' role + const badReview = makeValidRawPatch(); + (badReview['roles'] as Array>)[0]!['archetypeRoleId'] = 'mutator-sandboxed'; + (badReview['roles'] as Array>)[0]!['purpose'] = 'review'; + (badReview['roles'] as Array>)[0]!['tools'] = ['read', 'bash']; + assertEvolutionError( + () => validateAndCompileTeamPatch({ + rawPatch: badReview, + teamEvolution: TEAM_EVOLUTION_SPEC, + baseTaskContract, + taskpack, + trustedRegistry, + }), + 'TEAM_ENVELOPE_VIOLATION', + ); + + // 3a. Undeclared model + const badModel = makeValidRawPatch(); + (badModel['roles'] as Array>)[1]!['model'] = 'rogue-unpinned-model-99'; + assertEvolutionError( + () => validateAndCompileTeamPatch({ + rawPatch: badModel, + teamEvolution: TEAM_EVOLUTION_SPEC, + baseTaskContract, + taskpack, + trustedRegistry, + }), + 'TEAM_ENVELOPE_VIOLATION', + ); + + // 3b. Unpinned resourceId + const badResource = makeValidRawPatch(); + (badResource['roles'] as Array>)[0]!['resourceIds'] = ['res-arch-guide', 'res-unhashed-secret']; + assertEvolutionError( + () => validateAndCompileTeamPatch({ + rawPatch: badResource, + teamEvolution: TEAM_EVOLUTION_SPEC, + baseTaskContract, + taskpack, + trustedRegistry, + }), + 'TEAM_ENVELOPE_VIOLATION', + ); + + // 3c. timeoutSeconds exceeding archetype ceiling (probe-readonly toolWallMs = 60_000 -> 60s max) + const badTimeout = makeValidRawPatch(); + (badTimeout['roles'] as Array>)[0]!['timeoutSeconds'] = 120; + assertEvolutionError( + () => validateAndCompileTeamPatch({ + rawPatch: badTimeout, + teamEvolution: TEAM_EVOLUTION_SPEC, + baseTaskContract, + taskpack, + trustedRegistry, + }), + 'TEAM_ENVELOPE_VIOLATION', + ); + + // 4a. Scope / acceptance.required tampering in supervisor output + const tamperedScope = { + ...makeValidRawPatch(), + scope: { writable: ['**'], protected: [] }, + }; + assertEvolutionError( + () => validateAndCompileTeamPatch({ + rawPatch: tamperedScope, + teamEvolution: TEAM_EVOLUTION_SPEC, + baseTaskContract, + taskpack, + trustedRegistry, + }), + 'TEAM_ENVELOPE_VIOLATION', + ); + + const tamperedAcceptance = { + ...makeValidRawPatch(), + acceptance: { required: [] }, + }; + assertEvolutionError( + () => validateAndCompileTeamPatch({ + rawPatch: tamperedAcceptance, + teamEvolution: TEAM_EVOLUTION_SPEC, + baseTaskContract, + taskpack, + trustedRegistry, + }), + 'TEAM_ENVELOPE_VIOLATION', + ); + + // 4b. Step ID colliding with locked acceptance check identifier + const collidingStep = makeValidRawPatch(); + (collidingStep['steps'] as Array>)[0]!['id'] = 'evolve-guard'; + (collidingStep['steps'] as Array>)[1]!['dependsOn'] = ['evolve-guard']; + ((collidingStep['steps'] as Array>)[1]!['handoffs'] as Array>)[0]!['fromStep'] = 'evolve-guard'; + assertEvolutionError( + () => validateAndCompileTeamPatch({ + rawPatch: collidingStep, + teamEvolution: TEAM_EVOLUTION_SPEC, + baseTaskContract, + taskpack, + trustedRegistry, + }), + 'TEAM_ENVELOPE_VIOLATION', + ); + + // 4c. Checkpoint capacity overflow (D > 256) rejected BEFORE launching any child run + const highRepairContractRes = validateDocument( + { + ...baseTaskContract, + spec: { + ...baseTaskContract.spec, + budgets: { + ...baseTaskContract.spec.budgets, + maxModelCalls: 64, + maxImplementationRepairs: 24, + }, + }, + }, + 'TaskContract', + ); + assert.equal(highRepairContractRes.ok, true); + if (!highRepairContractRes.ok) throw new Error('unexpected'); + + assertEvolutionError( + () => validateAndCompileTeamPatch({ + rawPatch: makeValidRawPatch(), + teamEvolution: TEAM_EVOLUTION_SPEC, + baseTaskContract: highRepairContractRes.value, + taskpack, + trustedRegistry, + maxAttempts: 40, + }), + 'TEAM_ENVELOPE_VIOLATION', + ); + + // 5. Campaign continuity: rejected supervisor patch keeps incumbent activeTeamConfigId active in campaign.sqlite + const store = await EvolutionCampaignStore.open({ campaignRoot: join(tempDir, 'campaign') }); + try { + const lease = await store.acquireLease('envelope-owner'); + const manifest = parseEvolutionCampaignDocument(CAMPAIGN_WITH_TEAM_YAML); + await store.createCampaign(lease, { + campaignId: 'camp-env-1', + manifest, + manifestDigest: makeDigest(CAMPAIGN_WITH_TEAM_YAML), + baseRevision: 'b'.repeat(40), + lockHash: makeDigest('lock-env'), + modelIds: ['claude-sonnet-4-6', 'gpt-5.4'], + }); + await store.updateIslandProgress(lease, { + campaignId: 'camp-env-1', + islandId: 0, + currentGeneration: 4, + consecutiveNoGainGenerations: 4, + }); + const stalledIsland = (await store.getIsland('camp-env-1', 0))!; + const incumbentTeamId = stalledIsland.activeTeamConfigId; + + const rejectedTurn = await runPlateauSupervisorTurn({ + store, + lease, + campaignId: 'camp-env-1', + island: stalledIsland, + teamEvolution: TEAM_EVOLUTION_SPEC, + budgets: DEFAULT_BUDGETS, + evaluationsUsed: 12, + currentGeneration: 4, + baseTaskContract, + taskpack, + trustedRegistry, + stagingDir: join(tempDir, 'sup-stage-reject'), + supervisorRunner: async () => JSON.stringify(widenedReadonly), + }); + + assert.equal(rejectedTurn.invoked, true); + assert.equal(rejectedTurn.accepted, false); + assert.equal(rejectedTurn.error?.code, 'TEAM_ENVELOPE_VIOLATION'); + assert.equal(rejectedTurn.activeTeamConfigId, incumbentTeamId); + assert.equal((await store.getIsland('camp-env-1', 0))?.activeTeamConfigId, incumbentTeamId); + assert.equal((await store.listTeamConfigs('camp-env-1', 0)).length, 1); + } finally { + await store.close(); + } + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } +}); + +test('team-supervisor: valid probe-readonly -> mutator-sandboxed StepHandoffSelector patch compiles valid TaskContract, promotes on advance, and auto-rolls back after trialGenerations while ignoring BENCHMARK_PREEMPTED', async () => { + const tempDir = mkdtempSync(join(tmpdir(), 'evo-supervisor-trial-')); + try { + const { taskpack, baseTaskContract, trustedRegistry } = await makeCompiledBaseFixtures(); + + const validPatch: TeamPatchV1 = { + kind: 'TeamPatch', + schemaVersion: 'team-patch.v1', + diagnosis: { + summary: 'Single mutator repeats HBM uncoalesced access pattern', + plateauCategory: 'coupled_responsibilities', + rationale: 'Add read-only probe step feeding Bottleneck Analysis via StepHandoffSelector to sandboxed mutator', + }, + roles: [ + { + id: 'probe-auditor', + archetypeRoleId: 'probe-readonly', + purpose: 'task', + tools: ['read'], + model: 'claude-sonnet-4-6', + resourceIds: ['res-arch-guide'], + timeoutSeconds: 45, + prompt: 'Inspect memory coalescing and emit ## Bottleneck Analysis.', + }, + { + id: 'kernel-mutator', + archetypeRoleId: 'mutator-sandboxed', + purpose: 'task', + tools: ['read', 'write', 'edit'], + model: 'gpt-5.4', + resourceIds: ['res-arch-guide', 'res-scratchpad'], + timeoutSeconds: 120, + prompt: 'Implement vectorized float4 loads inside EVOLVE-BLOCK.', + }, + ], + steps: [ + { + id: 'step-probe', + roleId: 'probe-auditor', + dependsOn: [], + }, + { + id: 'step-mutate', + roleId: 'kernel-mutator', + dependsOn: ['step-probe'], + handoffs: [ + { + id: 'probe-to-mutator', + fromStep: 'step-probe', + source: { kind: 'submission' }, + select: { kind: 'markdown_heading', heading: 'Bottleneck Analysis', includeSubheadings: true }, + maxBytes: 4096, + required: true, + }, + ], + }, + ], + }; + + const compiled = validateAndCompileTeamPatch({ + rawPatch: JSON.stringify(validPatch), + teamEvolution: TEAM_EVOLUTION_SPEC, + baseTaskContract, + taskpack, + trustedRegistry, + }); + + assert.ok(compiled.capacity.D <= 256); + assert.equal(compiled.capacity.N, 2); + const validatedContract = validateDocument(compiled.taskContract, 'TaskContract'); + assert.equal(validatedContract.ok, true); + + assert.deepEqual(compiled.taskContract.spec.scope, baseTaskContract.spec.scope); + assert.deepEqual(compiled.taskContract.spec.acceptance, baseTaskContract.spec.acceptance); + assert.equal(compiled.taskContract.spec.trustedContext.discovery, 'disabled'); + + const mutateStep = compiled.taskContract.spec.steps.find(s => s.id === 'step-mutate'); + assert.ok(mutateStep?.kind === 'agent'); + assert.equal(mutateStep.handoffs?.length, 1); + assert.equal(mutateStep.handoffs?.[0]?.fromStep, 'step-probe'); + + const checkSteps = compiled.taskContract.spec.steps.filter(s => s.kind === 'check'); + assert.ok(checkSteps.length >= 2); + assert.ok(checkSteps.some(cs => cs.dependsOn.includes('step-mutate'))); + + const store = await EvolutionCampaignStore.open({ campaignRoot: join(tempDir, 'campaign') }); + try { + const lease = await store.acquireLease('trial-owner'); + const manifest = parseEvolutionCampaignDocument(CAMPAIGN_WITH_TEAM_YAML); + await store.createCampaign(lease, { + campaignId: 'camp-trial-1', + manifest, + manifestDigest: makeDigest(CAMPAIGN_WITH_TEAM_YAML), + baseRevision: 'c'.repeat(40), + lockHash: makeDigest('lock-trial'), + modelIds: ['claude-sonnet-4-6', 'gpt-5.4'], + }); + + await store.updateIslandProgress(lease, { + campaignId: 'camp-trial-1', + islandId: 0, + currentGeneration: 4, + consecutiveNoGainGenerations: 4, + }); + const island0 = (await store.getIsland('camp-trial-1', 0))!; + const baselineTeam0 = island0.activeTeamConfigId; + + const acceptedTurn0 = await runPlateauSupervisorTurn({ + store, + lease, + campaignId: 'camp-trial-1', + island: island0, + teamEvolution: TEAM_EVOLUTION_SPEC, + budgets: DEFAULT_BUDGETS, + evaluationsUsed: 8, + currentGeneration: 4, + baseTaskContract, + taskpack, + trustedRegistry, + stagingDir: join(tempDir, 'sup-stage-0'), + supervisorRunner: async ctx => { + assert.deepEqual(ctx.supervisorContract.spec.roles[0]?.tools, ['read']); + return JSON.stringify(validPatch); + }, + }); + + assert.equal(acceptedTurn0.invoked, true); + assert.equal(acceptedTurn0.accepted, true); + const trialTeam0Id = acceptedTurn0.teamConfig!.teamConfigId; + assert.equal(acceptedTurn0.teamConfig?.status, 'trial'); + assert.equal(acceptedTurn0.teamConfig?.trialBudgetGenerations, 2); + assert.equal((await store.getIsland('camp-trial-1', 0))?.activeTeamConfigId, trialTeam0Id); + + // Record a BENCHMARK_PREEMPTED child run bound to trialTeam0Id -> must NOT consume trial_used_generations + await store.recordIndividual(lease, { + individualId: 'ind-preempted-trial', + campaignId: 'camp-trial-1', + islandId: 0, + generation: 5, + bucketId: null, + teamConfigId: trialTeam0Id, + modelId: 'gpt-5.4', + trackId: 'cuda_raw', + mutationKind: 'diff_tune', + status: 'preempted', + failureReason: 'BENCHMARK_PREEMPTED', + nicheKey: null, + paretoRank: null, + crowdingDistance: null, + scalarFitness: null, + codeSliceCasDigest: makeDigest('code-preempt'), + evidenceDigest: null, + verdictReceiptCasDigest: null, + outputArtifacts: [], + metrics: {}, + }); + + const preemptOutcome = await recordTeamTrialOutcome(store, lease, { + campaignId: 'camp-trial-1', + islandId: 0, + teamConfigId: trialTeam0Id, + advancedPareto: false, + discoveredNiche: false, + preempted: true, + }); + assert.equal(preemptOutcome.ignoredPreemption, true); + assert.equal(preemptOutcome.teamConfig.trialUsedGenerations, 0); + assert.equal(preemptOutcome.nextStatus, 'trial'); + + const trialGen1 = await recordTeamTrialOutcome(store, lease, { + campaignId: 'camp-trial-1', + islandId: 0, + teamConfigId: trialTeam0Id, + advancedPareto: false, + discoveredNiche: false, + }); + assert.equal(trialGen1.teamConfig.trialUsedGenerations, 1); + assert.equal(trialGen1.nextStatus, 'trial'); + assert.equal(trialGen1.rolledBack, false); + + const trialGen2 = await recordTeamTrialOutcome(store, lease, { + campaignId: 'camp-trial-1', + islandId: 0, + teamConfigId: trialTeam0Id, + advancedPareto: false, + discoveredNiche: false, + }); + assert.equal(trialGen2.teamConfig.trialUsedGenerations, 2); + assert.equal(trialGen2.nextStatus, 'rolled_back'); + assert.equal(trialGen2.rolledBack, true); + assert.equal(trialGen2.activeTeamConfigId, baselineTeam0); + assert.equal((await store.getIsland('camp-trial-1', 0))?.activeTeamConfigId, baselineTeam0); + + // Island 1: stall -> synthesize trial team -> child evaluation advances Pareto -> promoted! + await store.updateIslandProgress(lease, { + campaignId: 'camp-trial-1', + islandId: 1, + currentGeneration: 4, + consecutiveNoGainGenerations: 4, + }); + const island1 = (await store.getIsland('camp-trial-1', 1))!; + const acceptedTurn1 = await runPlateauSupervisorTurn({ + store, + lease, + campaignId: 'camp-trial-1', + island: island1, + teamEvolution: TEAM_EVOLUTION_SPEC, + budgets: DEFAULT_BUDGETS, + evaluationsUsed: 12, + currentGeneration: 4, + baseTaskContract, + taskpack, + trustedRegistry, + stagingDir: join(tempDir, 'sup-stage-1'), + supervisorRunner: async () => JSON.stringify(validPatch), + }); + const trialTeam1Id = acceptedTurn1.teamConfig!.teamConfigId; + + await store.recordIndividual(lease, { + individualId: 'ind-promoted-child', + campaignId: 'camp-trial-1', + islandId: 1, + generation: 5, + bucketId: null, + teamConfigId: trialTeam1Id, + modelId: 'gpt-5.4', + trackId: 'cuda_raw', + mutationKind: 'diff_tune', + status: 'passed', + failureReason: null, + nicheKey: 'bound_pipeline=tensor_cube', + paretoRank: 1, + crowdingDistance: Number.POSITIVE_INFINITY, + scalarFitness: 0.95, + codeSliceCasDigest: makeDigest('code-promoted'), + evidenceDigest: makeDigest('ev-promoted'), + verdictReceiptCasDigest: makeDigest('vr-promoted'), + outputArtifacts: [], + metrics: { latency_us_p50: 48, goodput_rps: 2400 }, + }); + + const promoteOutcome = await recordTeamTrialOutcome(store, lease, { + campaignId: 'camp-trial-1', + islandId: 1, + teamConfigId: trialTeam1Id, + advancedPareto: true, + discoveredNiche: true, + }); + assert.equal(promoteOutcome.promoted, true); + assert.equal(promoteOutcome.nextStatus, 'promoted'); + assert.equal(promoteOutcome.activeTeamConfigId, trialTeam1Id); + assert.equal((await store.getIsland('camp-trial-1', 1))?.activeTeamConfigId, trialTeam1Id); + } finally { + await store.close(); + } + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } +}); + +test('team-supervisor: preserves role.thinking, role.timeoutSeconds (narrowing compiledRegistry toolWallMs), step.onRework, and rejects reworkGenerations D > 256 overflow', async () => { + const { taskpack, baseTaskContract, trustedRegistry } = await makeCompiledBaseFixtures(); + + const patchWithRework: TeamPatchV1 = { + kind: 'TeamPatch', + schemaVersion: 'team-patch.v1', + diagnosis: { + summary: 'Mutator needs reviewer rework loop with explicit thinking levels', + plateauCategory: 'correctness_ping_pong', + rationale: 'Forward thinking, timeoutSeconds, and onRework while accounting for reworkGenerations', + }, + roles: [ + { + id: 'mutator-worker', + archetypeRoleId: 'mutator-sandboxed', + purpose: 'task', + tools: ['read', 'edit'], + model: 'gpt-5.4', + thinking: 'low', + timeoutSeconds: 90, + prompt: 'Edit kernel inside EVOLVE-BLOCK.', + }, + { + id: 'diff-reviewer', + archetypeRoleId: 'reviewer', + purpose: 'review', + tools: ['read'], + model: 'claude-sonnet-4-6', + thinking: 'high', + timeoutSeconds: 30, + prompt: 'Verify numerical invariants and request rework if violated.', + }, + ], + steps: [ + { + id: 'step-mutate', + roleId: 'mutator-worker', + dependsOn: [], + }, + { + id: 'step-review', + roleId: 'diff-reviewer', + dependsOn: ['step-mutate'], + onRework: { + rejectTo: 'step-mutate', + maxReworks: 2, + }, + }, + ], + }; + + const compiled = validateAndCompileTeamPatch({ + rawPatch: patchWithRework, + teamEvolution: TEAM_EVOLUTION_SPEC, + baseTaskContract, + taskpack, + trustedRegistry, + }); + + // 1. role.thinking preserved on resolvedRoleModels and TaskContract.spec.roles + const mutRole = compiled.taskContract.spec.roles.find(r => r.id === 'mutator-worker'); + const revRole = compiled.taskContract.spec.roles.find(r => r.id === 'diff-reviewer'); + assert.equal(mutRole?.thinking, 'low'); + assert.equal(revRole?.thinking, 'high'); + + // 2. timeoutSeconds preserved on resolvedRoleModels and narrows compiledRegistry toolWallMs + assert.equal(compiled.resolvedRoleModels['mutator-worker']?.timeoutSeconds, 90); + assert.equal(compiled.resolvedRoleModels['diff-reviewer']?.timeoutSeconds, 30); + const mutProf = compiled.compiledRegistry?.spec.roleProfiles.find(p => p.id === 'taskpack.profile.mutator-worker'); + const revProf = compiled.compiledRegistry?.spec.roleProfiles.find(p => p.id === 'taskpack.profile.diff-reviewer'); + assert.equal(mutProf?.limits?.toolWallMs, 90_000); + assert.equal(revProf?.limits?.toolWallMs, 30_000); + + // 3. step.onRework forwarded onto TaskContract.spec.steps + const reviewStep = compiled.taskContract.spec.steps.find(s => s.id === 'step-review'); + assert.deepEqual({ ...reviewStep?.onRework }, { rejectTo: 'step-mutate', maxReworks: 2 }); + + // 4. High maxReworks + repair budget pushing D > 256 (even with small maxAttempts where R=0 would falsely pass!) fails closed + const highReworkPatch: TeamPatchV1 = { + ...patchWithRework, + steps: [ + { id: 'step-mutate', roleId: 'mutator-worker', dependsOn: [] }, + { + id: 'step-review', + roleId: 'diff-reviewer', + dependsOn: ['step-mutate'], + onRework: { rejectTo: 'step-mutate', maxReworks: 8 }, + }, + ], + }; + const contractNearCeiling = validateDocument( + { + ...baseTaskContract, + spec: { + ...baseTaskContract.spec, + budgets: { + ...baseTaskContract.spec.budgets, + maxModelCalls: 64, + maxImplementationRepairs: 16, + }, + }, + }, + 'TaskContract', + ); + assert.equal(contractNearCeiling.ok, true); + if (!contractNearCeiling.ok) throw new Error('unexpected'); + + assertEvolutionError( + () => validateAndCompileTeamPatch({ + rawPatch: highReworkPatch, + teamEvolution: TEAM_EVOLUTION_SPEC, + baseTaskContract: contractNearCeiling.value, + taskpack, + trustedRegistry, + maxAttempts: 28, + }), + 'TEAM_ENVELOPE_VIOLATION', + ); +}); + +test('team-supervisor: createLocalRunStoreSupervisorRunner executes supervisorRoleId in a fenced read-only LocalRunStore and refuses workspace mutations', async () => { + const tempDir = mkdtempSync(join(tmpdir(), 'evo-supervisor-local-runstore-')); + try { + const repoDir = join(tempDir, 'repo'); + mkdirSync(join(repoDir, 'src', 'kernels'), { recursive: true, mode: 0o700 }); + writeFileSync(join(repoDir, 'src', 'kernels', 'flash_decode.cu'), '// baseline\n', { mode: 0o644 }); + chmodSync(join(repoDir, 'src', 'kernels', 'flash_decode.cu'), 0o644); + + const { taskpack, baseTaskContract, trustedRegistry } = await makeCompiledBaseFixtures(); + const store = await EvolutionCampaignStore.open({ campaignRoot: join(tempDir, 'campaign') }); + try { + const lease = await store.acquireLease('supervisor-runstore-owner'); + const manifest = parseEvolutionCampaignDocument(CAMPAIGN_WITH_TEAM_YAML); + await store.createCampaign(lease, { + campaignId: 'camp-pm1', + manifest, + manifestDigest: makeDigest(CAMPAIGN_WITH_TEAM_YAML), + baseRevision: 'd'.repeat(40), + lockHash: makeDigest('lock-pm1'), + modelIds: ['claude-sonnet-4-6', 'gpt-5.4'], + }); + await store.updateIslandProgress(lease, { + campaignId: 'camp-pm1', + islandId: 0, + currentGeneration: 4, + consecutiveNoGainGenerations: 4, + }); + const island0 = (await store.getIsland('camp-pm1', 0))!; + + const proposedPatch: TeamPatchV1 = { + kind: 'TeamPatch', + schemaVersion: 'team-patch.v1', + diagnosis: { + summary: 'Isolated read-only LocalRunStore plateau supervisor diagnosis', + plateauCategory: 'coupled_responsibilities', + rationale: 'Split read-only probe from mutator', + }, + roles: [ + { + id: 'probe-worker', + archetypeRoleId: 'probe-readonly', + purpose: 'task', + tools: ['read'], + model: 'claude-sonnet-4-6', + prompt: 'Inspect bottleneck.', + }, + { + id: 'mutate-worker', + archetypeRoleId: 'mutator-sandboxed', + purpose: 'task', + tools: ['read', 'edit'], + model: 'gpt-5.4', + prompt: 'Edit kernel.', + }, + ], + steps: [ + { id: 'step-probe', roleId: 'probe-worker', dependsOn: [] }, + { id: 'step-mutate', roleId: 'mutate-worker', dependsOn: ['step-probe'] }, + ], + }; + + let observedTurnRole = ''; + let observedContextCount = 0; + const stagingDirOk = join(tempDir, 'sup-runstore-ok'); + const runnerOk = createLocalRunStoreSupervisorRunner({ + executeReadOnlySupervisorTurn: async turn => { + observedTurnRole = turn.roleId; + observedContextCount = turn.contextFiles.length; + assert.deepEqual(turn.tools, ['read']); + for (const cf of turn.contextFiles) { + const content = readFileSync(cf, 'utf8'); + assert.equal(content.includes('decode-bs1-4k'), false, 'heldOutWorkloadId must never enter supervisor context'); + } + return JSON.stringify(proposedPatch); + }, + }); + + const acceptedTurn = await runPlateauSupervisorTurn({ + store, + lease, + campaignId: 'camp-pm1', + island: island0, + teamEvolution: TEAM_EVOLUTION_SPEC, + budgets: DEFAULT_BUDGETS, + evaluationsUsed: 8, + currentGeneration: 4, + baseTaskContract, + taskpack, + trustedRegistry, + stagingDir: stagingDirOk, + supervisorRunner: runnerOk, + }); + + assert.equal(acceptedTurn.invoked, true); + assert.equal(acceptedTurn.accepted, true); + assert.equal(observedTurnRole, 'supervisor'); + assert.ok(observedContextCount >= 5); + assert.equal(existsSync(join(stagingDirOk, 'controller')), true); + + // Negative path: supervisor turn attempting to create a file inside candidateDir MUST fail closed with TEAM_ENVELOPE_VIOLATION! + await store.updateIslandProgress(lease, { + campaignId: 'camp-pm1', + islandId: 1, + currentGeneration: 4, + consecutiveNoGainGenerations: 4, + }); + const island1 = (await store.getIsland('camp-pm1', 1))!; + const incumbent1 = island1.activeTeamConfigId; + + const mutatingRogueRunner = createLocalRunStoreSupervisorRunner({ + executeReadOnlySupervisorTurn: async turn => { + writeFileSync(join(turn.candidateDir, 'rogue-write.txt'), 'illegal supervisor write\n', 'utf8'); + return JSON.stringify(proposedPatch); + }, + }); + + const rejectedRogueTurn = await runPlateauSupervisorTurn({ + store, + lease, + campaignId: 'camp-pm1', + island: island1, + teamEvolution: TEAM_EVOLUTION_SPEC, + budgets: DEFAULT_BUDGETS, + evaluationsUsed: 10, + currentGeneration: 4, + baseTaskContract, + taskpack, + trustedRegistry, + stagingDir: join(tempDir, 'sup-runstore-rogue'), + supervisorRunner: mutatingRogueRunner, + }); + + assert.equal(rejectedRogueTurn.invoked, true); + assert.equal(rejectedRogueTurn.accepted, false); + assert.equal(rejectedRogueTurn.error?.code, 'TEAM_ENVELOPE_VIOLATION'); + assert.equal((await store.getIsland('camp-pm1', 1))?.activeTeamConfigId, incumbent1); + } finally { + await store.close(); + } + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } +}); diff --git a/packages/evolution/tsconfig.json b/packages/evolution/tsconfig.json new file mode 100644 index 0000000..fe8e96c --- /dev/null +++ b/packages/evolution/tsconfig.json @@ -0,0 +1,20 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "composite": true, + "incremental": true, + "tsBuildInfoFile": "../../.test-build/tsbuildinfo/evolution.tsbuildinfo", + "noEmit": false, + "declaration": true, + "rootDir": "src", + "outDir": "dist" + }, + "include": ["src/**/*.ts"], + "references": [ + { "path": "../controller" }, + { "path": "../core" }, + { "path": "../decisions" }, + { "path": "../hardware-runner" }, + { "path": "../taskpack" } + ] +} diff --git a/packages/github-app/src/turnkey-memory.ts b/packages/github-app/src/turnkey-memory.ts index 6749288..8506849 100644 --- a/packages/github-app/src/turnkey-memory.ts +++ b/packages/github-app/src/turnkey-memory.ts @@ -35,6 +35,7 @@ import { isPlainRecord, listTreeEntriesAtRevision, MAX_REASON_CODEPOINTS, + projectMemoryHardwareScope, projectMemoryTargetMatrixCell, readRegularJsonBounded, removePathsFromIndex, @@ -728,6 +729,7 @@ export async function finalizeAndPublishTurnkeyMemory( ? options.targetMatrix : (manifestMatrix !== undefined && manifestMatrix !== null && manifestMatrix.length === 1 ? manifestMatrix[0]! : null); const targetMatrix = projectMemoryTargetMatrixCell(rawTargetMatrix); + const hardwareScope = projectMemoryHardwareScope(rawTargetMatrix); const expectedBindings: ExpectedSettledRunBindings = { runId: options.runId, @@ -748,6 +750,7 @@ export async function finalizeAndPublishTurnkeyMemory( checkCodeFingerprint, checkUpstreamVersions, targetMatrix, + ...(hardwareScope !== undefined ? { hardwareScope } : {}), upstreamVersions: buildUpstreamMemoryVersions(options.upstreamRecords as readonly UpstreamAcquisitionRecord[] | undefined), }; diff --git a/packages/github-app/test/self-upgrade-fixtures.ts b/packages/github-app/test/self-upgrade-fixtures.ts index 5849221..61538f7 100644 --- a/packages/github-app/test/self-upgrade-fixtures.ts +++ b/packages/github-app/test/self-upgrade-fixtures.ts @@ -227,6 +227,7 @@ export const ALL_WORKSPACES = [ 'packages/memory', 'packages/decisions', 'packages/hardware-runner', + 'packages/evolution', ] as const; export function fakeIntegrity(label: string): string { @@ -305,6 +306,10 @@ export function buildSyntheticLockfile(options: { version: '0.0.0', dependencies: { '@loopwright/core': '0.0.0', '@loopwright/taskpack': '0.0.0' }, }, + 'packages/evolution': { + version: '0.0.0', + dependencies: { '@loopwright/core': '0.0.0' }, + }, 'packages/agent-pi': { version: '0.0.0', dependencies: Object.fromEntries([ @@ -535,6 +540,7 @@ export async function createMiniSelfUpgradeRepo( 'packages/memory': { '@loopwright/core': '0.0.0' }, 'packages/taskpack-runner': { '@loopwright/core': '0.0.0' }, 'packages/hardware-runner': { '@loopwright/core': '0.0.0', '@loopwright/taskpack': '0.0.0' }, + 'packages/evolution': { '@loopwright/core': '0.0.0' }, 'packages/agent-pi': Object.fromEntries([ ...PI_PACKAGE_NAMES.map(pkg => [pkg, '1.5.0']), ['@loopwright/core', '0.0.0'], diff --git a/packages/github-app/test/turnkey-memory-hardware-projection.test.ts b/packages/github-app/test/turnkey-memory-hardware-projection.test.ts index abd8aa5..0f4f4cd 100644 --- a/packages/github-app/test/turnkey-memory-hardware-projection.test.ts +++ b/packages/github-app/test/turnkey-memory-hardware-projection.test.ts @@ -269,6 +269,162 @@ describe('github-app turnkey-memory hardware TargetMatrixCell projection', () => platform: 'linux/amd64', variant: 'cuda12', }); + assert.deepEqual({ ...loadedStore.index.entries[0]?.scope.hardwareScope }, { + accelerator: 'sm_90a', + driverConstraint: '>=550.54', + }); + } finally { + await githubServer.close(); + await rm(work, { recursive: true, force: true }); + } + }); + + it('omits hardwareScope completely for non-hardware target.matrix cells in separate-pull-request publication', async () => { + const baseTmp = await realpath(tmpdir()); + const work = await mkdtemp(join(baseTmp, 'lw-gh-nohw-mem-')); + const bareRemote = join(work, 'remote.git'); + const repo = join(work, 'repo'); + const runRoot = join(work, 'runs'); + await mkdir(bareRemote, { recursive: true }); + await mkdir(repo, { recursive: true }); + await mkdir(runRoot, { recursive: true, mode: 0o700 }); + + const githubServer = await startHttpServer(async (req, res) => { + const url = new URL(req.url ?? '/', 'http://127.0.0.1'); + if (req.method === 'GET' && url.pathname === '/repos/acme/cpu-repo/pulls') { + res.writeHead(200, { 'content-type': 'application/json' }); + res.end(JSON.stringify([])); + return; + } + if (req.method === 'POST' && url.pathname === '/repos/acme/cpu-repo/pulls') { + const chunks: Buffer[] = []; + for await (const c of req) chunks.push(Buffer.isBuffer(c) ? c : Buffer.from(c)); + const body = JSON.parse(Buffer.concat(chunks).toString('utf8')) as Record; + const headRef = String(body['head'] ?? ''); + const lsOut = await git(repo, ['ls-remote', bareRemote, `refs/heads/${headRef}`]); + const remoteSha = lsOut.split(/\s+/)[0] ?? ''; + const baseSha = await git(repo, ['rev-parse', 'HEAD']); + res.writeHead(201, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ + number: 89, + state: 'open', + html_url: 'https://github.invalid/acme/cpu-repo/pull/89', + head: { ref: headRef, sha: remoteSha, repo: { full_name: 'acme/cpu-repo', fork: false } }, + base: { ref: 'main', sha: baseSha, repo: { full_name: 'acme/cpu-repo', fork: false } }, + })); + return; + } + res.writeHead(404, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ message: 'not found' })); + }); + + try { + await git(bareRemote, ['init', '--bare', '-b', 'main']); + await git(repo, ['init', '-b', 'main']); + await mkdir(join(repo, '.auto-sync'), { recursive: true }); + await mkdir(join(repo, 'src'), { recursive: true }); + await writeFile(join(repo, 'src', 'app.ts'), '// app\n', 'utf8'); + + const manifestObj = { + apiVersion: 'loopwright.dev/v1alpha1', + kind: 'Taskpack', + metadata: { name: 'cpu-task' }, + spec: { + goal: { candidate: 'Update app.', noChange: 'No change.' }, + scope: { writable: ['src/**'], protected: [] }, + target: { + matrix: [{ id: 'cpu-linux', platform: 'linux/amd64', variant: 'node26' }], + }, + verification: { + localChecks: [{ id: 'scope-check', implementation: 'scope.v1' }], + externalGates: [], + }, + publication: { + mode: 'pull_request', + targetBranch: 'main', + headBranchPrefix: 'loopwright/', + titleTemplate: 'chore: update app', + }, + memory: { + directory: '.auto-sync/memory/cpu-task', + apply: 'separate-pull-request', + onNoModelBudget: 'deterministic-observations-only', + publishOnFailure: true, + }, + triggers: { schedule: false, workflowDispatch: true, releasePublished: false, commentCommands: [] }, + }, + }; + await writeFile(join(repo, '.auto-sync', 'taskpack.yaml'), serializePrettyYaml(manifestObj), 'utf8'); + await git(repo, ['add', '.']); + await git(repo, ['commit', '-m', 'init']); + await git(repo, ['remote', 'add', 'origin', bareRemote]); + await git(repo, ['push', '-u', 'origin', 'main']); + const headSha = await git(repo, ['rev-parse', 'HEAD']); + + const manifest = validateTaskpackV2Manifest(manifestObj as Json, { + policyProfile: 'github', + controlRoot: '.auto-sync', + manifestPath: '.auto-sync/taskpack.yaml', + }); + const compiled = await compileDeclarativeTaskpack(manifest, { + mode: 'candidate', + executionMode: 'delegated', + hostPolicy: { policyProfile: 'github' }, + repository: 'acme/cpu-repo', + repositoryRoot: repo, + taskpackPath: '.auto-sync/taskpack.yaml', + baseRevision: headSha, + sourceRevision: headSha, + budgets: DEFAULT_HOST_BUDGETS, + }); + + const runId = 'run-gh-nohw-mem-1'; + const locked = admitTask(compiled.config.spec.task, { admissionId: 'adm-gh-nohw-1', runId }); + assert.equal(locked.ok, true); + if (!locked.ok) throw new Error('admitTask failed'); + const runDir = join(runRoot, runId); + const artifactsDir = join(runDir, 'artifacts'); + await mkdir(artifactsDir, { recursive: true }); + await writeFile(join(runDir, 'run.json'), JSON.stringify({ version: 1, identity: { lock: locked.value } }), 'utf8'); + const planBytes = Buffer.from(JSON.stringify({ stage: 'execution', note: 'cpu timeout' }), 'utf8'); + const planRef = digestArtifact('plan-incident.bin', planBytes); + assert.equal(planRef.ok, true); + if (!planRef.ok) throw new Error('digestArtifact failed'); + await writeFile(join(artifactsDir, planRef.value.name), planBytes); + const incident: ControllerIncident = { + version: 1, + code: 'DEADLINE', + runId, + lockHash: locked.value.spec.lockHash, + stage: 'execution', + knownReferences: [planRef.value], + unavailable: ['candidate'], + cleanup: 'complete', + }; + await writeFile(join(artifactsDir, `incident-${runId}.bin`), JSON.stringify(incident), 'utf8'); + + const scrubber = new SecretScrubber(); + scrubber.register('ghp_nohw_mem_token_123456'); + const published = await finalizeAndPublishTurnkeyMemory({ + repositoryRoot: repo, + taskpackPath: '.auto-sync/taskpack.yaml', + manifest, + repositoryFullName: 'acme/cpu-repo', + baseRevision: headSha, + runRoot, + runId, + scrubber, + githubToken: 'ghp_nohw_mem_token_123456', + apiBaseUrl: githubServer.url, + remoteUrl: bareRemote, + }); + assert.equal(published.status, 'published', JSON.stringify(published)); + const memClone = join(work, 'mem-clone'); + await git(work, ['clone', '--branch', 'loopwright/memory/cpu-task/main', bareRemote, memClone]); + const loadedStore = await loadMemoryStore(memClone, 'cpu-task', 'acme/cpu-repo', '.auto-sync/memory'); + assert.equal(loadedStore.index.entries.length, 1); + const scope = loadedStore.index.entries[0]!.scope as unknown as Record; + assert.equal(Object.hasOwn(scope, 'hardwareScope'), false); } finally { await githubServer.close(); await rm(work, { recursive: true, force: true }); diff --git a/packages/hardware-runner/src/evaluator.ts b/packages/hardware-runner/src/evaluator.ts index c2b9847..e9d7828 100644 --- a/packages/hardware-runner/src/evaluator.ts +++ b/packages/hardware-runner/src/evaluator.ts @@ -17,9 +17,14 @@ import { isVerifierNamespacePath, LIMITS, SecretScrubber, + STAGE_A_STATIC_AUDIT_FAILED, + validateBucketMetrics, + validateHardwareDiagnostics, validateRelativePath, VERIFIER_ARTIFACT_LIMITS, + type BucketMetricEntry, type FindingSeverity, + type HardwareDiagnostics, type HardwareProvenance, type HardwareTargetSpec, type MetricThresholdRule, @@ -59,6 +64,7 @@ import { type BenchmarkCandidateArtifacts, type BenchmarkOutputArtifact, type LeaseGrant, + type StageAStaticAuditSpec, type WorkerConfig, } from './types.js'; @@ -69,8 +75,21 @@ const BASE_TREE_BUNDLE_MAGIC = Buffer.from(LWTREE01_MAGIC, 'ascii'); // (envelope + hardwareProvenance + outputArtifacts + lease credentials) stays within 64 KiB. export const MAX_STAGE_B_RESULT_BYTES = 49_152; export const MAX_STAGE_STDIO_BYTES = 1_048_576; +export const MAX_STAGE_A_AUDIT_SCAN_BYTES = 1_048_576; export const STAGE_B_RESULT_MARKER_PREFIX = 'LOOPWRIGHT_STAGE_B_RESULT:' as const; +export const TRUSTED_NM_PATHS: readonly string[] = Object.freeze([ + '/usr/bin/nm', + '/usr/local/bin/nm', + '/bin/nm', +]); + +export const TRUSTED_CUOBJDUMP_PATHS: readonly string[] = Object.freeze([ + '/usr/local/cuda/bin/cuobjdump', + '/usr/bin/cuobjdump', + '/usr/local/bin/cuobjdump', +]); + export class RunnerTeardownError extends HardwareRunnerError { readonly teardownFailed = true as const; readonly reasonCode = 'RUNNER_TEARDOWN_FAILED' as const; @@ -112,6 +131,8 @@ const STAGE_B_ENVELOPE_KEYS: ReadonlySet = new Set([ 'detail', 'metrics', 'findings', + 'bucketMetrics', + 'hardwareDiagnostics', ]); const FINDING_KEYS: ReadonlySet = new Set(['title', 'severity', 'path', 'line', 'evidence']); @@ -169,6 +190,37 @@ export interface StageBResultEnvelope { readonly detail?: string | null; readonly metrics?: MetricsMap; readonly findings?: readonly StructuredFinding[]; + readonly bucketMetrics?: readonly BucketMetricEntry[]; + readonly hardwareDiagnostics?: HardwareDiagnostics; +} + +export interface StageBFailureMetadata { + readonly timedOut: boolean; + readonly exitCode: number | null; + readonly signal: NodeJS.Signals | null; +} + +export type StageAAuditToolRunner = ( + tool: 'nm' | 'cuobjdump', + executablePath: string, + args: readonly string[], + options: { readonly timeoutMs: number; readonly maxOutputBytes: number; readonly signal?: AbortSignal }, +) => Promise<{ readonly exitCode: number; readonly stdout: string; readonly stderr: string }>; + +export interface AuditSealedStageAOutputsOptions { + readonly sealedOutputs: readonly SealedStageAArtifact[]; + readonly auditSpec: StageAStaticAuditSpec; + readonly scrubber: SecretScrubber; + readonly toolchainPaths?: readonly string[]; + readonly maxScanBytes?: number; + readonly auditToolRunner?: StageAAuditToolRunner; + readonly enableHostAuditTools?: boolean; + readonly signal?: AbortSignal; +} + +export interface StageAStaticAuditResult { + readonly passed: boolean; + readonly findings: readonly StructuredFinding[]; } export interface DockerSandboxCompileInput { @@ -216,6 +268,10 @@ export interface EvaluatedBenchmarkJob { readonly metrics?: MetricsMap; readonly findings?: readonly StructuredFinding[]; readonly hardwareProvenance?: HardwareProvenance; + readonly allocatedDeviceIndices?: readonly number[]; + readonly bucketMetrics?: readonly BucketMetricEntry[]; + readonly hardwareDiagnostics?: HardwareDiagnostics; + readonly stageBFailure?: StageBFailureMetadata; readonly sealedOutputs: readonly SealedStageAArtifact[]; cleanup(options?: EvaluatedJobCleanupOptions): Promise; } @@ -282,6 +338,8 @@ export interface EvaluateBenchmarkJobOptions { readonly stageBCommand?: { readonly command: string; readonly args?: readonly string[] }; readonly probe?: (options: CollectHardwareProvenanceOptions) => Promise; readonly processRunner?: (input: StageProcessExecutionInput) => Promise; + readonly auditToolRunner?: StageAAuditToolRunner; + readonly enableHostAuditTools?: boolean; readonly _testOnlyTrustedDockerRoot?: string; } @@ -2809,6 +2867,1137 @@ export async function sealStageAOutputs(options: { return Object.freeze(sealed); } +const AUDIT_BINARY_EXT_RE = /\.(?:so(?:\.[0-9]+)*|o|cubin|fatbin|elf|hsaco|dylib)$/i; +const AUDIT_TEXT_EXT_RE = /\.(?:ptx|sass|s|asm|isa|log|rpt|report|txt|json)$/i; +const FORBIDDEN_AUDIT_GLOB_RE = /[*?[\]]/; + +function resolveEffectiveStageAAuditSpec( + targetHardware: HardwareTargetSpec, + explicitAudit: StageAStaticAuditSpec | undefined, +): StageAStaticAuditSpec | null { + const mergedPatterns: string[] = []; + const seen = new Set(); + for (const list of [targetHardware.forbiddenSymbolPatterns, explicitAudit?.forbiddenSymbolPatterns]) { + if (list === undefined) continue; + for (const pat of list) { + if (!seen.has(pat)) { + seen.add(pat); + mergedPatterns.push(pat); + } + } + } + if (mergedPatterns.length > LIMITS.forbiddenSymbolPatterns) { + throw new HardwareRunnerError( + 'ARTIFACT_INVALID', + `combined forbiddenSymbolPatterns exceeds ${LIMITS.forbiddenSymbolPatterns}`, + '/stageAAudit/forbiddenSymbolPatterns', + ); + } + + let maxRegisterCount: number | undefined; + if (targetHardware.maxRegisterCount !== undefined && explicitAudit?.maxRegisterCount !== undefined) { + maxRegisterCount = Math.min(targetHardware.maxRegisterCount, explicitAudit.maxRegisterCount); + } else { + maxRegisterCount = targetHardware.maxRegisterCount ?? explicitAudit?.maxRegisterCount; + } + + let maxLocalSpillBytes: number | undefined; + if (targetHardware.maxLocalSpillBytes !== undefined && explicitAudit?.maxLocalSpillBytes !== undefined) { + maxLocalSpillBytes = Math.min(targetHardware.maxLocalSpillBytes, explicitAudit.maxLocalSpillBytes); + } else { + maxLocalSpillBytes = targetHardware.maxLocalSpillBytes ?? explicitAudit?.maxLocalSpillBytes; + } + + if (mergedPatterns.length === 0 && maxRegisterCount === undefined && maxLocalSpillBytes === undefined) { + return null; + } + + return Object.freeze({ + ...(mergedPatterns.length > 0 ? { forbiddenSymbolPatterns: Object.freeze(mergedPatterns) } : {}), + ...(maxRegisterCount !== undefined ? { maxRegisterCount } : {}), + ...(maxLocalSpillBytes !== undefined ? { maxLocalSpillBytes } : {}), + }); +} + +function validateAuditSpecInputs(spec: StageAStaticAuditSpec): void { + if (spec.forbiddenSymbolPatterns !== undefined) { + if (!Array.isArray(spec.forbiddenSymbolPatterns) || spec.forbiddenSymbolPatterns.length > LIMITS.forbiddenSymbolPatterns) { + throw new HardwareRunnerError( + 'CONFIG_INVALID', + `forbiddenSymbolPatterns must contain 0..${LIMITS.forbiddenSymbolPatterns} entries`, + '/stageAAudit/forbiddenSymbolPatterns', + ); + } + const seen = new Set(); + for (const pat of spec.forbiddenSymbolPatterns) { + if ( + typeof pat !== 'string' + || pat.length < 1 + || pat.length > LIMITS.forbiddenSymbolPattern + || pat.trim() !== pat + || !PRINTABLE_ASCII_RE.test(pat) + || FORBIDDEN_AUDIT_GLOB_RE.test(pat) + ) { + throw new HardwareRunnerError( + 'CONFIG_INVALID', + 'invalid or glob-containing pattern in forbiddenSymbolPatterns', + '/stageAAudit/forbiddenSymbolPatterns', + ); + } + if (seen.has(pat)) { + throw new HardwareRunnerError('CONFIG_INVALID', 'duplicate pattern in forbiddenSymbolPatterns'); + } + seen.add(pat); + } + } + if ( + spec.maxRegisterCount !== undefined + && (!Number.isSafeInteger(spec.maxRegisterCount) || Object.is(spec.maxRegisterCount, -0) || spec.maxRegisterCount < 0) + ) { + throw new HardwareRunnerError('CONFIG_INVALID', 'invalid maxRegisterCount', '/stageAAudit/maxRegisterCount'); + } + if ( + spec.maxLocalSpillBytes !== undefined + && (!Number.isSafeInteger(spec.maxLocalSpillBytes) || Object.is(spec.maxLocalSpillBytes, -0) || spec.maxLocalSpillBytes < 0) + ) { + throw new HardwareRunnerError('CONFIG_INVALID', 'invalid maxLocalSpillBytes', '/stageAAudit/maxLocalSpillBytes'); + } +} + +/** + * Deterministically decode length-prefixed Itanium C++ `_Z...` mangled identifiers (and leading + * Mach-O underscores) into `ns::name` forms so `forbiddenSymbolPatterns` such as `'at::native::'` + * match mangled symbols (`_ZN2at6native9gemm_cudaE`) offline with zero external `c++filt` dependency. + */ +function expandDemangledSymbolForms(rawSymbol: string): readonly string[] { + const out = new Set([rawSymbol]); + const stripped = rawSymbol.startsWith('__Z') ? rawSymbol.slice(1) : rawSymbol; + if (rawSymbol.startsWith('_') && !rawSymbol.startsWith('_Z')) { + out.add(rawSymbol.slice(1)); + } + if (!stripped.startsWith('_Z')) { + return [...out]; + } + + let cursor = 2; + if (stripped[cursor] === 'L') cursor += 1; + if (stripped[cursor] === 'N') { + cursor += 1; + while (cursor < stripped.length && (stripped[cursor] === 'K' || stripped[cursor] === 'V' || stripped[cursor] === 'r')) { + cursor += 1; + } + const parts: string[] = []; + while (cursor < stripped.length && stripped[cursor] !== 'E') { + if (stripped[cursor] === 'I') { + // Skip template argument list `<...>` balanced on I..E if nested + let depth = 1; + cursor += 1; + while (cursor < stripped.length && depth > 0) { + if (stripped[cursor] === 'I') depth += 1; + else if (stripped[cursor] === 'E') depth -= 1; + cursor += 1; + } + continue; + } + let numEnd = cursor; + while (numEnd < stripped.length && stripped.charCodeAt(numEnd) >= 48 && stripped.charCodeAt(numEnd) <= 57) { + numEnd += 1; + } + if (numEnd === cursor) break; + const segLen = Number.parseInt(stripped.slice(cursor, numEnd), 10); + if (!Number.isSafeInteger(segLen) || segLen <= 0 || numEnd + segLen > stripped.length) break; + parts.push(stripped.slice(numEnd, numEnd + segLen)); + cursor = numEnd + segLen; + } + if (parts.length > 0) { + const joined = parts.join('::'); + out.add(joined); + out.add(`${joined}::`); + } + } else { + let numEnd = cursor; + while (numEnd < stripped.length && stripped.charCodeAt(numEnd) >= 48 && stripped.charCodeAt(numEnd) <= 57) { + numEnd += 1; + } + if (numEnd > cursor) { + const segLen = Number.parseInt(stripped.slice(cursor, numEnd), 10); + if (Number.isSafeInteger(segLen) && segLen > 0 && numEnd + segLen <= stripped.length) { + out.add(stripped.slice(numEnd, numEnd + segLen)); + } + } + } + return [...out]; +} + +function readNullTerminatedCString(strTab: Buffer, startOffset: number): string { + if (startOffset < 0 || startOffset >= strTab.byteLength) return ''; + const end = strTab.indexOf(0, startOffset); + const sliceEnd = end === -1 ? Math.min(strTab.byteLength, startOffset + 512) : Math.min(end, startOffset + 512); + if (sliceEnd <= startOffset) return ''; + return strTab.subarray(startOffset, sliceEnd).toString('utf8'); +} + +interface ParsedArtifactStaticInfo { + readonly symbols: readonly string[]; + readonly maxRegisters: number | null; + readonly maxSpillBytes: number | null; + readonly embeddedTexts: readonly string[]; + readonly scanError: string | null; +} + +async function parseElfFromHandle( + fh: Awaited>, + fileSize: number, + maxScanBytes: number, +): Promise { + if (fileSize < 52) { + return { symbols: [], maxRegisters: null, maxSpillBytes: null, embeddedTexts: [], scanError: 'truncated ELF header (< 52 bytes)' }; + } + const hdrLen = Math.min(64, fileSize); + const ehdr = Buffer.allocUnsafe(hdrLen); + await readExactFromHandle(fh, ehdr, hdrLen, 0); + + const eiClass = ehdr[4]!; // 1 = 32-bit, 2 = 64-bit + const eiData = ehdr[5]!; // 1 = little-endian, 2 = big-endian + if ((eiClass !== 1 && eiClass !== 2) || (eiData !== 1 && eiData !== 2)) { + return { symbols: [], maxRegisters: null, maxSpillBytes: null, embeddedTexts: [], scanError: 'unsupported ELF class or endianness' }; + } + const is64 = eiClass === 2; + const isLE = eiData === 1; + if (is64 && fileSize < 64) { + return { symbols: [], maxRegisters: null, maxSpillBytes: null, embeddedTexts: [], scanError: 'truncated ELF64 header (< 64 bytes)' }; + } + + const readU16 = (buf: Buffer, off: number): number => (isLE ? buf.readUInt16LE(off) : buf.readUInt16BE(off)); + const readU32 = (buf: Buffer, off: number): number => (isLE ? buf.readUInt32LE(off) : buf.readUInt32BE(off)); + const readU64AsSafeNumber = (buf: Buffer, off: number): number | null => { + const v = isLE ? buf.readBigUInt64LE(off) : buf.readBigUInt64BE(off); + if (v > BigInt(Number.MAX_SAFE_INTEGER)) return null; + return Number(v); + }; + + const shOff = is64 ? readU64AsSafeNumber(ehdr, 40) : readU32(ehdr, 32); + const shEntSize = readU16(ehdr, is64 ? 58 : 46); + let shNum = readU16(ehdr, is64 ? 60 : 48); + let shStrNdx = readU16(ehdr, is64 ? 62 : 50); + + if (shOff === null || shOff === 0 || shEntSize < (is64 ? 64 : 40)) { + return { + symbols: [], + maxRegisters: null, + maxSpillBytes: null, + embeddedTexts: [], + scanError: 'ELF binary is missing a valid section header table for static symbol audit', + }; + } + + let scannedBytes = hdrLen; + if (shNum === 0 && shOff + shEntSize <= fileSize) { + const sh0 = Buffer.allocUnsafe(shEntSize); + await readExactFromHandle(fh, sh0, shEntSize, shOff); + scannedBytes += shEntSize; + const extNum = is64 ? readU64AsSafeNumber(sh0, 32) : readU32(sh0, 20); + if (extNum === null || extNum < 1 || extNum > 4096) { + return { symbols: [], maxRegisters: null, maxSpillBytes: null, embeddedTexts: [], scanError: 'invalid extended ELF section count' }; + } + shNum = extNum; + if (shStrNdx === 0xffff) { + shStrNdx = readU32(sh0, is64 ? 40 : 24); + } + } + + if (shNum < 1 || shNum > 4096) { + return { symbols: [], maxRegisters: null, maxSpillBytes: null, embeddedTexts: [], scanError: 'ELF section header count out of bounds' }; + } + const shTableBytes = shNum * shEntSize; + if (shOff + shTableBytes > fileSize) { + return { symbols: [], maxRegisters: null, maxSpillBytes: null, embeddedTexts: [], scanError: 'ELF section header table exceeds file size' }; + } + if (scannedBytes + shTableBytes > maxScanBytes) { + return { + symbols: [], + maxRegisters: null, + maxSpillBytes: null, + embeddedTexts: [], + scanError: `ELF section header table exceeds ${maxScanBytes}-byte Stage A static audit scan cap`, + }; + } + + const shTableBuf = Buffer.allocUnsafe(shTableBytes); + await readExactFromHandle(fh, shTableBuf, shTableBytes, shOff); + scannedBytes += shTableBytes; + + interface ElfSectionHeader { + readonly nameOffset: number; + readonly shType: number; + readonly shOffset: number; + readonly shSize: number; + readonly shLink: number; + readonly shInfo: number; + readonly shEntSize: number; + } + + const headers: ElfSectionHeader[] = []; + for (let idx = 0; idx < shNum; idx += 1) { + const base = idx * shEntSize; + const nameOffset = readU32(shTableBuf, base); + const shType = readU32(shTableBuf, base + 4); + const secOff = is64 ? readU64AsSafeNumber(shTableBuf, base + 24) : readU32(shTableBuf, base + 16); + const secSize = is64 ? readU64AsSafeNumber(shTableBuf, base + 32) : readU32(shTableBuf, base + 20); + const shLink = readU32(shTableBuf, base + 40 - (is64 ? 0 : 16)); + const shInfo = readU32(shTableBuf, base + 44 - (is64 ? 0 : 16)); + const secEntSize = is64 ? readU64AsSafeNumber(shTableBuf, base + 56) : readU32(shTableBuf, base + 36); + if (secOff === null || secSize === null || secEntSize === null) { + return { symbols: [], maxRegisters: null, maxSpillBytes: null, embeddedTexts: [], scanError: 'ELF section size overflow' }; + } + if (shType !== 0 && shType !== 8 && secSize > 0 && secOff + secSize > fileSize) { + return { symbols: [], maxRegisters: null, maxSpillBytes: null, embeddedTexts: [], scanError: 'ELF section payload exceeds file size' }; + } + headers.push({ + nameOffset, + shType, + shOffset: secOff, + shSize: secSize, + shLink, + shInfo, + shEntSize: secEntSize, + }); + } + + const cachedSections = new Map(); + const readSectionBounded = async (secIdx: number): Promise => { + const existing = cachedSections.get(secIdx); + if (existing !== undefined) return existing; + const sec = headers[secIdx]; + if (!sec || sec.shType === 0 || sec.shType === 8 || sec.shSize === 0) { + return Buffer.alloc(0); + } + if (sec.shSize > maxScanBytes - scannedBytes) { + return null; + } + const buf = Buffer.allocUnsafe(sec.shSize); + await readExactFromHandle(fh, buf, sec.shSize, sec.shOffset); + scannedBytes += sec.shSize; + cachedSections.set(secIdx, buf); + return buf; + }; + + let shStrBuf: Buffer = Buffer.alloc(0); + if (shStrNdx > 0 && shStrNdx < headers.length) { + const loaded = await readSectionBounded(shStrNdx); + if (loaded === null) { + return { + symbols: [], + maxRegisters: null, + maxSpillBytes: null, + embeddedTexts: [], + scanError: `ELF .shstrtab exceeds ${maxScanBytes}-byte Stage A static audit scan cap`, + }; + } + shStrBuf = loaded; + } + + const symbols = new Set(); + const embeddedTexts: string[] = []; + let maxRegisters: number | null = null; + let maxSpillBytes: number | null = null; + + for (let idx = 1; idx < headers.length; idx += 1) { + const sec = headers[idx]!; + const secName = shStrBuf.byteLength > 0 ? readNullTerminatedCString(shStrBuf, sec.nameOffset) : ''; + + // SHT_SYMTAB (2) or SHT_DYNSYM (11) + if (sec.shType === 2 || sec.shType === 11) { + const symBuf = await readSectionBounded(idx); + const strBuf = sec.shLink > 0 && sec.shLink < headers.length ? await readSectionBounded(sec.shLink) : Buffer.alloc(0); + if (symBuf === null || strBuf === null) { + return { + symbols: [], + maxRegisters: null, + maxSpillBytes: null, + embeddedTexts: [], + scanError: `ELF symbol/string table exceeds ${maxScanBytes}-byte Stage A static audit scan cap`, + }; + } + const entSize = sec.shEntSize >= (is64 ? 24 : 16) ? sec.shEntSize : (is64 ? 24 : 16); + for (let off = 0; off + entSize <= symBuf.byteLength; off += entSize) { + const stName = readU32(symBuf, off); + if (stName > 0 && stName < strBuf.byteLength) { + const symName = readNullTerminatedCString(strBuf, stName); + if (symName.length > 0) { + symbols.add(symName); + } + } + } + continue; + } + + // SHT_DYNAMIC (6): inspect DT_NEEDED (d_tag === 1) shared library names + if (sec.shType === 6 && sec.shLink > 0 && sec.shLink < headers.length) { + const dynBuf = await readSectionBounded(idx); + const dynStrBuf = await readSectionBounded(sec.shLink); + if (dynBuf === null || dynStrBuf === null) { + return { + symbols: [], + maxRegisters: null, + maxSpillBytes: null, + embeddedTexts: [], + scanError: `ELF .dynamic table exceeds ${maxScanBytes}-byte Stage A static audit scan cap`, + }; + } + const entSize = sec.shEntSize >= (is64 ? 16 : 8) ? sec.shEntSize : (is64 ? 16 : 8); + for (let off = 0; off + entSize <= dynBuf.byteLength; off += entSize) { + const tag = is64 ? readU64AsSafeNumber(dynBuf, off) : readU32(dynBuf, off); + if (tag === 0) break; + if (tag === 1) { + const valOff = is64 ? readU64AsSafeNumber(dynBuf, off + 8) : readU32(dynBuf, off + 4); + if (valOff !== null && valOff > 0 && valOff < dynStrBuf.byteLength) { + const neededLib = readNullTerminatedCString(dynStrBuf, valOff); + if (neededLib.length > 0) { + symbols.add(neededLib); + } + } + } + } + continue; + } + + // NVIDIA cubin .nv.info / .nv.info. sections (SHT_CUDA_INFO = 0x70000000) + if (secName === '.nv.info' || secName.startsWith('.nv.info.') || sec.shType === 0x70000000) { + const nvBuf = await readSectionBounded(idx); + if (nvBuf === null) { + return { + symbols: [], + maxRegisters: null, + maxSpillBytes: null, + embeddedTexts: [], + scanError: `ELF .nv.info metadata exceeds ${maxScanBytes}-byte Stage A static audit scan cap`, + }; + } + let pos = 0; + while (pos + 4 <= nvBuf.byteLength) { + const fmt = nvBuf[pos]!; + const attr = nvBuf[pos + 1]!; + if (fmt === 0x01 || fmt === 0x02) { + pos += 4; + continue; + } + if (fmt === 0x03) { + const hVal = readU16(nvBuf, pos + 2); + if (attr === 0x1b || attr === 0x2f) { + maxRegisters = Math.max(maxRegisters ?? 0, hVal); + } + pos += 4; + continue; + } + if (fmt === 0x04) { + const payloadSize = readU16(nvBuf, pos + 2); + const nextPos = pos + 4 + payloadSize; + if (nextPos > nvBuf.byteLength) break; + if (attr === 0x2f) { + const regVal = payloadSize >= 8 + ? readU32(nvBuf, pos + 8) + : payloadSize >= 4 + ? readU32(nvBuf, pos + 4) + : 0; + maxRegisters = Math.max(maxRegisters ?? 0, regVal); + } else if (attr === 0x11) { + const frameVal = payloadSize >= 8 + ? readU32(nvBuf, pos + 8) + : payloadSize >= 4 + ? readU32(nvBuf, pos + 4) + : 0; + maxSpillBytes = Math.max(maxSpillBytes ?? 0, frameVal); + } + const alignedStep = (4 + payloadSize + 3) & ~3; + pos += Math.max(4, alignedStep); + continue; + } + break; + } + continue; + } + + // Older cubin per-kernel .nv.local. section sh_size directly measures local spill/frame bytes! + if (secName.startsWith('.nv.local.')) { + maxSpillBytes = Math.max(maxSpillBytes ?? 0, sec.shSize); + continue; + } + + // Embedded PTX sections inside host fatbin ELF — fail closed when scan budget is exceeded + if ((secName.includes('ptx') || secName === '.nv_fatbin') && sec.shSize > 0) { + if (sec.shSize > maxScanBytes - scannedBytes) { + return { + symbols: [], + maxRegisters: null, + maxSpillBytes: null, + embeddedTexts: [], + scanError: `ELF embedded PTX section "${secName}" (${sec.shSize} bytes) exceeds remaining ${maxScanBytes}-byte Stage A static audit scan cap`, + }; + } + const embBuf = await readSectionBounded(idx); + if (embBuf === null) { + return { + symbols: [], + maxRegisters: null, + maxSpillBytes: null, + embeddedTexts: [], + scanError: `ELF embedded PTX section "${secName}" exceeded ${maxScanBytes}-byte Stage A static audit scan cap`, + }; + } + if (embBuf.byteLength > 0) { + embeddedTexts.push(embBuf.toString('latin1')); + } + } + } + + return { + symbols: [...symbols], + maxRegisters, + maxSpillBytes, + embeddedTexts, + scanError: null, + }; +} + +async function parseMachO64FromHandle( + fh: Awaited>, + fileSize: number, + maxScanBytes: number, +): Promise { + if (fileSize < 32 || fileSize > maxScanBytes) { + return { + symbols: [], + maxRegisters: null, + maxSpillBytes: null, + embeddedTexts: [], + scanError: fileSize > maxScanBytes + ? `Mach-O binary exceeds ${maxScanBytes}-byte Stage A static audit scan cap` + : 'truncated Mach-O header', + }; + } + const buf = Buffer.allocUnsafe(fileSize); + await readExactFromHandle(fh, buf, fileSize, 0); + const magic = buf.readUInt32LE(0); + const isLE = magic === 0xfeedfacf; + const readU32 = (off: number): number => (isLE ? buf.readUInt32LE(off) : buf.readUInt32BE(off)); + const ncmds = readU32(16); + const sizeofcmds = readU32(20); + if (ncmds > 2048 || 32 + sizeofcmds > fileSize) { + return { symbols: [], maxRegisters: null, maxSpillBytes: null, embeddedTexts: [], scanError: 'malformed Mach-O load commands' }; + } + const symbols = new Set(); + let cmdOff = 32; + for (let i = 0; i < ncmds && cmdOff + 8 <= 32 + sizeofcmds; i += 1) { + const cmd = readU32(cmdOff); + const cmdsize = readU32(cmdOff + 4); + if (cmdsize < 8 || cmdOff + cmdsize > fileSize) break; + // LC_SYMTAB = 0x2 + if (cmd === 0x2 && cmdsize >= 24) { + const symoff = readU32(cmdOff + 8); + const nsyms = readU32(cmdOff + 12); + const stroff = readU32(cmdOff + 16); + const strsize = readU32(cmdOff + 20); + if (symoff + nsyms * 16 <= fileSize && stroff + strsize <= fileSize && nsyms <= 131_072) { + const strSlice = buf.subarray(stroff, stroff + strsize); + for (let s = 0; s < nsyms; s += 1) { + const nStrx = readU32(symoff + s * 16); + if (nStrx > 0 && nStrx < strSlice.byteLength) { + const name = readNullTerminatedCString(strSlice, nStrx); + if (name.length > 0) symbols.add(name); + } + } + } + } + cmdOff += cmdsize; + } + return { symbols: [...symbols], maxRegisters: null, maxSpillBytes: null, embeddedTexts: [], scanError: null }; +} + +function stripCAndAsmComments(source: string): string { + // Remove /* ... */ block comments and // ... line comments while preserving newlines. + return source + .replace(/\/\*[\s\S]*?\*\//g, ' ') + .replace(/\/\/[^\r\n]*/g, ''); +} + +function parseTextAndPtxStaticInfo(rawText: string, fileName: string): { + readonly tokensAndLines: readonly string[]; + readonly maxRegisters: number | null; + readonly maxSpillBytes: number | null; +} { + let maxRegisters: number | null = null; + let maxSpillBytes: number | null = null; + const lowerName = fileName.toLowerCase(); + + // 1. Parse compiler/ptxas/cuobjdump/assembler resource metrics across full text (including header comments). + for (const m of rawText.matchAll(/\bUsed\s+(\d+)\s+registers\b/gi)) { + const n = Number.parseInt(m[1]!, 10); + if (Number.isSafeInteger(n) && n >= 0) maxRegisters = Math.max(maxRegisters ?? 0, n); + } + for (const m of rawText.matchAll(/\b(?:registerCount|register_count|vgpr_count)\s*[:=]\s*(\d+)\b/gi)) { + const n = Number.parseInt(m[1]!, 10); + if (Number.isSafeInteger(n) && n >= 0) maxRegisters = Math.max(maxRegisters ?? 0, n); + } + for (const m of rawText.matchAll(/\bREG\s*:\s*(\d+)\b/g)) { + const n = Number.parseInt(m[1]!, 10); + if (Number.isSafeInteger(n) && n >= 0) maxRegisters = Math.max(maxRegisters ?? 0, n); + } + for (const m of rawText.matchAll(/\b(\d+)\s+bytes\s+spill\s+(?:stores|loads)\b/gi)) { + const n = Number.parseInt(m[1]!, 10); + if (Number.isSafeInteger(n) && n >= 0) maxSpillBytes = Math.max(maxSpillBytes ?? 0, n); + } + for (const m of rawText.matchAll(/\b(\d+)\s+bytes\s+lmem\b/gi)) { + const n = Number.parseInt(m[1]!, 10); + if (Number.isSafeInteger(n) && n >= 0) maxSpillBytes = Math.max(maxSpillBytes ?? 0, n); + } + for (const m of rawText.matchAll(/\b(?:lmem|localSpillBytes|local_spill_bytes|spill_bytes)\s*[:=]\s*(\d+)\b/gi)) { + const n = Number.parseInt(m[1]!, 10); + if (Number.isSafeInteger(n) && n >= 0) maxSpillBytes = Math.max(maxSpillBytes ?? 0, n); + } + + // 2. Strip comments before scanning code tokens/directives and PTX .reg / .local declarations. + const codeOnly = stripCAndAsmComments(rawText); + + if (lowerName.endsWith('.ptx') || /\.version\s+\d+\.\d+/.test(codeOnly)) { + // Split by `.entry` / `.func` definitions so per-kernel register and local spill budgets are measured accurately. + const kernelScopes = codeOnly.split(/(?=\.(?:visible\s+|extern\s+|weak\s+)*(?:entry|func)\b)/g); + for (const scope of kernelScopes) { + let scopeRegs = 0; + let sawRegs = false; + for (const regMatch of scope.matchAll(/\.reg\s+(?:\.align\s+\d+\s+)?(\.[A-Za-z0-9_]+)\s+([^;]+);/g)) { + const regType = regMatch[1]!.toLowerCase(); + if (regType === '.pred') continue; + const declList = regMatch[2]!; + const paramRange = /<(\d+)>/.exec(declList); + if (paramRange !== null) { + const count = Number.parseInt(paramRange[1]!, 10); + if (Number.isSafeInteger(count) && count >= 0) { + scopeRegs += count; + sawRegs = true; + } + } else { + const count = declList.split(',').map(s => s.trim()).filter(Boolean).length; + if (count > 0) { + scopeRegs += count; + sawRegs = true; + } + } + } + if (sawRegs) { + maxRegisters = Math.max(maxRegisters ?? 0, scopeRegs); + } + + let scopeLocalBytes = 0; + let sawLocal = false; + for (const locMatch of scope.matchAll( + /\.local\s+(?:\.align\s+\d+\s+)?\.(?:b|u|s|f)(8|16|32|64|128)(?:x(\d+))?\s+([^;]+);/g, + )) { + const bitWidth = Number.parseInt(locMatch[1]!, 10); + const vecWidth = locMatch[2] !== undefined ? Number.parseInt(locMatch[2], 10) : 1; + const elemBytes = (bitWidth / 8) * vecWidth; + const decls = locMatch[3]!.split(',').map(s => s.trim()).filter(Boolean); + for (const decl of decls) { + const arrMatch = /\[(\d+)\]/.exec(decl); + const count = arrMatch !== null ? Number.parseInt(arrMatch[1]!, 10) : 1; + if (Number.isSafeInteger(count) && count > 0) { + scopeLocalBytes += elemBytes * count; + sawLocal = true; + } + } + } + if (sawLocal) { + maxSpillBytes = Math.max(maxSpillBytes ?? 0, scopeLocalBytes); + } + } + } + + // Structured JSON resource metadata support + if (lowerName.endsWith('.json')) { + try { + const parsedJson = parseStrictJsonBytes( + Buffer.from(rawText, 'utf8'), + MAX_STAGE_A_AUDIT_SCAN_BYTES, + 'ARTIFACT_INVALID', + '/resourceJson', + ); + const jsonSymbols: string[] = []; + const walkJson = (node: unknown, depth: number): void => { + if (depth > 16 || node === null || typeof node !== 'object') return; + if (Array.isArray(node)) { + for (const item of node) walkJson(item, depth + 1); + return; + } + const rec = node as Readonly>; + for (const key of Object.keys(rec)) { + if (!Object.hasOwn(rec, key)) continue; + const val = rec[key]; + if ( + (key === 'registerCount' || key === 'registers' || key === 'num_regs') + && typeof val === 'number' + && Number.isSafeInteger(val) + && val >= 0 + ) { + maxRegisters = Math.max(maxRegisters ?? 0, val); + } else if ( + (key === 'localSpillBytes' || key === 'spillBytes' || key === 'lmemBytes') + && typeof val === 'number' + && Number.isSafeInteger(val) + && val >= 0 + ) { + maxSpillBytes = Math.max(maxSpillBytes ?? 0, val); + } else if (key === 'symbols' && Array.isArray(val)) { + for (const s of val) { + if (typeof s === 'string') jsonSymbols.push(s); + } + } else { + walkJson(val, depth + 1); + } + } + }; + walkJson(parsedJson, 0); + if (jsonSymbols.length > 0) { + return { + tokensAndLines: jsonSymbols, + maxRegisters, + maxSpillBytes, + }; + } + } catch { + // Non-JSON or malformed JSON falls through to line/token text scan. + } + } + + const tokensAndLines: string[] = []; + for (const rawLine of codeOnly.split(/\r?\n/)) { + const trimmed = rawLine.trim(); + if (trimmed.length === 0) continue; + tokensAndLines.push(trimmed); + for (const tokMatch of trimmed.matchAll(/[A-Za-z_$][A-Za-z0-9_$:@.]*/g)) { + tokensAndLines.push(tokMatch[0]!); + } + } + + return { tokensAndLines, maxRegisters, maxSpillBytes }; +} + +const defaultStageAAuditToolRunner: StageAAuditToolRunner = ( + _tool, + executablePath, + args, + options, +): Promise<{ readonly exitCode: number; readonly stdout: string; readonly stderr: string }> => { + return new Promise((resolveCmd, rejectCmd) => { + const child = execFile( + executablePath, + [...args], + { + shell: false, + cwd: '/', + env: { + PATH: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + LANG: 'C', + LC_ALL: 'C', + }, + timeout: options.timeoutMs, + maxBuffer: options.maxOutputBytes, + killSignal: 'SIGKILL', + windowsHide: true, + }, + (error, stdout, stderr) => { + options.signal?.removeEventListener('abort', onAbort); + if (error !== null) { + const errno = error as NodeJS.ErrnoException & { code?: string | number; killed?: boolean }; + if (errno.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER') { + rejectCmd(new Error(`audit tool output exceeded ${options.maxOutputBytes} bytes`)); + return; + } + if (errno.killed || errno.code === 'ETIMEDOUT') { + rejectCmd(new Error('audit tool timed out')); + return; + } + if (typeof errno.code === 'number') { + resolveCmd({ exitCode: errno.code, stdout: String(stdout ?? ''), stderr: String(stderr ?? '') }); + return; + } + rejectCmd(error); + return; + } + resolveCmd({ exitCode: 0, stdout: String(stdout ?? ''), stderr: String(stderr ?? '') }); + }, + ); + const onAbort = () => child.kill('SIGKILL'); + options.signal?.addEventListener('abort', onAbort, { once: true }); + }); +}; + +function resolveOptionalTrustedAuditTool( + baseAllowlist: readonly string[], + toolchainPaths: readonly string[], + binaryName: 'nm' | 'cuobjdump', +): string | null { + const candidates: string[] = [...baseAllowlist]; + for (const tc of toolchainPaths) { + candidates.push(join(tc, 'bin', binaryName), join(tc, binaryName)); + } + const uniqueCandidates = [...new Set(candidates.map(p => resolve(p)))]; + for (const cand of uniqueCandidates) { + try { + return verifyTrustedSystemExecutableSync(cand, uniqueCandidates, {}, `Stage A ${binaryName}`); + } catch { + // Optional host tool not installed or not root-owned. + } + } + return null; +} + +/** + * Deterministically audit sealed Stage A outputs (`.so`, `.o`, `.cubin`, `.ptx`, `.sass`, and + * resource reports) using `O_NOFOLLOW`, `nlink === 1`, bounded `<= 1 MiB` reads, pure-TypeScript + * ELF/Mach-O/PTX/SASS parsers, and optional root-owned `nm`/`cuobjdump` inspection on Linux/CUDA hosts. + */ +export async function auditSealedStageAOutputs( + options: AuditSealedStageAOutputsOptions, +): Promise { + const { sealedOutputs, auditSpec, scrubber } = options; + validateAuditSpecInputs(auditSpec); + + const patterns = auditSpec.forbiddenSymbolPatterns ?? []; + const hasRules = + patterns.length > 0 + || auditSpec.maxRegisterCount !== undefined + || auditSpec.maxLocalSpillBytes !== undefined; + if (!hasRules || sealedOutputs.length === 0) { + return Object.freeze({ passed: true, findings: Object.freeze([]) }); + } + + const maxScanBytes = options.maxScanBytes ?? MAX_STAGE_A_AUDIT_SCAN_BYTES; + const noFollow = 'O_NOFOLLOW' in constants ? constants.O_NOFOLLOW : 0; + const findings: StructuredFinding[] = []; + + const pushAuditFinding = (title: string, relPath: string, evidence: string): void => { + if (findings.length >= LIMITS.findings) return; + const safeTitle = boundDiagnosticSnippet(title, scrubber, LIMITS.findingTitle) || 'Stage A static audit violation'; + const safeEvidence = boundDiagnosticSnippet(evidence, scrubber, LIMITS.findingEvidence) || STAGE_A_STATIC_AUDIT_FAILED; + const built: Record = Object.create(null) as Record; + built.title = safeTitle; + built.severity = 'high'; + built.path = relPath; + built.evidence = safeEvidence; + findings.push(Object.freeze(built as unknown as StructuredFinding)); + }; + + const useHostTools = options.auditToolRunner !== undefined + || (options.enableHostAuditTools ?? process.platform === 'linux'); + const toolRunner = options.auditToolRunner ?? defaultStageAAuditToolRunner; + const tcPaths = options.toolchainPaths ?? []; + const resolvedNm = useHostTools + ? (options.auditToolRunner !== undefined ? '/usr/bin/nm' : resolveOptionalTrustedAuditTool(TRUSTED_NM_PATHS, tcPaths, 'nm')) + : null; + const resolvedCuobjdump = useHostTools + ? ( + options.auditToolRunner !== undefined + ? '/usr/local/cuda/bin/cuobjdump' + : resolveOptionalTrustedAuditTool(TRUSTED_CUOBJDUMP_PATHS, tcPaths, 'cuobjdump') + ) + : null; + + for (const item of sealedOutputs) { + if (options.signal?.aborted) { + throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', 'Stage A static audit aborted'); + } + const relName = validateSafeRelativeArtifactPath(item.artifact.name, '/outputArtifacts'); + await assertNoSymlinkAncestors(item.sealedFilePath, { + checkLeaf: true, + code: 'ARTIFACT_INVALID', + diagPath: `/outputArtifacts/${relName}`, + }); + + const preStat = await lstat(item.sealedFilePath).catch(() => null); + if (preStat === null || preStat.isSymbolicLink() || !preStat.isFile() || preStat.nlink !== 1) { + throw new HardwareRunnerError( + 'ARTIFACT_INVALID', + `Stage A output "${relName}" failed O_NOFOLLOW/nlink===1 verification before static audit`, + ); + } + + const fh = await open(item.sealedFilePath, constants.O_RDONLY | noFollow).catch(() => { + throw new HardwareRunnerError('ARTIFACT_INVALID', `unable to open sealed Stage A output "${relName}" with O_NOFOLLOW`); + }); + + let isElf: boolean; + let parsedInfo: ParsedArtifactStaticInfo | null = null; + let textContent: string | null = null; + + try { + const st = await fh.stat(); + if ( + !st.isFile() + || st.isSymbolicLink() + || st.nlink !== 1 + || st.dev !== preStat.dev + || st.ino !== preStat.ino + || st.size !== item.artifact.byteLength + ) { + throw new HardwareRunnerError('ARTIFACT_INVALID', `sealed Stage A output "${relName}" mutated before static audit`); + } + const fileSize = st.size; + if (fileSize === 0) continue; + + const magicLen = Math.min(8, fileSize); + const magicHeader = Buffer.allocUnsafe(magicLen); + await readExactFromHandle(fh, magicHeader, magicLen, 0); + + isElf = + magicLen >= 4 + && magicHeader[0] === 0x7f + && magicHeader[1] === 0x45 + && magicHeader[2] === 0x4c + && magicHeader[3] === 0x46; + const magic32 = magicLen >= 4 ? magicHeader.readUInt32LE(0) : 0; + const isMachO64 = magicLen >= 4 && (magic32 === 0xfeedfacf || magic32 === 0xcffaedfe); + const isMachO32 = magicLen >= 4 && (magic32 === 0xfeedface || magic32 === 0xcefaedfe); + // Universal Mach-O fat magic is BE 0xCAFEBABE (LE 0xbebafeca), which collides with Java + // .class files. Bytes 4-7 encode (minor_version << 16) | major_version for Java (major >= 45) + // and nfat_arch for Mach-O fat (1..20), so the 1..20 content bound alone disambiguates + // without trusting the filename extension. + const isMachOFat = + magicLen >= 8 + && magic32 === 0xbebafeca + && magicHeader.readUInt32BE(4) >= 1 + && magicHeader.readUInt32BE(4) <= 20; + + if (isMachO32 || isMachOFat) { + pushAuditFinding( + 'Unsupported Mach-O binary format in Stage A static audit', + relName, + `File "${relName}" uses an unsupported 32-bit or universal Mach-O header and failed closed during Stage A static audit`, + ); + continue; + } + + const shouldInspectAsBinary = isElf || isMachO64 || AUDIT_BINARY_EXT_RE.test(relName); + const shouldInspectAsText = !isElf && !isMachO64 && (AUDIT_TEXT_EXT_RE.test(relName) || AUDIT_BINARY_EXT_RE.test(relName)); + + if (!shouldInspectAsBinary && !shouldInspectAsText) { + continue; + } + + if (isElf) { + parsedInfo = await parseElfFromHandle(fh, fileSize, maxScanBytes); + } else if (isMachO64) { + parsedInfo = await parseMachO64FromHandle(fh, fileSize, maxScanBytes); + } else { + if (fileSize > maxScanBytes) { + pushAuditFinding( + 'Stage A output exceeds static audit 1 MiB scan limit', + relName, + `File "${relName}" (${fileSize} bytes) exceeds ${maxScanBytes}-byte (1 MiB) Stage A static audit scan cap`, + ); + continue; + } + const rawBuf = Buffer.allocUnsafe(fileSize); + await readExactFromHandle(fh, rawBuf, fileSize, 0); + textContent = rawBuf.toString('utf8'); + } + } finally { + await fh.close(); + } + + if (parsedInfo !== null) { + if (parsedInfo.scanError !== null) { + pushAuditFinding( + 'Stage A binary failed static audit inspection', + relName, + `File "${relName}": ${parsedInfo.scanError}`, + ); + continue; + } + + const candidateSymbols = new Set(parsedInfo.symbols); + let maxRegisters = parsedInfo.maxRegisters; + let maxSpillBytes = parsedInfo.maxSpillBytes; + + for (const emb of parsedInfo.embeddedTexts) { + const embParsed = parseTextAndPtxStaticInfo(emb, `${relName}.ptx`); + for (const t of embParsed.tokensAndLines) candidateSymbols.add(t); + if (embParsed.maxRegisters !== null) maxRegisters = Math.max(maxRegisters ?? 0, embParsed.maxRegisters); + if (embParsed.maxSpillBytes !== null) maxSpillBytes = Math.max(maxSpillBytes ?? 0, embParsed.maxSpillBytes); + } + + const verifySealedInodeUnchanged = async (toolLabel: string): Promise => { + try { + const recheck = await lstat(item.sealedFilePath); + if ( + !recheck.isFile() + || recheck.isSymbolicLink() + || recheck.nlink !== 1 + || recheck.dev !== preStat.dev + || recheck.ino !== preStat.ino + || recheck.size !== item.artifact.byteLength + ) { + pushAuditFinding( + `Stage A file mutated before ${toolLabel} static audit`, + relName, + `File "${relName}" inode or size changed between sealed read and ${toolLabel} invocation`, + ); + return false; + } + return true; + } catch (statErr: unknown) { + pushAuditFinding( + `Stage A file unavailable before ${toolLabel} static audit`, + relName, + `File "${relName}" lstat failed before ${toolLabel}: ${statErr instanceof Error ? statErr.message : String(statErr)}`, + ); + return false; + } + }; + + // Optional root-owned Linux/CUDA host toolchain inspection (`nm` / `cuobjdump`, 1 MiB stdout cap) + if (isElf && resolvedNm !== null) { + for (const nmFlags of [['-a', item.sealedFilePath], ['-D', item.sealedFilePath]]) { + if (!(await verifySealedInodeUnchanged('nm'))) break; + try { + const nmRes = await toolRunner('nm', resolvedNm, nmFlags, { + timeoutMs: 10_000, + maxOutputBytes: maxScanBytes, + ...(options.signal !== undefined ? { signal: options.signal } : {}), + }); + if (nmRes.exitCode === 0 && nmRes.stdout.length > 0) { + for (const line of nmRes.stdout.split(/\r?\n/)) { + const symPart = line.trim().split(/\s+/).pop(); + if (symPart) candidateSymbols.add(symPart); + } + } + } catch (toolErr: unknown) { + const msg = toolErr instanceof Error ? toolErr.message : String(toolErr); + const title = msg.includes('exceeded') + ? 'Stage A nm output exceeded 1 MiB static audit cap' + : 'Stage A nm static audit invocation failed'; + pushAuditFinding(title, relName, `File "${relName}": ${msg}`); + } + } + } + + if (isElf && resolvedCuobjdump !== null && /\.(?:cubin|fatbin|so|o)$/i.test(relName)) { + if (await verifySealedInodeUnchanged('cuobjdump')) { + try { + const cuRes = await toolRunner( + 'cuobjdump', + resolvedCuobjdump, + ['--dump-resource-usage', '--dump-elf-symbols', item.sealedFilePath], + { + timeoutMs: 10_000, + maxOutputBytes: maxScanBytes, + ...(options.signal !== undefined ? { signal: options.signal } : {}), + }, + ); + if (cuRes.exitCode === 0 && cuRes.stdout.length > 0) { + const cuParsed = parseTextAndPtxStaticInfo(cuRes.stdout, `${relName}.sass`); + for (const tok of cuParsed.tokensAndLines) candidateSymbols.add(tok); + if (cuParsed.maxRegisters !== null) maxRegisters = Math.max(maxRegisters ?? 0, cuParsed.maxRegisters); + if (cuParsed.maxSpillBytes !== null) maxSpillBytes = Math.max(maxSpillBytes ?? 0, cuParsed.maxSpillBytes); + } + } catch (toolErr: unknown) { + const msg = toolErr instanceof Error ? toolErr.message : String(toolErr); + const title = msg.includes('exceeded') + ? 'Stage A cuobjdump output exceeded 1 MiB static audit cap' + : 'Stage A cuobjdump static audit invocation failed'; + pushAuditFinding(title, relName, `File "${relName}": ${msg}`); + } + } + } + + if (patterns.length > 0) { + const matchedPairs = new Set(); + for (const rawSym of candidateSymbols) { + const expanded = expandDemangledSymbolForms(rawSym); + for (const pat of patterns) { + if (expanded.some(form => form.includes(pat))) { + const pairKey = `${pat}\0${rawSym}`; + if (!matchedPairs.has(pairKey)) { + matchedPairs.add(pairKey); + pushAuditFinding( + `Forbidden symbol pattern "${pat}" in Stage A binary`, + relName, + `File "${relName}" matched forbidden symbol pattern "${pat}" on symbol "${rawSym}"`, + ); + } + } + } + } + } + + if (auditSpec.maxRegisterCount !== undefined && maxRegisters !== null && maxRegisters > auditSpec.maxRegisterCount) { + pushAuditFinding( + 'Stage A kernel exceeded maxRegisterCount ceiling', + relName, + `File "${relName}" uses ${maxRegisters} registers (maxRegisterCount=${auditSpec.maxRegisterCount})`, + ); + } + + if (auditSpec.maxLocalSpillBytes !== undefined && maxSpillBytes !== null && maxSpillBytes > auditSpec.maxLocalSpillBytes) { + pushAuditFinding( + 'Stage A kernel exceeded maxLocalSpillBytes ceiling', + relName, + `File "${relName}" has ${maxSpillBytes} local spill/frame bytes (maxLocalSpillBytes=${auditSpec.maxLocalSpillBytes})`, + ); + } + continue; + } + + if (textContent !== null) { + const parsedText = parseTextAndPtxStaticInfo(textContent, relName); + if (patterns.length > 0) { + const reportedPatterns = new Set(); + for (const tokenOrLine of parsedText.tokensAndLines) { + const forms = tokenOrLine.includes('_Z') ? expandDemangledSymbolForms(tokenOrLine) : [tokenOrLine]; + for (const pat of patterns) { + if (!reportedPatterns.has(pat) && forms.some(f => f.includes(pat))) { + reportedPatterns.add(pat); + pushAuditFinding( + `Forbidden symbol pattern "${pat}" in Stage A output`, + relName, + `File "${relName}" matched forbidden symbol pattern "${pat}" in "${tokenOrLine.slice(0, 160)}"`, + ); + } + } + } + } + + if ( + auditSpec.maxRegisterCount !== undefined + && parsedText.maxRegisters !== null + && parsedText.maxRegisters > auditSpec.maxRegisterCount + ) { + pushAuditFinding( + 'Stage A output exceeded maxRegisterCount ceiling', + relName, + `File "${relName}" uses ${parsedText.maxRegisters} registers (maxRegisterCount=${auditSpec.maxRegisterCount})`, + ); + } + + if ( + auditSpec.maxLocalSpillBytes !== undefined + && parsedText.maxSpillBytes !== null + && parsedText.maxSpillBytes > auditSpec.maxLocalSpillBytes + ) { + pushAuditFinding( + 'Stage A output exceeded maxLocalSpillBytes ceiling', + relName, + `File "${relName}" has ${parsedText.maxSpillBytes} local spill bytes (maxLocalSpillBytes=${auditSpec.maxLocalSpillBytes})`, + ); + } + } + } + + return Object.freeze({ + passed: findings.length === 0, + findings: Object.freeze(findings), + }); +} + function assertNoDecodedSecret(value: string, scrubber: SecretScrubber): void { if (scrubber.containsSecret(value)) { throw new HardwareRunnerError('ARTIFACT_INVALID', 'Stage B result envelope rejected by SecretScrubber'); @@ -2897,10 +4086,71 @@ function parseEnvelopeFindings(raw: unknown, scrubber: SecretScrubber): readonly return Object.freeze(out); } +function assertNoRawInvalidStageBNumbers(value: unknown, path: string, depth = 0): void { + if (depth > 32) { + throw new HardwareRunnerError('ARTIFACT_INVALID', 'Stage B structure exceeds maximum depth', path); + } + if (typeof value === 'number') { + if (!Number.isFinite(value) || Object.is(value, -0)) { + throw new HardwareRunnerError('ARTIFACT_INVALID', 'Stage B numeric value must be finite and not -0', path); + } + return; + } + if (typeof value === 'string') { + if (hasLoneSurrogate(value)) { + throw new HardwareRunnerError('ARTIFACT_INVALID', 'Stage B string contains lone UTF-16 surrogate', path); + } + return; + } + if (Array.isArray(value)) { + for (let i = 0; i < value.length; i += 1) { + assertNoRawInvalidStageBNumbers(value[i], `${path}/${i}`, depth + 1); + } + return; + } + if (value !== null && typeof value === 'object') { + const rec = value as Readonly>; + for (const key of Reflect.ownKeys(rec)) { + if (typeof key !== 'string' || FORBIDDEN_METRIC_KEYS.has(key) || hasLoneSurrogate(key)) { + throw new HardwareRunnerError('ARTIFACT_INVALID', 'forbidden key in Stage B result envelope', path); + } + assertNoRawInvalidStageBNumbers(rec[key], `${path}/${key}`, depth + 1); + } + } +} + +function parseEnvelopeBucketMetrics(raw: unknown, scrubber: SecretScrubber): readonly BucketMetricEntry[] { + assertNoRawInvalidStageBNumbers(raw, '/stageB/bucketMetrics'); + const validated = validateBucketMetrics(raw, scrubber); + if (!validated.ok) { + const first = validated.errors[0]; + throw new HardwareRunnerError( + 'ARTIFACT_INVALID', + `invalid Stage B bucketMetrics (${first?.code ?? 'INVALID'})`, + first?.path ? `/stageB/bucketMetrics${first.path}` : '/stageB/bucketMetrics', + ); + } + return validated.value; +} + +function parseEnvelopeHardwareDiagnostics(raw: unknown, scrubber: SecretScrubber): HardwareDiagnostics { + assertNoRawInvalidStageBNumbers(raw, '/stageB/hardwareDiagnostics'); + const validated = validateHardwareDiagnostics(raw, scrubber); + if (!validated.ok) { + const first = validated.errors[0]; + throw new HardwareRunnerError( + 'ARTIFACT_INVALID', + `invalid Stage B hardwareDiagnostics (${first?.code ?? 'INVALID'})`, + first?.path ? `/stageB/hardwareDiagnostics${first.path}` : '/stageB/hardwareDiagnostics', + ); + } + return validated.value; +} + /** - * Parse and validate the bounded (`<= 64 KiB`) Stage B JSON result envelope into null-prototype - * structures, accepting ONLY finite numeric metrics and scanning all decoded strings/keys with - * `SecretScrubber`. + * Parse and validate the bounded (`<= 48 KiB`) Stage B JSON result envelope into null-prototype + * structures, accepting ONLY finite numeric metrics, bounded `bucketMetrics`, and closed-enum + * sanitized `hardwareDiagnostics` while scanning all decoded strings/keys with `SecretScrubber`. */ export function parseStageBResultEnvelope( rawStdout: string, @@ -2967,6 +4217,12 @@ export function parseStageBResultEnvelope( const metrics = Object.hasOwn(obj, 'metrics') ? parseEnvelopeMetrics(obj.metrics, scrubber) : undefined; const findings = Object.hasOwn(obj, 'findings') ? parseEnvelopeFindings(obj.findings, scrubber) : undefined; + const bucketMetrics = Object.hasOwn(obj, 'bucketMetrics') + ? parseEnvelopeBucketMetrics(obj.bucketMetrics, scrubber) + : undefined; + const hardwareDiagnostics = Object.hasOwn(obj, 'hardwareDiagnostics') + ? parseEnvelopeHardwareDiagnostics(obj.hardwareDiagnostics, scrubber) + : undefined; const out: Record = Object.create(null) as Record; out.status = obj.status; @@ -2974,6 +4230,8 @@ export function parseStageBResultEnvelope( if (detail !== undefined) out.detail = detail; if (metrics !== undefined) out.metrics = metrics; if (findings !== undefined) out.findings = findings; + if (bucketMetrics !== undefined) out.bucketMetrics = bucketMetrics; + if (hardwareDiagnostics !== undefined) out.hardwareDiagnostics = hardwareDiagnostics; assertNoDecodedSecret(canonicalJson(out), scrubber); return Object.freeze(out as unknown as StageBResultEnvelope); } @@ -2985,40 +4243,74 @@ function readFiniteMetricValue(metrics: MetricsMap, key: string): number | undef return Object.is(val, -0) ? 0 : val; } -function checkMetricThresholds(rules: readonly MetricThresholdRule[], metrics: MetricsMap | undefined): string | null { - if (rules.length === 0) return null; - if (metrics === undefined) { - return 'required quantitative metrics map is missing from Stage B output'; +function checkSingleScopeMetricRule( + rule: MetricThresholdRule, + metrics: MetricsMap, + scopePrefix: string, +): string | null { + const observed = readFiniteMetricValue(metrics, rule.metric); + if (observed === undefined) { + return `${scopePrefix}missing numeric metric "${rule.metric}"`; } - for (const rule of rules) { - const observed = readFiniteMetricValue(metrics, rule.metric); - if (observed === undefined) { - return `missing numeric metric "${rule.metric}"`; + if (rule.kind === 'bounds') { + if (rule.min !== undefined && observed < rule.min) { + return `${scopePrefix}metric "${rule.metric}" (${observed}) is below min ${rule.min}`; } - if (rule.kind === 'bounds') { - if (rule.min !== undefined && observed < rule.min) { - return `metric "${rule.metric}" (${observed}) is below min ${rule.min}`; - } - if (rule.max !== undefined && observed > rule.max) { - return `metric "${rule.metric}" (${observed}) exceeds max ${rule.max}`; + if (rule.max !== undefined && observed > rule.max) { + return `${scopePrefix}metric "${rule.metric}" (${observed}) exceeds max ${rule.max}`; + } + return null; + } + const baseline = readFiniteMetricValue(metrics, rule.baselineMetric); + if (baseline === undefined) { + return `${scopePrefix}missing numeric baseline metric "${rule.baselineMetric}"`; + } + if (rule.operator === 'min_ratio') { + if (!(baseline > 0) || observed / baseline < rule.threshold) { + return `${scopePrefix}comparative ratio ${rule.metric}/${rule.baselineMetric} failed min_ratio ${rule.threshold}`; + } + } else if (rule.operator === 'max_ratio') { + if (!(baseline > 0) || observed / baseline > rule.threshold) { + return `${scopePrefix}comparative ratio ${rule.metric}/${rule.baselineMetric} failed max_ratio ${rule.threshold}`; + } + } else if (observed - baseline > rule.threshold) { + return `${scopePrefix}comparative delta ${rule.metric}-${rule.baselineMetric} failed max_delta ${rule.threshold}`; + } + return null; +} + +function checkMetricThresholds( + rules: readonly MetricThresholdRule[], + metrics: MetricsMap | undefined, + bucketMetrics?: readonly BucketMetricEntry[], +): string | null { + if (rules.length === 0) return null; + for (const rule of rules) { + const scope = rule.bucketScope ?? 'aggregate'; + if (scope === 'aggregate') { + if (metrics === undefined) { + return 'required quantitative metrics map is missing from Stage B output'; } + const err = checkSingleScopeMetricRule(rule, metrics, ''); + if (err !== null) return err; continue; } - const baseline = readFiniteMetricValue(metrics, rule.baselineMetric); - if (baseline === undefined) { - return `missing numeric baseline metric "${rule.baselineMetric}"`; + if (bucketMetrics === undefined || bucketMetrics.length === 0) { + return 'required bucketMetrics list is missing from Stage B output for bucket-scoped threshold rule'; } - if (rule.operator === 'min_ratio') { - if (!(baseline > 0) || observed / baseline < rule.threshold) { - return `comparative ratio ${rule.metric}/${rule.baselineMetric} failed min_ratio ${rule.threshold}`; - } - } else if (rule.operator === 'max_ratio') { - if (!(baseline > 0) || observed / baseline > rule.threshold) { - return `comparative ratio ${rule.metric}/${rule.baselineMetric} failed max_ratio ${rule.threshold}`; + if (scope === 'all_buckets') { + for (const bucket of bucketMetrics) { + const err = checkSingleScopeMetricRule(rule, bucket.metrics, `bucket "${bucket.bucketId}": `); + if (err !== null) return err; } - } else if (observed - baseline > rule.threshold) { - return `comparative delta ${rule.metric}-${rule.baselineMetric} failed max_delta ${rule.threshold}`; + continue; } + const targetBucket = bucketMetrics.find(entry => entry.bucketId === scope.bucketId); + if (targetBucket === undefined) { + return `target bucket "${scope.bucketId}" is missing from Stage B bucketMetrics`; + } + const err = checkSingleScopeMetricRule(rule, targetBucket.metrics, `bucket "${targetBucket.bucketId}": `); + if (err !== null) return err; } return null; } @@ -3149,7 +4441,7 @@ function buildDeviceVisibilityEnv(targetHardware: HardwareTargetSpec): Record Promise; + readonly scrubber?: SecretScrubber; + readonly extraSecrets?: readonly string[]; + readonly timeoutMs?: number; + readonly signal?: AbortSignal; +} + +function scrubHealthSnippet(raw: string, scrubber: SecretScrubber, maxLen = 512): string { + const scrubbed = stripAnsiSequences(scrubber.scrub(raw)) + .replace(/[\r\n\t]+/g, ' ') + .replace(/\s+/g, ' ') + .trim(); + if (!scrubbed) return ''; + if (scrubbed.length <= maxLen) return scrubbed; + return `${scrubbed.slice(0, Math.max(1, maxLen - 14))}...(truncated)`; +} + +function buildHealthFinding(title: string, evidence: string, scrubber: SecretScrubber): StructuredFinding { + const safeTitle = scrubHealthSnippet(title, scrubber, LIMITS.findingTitle) || 'Accelerator health fault'; + const safeEvidence = scrubHealthSnippet(evidence, scrubber, LIMITS.findingEvidence) || safeTitle; + const out: Record = Object.create(null) as Record; + out.title = safeTitle; + out.severity = 'critical'; + out.evidence = safeEvidence; + return Object.freeze(out as unknown as StructuredFinding); +} + +function buildUnhealthyProbeResult(options: { + readonly probeKind: 'physical' | 'synthetic_fixture'; + readonly vendor: 'nvidia' | 'amd' | 'huawei' | 'synthetic'; + readonly checkedDeviceIndices: readonly number[]; + readonly faultKind: AcceleratorFaultKind; + readonly externalHostLoss?: boolean; + readonly title: string; + readonly detail: string; + readonly scrubber: SecretScrubber; +}): AcceleratorHealthProbeResult { + const safeSummary = + scrubHealthSnippet(options.detail, options.scrubber, 512) + || `Accelerator health check failed (${options.faultKind})`; + const finding = buildHealthFinding(options.title, safeSummary, options.scrubber); + const out: Record = Object.create(null) as Record; + out.healthy = false; + out.quarantineRequired = true; + out.probeKind = options.probeKind; + out.vendor = options.vendor; + out.checkedDeviceIndices = Object.freeze([...options.checkedDeviceIndices]); + out.faultKind = options.faultKind; + if (options.externalHostLoss === true) { + out.externalHostLoss = true; + } + out.summary = safeSummary; + out.findings = Object.freeze([finding]); + return Object.freeze(out as unknown as AcceleratorHealthProbeResult); +} + +function parseOptionalNonNegativeCounter(raw: string): number | null { + const cleaned = raw.trim().replace(/^\[|\]$/g, '').trim(); + if ( + cleaned.length === 0 + || /^(?:n\/a|not\s+supported|disabled|none|unknown|-)$/i.test(cleaned) + ) { + return null; + } + const m = /^(\d+)\b/.exec(cleaned); + if (m === null) return null; + const n = Number.parseInt(m[1]!, 10); + return Number.isSafeInteger(n) && n >= 0 ? n : null; +} + +function classifyFailedProbeOutput( + vendor: 'nvidia' | 'amd' | 'huawei', + combinedOutput: string, +): { readonly faultKind: AcceleratorFaultKind; readonly externalHostLoss: boolean } { + const cleaned = stripAnsiSequences(combinedOutput); + if (/\bxid\b/i.test(cleaned)) { + return { faultKind: 'xid_error', externalHostLoss: false }; + } + if ( + /no devices were found|driver.*not loaded|failed to initialize nvml|no amd gpus|no npu/i.test(cleaned) + ) { + return { faultKind: 'device_lost', externalHostLoss: true }; + } + if (/gpu is lost|fallen off the bus|unable to determine the device handle/i.test(cleaned)) { + return { faultKind: 'device_lost', externalHostLoss: false }; + } + if (/gpu requires reset|reset required|gpu reset|gpu hang|gpu recovery|wedged/i.test(cleaned)) { + return { faultKind: 'gpu_reset_required', externalHostLoss: false }; + } + if (/remapping\s+failure/i.test(cleaned)) { + return { faultKind: 'row_remap_failure', externalHostLoss: false }; + } + if (/uncorrectable|double\s+bit\s+ecc/i.test(cleaned)) { + return { faultKind: 'ecc_uncorrectable', externalHostLoss: false }; + } + void vendor; + return { faultKind: 'probe_failed', externalHostLoss: false }; +} + +export function parseNvidiaHealthOutput( + queryOutput: string, + detailOutput: string, + checkedDeviceIndices: readonly number[], + scrubber: SecretScrubber, +): AcceleratorHealthProbeResult { + const combined = `${queryOutput}\n${detailOutput}`; + if (/\bxid\b/i.test(combined)) { + return buildUnhealthyProbeResult({ + probeKind: 'physical', + vendor: 'nvidia', + checkedDeviceIndices, + faultKind: 'xid_error', + title: 'NVIDIA sticky Xid fault detected', + detail: combined, + scrubber, + }); + } + if (/gpu is lost|fallen off the bus|unable to determine the device handle/i.test(combined)) { + return buildUnhealthyProbeResult({ + probeKind: 'physical', + vendor: 'nvidia', + checkedDeviceIndices, + faultKind: 'device_lost', + title: 'NVIDIA GPU lost on bus', + detail: combined, + scrubber, + }); + } + if (/no devices were found|failed to initialize nvml/i.test(combined)) { + return buildUnhealthyProbeResult({ + probeKind: 'physical', + vendor: 'nvidia', + checkedDeviceIndices, + faultKind: 'device_lost', + externalHostLoss: true, + title: 'NVIDIA host devices unavailable', + detail: combined, + scrubber, + }); + } + if (/gpu requires reset|reset required/i.test(combined)) { + return buildUnhealthyProbeResult({ + probeKind: 'physical', + vendor: 'nvidia', + checkedDeviceIndices, + faultKind: 'gpu_reset_required', + title: 'NVIDIA GPU requires reset', + detail: combined, + scrubber, + }); + } + + const lines = stripAnsiSequences(queryOutput) + .split(/\r?\n/) + .map(l => l.trim()) + .filter(l => l.length > 0); + if (lines.length === 0) { + return buildUnhealthyProbeResult({ + probeKind: 'physical', + vendor: 'nvidia', + checkedDeviceIndices, + faultKind: 'probe_failed', + title: 'Empty nvidia-smi health output', + detail: 'nvidia-smi returned empty GPU health output', + scrubber, + }); + } + + const rowsByIndex = new Map(); + for (const line of lines) { + const cols = line.split(',').map(c => c.trim()); + if (!/^\d+$/.test(cols[0] ?? '')) { + return buildUnhealthyProbeResult({ + probeKind: 'physical', + vendor: 'nvidia', + checkedDeviceIndices, + faultKind: 'probe_failed', + title: 'Malformed nvidia-smi GPU index column', + detail: `Expected integer GPU index in nvidia-smi health output row: ${line}`, + scrubber, + }); + } + rowsByIndex.set(Number.parseInt(cols[0]!, 10), cols); + } + + for (const idx of checkedDeviceIndices) { + const row = rowsByIndex.get(idx); + if (row === undefined) { + return buildUnhealthyProbeResult({ + probeKind: 'physical', + vendor: 'nvidia', + checkedDeviceIndices, + faultKind: 'device_lost', + title: `NVIDIA GPU ${idx} missing from health query`, + detail: `Allocated GPU index ${idx} was not reported by nvidia-smi`, + scrubber, + }); + } + if (row.some(col => /\b(?:err!|unknown error|gpu is lost)\b/i.test(col))) { + return buildUnhealthyProbeResult({ + probeKind: 'physical', + vendor: 'nvidia', + checkedDeviceIndices, + faultKind: 'health_degraded', + title: `NVIDIA GPU ${idx} reported error state`, + detail: row.join(', '), + scrubber, + }); + } + // Columns 6 and 7 are ecc.errors.uncorrected.volatile.total and aggregate.total when present; + // on GeForce SKUs (e.g. RTX 4090) these report "[N/A]", which is healthy. + for (const colIdx of [6, 7]) { + if (colIdx < row.length) { + const count = parseOptionalNonNegativeCounter(row[colIdx]!); + if (count !== null && count > 0) { + return buildUnhealthyProbeResult({ + probeKind: 'physical', + vendor: 'nvidia', + checkedDeviceIndices, + faultKind: 'ecc_uncorrectable', + title: `NVIDIA GPU ${idx} uncorrectable ECC error`, + detail: `GPU ${idx} reported ${count} uncorrectable ECC error(s)`, + scrubber, + }); + } + } + } + } + + if (detailOutput.trim().length > 0) { + const cleanedDetail = stripAnsiSequences(detailOutput); + if (/Remapping\s+Failure\s+Occurred\s*:\s*Yes/i.test(cleanedDetail)) { + return buildUnhealthyProbeResult({ + probeKind: 'physical', + vendor: 'nvidia', + checkedDeviceIndices, + faultKind: 'ecc_uncorrectable', + title: 'NVIDIA HBM/GDDR row remapping failure', + detail: 'nvidia-smi reported Remapping Failure Occurred: Yes', + scrubber, + }); + } + if (/(?:Channel|TPC)\s+Repair\s+Pending\s*:\s*Yes|Unrepairable\s+Memory\s*:\s*Yes|Pending\s+Page\s+Blacklist\s*:\s*Yes/i.test(cleanedDetail)) { + return buildUnhealthyProbeResult({ + probeKind: 'physical', + vendor: 'nvidia', + checkedDeviceIndices, + faultKind: 'ecc_uncorrectable', + title: 'NVIDIA memory repair/blacklist pending or unrepairable', + detail: cleanedDetail, + scrubber, + }); + } + for (const m of cleanedDetail.matchAll( + /^\s*(?:SRAM\s+Uncorrectable[^\r\n:]*|DRAM\s+Uncorrectable|Double\s+Bit\s+ECC|Uncorrectable\s+Error)\s*:\s*([^\r\n]+)$/gim, + )) { + // Ignore "Inactive Uncorrectable Error" historical counters when active Uncorrectable Error is 0; + // the regex anchors at start of line whitespace so "Inactive Uncorrectable Error" does not match. + const cnt = parseOptionalNonNegativeCounter(m[1]!); + if (cnt !== null && cnt > 0) { + return buildUnhealthyProbeResult({ + probeKind: 'physical', + vendor: 'nvidia', + checkedDeviceIndices, + faultKind: 'ecc_uncorrectable', + title: 'NVIDIA uncorrectable memory error counter > 0', + detail: `${m[0]!.trim()}`, + scrubber, + }); + } + } + } + + return Object.freeze({ + healthy: true, + quarantineRequired: false, + probeKind: 'physical', + vendor: 'nvidia', + checkedDeviceIndices: Object.freeze([...checkedDeviceIndices]), + summary: `NVIDIA GPU health OK (${checkedDeviceIndices.join(',')})`, + findings: Object.freeze([]), + }); +} + +export function parseRocmHealthOutput( + rocmOutput: string, + checkedDeviceIndices: readonly number[], + scrubber: SecretScrubber, +): AcceleratorHealthProbeResult { + const cleaned = stripAnsiSequences(rocmOutput); + if (cleaned.trim().length === 0) { + return buildUnhealthyProbeResult({ + probeKind: 'physical', + vendor: 'amd', + checkedDeviceIndices, + faultKind: 'probe_failed', + title: 'Empty rocm-smi health output', + detail: 'rocm-smi returned empty health output', + scrubber, + }); + } + if (/no amd gpus specified|no amd gpus found/i.test(cleaned)) { + return buildUnhealthyProbeResult({ + probeKind: 'physical', + vendor: 'amd', + checkedDeviceIndices, + faultKind: 'device_lost', + externalHostLoss: true, + title: 'AMD ROCm GPUs unavailable on host', + detail: cleaned, + scrubber, + }); + } + if (/\b(?:gpu\s+hang|gpu\s+reset|gpu\s+recovery|device\s+lost|wedged|ras\s+fatal)\b/i.test(cleaned)) { + return buildUnhealthyProbeResult({ + probeKind: 'physical', + vendor: 'amd', + checkedDeviceIndices, + faultKind: 'gpu_reset_required', + title: 'AMD ROCm GPU reset or hang detected', + detail: cleaned, + scrubber, + }); + } + + // Real rocm-smi --json on Radeon GPUs in runtime PM can emit leading "WARNING: AMD GPU device(s) is/are in a low-power state..." + // lines on stdout before the JSON payload `{...}`. Extract the JSON object cleanly after any non-JSON preamble. + const firstBrace = cleaned.indexOf('{'); + const lastBrace = cleaned.lastIndexOf('}'); + if (firstBrace !== -1 && lastBrace > firstBrace) { + const jsonSlice = cleaned.slice(firstBrace, lastBrace + 1); + let parsed: unknown; + try { + parsed = parseStrictJsonBytes( + Buffer.from(jsonSlice, 'utf8'), + MAX_PROBE_OUTPUT_BYTES, + 'RUNNER_SANDBOX_FAILED', + '/rocmHealth', + ); + } catch { + parsed = null; + } + if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) { + const root = parsed as Readonly>; + const inspectCardFaults = (node: unknown, cardIdx: number, keyPath: string): AcceleratorHealthProbeResult | null => { + if (node === null || node === undefined) return null; + if (typeof node === 'string' || typeof node === 'number') { + const textVal = String(node); + const lowerPath = keyPath.toLowerCase(); + if ( + (lowerPath.includes('uncorrectable') || /(?:^|[/._ -])ue$/i.test(lowerPath) || lowerPath.includes('unreservable')) + ) { + const cnt = parseOptionalNonNegativeCounter(textVal); + if (cnt !== null && cnt > 0) { + return buildUnhealthyProbeResult({ + probeKind: 'physical', + vendor: 'amd', + checkedDeviceIndices, + faultKind: 'ecc_uncorrectable', + title: `AMD GPU ${cardIdx} RAS/ECC uncorrectable error`, + detail: `card${cardIdx} ${keyPath}=${textVal}`, + scrubber, + }); + } + } + if (/\b(?:gpu\s+hang|gpu\s+reset|wedged|unresponsive|err!|fatal)\b/i.test(textVal)) { + return buildUnhealthyProbeResult({ + probeKind: 'physical', + vendor: 'amd', + checkedDeviceIndices, + faultKind: 'gpu_reset_required', + title: `AMD GPU ${cardIdx} degraded state`, + detail: `card${cardIdx} ${keyPath}=${textVal}`, + scrubber, + }); + } + return null; + } + if (typeof node === 'object' && !Array.isArray(node)) { + const rec = node as Readonly>; + for (const k of Object.keys(rec).sort()) { + if (!Object.hasOwn(rec, k)) continue; + const sub = inspectCardFaults(rec[k], cardIdx, keyPath ? `${keyPath}.${k}` : k); + if (sub !== null) return sub; + } + } + return null; + }; + + for (const idx of checkedDeviceIndices) { + const cardObj = Object.hasOwn(root, `card${idx}`) + ? root[`card${idx}`] + : Object.hasOwn(root, `gpu${idx}`) + ? root[`gpu${idx}`] + : undefined; + if (cardObj === undefined || cardObj === null || typeof cardObj !== 'object') { + return buildUnhealthyProbeResult({ + probeKind: 'physical', + vendor: 'amd', + checkedDeviceIndices, + faultKind: 'device_lost', + title: `AMD GPU ${idx} missing from rocm-smi JSON`, + detail: `Expected card${idx} in rocm-smi JSON output`, + scrubber, + }); + } + const fault = inspectCardFaults(cardObj, idx, ''); + if (fault !== null) return fault; + } + + return Object.freeze({ + healthy: true, + quarantineRequired: false, + probeKind: 'physical', + vendor: 'amd', + checkedDeviceIndices: Object.freeze([...checkedDeviceIndices]), + summary: `AMD ROCm GPU health OK (${checkedDeviceIndices.join(',')})`, + findings: Object.freeze([]), + }); + } + } + + // Plain-text rocm-smi fallback: check allocated GPU presence and RAS uncorrectable error counts + const seenGpus = new Set(); + for (const rawLine of cleaned.split(/\r?\n/)) { + const line = rawLine.trim(); + const gpuMatch = /^(?:GPU|card)\[(\d+)\]/i.exec(line); + if (gpuMatch !== null) { + seenGpus.add(Number.parseInt(gpuMatch[1]!, 10)); + } + const ueKv = /Uncorrectable\s+Error[s]?\s*:\s*(\d+)/i.exec(line); + if (ueKv !== null && Number.parseInt(ueKv[1]!, 10) > 0) { + return buildUnhealthyProbeResult({ + probeKind: 'physical', + vendor: 'amd', + checkedDeviceIndices, + faultKind: 'ecc_uncorrectable', + title: 'AMD ROCm RAS uncorrectable error', + detail: line, + scrubber, + }); + } + // RAS table row: + const rasRow = /^[A-Za-z0-9_]+\s+(?:ENABLED|ACTIVE|OK)\s+(\d+)\s+(\d+)\s*$/i.exec(line); + if (rasRow !== null && Number.parseInt(rasRow[2]!, 10) > 0) { + return buildUnhealthyProbeResult({ + probeKind: 'physical', + vendor: 'amd', + checkedDeviceIndices, + faultKind: 'ecc_uncorrectable', + title: 'AMD ROCm RAS block uncorrectable error', + detail: line, + scrubber, + }); + } + } + + for (const idx of checkedDeviceIndices) { + if (!seenGpus.has(idx)) { + return buildUnhealthyProbeResult({ + probeKind: 'physical', + vendor: 'amd', + checkedDeviceIndices, + faultKind: 'device_lost', + title: `AMD GPU ${idx} missing from rocm-smi output`, + detail: `GPU[${idx}] not present in rocm-smi health output`, + scrubber, + }); + } + } + + return Object.freeze({ + healthy: true, + quarantineRequired: false, + probeKind: 'physical', + vendor: 'amd', + checkedDeviceIndices: Object.freeze([...checkedDeviceIndices]), + summary: `AMD ROCm GPU health OK (${checkedDeviceIndices.join(',')})`, + findings: Object.freeze([]), + }); +} + +export function parseNpuHealthOutput( + npuOutput: string, + checkedDeviceIndices: readonly number[], + scrubber: SecretScrubber, +): AcceleratorHealthProbeResult { + const cleaned = stripAnsiSequences(npuOutput); + if (cleaned.trim().length === 0) { + return buildUnhealthyProbeResult({ + probeKind: 'physical', + vendor: 'huawei', + checkedDeviceIndices, + faultKind: 'probe_failed', + title: 'Empty npu-smi health output', + detail: 'npu-smi returned empty output', + scrubber, + }); + } + if (/no npu|device not found/i.test(cleaned)) { + return buildUnhealthyProbeResult({ + probeKind: 'physical', + vendor: 'huawei', + checkedDeviceIndices, + faultKind: 'device_lost', + externalHostLoss: true, + title: 'Ascend NPU unavailable on host', + detail: cleaned, + scrubber, + }); + } + + const healthByIndex = new Map(); + let activeKvIdx: number | null = null; + for (const rawLine of cleaned.split(/\r?\n/)) { + const trimmed = rawLine.trim(); + if (!trimmed) continue; + // Table row: | 0 910B3 | OK | 92.4 ... | + const tableRow = /^\|\s*(\d+)\s+(?:Ascend[\s_-]*)?[0-9]{3}[A-Za-z0-9_-]*\s*\|\s*([A-Za-z0-9_-]+)\s*\|/i.exec(trimmed); + if (tableRow !== null) { + const idx = Number.parseInt(tableRow[1]!, 10); + healthByIndex.set(idx, tableRow[2]!); + continue; + } + const kvId = /^(?:NPU\s+ID|NPU)\s*:\s*(\d+)\s*$/i.exec(trimmed); + if (kvId !== null) { + activeKvIdx = Number.parseInt(kvId[1]!, 10); + continue; + } + const kvHealth = /^Health(?:\s+Status)?\s*:\s*([A-Za-z0-9_-]+)\s*$/i.exec(trimmed); + if (kvHealth !== null) { + const targetIdx = activeKvIdx ?? 0; + healthByIndex.set(targetIdx, kvHealth[1]!); + continue; + } + const kvEcc = /(?:Uncorrectable|Double\s+Bit)[^\r\n:]*:\s*(\d+)/i.exec(trimmed); + if (kvEcc !== null && Number.parseInt(kvEcc[1]!, 10) > 0) { + return buildUnhealthyProbeResult({ + probeKind: 'physical', + vendor: 'huawei', + checkedDeviceIndices, + faultKind: 'ecc_uncorrectable', + title: 'Ascend NPU uncorrectable ECC fault', + detail: trimmed, + scrubber, + }); + } + } + + for (const idx of checkedDeviceIndices) { + const health = healthByIndex.get(idx); + if (health === undefined) { + return buildUnhealthyProbeResult({ + probeKind: 'physical', + vendor: 'huawei', + checkedDeviceIndices, + faultKind: 'device_lost', + title: `Ascend NPU ${idx} missing from npu-smi info`, + detail: `Allocated NPU ${idx} missing from npu-smi health output`, + scrubber, + }); + } + if (health.toUpperCase() !== 'OK') { + return buildUnhealthyProbeResult({ + probeKind: 'physical', + vendor: 'huawei', + checkedDeviceIndices, + faultKind: 'health_degraded', + title: `Ascend NPU ${idx} reported non-OK health (${health})`, + detail: `NPU ${idx} health status is "${health}"`, + scrubber, + }); + } + } + + return Object.freeze({ + healthy: true, + quarantineRequired: false, + probeKind: 'physical', + vendor: 'huawei', + checkedDeviceIndices: Object.freeze([...checkedDeviceIndices]), + summary: `Ascend NPU health OK (${checkedDeviceIndices.join(',')})`, + findings: Object.freeze([]), + }); +} + +/** + * Execute an out-of-band trusted host accelerator health probe (`nvidia-smi`, `rocm-smi`, `npu-smi`) + * to detect sticky GPU/NPU faults (`Xid`, uncorrectable ECC, row-remap failure, GPU reset/hang, or + * unresponsive device) after a Stage B timeout, crash signal, or non-zero exit. + * + * Always scrubs probe outputs through `SecretScrubber` and returns a structured + * `AcceleratorHealthProbeResult` (`quarantineRequired: true` on any unresponsive or degraded state). + */ +export async function probeAcceleratorHealth( + options: ProbeAcceleratorHealthOptions, +): Promise { + const scrubber = options.scrubber ?? new SecretScrubber(); + if (options.extraSecrets !== undefined) { + for (const sec of options.extraSecrets) { + if (typeof sec === 'string' && sec.length > 0) { + scrubber.register(sec); + } + } + } + + const family = inferAcceleratorFamily(options.capabilities.accelerator); + const requestedCount = options.targetHardware?.deviceCount ?? (options.allocatedDeviceIndices?.length ?? 1); + const safeCount = Math.min(Math.max(1, requestedCount), Math.max(1, options.capabilities.deviceCount)); + const checkedDeviceIndices: readonly number[] = options.allocatedDeviceIndices !== undefined && options.allocatedDeviceIndices.length > 0 + ? Object.freeze([...options.allocatedDeviceIndices]) + : Object.freeze(Array.from({ length: safeCount }, (_, i) => i)); + + if (options.probeMode === 'synthetic_fixture' && options.commandRunner === undefined) { + const syntheticVendor = family === 'unknown' ? 'synthetic' : family; + return Object.freeze({ + healthy: true, + quarantineRequired: false, + probeKind: 'synthetic_fixture', + vendor: syntheticVendor, + checkedDeviceIndices, + summary: `Synthetic accelerator fixture healthy (${options.capabilities.accelerator})`, + findings: Object.freeze([]), + }); + } + + if (family === 'unknown') { + return buildUnhealthyProbeResult({ + probeKind: options.probeMode, + vendor: 'synthetic', + checkedDeviceIndices, + faultKind: 'probe_failed', + title: 'Unsupported accelerator family for physical health probe', + detail: `Unsupported accelerator "${options.capabilities.accelerator}"`, + scrubber, + }); + } + + const timeoutMs = options.timeoutMs ?? DEFAULT_HEALTH_PROBE_TIMEOUT_MS; + const runner = options.commandRunner ?? defaultProbeCommandRunner; + const verifier = options.verifyExecutable ?? ((binPath: string, allowlist: readonly string[]) => + verifyTrustedProbeExecutable(binPath, allowlist)); + const runOpts = { timeoutMs, ...(options.signal !== undefined ? { signal: options.signal } : {}) }; + + try { + if (family === 'nvidia') { + const nvidiaBin = await resolveFirstTrustedProbeExecutable( + options.executableOverrides?.nvidiaSmiPath, + TRUSTED_NVIDIA_SMI_PATHS, + verifier, + ); + const queryRes = await runner( + nvidiaBin, + [ + '--query-gpu=index,name,uuid,pci.bus_id,pstate,ecc.mode.current,ecc.errors.uncorrected.volatile.total,ecc.errors.uncorrected.aggregate.total', + '--format=csv,noheader,nounits', + ], + runOpts, + ); + if (queryRes.exitCode !== 0) { + const combined = `${queryRes.stdout}\n${queryRes.stderr}`; + const classified = classifyFailedProbeOutput('nvidia', combined); + return buildUnhealthyProbeResult({ + probeKind: options.probeMode, + vendor: 'nvidia', + checkedDeviceIndices, + faultKind: classified.faultKind, + externalHostLoss: classified.externalHostLoss, + title: `nvidia-smi health query failed (exit ${queryRes.exitCode})`, + detail: combined || `nvidia-smi exited with status ${queryRes.exitCode}`, + scrubber, + }); + } + const targetIdsCsv = checkedDeviceIndices.join(','); + let detailRes = await runner( + nvidiaBin, + ['-i', targetIdsCsv, '-q', '-d', 'ECC,PAGE_RETIREMENT,ROW_REMAPPER'], + runOpts, + ); + if ( + detailRes.exitCode !== 0 + && /failed to parse --display\/-d flags/i.test(`${detailRes.stdout}\n${detailRes.stderr}`) + ) { + detailRes = await runner(nvidiaBin, ['-i', targetIdsCsv, '-q'], runOpts); + } + if (detailRes.exitCode !== 0) { + const combined = `${detailRes.stdout}\n${detailRes.stderr}`; + const classified = classifyFailedProbeOutput('nvidia', combined); + return buildUnhealthyProbeResult({ + probeKind: options.probeMode, + vendor: 'nvidia', + checkedDeviceIndices, + faultKind: classified.faultKind, + externalHostLoss: classified.externalHostLoss, + title: `nvidia-smi detail health query failed (exit ${detailRes.exitCode})`, + detail: combined || `nvidia-smi -q exited with status ${detailRes.exitCode}`, + scrubber, + }); + } + return parseNvidiaHealthOutput(queryRes.stdout, detailRes.stdout, checkedDeviceIndices, scrubber); + } + + if (family === 'amd') { + const rocmBin = await resolveFirstTrustedProbeExecutable( + options.executableOverrides?.rocmSmiPath, + TRUSTED_ROCM_SMI_PATHS, + verifier, + ); + let smiRes = await runner( + rocmBin, + ['--showproductname', '--showuse', '--showrasinfo', 'all', '--showretiredpages', '--json'], + runOpts, + ); + if ( + smiRes.exitCode !== 0 + && /unrecognized arguments/i.test(`${smiRes.stdout}\n${smiRes.stderr}`) + ) { + smiRes = await runner(rocmBin, ['--showproductname', '--showuse', '--json'], runOpts); + } + if (smiRes.exitCode !== 0) { + const combined = `${smiRes.stdout}\n${smiRes.stderr}`; + const classified = classifyFailedProbeOutput('amd', combined); + return buildUnhealthyProbeResult({ + probeKind: options.probeMode, + vendor: 'amd', + checkedDeviceIndices, + faultKind: classified.faultKind, + externalHostLoss: classified.externalHostLoss, + title: `rocm-smi health query failed (exit ${smiRes.exitCode})`, + detail: combined || `rocm-smi exited with status ${smiRes.exitCode}`, + scrubber, + }); + } + return parseRocmHealthOutput(smiRes.stdout, checkedDeviceIndices, scrubber); + } + + const npuBin = await resolveFirstTrustedProbeExecutable( + options.executableOverrides?.npuSmiPath, + TRUSTED_NPU_SMI_PATHS, + verifier, + ); + const npuRes = await runner(npuBin, ['info'], runOpts); + if (npuRes.exitCode !== 0) { + const combined = `${npuRes.stdout}\n${npuRes.stderr}`; + const classified = classifyFailedProbeOutput('huawei', combined); + return buildUnhealthyProbeResult({ + probeKind: options.probeMode, + vendor: 'huawei', + checkedDeviceIndices, + faultKind: classified.faultKind, + externalHostLoss: classified.externalHostLoss, + title: `npu-smi health query failed (exit ${npuRes.exitCode})`, + detail: combined || `npu-smi info exited with status ${npuRes.exitCode}`, + scrubber, + }); + } + return parseNpuHealthOutput(npuRes.stdout, checkedDeviceIndices, scrubber); + } catch (err: unknown) { + const rawMsg = err instanceof Error ? err.message : String(err); + const isTimeout = /timed?\s*out|exceeded bounds|ETIMEDOUT/i.test(rawMsg); + return buildUnhealthyProbeResult({ + probeKind: options.probeMode, + vendor: family, + checkedDeviceIndices, + faultKind: isTimeout ? 'probe_timeout' : 'probe_failed', + title: isTimeout ? 'Accelerator health probe timed out (device unresponsive)' : 'Accelerator health probe failed', + detail: rawMsg, + scrubber, + }); + } +} diff --git a/packages/hardware-runner/src/queue.ts b/packages/hardware-runner/src/queue.ts index a4159da..76999b0 100644 --- a/packages/hardware-runner/src/queue.ts +++ b/packages/hardware-runner/src/queue.ts @@ -172,6 +172,7 @@ function buildWorkerJobPayload(request: BenchmarkRequest, preemptionCount: numbe subject: request.subject, targetCellId: request.targetCellId, targetHardware: request.targetHardware, + ...(request.stageAAudit !== undefined ? { stageAAudit: request.stageAAudit } : {}), heldOutWorkloadId: request.heldOutWorkloadId, metricThresholds: request.metricThresholds, maxPreemptions: request.maxPreemptions, @@ -1101,6 +1102,8 @@ export class RelayPullQueue { ...(input.metrics !== undefined ? { metrics: input.metrics } : {}), ...(input.findings !== undefined ? { findings: input.findings } : {}), ...(input.hardwareProvenance !== undefined ? { hardwareProvenance: input.hardwareProvenance } : {}), + ...(input.bucketMetrics !== undefined ? { bucketMetrics: input.bucketMetrics } : {}), + ...(input.hardwareDiagnostics !== undefined ? { hardwareDiagnostics: input.hardwareDiagnostics } : {}), ...(outputArtifacts !== undefined ? { outputArtifacts: Object.freeze(outputArtifacts) } : {}), }); diff --git a/packages/hardware-runner/src/relay-server.ts b/packages/hardware-runner/src/relay-server.ts index ba2b526..58e7e3e 100644 --- a/packages/hardware-runner/src/relay-server.ts +++ b/packages/hardware-runner/src/relay-server.ts @@ -15,13 +15,18 @@ import { isVerifierNamespacePath, LIMITS, SecretScrubber, + validateBucketMetrics, + validateHardwareDiagnostics, validateRelativePath, VERIFIER_ARTIFACT_LIMITS, type BaseTreeAnchor, + type BucketMetricEntry, type Digest, type FindingSeverity, + type HardwareDiagnostics, type HardwareProvenance, type HardwareTargetSpec, + type MetricBucketScope, type MetricThresholdRule, type MetricsMap, type MetricValue, @@ -61,6 +66,7 @@ import { type PreemptLeaseInput, type RelayServerHandle, type RelayServerOptions, + type StageAStaticAuditSpec, } from './types.js'; export const MAX_CONTROL_BODY_BYTES = 65_536; @@ -261,7 +267,18 @@ const HARDWARE_TARGET_KEYS: ReadonlySet = new Set([ 'deviceCount', 'driverConstraint', 'topology', + 'forbiddenSymbolPatterns', + 'maxRegisterCount', + 'maxLocalSpillBytes', ]); +const STAGE_A_AUDIT_KEYS: ReadonlySet = new Set([ + 'forbiddenSymbolPatterns', + 'maxRegisterCount', + 'maxLocalSpillBytes', +]); +const BUCKET_SCOPE_TARGET_KEYS: ReadonlySet = new Set(['bucketId']); +const BUCKET_ID_WIRE_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]*$/; +const FORBIDDEN_SYMBOL_GLOB_WIRE_RE = /[*?[\]]/; function isValidDottedVersion(value: string): boolean { if (!value.length || !DOTTED_VERSION_RE.test(value)) return false; @@ -271,6 +288,53 @@ function isValidDottedVersion(value: string): boolean { }); } +function parseStageAStaticAuditFields( + obj: Record, + path: string, +): StageAStaticAuditSpec { + let forbiddenSymbolPatterns: readonly string[] | undefined; + if (Object.hasOwn(obj, 'forbiddenSymbolPatterns')) { + const rawList = obj.forbiddenSymbolPatterns; + if (!Array.isArray(rawList) || rawList.length > LIMITS.forbiddenSymbolPatterns) { + wireInvalid( + `forbiddenSymbolPatterns must contain 0..${LIMITS.forbiddenSymbolPatterns} patterns`, + `${path}/forbiddenSymbolPatterns`, + ); + } + const seen = new Set(); + const parsedPatterns = rawList.map((entry, idx) => { + const pPath = `${path}/forbiddenSymbolPatterns/${idx}`; + const pat = parsePrintableText(entry, 1, LIMITS.forbiddenSymbolPattern, pPath, true); + if (FORBIDDEN_SYMBOL_GLOB_WIRE_RE.test(pat)) { + wireInvalid('glob wildcards are forbidden in forbiddenSymbolPatterns', pPath); + } + if (seen.has(pat)) { + wireInvalid(`duplicate forbiddenSymbolPattern "${pat}"`, pPath); + } + seen.add(pat); + return pat; + }); + forbiddenSymbolPatterns = Object.freeze(parsedPatterns); + } + const maxRegisterCount = Object.hasOwn(obj, 'maxRegisterCount') + ? parseIntStrict(obj.maxRegisterCount, 0, Number.MAX_SAFE_INTEGER, `${path}/maxRegisterCount`) + : undefined; + const maxLocalSpillBytes = Object.hasOwn(obj, 'maxLocalSpillBytes') + ? parseIntStrict(obj.maxLocalSpillBytes, 0, Number.MAX_SAFE_INTEGER, `${path}/maxLocalSpillBytes`) + : undefined; + + return Object.freeze({ + ...(forbiddenSymbolPatterns !== undefined ? { forbiddenSymbolPatterns } : {}), + ...(maxRegisterCount !== undefined ? { maxRegisterCount } : {}), + ...(maxLocalSpillBytes !== undefined ? { maxLocalSpillBytes } : {}), + }); +} + +function parseStageAStaticAuditSpec(value: unknown, path: string): StageAStaticAuditSpec { + const obj = expectNullProtoRecord(value, STAGE_A_AUDIT_KEYS, [], 'ARTIFACT_INVALID', path); + return parseStageAStaticAuditFields(obj, path); +} + function parseHardwareTarget(value: unknown, path: string): HardwareTargetSpec { const obj = expectNullProtoRecord( value, @@ -296,6 +360,7 @@ function parseHardwareTarget(value: unknown, path: string): HardwareTargetSpec { const topology = Object.hasOwn(obj, 'topology') ? parsePrintableText(obj.topology, 1, 128, `${path}/topology`, false) : undefined; + const auditFields = parseStageAStaticAuditFields(obj, path); return Object.freeze({ accelerator, @@ -303,11 +368,38 @@ function parseHardwareTarget(value: unknown, path: string): HardwareTargetSpec { ...(deviceCount !== undefined ? { deviceCount } : {}), ...(driverConstraint !== undefined ? { driverConstraint } : {}), ...(topology !== undefined ? { topology } : {}), + ...(auditFields.forbiddenSymbolPatterns !== undefined + ? { forbiddenSymbolPatterns: auditFields.forbiddenSymbolPatterns } + : {}), + ...(auditFields.maxRegisterCount !== undefined ? { maxRegisterCount: auditFields.maxRegisterCount } : {}), + ...(auditFields.maxLocalSpillBytes !== undefined ? { maxLocalSpillBytes: auditFields.maxLocalSpillBytes } : {}), }); } -const BOUNDS_RULE_KEYS: ReadonlySet = new Set(['kind', 'metric', 'min', 'max']); -const COMPARATIVE_RULE_KEYS: ReadonlySet = new Set(['kind', 'metric', 'baselineMetric', 'operator', 'threshold']); +const BOUNDS_RULE_KEYS: ReadonlySet = new Set(['kind', 'metric', 'min', 'max', 'bucketScope']); +const COMPARATIVE_RULE_KEYS: ReadonlySet = new Set([ + 'kind', + 'metric', + 'baselineMetric', + 'operator', + 'threshold', + 'bucketScope', +]); + +function parseMetricBucketScope(value: unknown, path: string): MetricBucketScope { + if (value === 'aggregate' || value === 'all_buckets') { + return value; + } + if (value !== null && typeof value === 'object' && !Array.isArray(value)) { + const obj = expectNullProtoRecord(value, BUCKET_SCOPE_TARGET_KEYS, ['bucketId'], 'ARTIFACT_INVALID', path); + const bucketId = parseStringStrict(obj.bucketId, 1, LIMITS.bucketId, `${path}/bucketId`); + if (FORBIDDEN_METRIC_KEYS.has(bucketId) || !BUCKET_ID_WIRE_RE.test(bucketId)) { + wireInvalid('invalid bucketScope.bucketId', `${path}/bucketId`); + } + return Object.freeze({ bucketId }); + } + wireInvalid('invalid metric threshold bucketScope', path); +} function parseMetricKey(value: unknown, path: string): string { const key = parseStringStrict(value, 1, LIMITS.metricKey, path); @@ -341,11 +433,15 @@ function parseMetricThresholdRule(value: unknown, path: string): MetricThreshold if (min !== undefined && max !== undefined && min > max) { wireInvalid('bounds min must not exceed max', path); } + const bucketScope = Object.hasOwn(obj, 'bucketScope') + ? parseMetricBucketScope(obj.bucketScope, `${path}/bucketScope`) + : undefined; return Object.freeze({ kind: 'bounds', metric, ...(min !== undefined ? { min } : {}), ...(max !== undefined ? { max } : {}), + ...(bucketScope !== undefined ? { bucketScope } : {}), }); } if (rawObj.kind === 'comparative') { @@ -362,12 +458,16 @@ function parseMetricThresholdRule(value: unknown, path: string): MetricThreshold wireInvalid('invalid comparative operator', `${path}/operator`); } const threshold = parseFiniteControlNumber(obj.threshold, `${path}/threshold`); + const bucketScope = Object.hasOwn(obj, 'bucketScope') + ? parseMetricBucketScope(obj.bucketScope, `${path}/bucketScope`) + : undefined; return Object.freeze({ kind: 'comparative', metric, baselineMetric, operator: obj.operator, threshold, + ...(bucketScope !== undefined ? { bucketScope } : {}), }); } wireInvalid('unsupported threshold rule kind', `${path}/kind`); @@ -521,6 +621,7 @@ const BENCHMARK_REQUEST_KEYS: ReadonlySet = new Set([ 'subject', 'targetCellId', 'targetHardware', + 'stageAAudit', 'heldOutWorkloadId', 'metricThresholds', 'maxPreemptions', @@ -576,6 +677,24 @@ export function parseBenchmarkRequest( } const targetCellId = parseIdentifier(root.targetCellId, '/targetCellId'); const targetHardware = parseHardwareTarget(root.targetHardware, '/targetHardware'); + const stageAAudit = Object.hasOwn(root, 'stageAAudit') + ? parseStageAStaticAuditSpec(root.stageAAudit, '/stageAAudit') + : undefined; + if ( + targetHardware.forbiddenSymbolPatterns !== undefined + && stageAAudit?.forbiddenSymbolPatterns !== undefined + ) { + const combinedPatterns = new Set([ + ...targetHardware.forbiddenSymbolPatterns, + ...stageAAudit.forbiddenSymbolPatterns, + ]); + if (combinedPatterns.size > LIMITS.forbiddenSymbolPatterns) { + wireInvalid( + `combined forbiddenSymbolPatterns exceeds ${LIMITS.forbiddenSymbolPatterns}`, + '/stageAAudit/forbiddenSymbolPatterns', + ); + } + } const heldOutWorkloadId = parsePrintableText(root.heldOutWorkloadId, 1, 128, '/heldOutWorkloadId', true); if (!SAFE_FILENAME_ID_RE.test(heldOutWorkloadId)) { wireInvalid('invalid heldOutWorkloadId', '/heldOutWorkloadId'); @@ -613,6 +732,7 @@ export function parseBenchmarkRequest( subject, targetCellId, targetHardware, + ...(stageAAudit !== undefined ? { stageAAudit } : {}), heldOutWorkloadId, metricThresholds, maxPreemptions, @@ -633,6 +753,8 @@ const COMPLETE_KEYS: ReadonlySet = new Set([ 'metrics', 'findings', 'hardwareProvenance', + 'bucketMetrics', + 'hardwareDiagnostics', 'outputArtifacts', ]); const PROVENANCE_KEYS: ReadonlySet = new Set([ @@ -672,6 +794,8 @@ const SIGNED_RECEIPT_KEYS: ReadonlySet = new Set([ 'metrics', 'findings', 'hardwareProvenance', + 'bucketMetrics', + 'hardwareDiagnostics', 'outputArtifacts', 'signature', ]); @@ -941,7 +1065,80 @@ function parseOutputArtifacts( return Object.freeze(out); } -function parseCompleteInput(raw: Json, maxBlobBytes: number): CompleteLeaseInput { +const DEFAULT_WIRE_SCRUBBER = new SecretScrubber(); + +function assertNoRawInvalidWireNumbers(value: unknown, path: string, depth = 0): void { + if (depth > 32) { + wireInvalid('wire structure exceeds maximum depth', path); + } + if (typeof value === 'number') { + if (!Number.isFinite(value) || Object.is(value, -0)) { + wireInvalid('numeric value must be finite and not -0', path); + } + return; + } + if (typeof value === 'string') { + if (hasLoneSurrogate(value)) { + wireInvalid('string contains lone UTF-16 surrogate', path); + } + return; + } + if (Array.isArray(value)) { + for (let i = 0; i < value.length; i += 1) { + assertNoRawInvalidWireNumbers(value[i], `${path}/${i}`, depth + 1); + } + return; + } + if (value !== null && typeof value === 'object') { + const rec = value as Readonly>; + for (const key of Reflect.ownKeys(rec)) { + if (typeof key !== 'string' || FORBIDDEN_METRIC_KEYS.has(key) || hasLoneSurrogate(key)) { + wireInvalid('forbidden object key', path); + } + assertNoRawInvalidWireNumbers(rec[key], `${path}/${key}`, depth + 1); + } + } +} + +function parseWireBucketMetrics( + value: unknown, + path: string, + scrubber: SecretScrubber = DEFAULT_WIRE_SCRUBBER, +): readonly BucketMetricEntry[] { + assertNoRawInvalidWireNumbers(value, path); + const validated = validateBucketMetrics(value, scrubber); + if (!validated.ok) { + const first = validated.errors[0]; + wireInvalid( + `invalid bucketMetrics (${first?.code ?? 'INVALID'})`, + first?.path ? `${path}${first.path}` : path, + ); + } + return validated.value; +} + +function parseWireHardwareDiagnostics( + value: unknown, + path: string, + scrubber: SecretScrubber = DEFAULT_WIRE_SCRUBBER, +): HardwareDiagnostics { + assertNoRawInvalidWireNumbers(value, path); + const validated = validateHardwareDiagnostics(value, scrubber); + if (!validated.ok) { + const first = validated.errors[0]; + wireInvalid( + `invalid hardwareDiagnostics (${first?.code ?? 'INVALID'})`, + first?.path ? `${path}${first.path}` : path, + ); + } + return validated.value; +} + +function parseCompleteInput( + raw: Json, + maxBlobBytes: number, + scrubber: SecretScrubber = DEFAULT_WIRE_SCRUBBER, +): CompleteLeaseInput { const obj = expectNullProtoRecord( raw, COMPLETE_KEYS, @@ -971,6 +1168,12 @@ function parseCompleteInput(raw: Json, maxBlobBytes: number): CompleteLeaseInput if (obj.status === 'approved' && hardwareProvenance === undefined) { wireInvalid('approved verdict requires hardwareProvenance', '/hardwareProvenance'); } + const bucketMetrics = Object.hasOwn(obj, 'bucketMetrics') + ? parseWireBucketMetrics(obj.bucketMetrics, '/bucketMetrics', scrubber) + : undefined; + const hardwareDiagnostics = Object.hasOwn(obj, 'hardwareDiagnostics') + ? parseWireHardwareDiagnostics(obj.hardwareDiagnostics, '/hardwareDiagnostics', scrubber) + : undefined; const outputArtifacts = Object.hasOwn(obj, 'outputArtifacts') ? parseOutputArtifacts(obj.outputArtifacts, maxBlobBytes, '/outputArtifacts') : undefined; @@ -983,6 +1186,8 @@ function parseCompleteInput(raw: Json, maxBlobBytes: number): CompleteLeaseInput ...(metrics !== undefined ? { metrics } : {}), ...(findings !== undefined ? { findings } : {}), ...(hardwareProvenance !== undefined ? { hardwareProvenance } : {}), + ...(bucketMetrics !== undefined ? { bucketMetrics } : {}), + ...(hardwareDiagnostics !== undefined ? { hardwareDiagnostics } : {}), ...(outputArtifacts !== undefined ? { outputArtifacts } : {}), }); } @@ -1072,6 +1277,12 @@ function parseAuthenticatedReceiptBytes( if (status === 'approved' && hardwareProvenance === undefined) { wireInvalid('approved receipt requires hardwareProvenance', '/receipt/hardwareProvenance'); } + const bucketMetrics = Object.hasOwn(obj, 'bucketMetrics') + ? parseWireBucketMetrics(obj.bucketMetrics, '/receipt/bucketMetrics', scrubber) + : undefined; + const hardwareDiagnostics = Object.hasOwn(obj, 'hardwareDiagnostics') + ? parseWireHardwareDiagnostics(obj.hardwareDiagnostics, '/receipt/hardwareDiagnostics', scrubber) + : undefined; const outputArtifacts = Object.hasOwn(obj, 'outputArtifacts') ? parseOutputArtifacts(obj.outputArtifacts, maxBlobBytes, '/receipt/outputArtifacts') : undefined; @@ -1097,6 +1308,8 @@ function parseAuthenticatedReceiptBytes( ...(metrics !== undefined ? { metrics } : {}), ...(findings !== undefined ? { findings } : {}), ...(hardwareProvenance !== undefined ? { hardwareProvenance } : {}), + ...(bucketMetrics !== undefined ? { bucketMetrics } : {}), + ...(hardwareDiagnostics !== undefined ? { hardwareDiagnostics } : {}), ...(outputArtifacts !== undefined ? { outputArtifacts } : {}), }); @@ -3091,7 +3304,7 @@ export async function startRelayServer(options: RelayServerOptions): Promise { const prepared = queue.prepareCompleteLease(jobId, completeInput); let stagedReceipt: Awaited> | null = null; diff --git a/packages/hardware-runner/src/types.ts b/packages/hardware-runner/src/types.ts index 7c988f6..375fbe9 100644 --- a/packages/hardware-runner/src/types.ts +++ b/packages/hardware-runner/src/types.ts @@ -1,14 +1,33 @@ import type { BaseTreeAnchor, + BucketDimensionValue, + BucketDimensionsMap, + BucketMetricEntry, Digest, + HardwareBoundPipeline, + HardwareDiagnostics, HardwareProvenance, + HardwareStallReason, HardwareTargetSpec, + MetricBucketScope, MetricThresholdRule, MetricsMap, StructuredFinding, Subject, } from '@loopwright/core'; +export type { + BucketDimensionValue, + BucketDimensionsMap, + BucketMetricEntry, + HardwareBoundPipeline, + HardwareDiagnostics, + HardwareStallReason, + MetricBucketScope, +}; + +export type HardwareDiagnosticsSummary = HardwareDiagnostics; + export type HardwareRunnerErrorCode = | 'CONFIG_INVALID' | 'QUEUE_LEASE_FENCED' @@ -21,7 +40,36 @@ export type HardwareRunnerErrorCode = | 'AUTH_FORBIDDEN' | 'PAYLOAD_TOO_LARGE' | 'NOT_FOUND' - | 'RUNNER_SANDBOX_FAILED'; + | 'RUNNER_SANDBOX_FAILED' + | 'WORKER_DEVICE_QUARANTINED'; + +export interface StageAStaticAuditSpec { + readonly forbiddenSymbolPatterns?: readonly string[]; + readonly maxRegisterCount?: number; + readonly maxLocalSpillBytes?: number; +} + +export type AcceleratorFaultKind = + | 'xid_error' + | 'ecc_uncorrectable' + | 'row_remap_failure' + | 'gpu_reset_required' + | 'device_lost' + | 'probe_timeout' + | 'probe_failed' + | 'health_degraded'; + +export interface AcceleratorHealthProbeResult { + readonly healthy: boolean; + readonly quarantineRequired: boolean; + readonly probeKind: 'physical' | 'synthetic_fixture'; + readonly vendor: 'nvidia' | 'amd' | 'huawei' | 'synthetic'; + readonly checkedDeviceIndices: readonly number[]; + readonly faultKind?: AcceleratorFaultKind; + readonly externalHostLoss?: boolean; + readonly summary: string; + readonly findings: readonly StructuredFinding[]; +} export class HardwareRunnerError extends Error { readonly code: HardwareRunnerErrorCode; @@ -154,6 +202,7 @@ export interface BenchmarkRequest { readonly subject: Subject; readonly targetCellId: string; readonly targetHardware: HardwareTargetSpec; + readonly stageAAudit?: StageAStaticAuditSpec; readonly heldOutWorkloadId: string; readonly metricThresholds: readonly MetricThresholdRule[]; readonly maxPreemptions: number; @@ -183,6 +232,8 @@ export interface BenchmarkVerdict { readonly metrics?: MetricsMap; readonly findings?: readonly StructuredFinding[]; readonly hardwareProvenance?: HardwareProvenance; + readonly bucketMetrics?: readonly BucketMetricEntry[]; + readonly hardwareDiagnostics?: HardwareDiagnostics; readonly outputArtifacts?: readonly BenchmarkOutputArtifact[]; } @@ -198,6 +249,7 @@ export interface WorkerJobPayload { readonly subject: Subject; readonly targetCellId: string; readonly targetHardware: HardwareTargetSpec; + readonly stageAAudit?: StageAStaticAuditSpec; readonly heldOutWorkloadId: string; readonly metricThresholds: readonly MetricThresholdRule[]; readonly maxPreemptions: number; @@ -276,6 +328,8 @@ export interface CompleteLeaseInput extends LeaseCredentials { readonly metrics?: MetricsMap; readonly findings?: readonly StructuredFinding[]; readonly hardwareProvenance?: HardwareProvenance; + readonly bucketMetrics?: readonly BucketMetricEntry[]; + readonly hardwareDiagnostics?: HardwareDiagnostics; readonly outputArtifacts?: readonly BenchmarkOutputArtifact[]; } diff --git a/packages/hardware-runner/src/worker.ts b/packages/hardware-runner/src/worker.ts index aa4ac5e..abe1f23 100644 --- a/packages/hardware-runner/src/worker.ts +++ b/packages/hardware-runner/src/worker.ts @@ -5,7 +5,7 @@ import { request as httpRequest, type IncomingMessage, type RequestOptions } fro import { Agent as HttpsAgent, request as httpsRequest, type RequestOptions as HttpsRequestOptions } from 'node:https'; import { resolve } from 'node:path'; import type { TLSSocket } from 'node:tls'; -import { OVERLAY_LIMITS, SecretScrubber } from '@loopwright/core'; +import { LIMITS, OVERLAY_LIMITS, SecretScrubber, type StructuredFinding } from '@loopwright/core'; import { readBoundedRegularFile } from '@loopwright/taskpack'; import { assertNoSymlinkAncestors, @@ -20,7 +20,11 @@ import { type BenchmarkJobEvaluator, type EvaluatedBenchmarkJob, } from './evaluator.js'; -import type { CollectHardwareProvenanceOptions } from './provenance.js'; +import { + probeAcceleratorHealth, + type CollectHardwareProvenanceOptions, + type ProbeAcceleratorHealthOptions, +} from './provenance.js'; import { EMPTY_SHA256_HEX, MAX_CAS_CHUNK_BYTES, @@ -29,6 +33,7 @@ import { } from './relay-server.js'; import { HardwareRunnerError, + type AcceleratorHealthProbeResult, type CompleteLeaseInput, type HardwareRunnerErrorCode, type HeartbeatResponse, @@ -66,6 +71,7 @@ export interface RunHardwareWorkerOptions { readonly clock?: WorkerMonotonicClock; readonly evaluator?: BenchmarkJobEvaluator; readonly probe?: (options: CollectHardwareProvenanceOptions) => ReturnType; + readonly healthProbe?: (options: ProbeAcceleratorHealthOptions) => Promise; readonly onLeaseAcquired?: (grant: LeaseGrant) => void | Promise; readonly onJobSettled?: (summary: WorkerJobSettlementSummary) => void | Promise; } @@ -142,6 +148,7 @@ const VALID_ERROR_CODES: ReadonlySet = new Set([ 'PAYLOAD_TOO_LARGE', 'NOT_FOUND', 'RUNNER_SANDBOX_FAILED', + 'WORKER_DEVICE_QUARANTINED', ]); const DETERMINISTIC_EVAL_ERROR_CODES: ReadonlySet = new Set([ 'ARTIFACT_INVALID', @@ -452,6 +459,7 @@ function parseLeaseGrantPayload(bytes: Buffer, maxBlobBytes: number): LeaseGrant subject: jobObj.subject, targetCellId: jobObj.targetCellId, targetHardware: jobObj.targetHardware, + ...(Object.hasOwn(jobObj, 'stageAAudit') ? { stageAAudit: jobObj.stageAAudit } : {}), heldOutWorkloadId: jobObj.heldOutWorkloadId, ...(Object.hasOwn(jobObj, 'metricThresholds') ? { metricThresholds: jobObj.metricThresholds } : {}), ...(Object.hasOwn(jobObj, 'maxPreemptions') ? { maxPreemptions: jobObj.maxPreemptions } : {}), @@ -477,6 +485,7 @@ function parseLeaseGrantPayload(bytes: Buffer, maxBlobBytes: number): LeaseGrant subject: validatedReq.subject, targetCellId: validatedReq.targetCellId, targetHardware: validatedReq.targetHardware, + ...(validatedReq.stageAAudit !== undefined ? { stageAAudit: validatedReq.stageAAudit } : {}), heldOutWorkloadId: validatedReq.heldOutWorkloadId, metricThresholds: validatedReq.metricThresholds, maxPreemptions: validatedReq.maxPreemptions, @@ -1141,12 +1150,17 @@ export async function runHardwareWorker(options: RunHardwareWorkerOptions): Prom const client = await createOutboundHttpClient(config); const evaluator: BenchmarkJobEvaluator = options.evaluator ?? evaluateBenchmarkJob; + const healthProbeRunner = options.healthProbe ?? probeAcceleratorHealth; let polls = 0; let jobsProcessed = 0; let lastSettlement: WorkerJobSettlementSummary | null = null; + let quarantineError: HardwareRunnerError | null = null; try { while (true) { + if (quarantineError !== null) { + throw quarantineError; + } if (preemptSignal.aborted) { return { polls, jobsProcessed, lastSettlement, exitReason: 'preempted' }; } @@ -1532,6 +1546,7 @@ export async function runHardwareWorker(options: RunHardwareWorkerOptions): Prom let ackedOutputCount = 0; let unackedUploadFailure = false; let jobCleanupAttempted = false; + let forcePreemptForExternalDeviceLoss = false; const shouldPreserveSealedOutputs = (): boolean => { if (evaluated === null || evaluated.sealedOutputs.length === 0) { return false; @@ -1540,7 +1555,8 @@ export async function runHardwareWorker(options: RunHardwareWorkerOptions): Prom return true; } if ( - abortState.cause === 'preempt' + forcePreemptForExternalDeviceLoss + || abortState.cause === 'preempt' || preemptSignal.aborted || abortState.cause === 'cancel' || abortState.cause === 'shutdown' @@ -1570,9 +1586,84 @@ export async function runHardwareWorker(options: RunHardwareWorkerOptions): Prom let bodyLoopErr: unknown = null; try { + // Post-crash / post-timeout out-of-band accelerator health probe MUST execute BEFORE reporting + // completion/preemption or polling `/v1/runner/leases:acquire` for another job! + const stageBCrashedOrTimedOut = + teardownFailure === null + && evaluatorInfraError === null + && evaluated !== null + && ( + evaluated.stageBFailure !== undefined + || evaluated.reason === 'STAGE_B_TIMEOUT' + || evaluated.reason === 'STAGE_B_EXECUTION_FAILED' + ); + + if (stageBCrashedOrTimedOut && evaluated !== null && !shutdownSignal.aborted) { + let healthResult: AcceleratorHealthProbeResult; + try { + healthResult = await healthProbeRunner({ + probeMode: config.probeMode, + capabilities: config.capabilities, + targetHardware: grant.job.targetHardware, + ...(evaluated.allocatedDeviceIndices !== undefined + ? { allocatedDeviceIndices: evaluated.allocatedDeviceIndices } + : {}), + scrubber, + }); + } catch (probeErr: unknown) { + const safeProbeErr = scrubber.scrub(probeErr instanceof Error ? probeErr.message : String(probeErr)).trim() + || 'post-crash accelerator health probe failed'; + healthResult = Object.freeze({ + healthy: false, + quarantineRequired: true, + probeKind: config.probeMode, + vendor: 'synthetic', + checkedDeviceIndices: Object.freeze([]), + faultKind: 'probe_failed', + summary: safeProbeErr, + findings: Object.freeze([ + Object.freeze({ + title: 'Post-crash accelerator health probe failed', + severity: 'critical' as const, + evidence: safeProbeErr, + }), + ]), + }); + } + + if (!healthResult.healthy || healthResult.quarantineRequired) { + const safeSummary = + scrubber.scrub(healthResult.summary).trim() + || 'worker accelerator device quarantined after Stage B crash/timeout'; + quarantineError = new HardwareRunnerError('WORKER_DEVICE_QUARANTINED', safeSummary); + + if (healthResult.externalHostLoss === true) { + forcePreemptForExternalDeviceLoss = true; + } else if (healthResult.findings.length > 0) { + const scrubbedHealthFindings: StructuredFinding[] = healthResult.findings.map(f => { + const copy: Record = Object.create(null) as Record; + copy.title = (scrubber.scrub(f.title).trim() || 'Accelerator fault').slice(0, LIMITS.findingTitle); + copy.severity = f.severity; + copy.evidence = (scrubber.scrub(f.evidence).trim() || safeSummary).slice(0, LIMITS.findingEvidence); + return Object.freeze(copy as unknown as StructuredFinding); + }); + const existingFindings = evaluated.findings ?? []; + const keepCount = Math.max(0, LIMITS.findings - scrubbedHealthFindings.length); + evaluated = Object.freeze({ + ...evaluated, + findings: Object.freeze([ + ...existingFindings.slice(0, keepCount), + ...scrubbedHealthFindings.slice(0, LIMITS.findings), + ]), + }); + } + } + } + // Upload sealed Stage A output blobs while heartbeat and local lease authority remain active. if ( - teardownFailure === null + !forcePreemptForExternalDeviceLoss + && teardownFailure === null && evaluated !== null && evaluatorInfraError === null && assertAuthorityLive() @@ -1630,7 +1721,7 @@ export async function runHardwareWorker(options: RunHardwareWorkerOptions): Prom throw teardownFailure; } - if (abortState.cause === 'preempt' || preemptSignal.aborted) { + if (abortState.cause === 'preempt' || preemptSignal.aborted || forcePreemptForExternalDeviceLoss) { hbStopped = true; clearLeaseDeadlineTimer(); jobAbort.abort(); @@ -1645,7 +1736,7 @@ export async function runHardwareWorker(options: RunHardwareWorkerOptions): Prom relayBootId: creds.relayBootId, leaseEpoch: creds.leaseEpoch, leaseToken: creds.leaseToken, - reason: 'worker_preempted', + reason: forcePreemptForExternalDeviceLoss ? 'worker_device_lost' : 'worker_preempted', }, timeoutMs: config.requestTimeoutMs, }); @@ -1700,6 +1791,9 @@ export async function runHardwareWorker(options: RunHardwareWorkerOptions): Prom if (options.onJobSettled !== undefined) { await options.onJobSettled(lastSettlement); } + if (quarantineError !== null) { + throw quarantineError; + } return { polls, jobsProcessed, lastSettlement, exitReason: 'preempted' }; } @@ -1729,6 +1823,9 @@ export async function runHardwareWorker(options: RunHardwareWorkerOptions): Prom if (options.onJobSettled !== undefined) { await options.onJobSettled(lastSettlement); } + if (quarantineError !== null) { + throw quarantineError; + } return { polls, jobsProcessed, lastSettlement, exitReason: 'aborted' }; } @@ -1748,6 +1845,9 @@ export async function runHardwareWorker(options: RunHardwareWorkerOptions): Prom if (options.onJobSettled !== undefined) { await options.onJobSettled(lastSettlement); } + if (quarantineError !== null) { + throw quarantineError; + } if (options.once === true) { return { polls, jobsProcessed, lastSettlement, exitReason: 'once_completed' }; } @@ -1759,6 +1859,9 @@ export async function runHardwareWorker(options: RunHardwareWorkerOptions): Prom clearLeaseDeadlineTimer(); jobAbort.abort(); await heartbeatLoop.catch(() => {}); + if (quarantineError !== null) { + throw quarantineError; + } return { polls, jobsProcessed, lastSettlement, exitReason: 'aborted' }; } @@ -1772,6 +1875,8 @@ export async function runHardwareWorker(options: RunHardwareWorkerOptions): Prom ...(evaluated.metrics !== undefined ? { metrics: evaluated.metrics } : {}), ...(evaluated.findings !== undefined ? { findings: evaluated.findings } : {}), ...(evaluated.hardwareProvenance !== undefined ? { hardwareProvenance: evaluated.hardwareProvenance } : {}), + ...(evaluated.bucketMetrics !== undefined ? { bucketMetrics: evaluated.bucketMetrics } : {}), + ...(evaluated.hardwareDiagnostics !== undefined ? { hardwareDiagnostics: evaluated.hardwareDiagnostics } : {}), ...(evaluated.sealedOutputs.length > 0 ? { outputArtifacts: evaluated.sealedOutputs.map(item => item.artifact) } : {}), @@ -1828,6 +1933,9 @@ export async function runHardwareWorker(options: RunHardwareWorkerOptions): Prom if (options.onJobSettled !== undefined) { await options.onJobSettled(lastSettlement); } + if (quarantineError !== null) { + throw quarantineError; + } if (options.once === true) { return { polls, jobsProcessed, lastSettlement, exitReason: 'once_completed' }; } @@ -1886,6 +1994,10 @@ export async function runHardwareWorker(options: RunHardwareWorkerOptions): Prom await options.onJobSettled(lastSettlement); } + if (quarantineError !== null) { + throw quarantineError; + } + if (options.once === true) { return { polls, jobsProcessed, lastSettlement, exitReason: 'once_completed' }; } diff --git a/packages/hardware-runner/test/stage-audit-and-quarantine.test.ts b/packages/hardware-runner/test/stage-audit-and-quarantine.test.ts new file mode 100644 index 0000000..32cf042 --- /dev/null +++ b/packages/hardware-runner/test/stage-audit-and-quarantine.test.ts @@ -0,0 +1,1566 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { createHash } from 'node:crypto'; +import { chmod, link, mkdir, mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { + evaluateMetricThresholds, + SecretScrubber, + STAGE_A_STATIC_AUDIT_FAILED, + type BucketMetricEntry, + type HardwareDiagnostics, + type MetricThresholdRule, +} from '@loopwright/core'; +import { + auditSealedStageAOutputs, + canonicalJson, + evaluateBenchmarkJob, + HardwareRunnerError, + MAX_STAGE_B_RESULT_BYTES, + parseBenchmarkRequest, + parseStageBResultEnvelope, + probeAcceleratorHealth, + runHardwareWorker, + sealStageAOutputs, + signRelayPayload, + startRelayServer, + verifyBenchmarkVerdictSignature, + type AcceleratorHealthProbeResult, + type BenchmarkRequest, + type BenchmarkVerdict, + type HardwareDiagnosticsSummary, + type HardwareRunnerErrorCode, + type LeaseGrant, + type ProbeCommandRunner, + type SignedBenchmarkVerdictReceipt, + type StageAStaticAuditSpec, + type WorkerConfig, + type WorkerJobSettlementSummary, +} from '../src/index.js'; + +const CONTROLLER_SECRET = 'stage-audit-hmac-secret-0123456789abcdef'; +const WORKER_TOKEN = 'stage-audit-worker-bearer-0123456789abcdef'; + +function sha256Hex(data: Uint8Array | string): string { + return createHash('sha256').update(data).digest('hex'); +} + +/** + * Deterministic pure-TypeScript ELF64 little-endian builder producing valid `.so`, `.o`, or `.cubin` + * binaries with `.shstrtab`, `.strtab`, `.symtab`, optional `.dynstr`/`.dynsym`/`.dynamic` (`DT_NEEDED`), + * and optional NVIDIA `.nv.info` (`EIATTR_REGCOUNT` `0x2f` + `EIATTR_FRAME_SIZE` `0x11`) sections. + */ +function buildTestElf64Binary(options: { + readonly elfType?: number; // ET_REL=1 (.o), ET_EXEC=2 (.cubin), ET_DYN=3 (.so) + readonly machine?: number; // EM_CUDA=190, EM_X86_64=62, EM_AARCH64=183 + readonly symbols?: readonly string[]; + readonly dynSymbols?: readonly string[]; + readonly dtNeeded?: readonly string[]; + readonly nvInfoRegCount?: number; + readonly nvInfoSpillFrameBytes?: number; +}): Buffer { + const elfType = options.elfType ?? 3; + const machine = options.machine ?? 190; // EM_CUDA + + const buildStrTab = (items: readonly string[]): { readonly buf: Buffer; readonly offsets: readonly number[] } => { + const parts: Buffer[] = [Buffer.from([0])]; + const offsets: number[] = []; + let cursor = 1; + for (const s of items) { + offsets.push(cursor); + const b = Buffer.from(`${s}\0`, 'utf8'); + parts.push(b); + cursor += b.byteLength; + } + return { buf: Buffer.concat(parts), offsets }; + }; + + const buildSymTab64 = (nameOffsets: readonly number[]): Buffer => { + // Entry 0 is STN_UNDEF (24 zero bytes); each symbol entry in Elf64_Sym is 24 bytes. + const buf = Buffer.alloc((1 + nameOffsets.length) * 24, 0); + for (let i = 0; i < nameOffsets.length; i += 1) { + const off = (i + 1) * 24; + buf.writeUInt32LE(nameOffsets[i]!, off); // st_name + buf.writeUInt8(0x12, off + 4); // STB_GLOBAL | STT_FUNC + buf.writeUInt8(0, off + 5); // st_other + buf.writeUInt16LE(0, off + 6); // st_shndx = SHN_UNDEF (imported) + } + return buf; + }; + + interface SectionSpec { + readonly name: string; + readonly shType: number; + readonly shLink: number; + readonly shEntSize: number; + readonly data: Buffer; + } + + const sections: SectionSpec[] = []; + + if (options.symbols !== undefined && options.symbols.length > 0) { + const strTab = buildStrTab(options.symbols); + const symTab = buildSymTab64(strTab.offsets); + const strTabSecIdx = 1 + sections.length; + sections.push({ name: '.strtab', shType: 3, shLink: 0, shEntSize: 0, data: strTab.buf }); + sections.push({ name: '.symtab', shType: 2, shLink: strTabSecIdx, shEntSize: 24, data: symTab }); + } + + if ( + (options.dynSymbols !== undefined && options.dynSymbols.length > 0) + || (options.dtNeeded !== undefined && options.dtNeeded.length > 0) + ) { + const dynStrings = [...(options.dynSymbols ?? []), ...(options.dtNeeded ?? [])]; + const dynStr = buildStrTab(dynStrings); + const dynSymCount = options.dynSymbols?.length ?? 0; + const dynSymOffsets = dynStr.offsets.slice(0, dynSymCount); + const neededOffsets = dynStr.offsets.slice(dynSymCount); + const dynStrSecIdx = 1 + sections.length; + sections.push({ name: '.dynstr', shType: 3, shLink: 0, shEntSize: 0, data: dynStr.buf }); + if (dynSymOffsets.length > 0) { + sections.push({ + name: '.dynsym', + shType: 11, + shLink: dynStrSecIdx, + shEntSize: 24, + data: buildSymTab64(dynSymOffsets), + }); + } + if (neededOffsets.length > 0) { + // Elf64_Dyn: { int64 d_tag; uint64 d_val } (16 bytes each) + DT_NULL terminator + const dynBuf = Buffer.alloc((neededOffsets.length + 1) * 16, 0); + for (let i = 0; i < neededOffsets.length; i += 1) { + dynBuf.writeBigInt64LE(1n, i * 16); // DT_NEEDED = 1 + dynBuf.writeBigUInt64LE(BigInt(neededOffsets[i]!), i * 16 + 8); + } + sections.push({ + name: '.dynamic', + shType: 6, + shLink: dynStrSecIdx, + shEntSize: 16, + data: dynBuf, + }); + } + } + + if (options.nvInfoRegCount !== undefined || options.nvInfoSpillFrameBytes !== undefined) { + const records: Buffer[] = []; + if (options.nvInfoRegCount !== undefined) { + // EIFMT_SVAL (0x04), EIATTR_REGCOUNT (0x2f), size=8, { uint32 symIdx, uint32 regCount } + const rec = Buffer.alloc(12, 0); + rec.writeUInt8(0x04, 0); + rec.writeUInt8(0x2f, 1); + rec.writeUInt16LE(8, 2); + rec.writeUInt32LE(1, 4); + rec.writeUInt32LE(options.nvInfoRegCount, 8); + records.push(rec); + } + if (options.nvInfoSpillFrameBytes !== undefined) { + // EIFMT_SVAL (0x04), EIATTR_FRAME_SIZE (0x11), size=8, { uint32 symIdx, uint32 frameSize } + const rec = Buffer.alloc(12, 0); + rec.writeUInt8(0x04, 0); + rec.writeUInt8(0x11, 1); + rec.writeUInt16LE(8, 2); + rec.writeUInt32LE(1, 4); + rec.writeUInt32LE(options.nvInfoSpillFrameBytes, 8); + records.push(rec); + } + sections.push({ + name: '.nv.info', + shType: 0x70000000, // SHT_CUDA_INFO + shLink: 0, + shEntSize: 0, + data: Buffer.concat(records), + }); + } + + const shNames = [...sections.map(s => s.name), '.shstrtab']; + const shStrTab = buildStrTab(shNames); + const shStrTabSecIdx = 1 + sections.length; + sections.push({ + name: '.shstrtab', + shType: 3, + shLink: 0, + shEntSize: 0, + data: shStrTab.buf, + }); + + // Layout: [64-byte Elf64_Ehdr] [section payloads 8-byte aligned] [Elf64_Shdr table (64 bytes * (1 + sections.length))] + const ehdr = Buffer.alloc(64, 0); + ehdr[0] = 0x7f; + ehdr[1] = 0x45; // 'E' + ehdr[2] = 0x4c; // 'L' + ehdr[3] = 0x46; // 'F' + ehdr[4] = 2; // ELFCLASS64 + ehdr[5] = 1; // ELFDATA2LSB + ehdr[6] = 1; // EV_CURRENT + ehdr.writeUInt16LE(elfType, 16); + ehdr.writeUInt16LE(machine, 18); + ehdr.writeUInt32LE(1, 20); // e_version + ehdr.writeUInt16LE(64, 52); // e_ehsize + ehdr.writeUInt16LE(64, 58); // e_shentsize + ehdr.writeUInt16LE(1 + sections.length, 60); // e_shnum + ehdr.writeUInt16LE(shStrTabSecIdx, 62); // e_shstrndx + + const chunks: Buffer[] = [ehdr]; + const sectionOffsets: 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; + } + sectionOffsets.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; + } + const shoff = offset; + ehdr.writeBigUInt64LE(BigInt(shoff), 40); + + // Null section header 0 + 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(shStrTab.offsets[i]!, 0); // sh_name + shdr.writeUInt32LE(sec.shType, 4); // sh_type + shdr.writeBigUInt64LE(BigInt(sectionOffsets[i]!), 24); // sh_offset + shdr.writeBigUInt64LE(BigInt(sec.data.byteLength), 32); // sh_size + shdr.writeUInt32LE(sec.shLink, 40); // sh_link + shdr.writeBigUInt64LE(1n, 48); // sh_addralign + shdr.writeBigUInt64LE(BigInt(sec.shEntSize), 56); // sh_entsize + chunks.push(shdr); + } + + return Buffer.concat(chunks); +} + +function makeWorkerConfig(workDir: string, heldOutWorkloadsDir: string, overrides: Partial = {}): WorkerConfig { + return { + workerId: 'worker-audit-test', + relayUrl: 'http://127.0.0.1:19999', + workerToken: WORKER_TOKEN, + workDir, + heldOutWorkloadsDir, + sandboxBackend: 'native_os', + capabilities: { + accelerator: 'sm_90a', + isolationModes: ['whole_device'], + deviceCount: 1, + driverVersion: '550.90.07', + workloadIds: ['decode-holdout'], + }, + pollWaitMs: 60, + heartbeatIntervalMs: 50, + requestTimeoutMs: 5_000, + stageATimeoutMs: 15_000, + stageBTimeoutMs: 15_000, + toolchainPaths: [join(process.execPath, '..')], + probeMode: 'synthetic_fixture', + ...overrides, + }; +} + +function makeLeaseGrant(overrides: Partial = {}): LeaseGrant { + const digest = { algorithm: 'sha256' as const, hex: 'a'.repeat(64) }; + return { + relayBootId: 'boot-audit-01', + jobId: 'job-audit-01', + operationId: 'verify.0.check.decode-bench', + leaseEpoch: 1, + leaseToken: 'LEASE_TOKEN_AUDIT_SECRET_99887766', + leaseTtlMs: 30_000, + job: { + operationId: 'verify.0.check.decode-bench', + gateId: 'sm90-gate', + checkId: 'decode-bench', + candidateDigest: 'b'.repeat(64), + subject: { + lockHash: digest, + contractHash: digest, + repository: 'org/kernels', + baseRevision: '1'.repeat(40), + sourceRevision: '1'.repeat(40), + candidateDigest: { algorithm: 'sha256', hex: 'b'.repeat(64) }, + targetMatrixDigest: digest, + }, + targetCellId: 'cuda-sm90', + targetHardware: { + accelerator: 'sm_90a', + isolationMode: 'whole_device', + deviceCount: 1, + }, + heldOutWorkloadId: 'decode-holdout', + metricThresholds: [], + maxPreemptions: 3, + preemptionCount: 0, + candidateArtifacts: { + entries: [], + deleted: [], + }, + ...overrides, + }, + }; +} + +test('types & backward parity: legacy BenchmarkRequest and SignedBenchmarkVerdictReceipt canonical hashes remain unchanged while optional audit/bucket/diagnostics parse cleanly', () => { + const legacyReq: BenchmarkRequest = { + version: 1, + kind: 'benchmark_request', + storeId: 'store-legacy', + runId: 'run-legacy', + lockHash: { algorithm: 'sha256', hex: '1'.repeat(64) }, + operationId: 'verify.0.check.gemm', + dispatchId: 'disp-1', + dispatchGeneration: 0, + requestDigest: '2'.repeat(64), + gateId: 'cuda-gate', + checkId: 'gemm', + candidateDigest: '3'.repeat(64), + subject: { + lockHash: { algorithm: 'sha256', hex: '1'.repeat(64) }, + contractHash: { algorithm: 'sha256', hex: '4'.repeat(64) }, + repository: 'org/repo', + baseRevision: 'a'.repeat(40), + sourceRevision: 'b'.repeat(40), + candidateDigest: { algorithm: 'sha256', hex: '3'.repeat(64) }, + targetMatrixDigest: null, + }, + targetCellId: 'sm90', + targetHardware: { + accelerator: 'sm_90a', + isolationMode: 'whole_device', + deviceCount: 1, + }, + heldOutWorkloadId: 'wl-1', + metricThresholds: [{ kind: 'bounds', metric: 'max_ulp', max: 1 }], + maxPreemptions: 3, + candidateArtifacts: { entries: [], deleted: [] }, + }; + + const parsedLegacy = parseBenchmarkRequest(JSON.parse(canonicalJson(legacyReq))); + assert.equal(canonicalJson(parsedLegacy), canonicalJson(legacyReq)); + assert.equal(Object.keys(parsedLegacy).length, 19); + assert.equal('stageAAudit' in parsedLegacy, false); + assert.equal('forbiddenSymbolPatterns' in parsedLegacy.targetHardware, false); + assert.equal('bucketScope' in parsedLegacy.metricThresholds[0]!, false); + + const auditSpec: StageAStaticAuditSpec = { + forbiddenSymbolPatterns: ['cublas', 'cudnn', 'rocblas', 'aclnn', 'at::native::'], + maxRegisterCount: 128, + maxLocalSpillBytes: 0, + }; + const extendedReq = parseBenchmarkRequest({ + ...legacyReq, + targetHardware: { + ...legacyReq.targetHardware, + ...auditSpec, + }, + stageAAudit: { + forbiddenSymbolPatterns: ['torch_cuda'], + maxLocalSpillBytes: 0, + }, + metricThresholds: [ + { kind: 'bounds', metric: 'max_ulp', max: 1, bucketScope: 'all_buckets' }, + { kind: 'bounds', metric: 'latency_us_p50', max: 50, bucketScope: { bucketId: 'bs1-isl4k' } }, + ], + }); + assert.deepEqual(extendedReq.targetHardware.forbiddenSymbolPatterns, [ + 'cublas', + 'cudnn', + 'rocblas', + 'aclnn', + 'at::native::', + ]); + assert.equal(extendedReq.targetHardware.maxRegisterCount, 128); + assert.equal(extendedReq.targetHardware.maxLocalSpillBytes, 0); + assert.deepEqual(extendedReq.stageAAudit?.forbiddenSymbolPatterns, ['torch_cuda']); + assert.deepEqual(extendedReq.metricThresholds[1]?.bucketScope, { bucketId: 'bs1-isl4k' }); + + // Reject glob characters in forbiddenSymbolPatterns + assert.throws( + () => + parseBenchmarkRequest({ + ...legacyReq, + targetHardware: { + ...legacyReq.targetHardware, + forbiddenSymbolPatterns: ['cublas*'], + }, + }), + (err: unknown) => err instanceof HardwareRunnerError && err.code === 'ARTIFACT_INVALID', + ); + + // Reject combined targetHardware + stageAAudit forbiddenSymbolPatterns exceeding LIMITS.forbiddenSymbolPatterns + assert.throws( + () => + parseBenchmarkRequest({ + ...legacyReq, + targetHardware: { + ...legacyReq.targetHardware, + forbiddenSymbolPatterns: Array.from({ length: 40 }, (_, i) => `hw_sym_${i}`), + }, + stageAAudit: { + forbiddenSymbolPatterns: Array.from({ length: 30 }, (_, i) => `audit_sym_${i}`), + }, + }), + (err: unknown) => err instanceof HardwareRunnerError && err.code === 'ARTIFACT_INVALID', + ); + + // Verify HardwareDiagnosticsSummary type alignment and quarantine error code typing + const errCode: HardwareRunnerErrorCode = 'WORKER_DEVICE_QUARANTINED'; + assert.equal(errCode, 'WORKER_DEVICE_QUARANTINED'); + const diagSummary: HardwareDiagnosticsSummary = { + boundPipeline: 'tensor_cube', + rooflineHeadroom: 1.12, + }; + const receipt: SignedBenchmarkVerdictReceipt = { + version: 1, + kind: 'benchmark_verdict', + storeId: 's', + runId: 'r', + lockHash: { algorithm: 'sha256', hex: '1'.repeat(64) }, + operationId: 'op1', + dispatchId: 'd1', + dispatchGeneration: 0, + gateId: 'g1', + checkId: 'c1', + candidateDigest: '3'.repeat(64), + status: 'approved', + reason: null, + expiresAtMs: '1900000000000', + preemptionCount: 0, + bucketMetrics: [{ bucketId: 'bs1-isl4k', metrics: { latency_us_p50: 14.2 } }], + hardwareDiagnostics: diagSummary, + signature: 'f'.repeat(64), + }; + assert.equal(receipt.hardwareDiagnostics?.boundPipeline, 'tensor_cube'); +}); + +test('Stage A static symbol & spill audit: denies ELF64 (.so/.o/.cubin), PTX, and SASS cublasGemmEx / at::native:: / maxLocalSpillBytes: 0 with ZERO Stage B executions', async () => { + const root = await mkdtemp(join(tmpdir(), 'lw-stagea-audit-')); + try { + const workDir = join(root, 'work'); + const workloadsDir = join(root, 'held_out_workloads'); + const wlDir = join(workloadsDir, 'decode-holdout'); + await mkdir(workDir, { recursive: true, mode: 0o700 }); + await mkdir(wlDir, { recursive: true, mode: 0o700 }); + + const stageBRanSentinel = join(root, 'stage-b-should-never-run.flag'); + await writeFile( + join(wlDir, 'evaluate.sh'), + `#!${process.execPath}\nprocess.stdout.write('LOOPWRIGHT_STAGE_B_RESULT:{"status":"approved","metrics":{"latency_us":10}}\\n');\n`, + { mode: 0o755 }, + ); + + const runWithBuildPayload = async ( + outputFiles: Readonly>, + audit: StageAStaticAuditSpec, + ) => { + let stageBInvocations = 0; + const fileWrites = Object.entries(outputFiles) + .map( + ([relName, buf]) => + `fs.writeFileSync(path.join(process.env.LOOPWRIGHT_STAGE_A_OUT, ${JSON.stringify(relName)}), Buffer.from(${JSON.stringify(buf.toString('base64'))}, 'base64'));`, + ) + .join('\n'); + const buildScript = Buffer.from( + [`#!${process.execPath}`, 'const fs = require("node:fs"), path = require("node:path");', fileWrites].join('\n'), + 'utf8', + ); + const buildSha = sha256Hex(buildScript); + const grant = makeLeaseGrant({ + targetHardware: { + accelerator: 'sm_90a', + isolationMode: 'whole_device', + deviceCount: 1, + ...audit, + }, + candidateArtifacts: { + entries: [ + { + name: 'scripts/build.sh', + digest: { algorithm: 'sha256', hex: buildSha }, + byteLength: buildScript.byteLength, + mode: '100755', + }, + ], + deleted: [], + }, + }); + + const evaluated = await evaluateBenchmarkJob({ + config: makeWorkerConfig(workDir, workloadsDir), + grant, + downloadInputBlob: async (_sha, _len, onChunk) => onChunk(buildScript), + processRunner: async input => { + if (input.stage === 'B') { + stageBInvocations += 1; + await writeFile(stageBRanSentinel, 'RAN'); + return { + exitCode: 0, + signal: null, + stdout: 'LOOPWRIGHT_STAGE_B_RESULT:{"status":"approved","metrics":{"latency_us":10}}\n', + stderr: '', + timedOut: false, + }; + } + // Execute Stage A build script directly into isolated stageAOutDir + const { spawn } = await import('node:child_process'); + return await new Promise((resRun, rejRun) => { + const child = spawn(input.command, [...input.args], { cwd: input.cwd, env: { ...input.env } }); + let out = ''; + let err = ''; + child.stdout.on('data', (c: Buffer) => { out += c.toString('utf8'); }); + child.stderr.on('data', (c: Buffer) => { err += c.toString('utf8'); }); + child.on('error', rejRun); + child.on('close', (code, sig) => + resRun({ exitCode: code, signal: sig, stdout: out, stderr: err, timedOut: false }), + ); + }); + }, + }); + try { + return { evaluated, stageBInvocations }; + } finally { + await evaluated.cleanup(); + } + }; + + const strictAudit: StageAStaticAuditSpec = { + forbiddenSymbolPatterns: ['cublas', 'cudnn', 'rocblas', 'miopen', 'aclnn', 'at::native::', 'torch_cuda'], + maxRegisterCount: 128, + maxLocalSpillBytes: 0, + }; + + // 1. ELF64 .so importing cublasGemmEx in .dynsym -> denied BEFORE Stage B! + const elfSoCublas = buildTestElf64Binary({ + elfType: 3, + machine: 62, + dynSymbols: ['cudaLaunchKernel', 'cublasGemmEx'], + }); + const r1 = await runWithBuildPayload({ 'libkernel.so': elfSoCublas }, strictAudit); + assert.equal(r1.stageBInvocations, 0, 'Stage B must NOT run when ELF .so links cublasGemmEx'); + assert.equal(r1.evaluated.status, 'denied'); + assert.equal(r1.evaluated.reason, STAGE_A_STATIC_AUDIT_FAILED); + assert.equal(r1.evaluated.findings?.some(f => f.evidence.includes('cublasGemmEx')), true); + + // 2. ELF64 .o with Itanium-mangled _ZN2at6native9gemm_cudaE -> matches 'at::native::' with 0 Stage B runs! + const elfObjAtNative = buildTestElf64Binary({ + elfType: 1, + machine: 62, + symbols: ['_ZN2at6native9gemm_cudaE'], + }); + const r2 = await runWithBuildPayload({ 'dispatch.o': elfObjAtNative }, strictAudit); + assert.equal(r2.stageBInvocations, 0); + assert.equal(r2.evaluated.status, 'denied'); + assert.equal(r2.evaluated.reason, STAGE_A_STATIC_AUDIT_FAILED); + assert.equal(r2.evaluated.findings?.some(f => f.evidence.includes('at::native::')), true); + + // 3. ELF64 .cubin exceeding maxLocalSpillBytes: 0 via .nv.info EIATTR_FRAME_SIZE -> denied with 0 Stage B runs! + const elfCubinSpill = buildTestElf64Binary({ + elfType: 2, + machine: 190, + symbols: ['flash_decode_kernel'], + nvInfoRegCount: 96, + nvInfoSpillFrameBytes: 32, + }); + const r3 = await runWithBuildPayload({ 'flash_decode.cubin': elfCubinSpill }, strictAudit); + assert.equal(r3.stageBInvocations, 0); + assert.equal(r3.evaluated.status, 'denied'); + assert.equal(r3.evaluated.reason, STAGE_A_STATIC_AUDIT_FAILED); + assert.equal(r3.evaluated.findings?.some(f => /spill|32/i.test(f.evidence)), true); + + // 4. PTX (.ptx) with .extern .func cublasGemmEx AND .local spill buffer -> denied with 0 Stage B runs! + const badPtx = Buffer.from( + [ + '.version 8.4', + '.target sm_90a', + '.extern .func cublasGemmEx (.param .b64 p0);', + '.visible .entry gemm_entry() {', + ' .reg .b32 %r<96>;', + ' .reg .f32 %f<48>;', + ' .local .align 8 .b8 __local_depot0[16];', + ' ret;', + '}', + ].join('\n'), + 'utf8', + ); + const r4 = await runWithBuildPayload({ 'gemm.ptx': badPtx }, strictAudit); + assert.equal(r4.stageBInvocations, 0); + assert.equal(r4.evaluated.status, 'denied'); + assert.equal(r4.evaluated.reason, STAGE_A_STATIC_AUDIT_FAILED); + assert.equal((r4.evaluated.findings?.length ?? 0) >= 2, true); + + // 5. SASS (.sass) with ptxas spill stores / Used N registers breach -> denied with 0 Stage B runs! + const badSass = Buffer.from( + [ + '//--------------------- .text.flash_decode --------------------------', + '// ptxas info : Used 160 registers, 24 bytes stack frame, 16 bytes spill stores, 16 bytes spill loads', + '/*0000*/ MOV R1, c[0x0][0x28] ;', + '/*0010*/ CALL.ABS.NOINC `rocblas_hgemm ;', + ].join('\n'), + 'utf8', + ); + const r5 = await runWithBuildPayload({ 'flash_decode.sass': badSass }, strictAudit); + assert.equal(r5.stageBInvocations, 0); + assert.equal(r5.evaluated.status, 'denied'); + assert.equal(r5.evaluated.reason, STAGE_A_STATIC_AUDIT_FAILED); + assert.equal(r5.evaluated.findings?.some(f => f.evidence.includes('rocblas')), true); + assert.equal(r5.evaluated.findings?.some(f => f.evidence.includes('160')), true); + + // 6. Clean ELF64 .cubin + clean PTX (comment mentioning cublas ignored, 64 regs, 0 spill) PASSES Stage A and runs Stage B! + const cleanCubin = buildTestElf64Binary({ + elfType: 2, + machine: 190, + symbols: ['flash_decode_sm90_kernel'], + nvInfoRegCount: 64, + nvInfoSpillFrameBytes: 0, + }); + const cleanPtx = Buffer.from( + [ + '// Pure custom WGMMA kernel without cublas or cudnn fallback', + '.version 8.4', + '.target sm_90a', + '.visible .entry flash_decode_sm90_kernel() {', + ' .reg .pred %p<8>;', + ' .reg .b32 %r<48>;', + ' .reg .f32 %f<16>;', + ' ret;', + '}', + ].join('\n'), + 'utf8', + ); + const r6 = await runWithBuildPayload( + { 'flash_decode.cubin': cleanCubin, 'flash_decode.ptx': cleanPtx }, + strictAudit, + ); + assert.equal(r6.stageBInvocations, 1, 'Clean candidate must proceed to Stage B'); + assert.equal(r6.evaluated.status, 'approved'); + + // 7. Direct auditSealedStageAOutputs checks O_NOFOLLOW, nlink===1, 1 MiB cap, and optional nm/cuobjdump hook + const directOutDir = join(root, 'direct-out'); + await mkdir(directOutDir, { mode: 0o700 }); + const over1MibPtx = Buffer.alloc(1_048_577, 0x20); + await writeFile(join(directOutDir, 'huge.ptx'), over1MibPtx, { mode: 0o600 }); + const sealedHuge = await sealStageAOutputs({ + stageAOutDir: directOutDir, + scrubber: new SecretScrubber(), + secretOverlapBytes: 16_384, + }); + const hugeAudit = await auditSealedStageAOutputs({ + sealedOutputs: sealedHuge, + auditSpec: { forbiddenSymbolPatterns: ['cublas'] }, + scrubber: new SecretScrubber(), + }); + assert.equal(hugeAudit.passed, false); + assert.equal(hugeAudit.findings.some(f => /1048576|1 MiB|exceeds/i.test(f.evidence)), true); + + // Optional Linux/CUDA nm + cuobjdump toolchain hook catches toolchain-reported spill/symbol and 1 MiB stdout overflow + const toolDir = join(root, 'tool-out'); + await mkdir(toolDir, { mode: 0o700 }); + await writeFile(join(toolDir, 'kern.cubin'), cleanCubin, { mode: 0o600 }); + const sealedCleanForTool = await sealStageAOutputs({ + stageAOutDir: toolDir, + scrubber: new SecretScrubber(), + secretOverlapBytes: 16_384, + }); + const cuobjdumpCaught = await auditSealedStageAOutputs({ + sealedOutputs: sealedCleanForTool, + auditSpec: { forbiddenSymbolPatterns: ['cudnn'], maxLocalSpillBytes: 0 }, + scrubber: new SecretScrubber(), + auditToolRunner: async tool => { + if (tool === 'cuobjdump') { + return { + exitCode: 0, + stdout: 'Function gemm:\nREG:64 STACK:16 SHARED:0 LOCAL:16\n16 bytes spill stores, 16 bytes spill loads\ncudnnConvolutionForward\n', + stderr: '', + }; + } + return { exitCode: 0, stdout: '', stderr: '' }; + }, + }); + assert.equal(cuobjdumpCaught.passed, false); + assert.equal(cuobjdumpCaught.findings.some(f => f.evidence.includes('cudnn')), true); + assert.equal(cuobjdumpCaught.findings.some(f => f.evidence.includes('16')), true); + + const nmOverflow = await auditSealedStageAOutputs({ + sealedOutputs: sealedCleanForTool, + auditSpec: { forbiddenSymbolPatterns: ['cublas'] }, + scrubber: new SecretScrubber(), + auditToolRunner: async tool => { + if (tool === 'nm') { + throw new Error('audit tool output exceeded 1048576 bytes'); + } + return { exitCode: 0, stdout: '', stderr: '' }; + }, + }); + assert.equal(nmOverflow.passed, false); + assert.equal(nmOverflow.findings.some(f => /1048576|1 MiB/i.test(f.evidence)), true); + + // Symlink / hardlink tamper check on auditSealedStageAOutputs fails closed + const tamperDir = join(root, 'tamper-out'); + await mkdir(tamperDir, { mode: 0o700 }); + const realFile = join(tamperDir, 'k.ptx'); + await writeFile(realFile, '.version 8.4\n', { mode: 0o400 }); + const hardlinkPath = join(tamperDir, 'hardlink.ptx'); + await link(realFile, hardlinkPath); + await assert.rejects( + () => + auditSealedStageAOutputs({ + sealedOutputs: [ + { + artifact: { name: 'k.ptx', digest: { algorithm: 'sha256', hex: sha256Hex('.version 8.4\n') }, byteLength: 13 }, + sealedFilePath: realFile, + }, + ], + auditSpec: { forbiddenSymbolPatterns: ['cublas'] }, + scrubber: new SecretScrubber(), + }), + (err: unknown) => err instanceof HardwareRunnerError && err.code === 'ARTIFACT_INVALID', + ); + // Unsupported 32-bit Mach-O .dylib fails closed instead of falling through to UTF-8 text scan + const machO32Path = join(tamperDir, 'legacy32.dylib'); + const machO32Buf = Buffer.alloc(32, 0); + machO32Buf.writeUInt32LE(0xfeedface, 0); + await writeFile(machO32Path, machO32Buf, { mode: 0o400 }); + const machO32Audit = await auditSealedStageAOutputs({ + sealedOutputs: [ + { + artifact: { + name: 'legacy32.dylib', + digest: { algorithm: 'sha256', hex: sha256Hex(machO32Buf) }, + byteLength: machO32Buf.byteLength, + }, + sealedFilePath: machO32Path, + }, + ], + auditSpec: { forbiddenSymbolPatterns: ['cublas'] }, + scrubber: new SecretScrubber(), + }); + assert.equal(machO32Audit.passed, false); + assert.match(machO32Audit.findings[0]?.title ?? '', /Unsupported Mach-O/i); + + // Universal Mach-O fat binary (.dylib with CA FE BA BE + nfat_arch=2) fails closed, + // while a Java .class file (CA FE BA BE + minor=0, major=61) is NOT misclassified as Mach-O + const fatMachOPath = join(tamperDir, 'universal.dylib'); + const fatMachOBuf = Buffer.alloc(32, 0); + fatMachOBuf.writeUInt32BE(0xcafebabe, 0); + fatMachOBuf.writeUInt32BE(2, 4); + await writeFile(fatMachOPath, fatMachOBuf, { mode: 0o400 }); + const fatAudit = await auditSealedStageAOutputs({ + sealedOutputs: [ + { + artifact: { + name: 'universal.dylib', + digest: { algorithm: 'sha256', hex: sha256Hex(fatMachOBuf) }, + byteLength: fatMachOBuf.byteLength, + }, + sealedFilePath: fatMachOPath, + }, + ], + auditSpec: { forbiddenSymbolPatterns: ['cublas'] }, + scrubber: new SecretScrubber(), + }); + assert.equal(fatAudit.passed, false); + assert.match(fatAudit.findings[0]?.title ?? '', /Unsupported Mach-O/i); + + // Universal Mach-O disguised with a .class extension must STILL fail closed (content-based check) + const spoofedFatPath = join(tamperDir, 'spoofed.class'); + await writeFile(spoofedFatPath, fatMachOBuf, { mode: 0o400 }); + const spoofedFatAudit = await auditSealedStageAOutputs({ + sealedOutputs: [ + { + artifact: { + name: 'spoofed.class', + digest: { algorithm: 'sha256', hex: sha256Hex(fatMachOBuf) }, + byteLength: fatMachOBuf.byteLength, + }, + sealedFilePath: spoofedFatPath, + }, + ], + auditSpec: { forbiddenSymbolPatterns: ['cublas'] }, + scrubber: new SecretScrubber(), + }); + assert.equal(spoofedFatAudit.passed, false); + assert.match(spoofedFatAudit.findings[0]?.title ?? '', /Unsupported Mach-O/i); + + const javaClassPath = join(tamperDir, 'Helper.class'); + const javaClassBuf = Buffer.alloc(32, 0); + javaClassBuf.writeUInt32BE(0xcafebabe, 0); + javaClassBuf.writeUInt32BE(61, 4); // Java 17 major version + await writeFile(javaClassPath, javaClassBuf, { mode: 0o400 }); + const javaAudit = await auditSealedStageAOutputs({ + sealedOutputs: [ + { + artifact: { + name: 'Helper.class', + digest: { algorithm: 'sha256', hex: sha256Hex(javaClassBuf) }, + byteLength: javaClassBuf.byteLength, + }, + sealedFilePath: javaClassPath, + }, + ], + auditSpec: { forbiddenSymbolPatterns: ['cublas'] }, + scrubber: new SecretScrubber(), + }); + assert.equal(javaAudit.passed, true); + + const symPath = join(tamperDir, 'sym.ptx'); + await symlink(realFile, symPath); + await assert.rejects( + () => + auditSealedStageAOutputs({ + sealedOutputs: [ + { + artifact: { name: 'sym.ptx', digest: { algorithm: 'sha256', hex: sha256Hex('.version 8.4\n') }, byteLength: 13 }, + sealedFilePath: symPath, + }, + ], + auditSpec: { forbiddenSymbolPatterns: ['cublas'] }, + scrubber: new SecretScrubber(), + }), + (err: unknown) => err instanceof HardwareRunnerError && err.code === 'ARTIFACT_INVALID', + ); + } finally { + await chmod(join(root, 'direct-out'), 0o700).catch(() => {}); + await chmod(join(root, 'tool-out'), 0o700).catch(() => {}); + await rm(root, { recursive: true, force: true }); + } +}); + +test('Stage B 49,152-byte bucketMetrics + sanitized hardwareDiagnostics parser, secret/free-text/file-export rejection, and all_buckets threshold denial', async () => { + const scrubber = new SecretScrubber(); + const canarySecret = 'HELDOUT_SECRET_CANARY_TOKEN_778899AABBCC'; + scrubber.register(canarySecret); + + // 1. Maximal 64-bucket Stage B envelope + hardwareDiagnostics fits comfortably under 49,152 bytes + const sixtyFourBuckets: BucketMetricEntry[] = Array.from({ length: 64 }, (_, i) => ({ + bucketId: `bs${(i % 8) + 1}-isl${(Math.floor(i / 8) + 1) * 1024}`, + dimensions: { + batch_size: (i % 8) + 1, + isl_tokens: (Math.floor(i / 8) + 1) * 1024, + dtype: 'fp16', + }, + metrics: { + latency_us_p50: 18.5 + i * 0.25, + latency_us_p95: 21.0 + i * 0.25, + goodput_rps: 420.0, + peak_mem_bytes: 1_048_576, + max_ulp: 1, + token_force_max_delta: 0.005, + }, + })); + const hwDiag: HardwareDiagnostics = { + boundPipeline: 'tensor_cube', + rooflineHeadroom: 1.14, + achievedSolPct: 87.5, + arithmeticIntensity: 192.4, + occupancyPct: 75.0, + registerCount: 96, + sharedMemBytes: 98_304, + localSpillBytes: 0, + l2HitPct: 91.2, + bankConflictPct: 1.5, + topStallReasons: [ + { reason: 'math_pipe_throttle', pct: 48.2 }, + { reason: 'mio_throttle', pct: 12.1 }, + ], + }; + + const validEnvelopeJson = JSON.stringify({ + status: 'approved', + metrics: { latency_us_p50: 24.0, max_ulp: 1, token_force_max_delta: 0.005 }, + bucketMetrics: sixtyFourBuckets, + hardwareDiagnostics: hwDiag, + }); + assert.ok(Buffer.byteLength(validEnvelopeJson, 'utf8') < MAX_STAGE_B_RESULT_BYTES); + + const parsedEnv = parseStageBResultEnvelope(`LOOPWRIGHT_STAGE_B_RESULT:${validEnvelopeJson}\n`, scrubber); + assert.equal(parsedEnv.status, 'approved'); + assert.equal(parsedEnv.bucketMetrics?.length, 64); + assert.equal(parsedEnv.hardwareDiagnostics?.boundPipeline, 'tensor_cube'); + assert.equal(parsedEnv.hardwareDiagnostics?.rooflineHeadroom, 1.14); + + // 2. Reject raw -0, NaN/Infinity, prototype keys, unknown keys, free-text/non-ASCII strings, secrets, and file export attempts! + const invalidPayloads: readonly string[] = [ + // Raw -0 in bucketMetrics and hardwareDiagnostics (must fail BEFORE @loopwright/core snapshot normalizes -0!) + '{"status":"approved","bucketMetrics":[{"bucketId":"b1","metrics":{"max_ulp":-0}}]}', + '{"status":"approved","bucketMetrics":[{"bucketId":"b1","dimensions":{"bs":-0},"metrics":{"max_ulp":0}}]}', + '{"status":"approved","hardwareDiagnostics":{"boundPipeline":"hbm","localSpillBytes":-0}}', + '{"status":"approved","hardwareDiagnostics":{"boundPipeline":"hbm","topStallReasons":[{"reason":"lg_throttle","pct":-0}]}}', + // Prototype pollution keys + '{"status":"approved","bucketMetrics":[{"bucketId":"__proto__","metrics":{"x":1}}]}', + '{"status":"approved","hardwareDiagnostics":{"boundPipeline":"hbm","__proto__":{}}}', + // Free-text / spaces / non-ASCII exfiltration attempts in hardwareDiagnostics and bucketMetrics + '{"status":"approved","hardwareDiagnostics":{"boundPipeline":"hbm","topStallReasons":[{"reason":"leaked held out prompt text","pct":10}]}}', + '{"status":"approved","hardwareDiagnostics":{"boundPipeline":"free text pipeline"}}', + '{"status":"approved","bucketMetrics":[{"bucketId":"b1","dimensions":{"prompt":"leaked prompt with spaces"},"metrics":{"x":1}}]}', + '{"status":"approved","bucketMetrics":[{"bucketId":"non_ascii_\u00e9","metrics":{"x":1}}]}', + // SecretScrubber leak (including JSON-escaped secret) + `{"status":"approved","hardwareDiagnostics":{"boundPipeline":"hbm","topStallReasons":[{"reason":"\\u0048${canarySecret.slice(1)}","pct":10}]}}`, + `{"status":"approved","bucketMetrics":[{"bucketId":"b1","dimensions":{"tag":"${canarySecret}"},"metrics":{"x":1}}]}`, + // Stage B file export attempts + '{"status":"approved","metrics":{"x":1},"outputArtifacts":[{"name":"ncu.ncu-rep","digest":{"algorithm":"sha256","hex":"' + 'a'.repeat(64) + '"},"byteLength":12}]}', + '{"status":"approved","metrics":{"x":1},"files":["leak.bin"]}', + // Collection ceiling breaches (> 16 metrics in bucket, > 8 dimensions in bucket) + JSON.stringify({ + status: 'approved', + bucketMetrics: [ + { + bucketId: 'b1', + metrics: Object.fromEntries(Array.from({ length: 17 }, (_, i) => [`m${i}`, i])), + }, + ], + }), + JSON.stringify({ + status: 'approved', + bucketMetrics: [ + { + bucketId: 'b1', + dimensions: Object.fromEntries(Array.from({ length: 9 }, (_, i) => [`d${i}`, i])), + metrics: { m0: 1 }, + }, + ], + }), + ]; + + for (const badPayload of invalidPayloads) { + assert.throws( + () => parseStageBResultEnvelope(badPayload, scrubber), + (err: unknown) => err instanceof HardwareRunnerError && err.code === 'ARTIFACT_INVALID', + `expected ARTIFACT_INVALID for payload: ${badPayload}`, + ); + } + + // 3. End-to-end Relay + Worker round-trip of bucketMetrics + hardwareDiagnostics & all_buckets METRIC_THRESHOLD_FAILED + const root = await mkdtemp(join(tmpdir(), 'lw-stageb-e2e-')); + const casDir = join(root, 'cas'); + const workDir = join(root, 'work'); + const workloadsDir = join(root, 'workloads'); + await mkdir(workDir, { recursive: true, mode: 0o700 }); + await mkdir(join(workloadsDir, 'decode-holdout'), { recursive: true, mode: 0o700 }); + + const relay = await startRelayServer({ + port: 0, + casDir, + controllerSigningSecret: CONTROLLER_SECRET, + workerTokens: [WORKER_TOKEN], + leaseTtlMs: 10_000, + sweepIntervalMs: 250, + }); + + try { + const stageAndEval = async ( + opId: string, + stageBEnvelopeObj: Record, + thresholds: readonly MetricThresholdRule[], + ): Promise => { + await writeFile( + join(workloadsDir, 'decode-holdout', 'evaluate.sh'), + `#!${process.execPath}\nprocess.stdout.write('LOOPWRIGHT_STAGE_B_RESULT:' + ${JSON.stringify(JSON.stringify(stageBEnvelopeObj))} + '\\n');\n`, + { mode: 0o755 }, + ); + const buildScript = Buffer.from( + `#!${process.execPath}\nrequire("node:fs").writeFileSync(process.env.LOOPWRIGHT_STAGE_A_OUT + "/k.cubin", "cubin");\n`, + 'utf8', + ); + const buildSha = sha256Hex(buildScript); + const putSig = signRelayPayload(CONTROLLER_SECRET, `PUT\n${opId}\n${buildSha}\n${buildScript.byteLength}`); + const putRes = await fetch(`${relay.url}/v1/benchmark/jobs/${opId}/blobs/${buildSha}`, { + method: 'PUT', + headers: { + 'content-type': 'application/octet-stream', + 'x-loopwright-blob-sha256': buildSha, + 'x-loopwright-blob-length': String(buildScript.byteLength), + 'x-loopwright-signature': putSig, + }, + body: new Uint8Array(buildScript), + }); + assert.equal(putRes.status === 200 || putRes.status === 201, true); + + const lockHex = sha256Hex(`lock:${opId}`); + const req: BenchmarkRequest = { + version: 1, + kind: 'benchmark_request', + storeId: 'store-t6', + runId: 'run-t6', + lockHash: { algorithm: 'sha256', hex: lockHex }, + operationId: opId, + dispatchId: `disp-${opId}`, + dispatchGeneration: 1, + requestDigest: sha256Hex(`req:${opId}`), + gateId: 'sm90-gate', + checkId: 'decode-bench', + candidateDigest: buildSha, + subject: { + lockHash: { algorithm: 'sha256', hex: lockHex }, + contractHash: { algorithm: 'sha256', hex: lockHex }, + repository: 'org/kernels', + baseRevision: '1'.repeat(40), + sourceRevision: '1'.repeat(40), + candidateDigest: { algorithm: 'sha256', hex: buildSha }, + targetMatrixDigest: null, + }, + targetCellId: 'cuda-sm90', + targetHardware: { + accelerator: 'sm_90a', + isolationMode: 'whole_device', + deviceCount: 1, + }, + heldOutWorkloadId: 'decode-holdout', + metricThresholds: thresholds, + maxPreemptions: 3, + candidateArtifacts: { + entries: [ + { + name: 'scripts/build.sh', + digest: { algorithm: 'sha256', hex: buildSha }, + byteLength: buildScript.byteLength, + mode: '100755', + }, + ], + deleted: [], + }, + }; + const reqBytes = Buffer.from(canonicalJson(req), 'utf8'); + const submitRes = await fetch(`${relay.url}/v1/benchmark/jobs`, { + method: 'POST', + headers: { + 'content-type': 'application/json', + 'x-loopwright-signature': signRelayPayload(CONTROLLER_SECRET, reqBytes), + }, + body: new Uint8Array(reqBytes), + }); + assert.equal(submitRes.status, 200); + + await runHardwareWorker({ + config: makeWorkerConfig(workDir, workloadsDir, { relayUrl: relay.url }), + once: true, + registerProcessSignalHandlers: false, + }); + + const pollRes = await fetch(`${relay.url}/v1/benchmark/jobs`, { + method: 'POST', + headers: { + 'content-type': 'application/json', + 'x-loopwright-signature': signRelayPayload(CONTROLLER_SECRET, reqBytes), + }, + body: new Uint8Array(reqBytes), + }); + assert.equal(pollRes.status, 200); + return (await pollRes.json()) as BenchmarkVerdict; + }; + + const allBucketsRules: readonly MetricThresholdRule[] = [ + { kind: 'bounds', metric: 'max_ulp', max: 1, bucketScope: 'all_buckets' }, + { kind: 'bounds', metric: 'token_force_max_delta', max: 0.02, bucketScope: 'all_buckets' }, + ]; + + // 3a. Bucket 1 violates max_ulp <= 1 (max_ulp = 2.5) -> denied with METRIC_THRESHOLD_FAILED! + const failingBuckets: readonly BucketMetricEntry[] = [ + { bucketId: 'bs1-isl4k', metrics: { latency_us_p50: 12.1, max_ulp: 0.5, token_force_max_delta: 0.008 } }, + { bucketId: 'bs16-isl8k', metrics: { latency_us_p50: 29.4, max_ulp: 2.5, token_force_max_delta: 0.015 } }, + ]; + assert.equal(evaluateMetricThresholds(allBucketsRules, { max_ulp: 0.5 }, failingBuckets), false); + + const deniedVerdict = await stageAndEval( + 'verify.0.check.bucket-fail', + { + status: 'approved', + metrics: { max_ulp: 0.5, token_force_max_delta: 0.008 }, + bucketMetrics: failingBuckets, + hardwareDiagnostics: hwDiag, + }, + allBucketsRules, + ); + assert.equal(deniedVerdict.status, 'denied'); + assert.equal(deniedVerdict.reason, 'METRIC_THRESHOLD_FAILED'); + assert.equal(deniedVerdict.bucketMetrics?.length, 2); + assert.equal(deniedVerdict.hardwareDiagnostics?.boundPipeline, 'tensor_cube'); + + // 3b. All buckets pass -> approved + signed receipt on disk binds bucketMetrics & hardwareDiagnostics! + const passingBuckets: readonly BucketMetricEntry[] = [ + { bucketId: 'bs1-isl4k', dimensions: { bs: 1, isl: 4096 }, metrics: { latency_us_p50: 12.1, max_ulp: 1, token_force_max_delta: 0.01 } }, + { bucketId: 'bs16-isl8k', dimensions: { bs: 16, isl: 8192 }, metrics: { latency_us_p50: 29.4, max_ulp: 0.75, token_force_max_delta: 0.019 } }, + ]; + const approvedVerdict = await stageAndEval( + 'verify.0.check.bucket-pass', + { + status: 'approved', + metrics: { latency_us_p50: 20.75 }, + bucketMetrics: passingBuckets, + hardwareDiagnostics: hwDiag, + }, + [ + ...allBucketsRules, + { kind: 'bounds', metric: 'latency_us_p50', max: 35, bucketScope: { bucketId: 'bs16-isl8k' } }, + ], + ); + assert.equal(approvedVerdict.status, 'approved'); + assert.equal(approvedVerdict.reason, null); + assert.deepEqual(approvedVerdict.bucketMetrics, passingBuckets); + assert.deepEqual(approvedVerdict.hardwareDiagnostics, hwDiag); + + const persistedReceipt = JSON.parse( + await readFile(join(casDir, 'receipts', 'verify.0.check.bucket-pass.json'), 'utf8'), + ) as SignedBenchmarkVerdictReceipt; + assert.equal( + verifyBenchmarkVerdictSignature( + CONTROLLER_SECRET, + persistedReceipt as unknown as Readonly>, + persistedReceipt.signature, + ), + true, + ); + assert.deepEqual(persistedReceipt.bucketMetrics, passingBuckets); + assert.deepEqual(persistedReceipt.hardwareDiagnostics, hwDiag); + } finally { + await relay.close(); + await rm(root, { recursive: true, force: true }); + } +}); + +test('probeAcceleratorHealth: validates RTX 4090, RX 7800 XT low-power banner, and Ascend fixtures, detecting sticky Xid/ECC/hang faults and scrubbing secrets', async () => { + const secretToken = 'PROBE_STDERR_SECRET_TOKEN_5544332211'; + const scrubber = new SecretScrubber(); + scrubber.register(secretToken); + + // 1a. Healthy NVIDIA GeForce RTX 4090 (measured [N/A] ECC columns + 0 remapped rows) + const rtx4090Csv = [ + '0, NVIDIA GeForce RTX 4090, GPU-bbc521eb-4a08-800b-eb2a-770a4a5b8a8c, 00000000:02:00.0, P8, Disabled, [N/A], [N/A]', + '1, NVIDIA GeForce RTX 4090, GPU-1068d7f6-26eb-5225-371e-58ca20150673, 00000000:03:00.0, P8, Disabled, [N/A], [N/A]', + ].join('\n'); + const rtx4090Detail = [ + 'GPU 00000000:02:00.0', + ' ECC Mode', + ' Current : Disabled', + ' ECC Errors', + ' Volatile', + ' DRAM Uncorrectable : N/A', + ' Channel Repair Pending : No', + ' TPC Repair Pending : No', + ' Remapped Rows', + ' Uncorrectable Error : 0', + ' Pending : No', + ' Remapping Failure Occurred : No', + ].join('\n'); + + const healthyNvidia = await probeAcceleratorHealth({ + probeMode: 'physical', + capabilities: { + accelerator: 'sm_89', + isolationModes: ['whole_device'], + deviceCount: 2, + driverVersion: '610.43.02', + }, + allocatedDeviceIndices: [0], + verifyExecutable: async p => p, + commandRunner: async (_bin, args) => { + if (args.includes('-q')) return { exitCode: 0, stdout: rtx4090Detail, stderr: '' }; + return { exitCode: 0, stdout: rtx4090Csv, stderr: '' }; + }, + scrubber, + }); + assert.equal(healthyNvidia.healthy, true); + assert.equal(healthyNvidia.quarantineRequired, false); + assert.equal(healthyNvidia.vendor, 'nvidia'); + + // 1b. NVIDIA sticky Xid / GPU lost + secret in stderr -> unhealthy, quarantineRequired, secret scrubbed! + const xidNvidia = await probeAcceleratorHealth({ + probeMode: 'physical', + capabilities: { + accelerator: 'sm_90a', + isolationModes: ['whole_device'], + deviceCount: 1, + driverVersion: '550.90.07', + }, + verifyExecutable: async p => p, + commandRunner: async () => ({ + exitCode: 15, + stdout: 'Unable to determine the device handle for GPU 0000:02:00.0: Unknown Error (Xid 79)\n', + stderr: `NVML error context=${secretToken}\n`, + }), + scrubber, + }); + assert.equal(xidNvidia.healthy, false); + assert.equal(xidNvidia.quarantineRequired, true); + assert.equal(xidNvidia.summary.includes(secretToken), false); + assert.equal(JSON.stringify(xidNvidia.findings).includes(secretToken), false); + + // 1c. NVIDIA uncorrectable ECC > 0 on H100 -> quarantineRequired + const eccNvidia = await probeAcceleratorHealth({ + probeMode: 'physical', + capabilities: { + accelerator: 'sm_90a', + isolationModes: ['whole_device'], + deviceCount: 1, + driverVersion: '550.90.07', + }, + verifyExecutable: async p => p, + commandRunner: async (_bin, args) => { + if (args.includes('-q')) return { exitCode: 0, stdout: 'Remapping Failure Occurred : Yes\n', stderr: '' }; + return { + exitCode: 0, + stdout: '0, NVIDIA H100 80GB HBM3, GPU-1111, 00000000:01:00.0, P0, Enabled, 3, 3\n', + stderr: '', + }; + }, + scrubber, + }); + assert.equal(eccNvidia.healthy, false); + assert.equal(eccNvidia.quarantineRequired, true); + assert.equal(eccNvidia.faultKind, 'ecc_uncorrectable'); + + // 2a. Healthy AMD Radeon RX 7800 XT (measured leading low-power WARNING line before JSON!) + const rx7800JsonWithBanner = [ + 'WARNING: AMD GPU device(s) is/are in a low-power state. Check power control/runtime_status', + '', + JSON.stringify({ + card0: { + 'GPU use (%)': '0', + 'Card Series': 'AMD Radeon RX 7800 XT', + 'Card Model': '0x747e', + 'GFX Version': 'gfx1101', + }, + card1: { + 'GPU use (%)': '0', + 'Card Series': 'AMD Radeon RX 7800 XT', + 'Card Model': '0x747e', + 'GFX Version': 'gfx1101', + }, + }), + ].join('\n'); + const healthyRocm = await probeAcceleratorHealth({ + probeMode: 'physical', + capabilities: { + accelerator: 'gfx1101', + isolationModes: ['whole_device'], + deviceCount: 2, + driverVersion: '6.16.13', + }, + allocatedDeviceIndices: [0], + verifyExecutable: async p => p, + commandRunner: async () => ({ exitCode: 0, stdout: rx7800JsonWithBanner, stderr: '' }), + scrubber, + }); + assert.equal(healthyRocm.healthy, true); + assert.equal(healthyRocm.quarantineRequired, false); + assert.equal(healthyRocm.vendor, 'amd'); + + // 2b. AMD ROCm RAS uncorrectable error / GPU hang -> quarantineRequired + const wedgedRocm = await probeAcceleratorHealth({ + probeMode: 'physical', + capabilities: { + accelerator: 'gfx942', + isolationModes: ['whole_device'], + deviceCount: 1, + driverVersion: '6.8.5', + }, + verifyExecutable: async p => p, + commandRunner: async () => ({ + exitCode: 0, + stdout: JSON.stringify({ + card0: { + 'Card Series': 'AMD Instinct MI300X', + 'GFX Version': 'gfx942', + 'UMC Uncorrectable Error': '2', + }, + }), + stderr: '', + }), + scrubber, + }); + assert.equal(wedgedRocm.healthy, false); + assert.equal(wedgedRocm.quarantineRequired, true); + + // 3a. Huawei Ascend NPU healthy vs Alarm health column -> quarantineRequired + const healthyAscendOut = [ + '+------------------------------------------------------------------------------------------------+', + '| npu-smi 24.1.0 Version: 24.1.0 |', + '+---------------------------+---------------+----------------------------------------------------+', + '| 0 910B3 | OK | 92.4 38 0 / 0 |', + '+===========================+===============+====================================================+', + ].join('\n'); + const okAscend = await probeAcceleratorHealth({ + probeMode: 'physical', + capabilities: { + accelerator: 'ascend_910b', + isolationModes: ['whole_device'], + deviceCount: 1, + driverVersion: '24.1.0', + }, + verifyExecutable: async p => p, + commandRunner: async () => ({ exitCode: 0, stdout: healthyAscendOut, stderr: '' }), + scrubber, + }); + assert.equal(okAscend.healthy, true); + assert.equal(okAscend.quarantineRequired, false); + + const alarmAscend = await probeAcceleratorHealth({ + probeMode: 'physical', + capabilities: { + accelerator: 'ascend_910b', + isolationModes: ['whole_device'], + deviceCount: 1, + driverVersion: '24.1.0', + }, + verifyExecutable: async p => p, + commandRunner: async () => ({ + exitCode: 0, + stdout: healthyAscendOut.replace('| OK |', '| Alarm |'), + stderr: '', + }), + scrubber, + }); + assert.equal(alarmAscend.healthy, false); + assert.equal(alarmAscend.quarantineRequired, true); + + // 4. Unresponsive / timed-out probe runner returns probe_timeout with quarantineRequired: true + const hungRunner: ProbeCommandRunner = async () => { + throw new HardwareRunnerError('RUNNER_SANDBOX_FAILED', 'hardware probe failed or exceeded bounds: Command timed out (ETIMEDOUT)'); + }; + const timeoutProbe = await probeAcceleratorHealth({ + probeMode: 'physical', + capabilities: { + accelerator: 'sm_90a', + isolationModes: ['whole_device'], + deviceCount: 1, + driverVersion: '550.90.07', + }, + verifyExecutable: async p => p, + commandRunner: hungRunner, + scrubber, + }); + assert.equal(timeoutProbe.healthy, false); + assert.equal(timeoutProbe.quarantineRequired, true); + assert.equal(timeoutProbe.faultKind, 'probe_timeout'); +}); + +test('worker.ts post-crash GPU quarantine: runs healthProbe after Stage B crash BEFORE :complete and throws WORKER_DEVICE_QUARANTINED before a second /v1/runner/leases:acquire', async () => { + const root = await mkdtemp(join(tmpdir(), 'lw-worker-quarantine-')); + const casDir = join(root, 'cas'); + const workDir = join(root, 'work'); + const workloadsDir = join(root, 'workloads'); + await mkdir(workDir, { recursive: true, mode: 0o700 }); + await mkdir(join(workloadsDir, 'decode-holdout'), { recursive: true, mode: 0o700 }); + + // Stage B simulates a faulty TMA/async kernel segfault (exit 139) + await writeFile( + join(workloadsDir, 'decode-holdout', 'evaluate.sh'), + '#!/bin/sh\nexit 139\n', + { mode: 0o755 }, + ); + + const relay = await startRelayServer({ + port: 0, + casDir, + controllerSigningSecret: CONTROLLER_SECRET, + workerTokens: [WORKER_TOKEN], + leaseTtlMs: 10_000, + sweepIntervalMs: 250, + }); + + try { + const submitJob = async (opId: string): Promise => { + const buildScript = Buffer.from( + `#!${process.execPath}\nrequire("node:fs").writeFileSync(process.env.LOOPWRIGHT_STAGE_A_OUT + "/k.cubin", "cubin");\n`, + 'utf8', + ); + const buildSha = sha256Hex(buildScript); + const putSig = signRelayPayload(CONTROLLER_SECRET, `PUT\n${opId}\n${buildSha}\n${buildScript.byteLength}`); + const putRes = await fetch(`${relay.url}/v1/benchmark/jobs/${opId}/blobs/${buildSha}`, { + method: 'PUT', + headers: { + 'content-type': 'application/octet-stream', + 'x-loopwright-blob-sha256': buildSha, + 'x-loopwright-blob-length': String(buildScript.byteLength), + 'x-loopwright-signature': putSig, + }, + body: new Uint8Array(buildScript), + }); + assert.equal(putRes.status === 200 || putRes.status === 201, true); + + const lockHex = sha256Hex(`lock:${opId}`); + const req: BenchmarkRequest = { + version: 1, + kind: 'benchmark_request', + storeId: 'store-q', + runId: 'run-q', + lockHash: { algorithm: 'sha256', hex: lockHex }, + operationId: opId, + dispatchId: `disp-${opId}`, + dispatchGeneration: 1, + requestDigest: sha256Hex(`req:${opId}`), + gateId: 'sm90-gate', + checkId: 'decode-bench', + candidateDigest: buildSha, + subject: { + lockHash: { algorithm: 'sha256', hex: lockHex }, + contractHash: { algorithm: 'sha256', hex: lockHex }, + repository: 'org/kernels', + baseRevision: '1'.repeat(40), + sourceRevision: '1'.repeat(40), + candidateDigest: { algorithm: 'sha256', hex: buildSha }, + targetMatrixDigest: null, + }, + targetCellId: 'cuda-sm90', + targetHardware: { + accelerator: 'sm_90a', + isolationMode: 'whole_device', + deviceCount: 1, + }, + heldOutWorkloadId: 'decode-holdout', + metricThresholds: [], + maxPreemptions: 3, + candidateArtifacts: { + entries: [ + { + name: 'scripts/build.sh', + digest: { algorithm: 'sha256', hex: buildSha }, + byteLength: buildScript.byteLength, + mode: '100755', + }, + ], + deleted: [], + }, + }; + const reqBytes = Buffer.from(canonicalJson(req), 'utf8'); + const submitRes = await fetch(`${relay.url}/v1/benchmark/jobs`, { + method: 'POST', + headers: { + 'content-type': 'application/json', + 'x-loopwright-signature': signRelayPayload(CONTROLLER_SECRET, reqBytes), + }, + body: new Uint8Array(reqBytes), + }); + assert.equal(submitRes.status, 200); + return req; + }; + + const pollVerdict = async (req: BenchmarkRequest): Promise => { + const reqBytes = Buffer.from(canonicalJson(req), 'utf8'); + const res = await fetch(`${relay.url}/v1/benchmark/jobs`, { + method: 'POST', + headers: { + 'content-type': 'application/json', + 'x-loopwright-signature': signRelayPayload(CONTROLLER_SECRET, reqBytes), + }, + body: new Uint8Array(reqBytes), + }); + assert.equal(res.status, 200); + return (await res.json()) as BenchmarkVerdict; + }; + + // Enqueue TWO jobs back-to-back in the Relay queue! + const req1 = await submitJob('verify.0.check.crash-xid-1'); + const req2 = await submitJob('verify.1.check.healthy-victim-2'); + + const events: string[] = []; + const settlements: WorkerJobSettlementSummary[] = []; + let leasedCount = 0; + + // Run worker in CONTINUOUS mode (once: false)! Without quarantine it would immediately acquire req2! + await assert.rejects( + () => + runHardwareWorker({ + config: makeWorkerConfig(workDir, workloadsDir, { relayUrl: relay.url }), + once: false, + registerProcessSignalHandlers: false, + onLeaseAcquired: grant => { + leasedCount += 1; + events.push(`lease:${grant.operationId}`); + }, + healthProbe: async (): Promise => { + // Verify req1 is STILL pending on Relay when healthProbe executes (strictly BEFORE :complete!) + const midVerdict = await pollVerdict(req1); + assert.equal(midVerdict.status, 'pending', 'healthProbe must execute BEFORE reporting :complete'); + events.push('health_probe'); + return { + healthy: false, + quarantineRequired: true, + probeKind: 'physical', + vendor: 'nvidia', + checkedDeviceIndices: [0], + faultKind: 'xid_error', + summary: 'Sticky NVIDIA Xid 79 detected after Stage B crash', + findings: [ + { + title: 'Accelerator sticky fault detected after Stage B failure', + severity: 'critical', + evidence: 'Sticky NVIDIA Xid 79 detected after Stage B crash', + }, + ], + }; + }, + onJobSettled: s => { + events.push(`settled:${s.operationId}:${s.outcome}:${s.status ?? ''}`); + settlements.push(s); + }, + }), + (err: unknown) => err instanceof HardwareRunnerError && err.code === 'WORKER_DEVICE_QUARANTINED', + ); + + // Worker acquired ONLY req1, ran healthProbe BEFORE settling req1 as denied, and NEVER acquired req2! + assert.equal(leasedCount, 1, 'quarantined worker must NEVER acquire a second job from Relay'); + assert.deepEqual(events, [ + 'lease:verify.0.check.crash-xid-1', + 'health_probe', + 'settled:verify.0.check.crash-xid-1:completed:denied', + ]); + assert.equal(settlements.length, 1); + + const v1 = await pollVerdict(req1); + assert.equal(v1.status, 'denied'); + assert.equal(v1.reason, 'STAGE_B_EXECUTION_FAILED'); + assert.equal(v1.findings?.some(f => f.evidence.includes('Xid 79')), true); + + const v2 = await pollVerdict(req2); + assert.equal(v2.status, 'pending', 'second healthy job in Relay queue must remain untouched for healthy workers'); + + // External host GPU loss (externalHostLoss: true) preempts req2 cleanly so it requeues while still quarantining worker! + let externalPreemptLeases = 0; + await assert.rejects( + () => + runHardwareWorker({ + config: makeWorkerConfig(workDir, workloadsDir, { relayUrl: relay.url, workerId: 'worker-ext-loss' }), + once: false, + registerProcessSignalHandlers: false, + onLeaseAcquired: () => { + externalPreemptLeases += 1; + }, + healthProbe: async (): Promise => ({ + healthy: false, + quarantineRequired: true, + probeKind: 'physical', + vendor: 'nvidia', + checkedDeviceIndices: [0], + faultKind: 'device_lost', + externalHostLoss: true, + summary: 'No devices were found on host bus', + findings: [ + { + title: 'External host accelerator loss', + severity: 'critical', + evidence: 'No devices were found on host bus', + }, + ], + }), + }), + (err: unknown) => err instanceof HardwareRunnerError && err.code === 'WORKER_DEVICE_QUARANTINED', + ); + assert.equal(externalPreemptLeases, 1); + const v2AfterPreempt = await pollVerdict(req2); + assert.equal(v2AfterPreempt.status, 'pending'); + assert.equal(v2AfterPreempt.preemptionCount, 1); + } finally { + await relay.close(); + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/packages/hardware-runner/test/worker.test.ts b/packages/hardware-runner/test/worker.test.ts index 7e24aab..0776bc9 100644 --- a/packages/hardware-runner/test/worker.test.ts +++ b/packages/hardware-runner/test/worker.test.ts @@ -1954,6 +1954,7 @@ test('delayed acquisition pre-start renewal, shorter renewal TTL shrinking deadl scenario = 'preempt_docker_rm_fail'; preemptCalls = 0; const mockDockerDir = join(root, 'mock-docker-fail'); + const mockDockerStartedFlag = join(root, 'mock-docker-started.flag'); await mkdir(mockDockerDir, { recursive: true, mode: 0o755 }); const mockDockerScript = join(mockDockerDir, 'docker'); await writeFile( @@ -1964,6 +1965,7 @@ test('delayed acquisition pre-start renewal, shorter renewal TTL shrinking deadl ' echo "docker daemon unreachable during rm -f" >&2', ' exit 1', 'fi', + `: > "${mockDockerStartedFlag}"`, 'sleep 10', ].join('\n'), { mode: 0o555 }, @@ -1987,7 +1989,17 @@ test('delayed acquisition pre-start renewal, shorter renewal TTL shrinking deadl preemptSignal: dockerFailPreempt.signal, registerProcessSignalHandlers: false, evaluator: opts => { - setTimeout(() => dockerFailPreempt.abort(), 40); + void (async () => { + for (let i = 0; i < 400 && !dockerFailPreempt.signal.aborted; i += 1) { + const started = await lstat(mockDockerStartedFlag).then(() => true, () => false); + if (started) { + dockerFailPreempt.abort(); + return; + } + await new Promise(r => setTimeout(r, 10)); + } + dockerFailPreempt.abort(); + })(); return realEval({ ...opts, stageACommand: { command: '/bin/sleep', args: ['10'] }, diff --git a/packages/memory/src/compaction.ts b/packages/memory/src/compaction.ts index cdee48b..5413a30 100644 --- a/packages/memory/src/compaction.ts +++ b/packages/memory/src/compaction.ts @@ -52,7 +52,7 @@ export function evaluateCompactionPolicy(input: CompactionPolicyInput): Compacti export function buildCompactionSummary(input: CompactionSummaryInput): { readonly summary: CompactionCheckpointSummary; readonly digest: Digest } { const snapshot = selectActiveMemory({ store: input.memory.store, contract: input.memory.contract, nowMs: input.memory.nowMs, currentCodeFingerprint: input.memory.currentCodeFingerprint, currentUpstreamVersions: input.memory.currentUpstreamVersions, - targetCell: input.memory.targetCell }); + targetCell: input.memory.targetCell, hardwareScope: input.memory.hardwareScope }); const summary: CompactionCheckpointSummary = { version: 1, goal: { goal: input.lock.spec.contract.spec.goal, nonGoals: [...input.nonGoals] }, contractHash: { ...input.lock.spec.lockHash }, currentNodeId: input.currentNodeId, diff --git a/packages/memory/src/finalizer.ts b/packages/memory/src/finalizer.ts index f8d019a..c122292 100644 --- a/packages/memory/src/finalizer.ts +++ b/packages/memory/src/finalizer.ts @@ -3,9 +3,10 @@ import { lstat, open, readdir, readFile } from 'node:fs/promises'; import { join, resolve, sep } from 'node:path'; import { digestArtifact, identifyManifest, validateDocument, type ArtifactRef, type Digest, type Evidence, type RunResult, type TaskLock } from '@loopwright/core'; import type { ControllerIncident } from '@loopwright/controller'; -import { canonical, controllerIncidentSchema, digestEqual, fail, hashDomain, incidentReferenceDigest, MemoryDiagnosticError, memoryProposalSchema, serializeMemoryStoreIndex, syntheticIncidentArtifact, unifiedFileDiff } from './schema.js'; +import { canonical, controllerIncidentSchema, digestEqual, fail, hardwareMemoryScopeSchema, hardwareScopesOverlap, hashDomain, incidentReferenceDigest, MemoryDiagnosticError, memoryProposalSchema, serializeMemoryStoreIndex, syntheticIncidentArtifact, unifiedFileDiff } from './schema.js'; import { clampMemoryMaxEntries, compareEntriesForEviction, computeCodeFingerprint, loadMemoryStore, memoryDirectoryFor, normalizeMemoryRoot, projectMemoryStore } from './store.js'; import type { + HardwareMemoryScope, MemoryBudgetLedger, MemoryCuratorRequest, MemoryEntry, @@ -270,6 +271,7 @@ function applyLifecycleSweepAndEviction(options: { const sortedBaseEntries = [...baseEntries].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)); const runSucceeded = settledStatus === 'completed' || settledStatus === 'no_change'; const currentTargetMatrix = config.targetMatrix ?? null; + const currentHardwareScope = config.hardwareScope; for (const entry of sortedBaseEntries) { if (targetedOrSuperseded.has(entry.id)) continue; let retireReason: string | null = null; @@ -283,6 +285,7 @@ function applyLifecycleSweepAndEviction(options: { } else if ( entry.kind === 'failure_observation' && targetMatrixOverlaps(entry.scope.targetMatrix, currentTargetMatrix) + && hardwareScopesOverlap(entry.scope.hardwareScope, currentHardwareScope) && (runSucceeded || passedCheckClaimKeys.has(entry.claimKey)) ) { retireReason = 'Prior failure observation healed.'; @@ -422,16 +425,61 @@ export async function finalizeRunMemory(input: MemoryFinalizerInput): Promise + const hardwareScope = config.hardwareScope === undefined + ? undefined + : hardwareMemoryScopeSchema(config.hardwareScope, '/config/hardwareScope'); + const priorSameClaim = (claimKey: string, entryHardwareScope: MemoryEntry['scope']['hardwareScope']): readonly string[] => [...new Set( loaded.index.entries - .filter(candidate => candidate.claimKey === claimKey && targetMatrixOverlaps(candidate.scope.targetMatrix, targetMatrix)) + .filter(candidate => + candidate.claimKey === claimKey + && targetMatrixOverlaps(candidate.scope.targetMatrix, targetMatrix) + && hardwareScopesOverlap(candidate.scope.hardwareScope, entryHardwareScope)) .map(candidate => candidate.id), )].sort().slice(0, 32); - const buildEntry = (id: string, claimKey: string, claim: string, kind: MemoryEntry['kind'], refs: readonly MemoryEvidenceRef[]): MemoryEntry => - ({ version: 1, id, claimKey, claim: boundedClaim(claim), kind, scope: { taskpack: config.taskpack, repository: contract.spec.target.repository, - paths: normalizedWritablePaths, targetMatrix }, sourceRef, sourceDigest, verifiedAtMs: config.nowMs, - validFor: validity, expiresAtMs: config.nowMs + config.ttlMs, supersedes: priorSameClaim(claimKey), evidenceRefs: refs }); + let skippedForHardwareEvidenceCount = 0; + const buildEntry = (id: string, claimKey: string, claim: string, kind: MemoryEntry['kind'], refs: readonly MemoryEvidenceRef[]): MemoryEntry | null => { + let entryHardwareScope: HardwareMemoryScope | undefined; + if (hardwareScope !== undefined) { + const requiresHardwareEvidence = kind === 'fact' || kind === 'invariant'; + const hasPassingHardwareEvidence = refs.some(ref => ref.level === 'hardware_execution' && ref.observedStatus === 'passed'); + if (!requiresHardwareEvidence || hasPassingHardwareEvidence) { + entryHardwareScope = hardwareScope; + } else { + // Do not silently widen a fact/invariant to hardware-universal if an active entry for a + // different hardware accelerator already exists on this claimKey. + const wouldClobberOtherHardware = loaded.index.entries.some( + candidate => + candidate.claimKey === claimKey + && targetMatrixOverlaps(candidate.scope.targetMatrix, targetMatrix) + && candidate.scope.hardwareScope !== undefined + && !hardwareScopesOverlap(candidate.scope.hardwareScope, hardwareScope), + ); + if (wouldClobberOtherHardware) { + skippedForHardwareEvidenceCount += 1; + return null; + } + entryHardwareScope = undefined; + } + } + return { + version: 1, + id, + claimKey, + claim: boundedClaim(claim), + kind, + scope: entryHardwareScope === undefined + ? { taskpack: config.taskpack, repository: contract.spec.target.repository, paths: normalizedWritablePaths, targetMatrix } + : { taskpack: config.taskpack, repository: contract.spec.target.repository, paths: normalizedWritablePaths, targetMatrix, hardwareScope: entryHardwareScope }, + sourceRef, + sourceDigest, + verifiedAtMs: config.nowMs, + validFor: validity, + expiresAtMs: config.nowMs + config.ttlMs, + supersedes: priorSameClaim(claimKey, entryHardwareScope), + evidenceRefs: refs, + }; + }; const deterministicEntries: MemoryEntry[] = []; const rows = settled.result === null ? [] : [...settled.result.spec.verification.spec.required, ...settled.result.spec.verification.spec.optional]; const passedCheckClaimKeys = new Set( @@ -441,8 +489,9 @@ export async function finalizeRunMemory(input: MemoryFinalizerInput): Promise row.status === 'passed')) { const reference = evidenceRefFor(row, settled.evidence); if (reference === null) continue; - deterministicEntries.push(buildEntry(`entry.${runToken}.check.${boundedToken(row.checkId)}`, `claim.check.${row.checkId}`, - `Check ${row.checkId} passed on run ${runId} with ${reference.level} evidence.`, 'fact', [reference])); + const built = buildEntry(`entry.${runToken}.check.${boundedToken(row.checkId)}`, `claim.check.${row.checkId}`, + `Check ${row.checkId} passed on run ${runId} with ${reference.level} evidence.`, 'fact', [reference]); + if (built !== null) deterministicEntries.push(built); } } else if (settled.result !== null && OBSERVATION_STATUSES.includes(settled.result.spec.status as (typeof OBSERVATION_STATUSES)[number])) { for (const row of rows.filter(row => row.status !== 'passed')) { @@ -455,16 +504,18 @@ export async function finalizeRunMemory(input: MemoryFinalizerInput): Promise 0) { + const skipNote = `hardware_evidence_required_skipped:${skippedForHardwareEvidenceCount}`; + reason = reason === null ? skipNote : `${reason}; ${skipNote}`; + } if (deterministicTruncated || swept.truncated) { reason = reason === null ? 'proposal_operations_truncated_at_limit' diff --git a/packages/memory/src/index.ts b/packages/memory/src/index.ts index 7a48e91..1c62766 100644 --- a/packages/memory/src/index.ts +++ b/packages/memory/src/index.ts @@ -1,7 +1,7 @@ export { MemoryDiagnosticError, diagnostic, fail, digestEqual, canonical, hashDomain, digestBytes, storeDigestOf, - incidentReferenceDigest, syntheticIncidentArtifact, memoryIdentifierPattern, hasControlCharacter, memoryEntrySchema, - memoryStoreIndexSchema, memoryProposalSchema, renderEntryMarkdown, serializeMemoryStoreIndex, parseEntryMarkdown, unifiedFileDiff, - MEMORY_STORE_DIGEST_DOMAIN, MEMORY_ENTRY_HEADER_FENCE } from './schema.js'; + incidentReferenceDigest, syntheticIncidentArtifact, memoryIdentifierPattern, hasControlCharacter, hardwareMemoryScopeSchema, + memoryEntrySchema, memoryStoreIndexSchema, memoryProposalSchema, renderEntryMarkdown, serializeMemoryStoreIndex, + parseEntryMarkdown, unifiedFileDiff, MEMORY_STORE_DIGEST_DOMAIN, MEMORY_ENTRY_HEADER_FENCE } from './schema.js'; export { MEMORY_ROOT, normalizeMemoryRoot, memoryDirectoryFor, forbiddenMemoryArtifactName, isMemoryManagedPath, emptyMemoryStoreIndex, loadMemoryStore, computeCodeFingerprint, compileScopePattern, matchScopePattern, entryFileBytes, projectMemoryStore, ensureMemoryDirectories } from './store.js'; @@ -20,7 +20,7 @@ export { finalizeRunMemory, resolveSettledCycleContext, type ResolvedSettledCycl export { verifyMemoryProposal, verifyRebasedProposal } from './verifier.js'; export { applyMemoryProposalCAS } from './cas.js'; export { evaluateCompactionPolicy, buildCompactionSummary, restoreFromCompactionLedger } from './compaction.js'; -export type { MemoryEntryKind, MemoryEvidenceRef, MemoryEntryScope, MemoryEntrySourceRef, MemoryEntryValidity, MemoryEntry, +export type { HardwareMemoryScope, MemoryEntryKind, MemoryEvidenceRef, MemoryEntryScope, MemoryEntrySourceRef, MemoryEntryValidity, MemoryEntry, RetiredMemoryEntry, MemoryStoreIndex, MemoryOperation, MemoryProposal, MemoryGateName, MemoryGateStatus, MemoryErrorCode, MemoryDiagnostic, MemoryGateResult, MemoryVerificationReport, MemoryVerificationInput, MemoryExclusionReason, ExcludedMemoryEntry, ActiveMemorySnapshot, MemorySelectorInput, MemoryBudgetLedger, SettledRunSummary, MemoryCuratorRequest, diff --git a/packages/memory/src/schema.ts b/packages/memory/src/schema.ts index 0e6453b..dab5f38 100644 --- a/packages/memory/src/schema.ts +++ b/packages/memory/src/schema.ts @@ -8,9 +8,11 @@ import { } from '@loopwright/controller'; import { MAX_MEMORY_INDEX_BLOB_BYTES, + type HardwareMemoryScope, type MemoryDiagnostic, type MemoryErrorCode, type MemoryEntry, + type MemoryEntryScope, type MemoryEvidenceRef, type MemoryOperation, type MemoryProposal, @@ -63,14 +65,50 @@ export function hasControlCharacter(value: string): boolean { return false; } const revisionPattern = /^[A-Za-z0-9][A-Za-z0-9._:/-]*$/; +const PRINTABLE_ASCII_RE = /^[\x20-\x7E]+$/; +const FORBIDDEN_PROTOTYPE_KEYS = new Set(['__proto__', 'constructor', 'prototype']); +const HARDWARE_SCOPE_KEYS = ['accelerator', 'driverConstraint', 'operatorFamily', 'boundPipeline'] as const; + +export const MEMORY_CREDENTIAL_PATTERNS: readonly { readonly source: RegExp; readonly label: string }[] = [ + { source: /ghp_[A-Za-z0-9]{20,}/, label: 'GitHub user token' }, + { source: /ghs_[A-Za-z0-9]{20,}/, label: 'GitHub server token' }, + { source: /github_pat_[A-Za-z0-9_]{20,}/, label: 'GitHub fine-grained token' }, + { source: /sk-[A-Za-z0-9_-]{20,}/, label: 'API key' }, + { source: /Bearer [A-Za-z0-9._~+/=-]{16,}/, label: 'bearer token' }, + { source: /-----BEGIN [A-Z ]*PRIVATE KEY-----/, label: 'private key' }, + { source: /AKIA[0-9A-Z]{16}/, label: 'AWS access key' }, +]; + +function hasLoneSurrogate(value: string): boolean { + for (let index = 0; index < value.length; index++) { + const code = value.charCodeAt(index); + if (code >= 0xd800 && code <= 0xdbff) { + const next = index + 1 < value.length ? value.charCodeAt(index + 1) : 0; + if (next < 0xdc00 || next > 0xdfff) return true; + index++; + } else if (code >= 0xdc00 && code <= 0xdfff) { + return true; + } + } + return false; +} function objectShape(value: unknown, path: string): Record { if (value === null || typeof value !== 'object' || Array.isArray(value)) fail('MEMORY_SCHEMA_INVALID', path, 'expected object'); return value as Record; } -function field(input: Record, keys: readonly string[], path: string): void { +function field( + input: Record, + keys: readonly string[], + path: string, + optionalKeys: readonly string[] = [], +): void { for (const key of keys) if (!Object.hasOwn(input, key)) fail('MEMORY_SCHEMA_INVALID', `${path}/${key}`, 'field required'); - for (const key of Object.keys(input)) if (!keys.includes(key)) fail('MEMORY_SCHEMA_INVALID', `${path}/${key}`, 'unknown field'); + for (const key of Object.getOwnPropertyNames(input)) { + if (FORBIDDEN_PROTOTYPE_KEYS.has(key) || (!keys.includes(key) && !optionalKeys.includes(key))) { + fail('MEMORY_SCHEMA_INVALID', `${path}/${key}`, 'unknown field'); + } + } } function text(value: unknown, path: string, min: number, max: number): string { if (typeof value !== 'string') fail('MEMORY_SCHEMA_INVALID', path, 'expected string'); @@ -216,6 +254,49 @@ function targetMatrix(value: unknown, path: string): MemoryEntry['scope']['targe field(input, ['id', 'platform', 'variant'], path); return { id: identifier(input['id'], `${path}/id`, 128), platform: text(input['platform'], `${path}/platform`, 1, 128), variant: text(input['variant'], `${path}/variant`, 1, 128) }; } +function hardwareScopeField(value: unknown, path: string, max: number): string { + const raw = text(value, path, 1, max); + if (hasLoneSurrogate(raw)) fail('MEMORY_SCHEMA_INVALID', path, 'lone UTF-16 surrogate in hardwareScope field'); + if (!PRINTABLE_ASCII_RE.test(raw) || raw.trim().length === 0) { + fail('MEMORY_SCHEMA_INVALID', path, 'expected non-empty printable ASCII string'); + } + for (const pattern of MEMORY_CREDENTIAL_PATTERNS) { + if (pattern.source.test(raw)) fail('MEMORY_SECRET_LEAK', path, `credential pattern detected: ${pattern.label}`); + } + return raw; +} +export function hardwareMemoryScopeSchema(value: unknown, path = '/hardwareScope'): HardwareMemoryScope { + const input = objectShape(value, path); + field(input, ['accelerator'], path, HARDWARE_SCOPE_KEYS.slice(1)); + const out: Record = Object.create(null); + out['accelerator'] = hardwareScopeField(input['accelerator'], `${path}/accelerator`, 64); + if (Object.hasOwn(input, 'driverConstraint') && input['driverConstraint'] !== undefined) { + out['driverConstraint'] = hardwareScopeField(input['driverConstraint'], `${path}/driverConstraint`, 128); + } + if (Object.hasOwn(input, 'operatorFamily') && input['operatorFamily'] !== undefined) { + out['operatorFamily'] = hardwareScopeField(input['operatorFamily'], `${path}/operatorFamily`, 64); + } + if (Object.hasOwn(input, 'boundPipeline') && input['boundPipeline'] !== undefined) { + out['boundPipeline'] = hardwareScopeField(input['boundPipeline'], `${path}/boundPipeline`, 64); + } + return Object.freeze(out) as unknown as HardwareMemoryScope; +} +/** + * Symmetric overlap check for two optional hardware scopes (used by conflict and supersession gates). + * An omitted scope or optional sub-field is treated as wildcard-compatible for overlap purposes; + * directional query selection uses `hardwareScopeMatches` in `selector.ts`. + */ +export function hardwareScopesOverlap( + a: HardwareMemoryScope | undefined, + b: HardwareMemoryScope | undefined, +): boolean { + if (a === undefined || b === undefined) return true; + if (a.accelerator !== b.accelerator) return false; + if (a.driverConstraint !== undefined && b.driverConstraint !== undefined && a.driverConstraint !== b.driverConstraint) return false; + if (a.operatorFamily !== undefined && b.operatorFamily !== undefined && a.operatorFamily !== b.operatorFamily) return false; + if (a.boundPipeline !== undefined && b.boundPipeline !== undefined && a.boundPipeline !== b.boundPipeline) return false; + return true; +} const ENTRY_KINDS = ['fact', 'failure_observation', 'invariant'] as const; export function memoryEntrySchema(value: unknown, path = ''): MemoryEntry { const input = objectShape(value, path); @@ -224,7 +305,10 @@ export function memoryEntrySchema(value: unknown, path = ''): MemoryEntry { const kind = text(input['kind'], `${path}/kind`, 1, 32); if (!ENTRY_KINDS.includes(kind as (typeof ENTRY_KINDS)[number])) fail('MEMORY_SCHEMA_INVALID', `${path}/kind`, 'unknown entry kind'); const scope = objectShape(input['scope'], `${path}/scope`); - field(scope, ['taskpack', 'repository', 'paths', 'targetMatrix'], `${path}/scope`); + field(scope, ['taskpack', 'repository', 'paths', 'targetMatrix'], `${path}/scope`, ['hardwareScope']); + const parsedHardwareScope = Object.hasOwn(scope, 'hardwareScope') && scope['hardwareScope'] !== undefined + ? hardwareMemoryScopeSchema(scope['hardwareScope'], `${path}/scope/hardwareScope`) + : undefined; const sourceRef = objectShape(input['sourceRef'], `${path}/sourceRef`); field(sourceRef, ['runId', 'lockHash', 'candidateDigest'], `${path}/sourceRef`); const validFor = objectShape(input['validFor'], `${path}/validFor`); @@ -233,11 +317,23 @@ export function memoryEntrySchema(value: unknown, path = ''): MemoryEntry { const expiresAtMs = integer(input['expiresAtMs'], `${path}/expiresAtMs`, 1); if (expiresAtMs <= verifiedAtMs) fail('MEMORY_SCHEMA_INVALID', `${path}/expiresAtMs`, 'expiresAtMs must exceed verifiedAtMs'); const paths = sortedUnique(scope['paths'], `${path}/scope/paths`, 1, 128, 1024); + const normalizedScope: MemoryEntryScope = parsedHardwareScope === undefined + ? { + taskpack: identifier(scope['taskpack'], `${path}/scope/taskpack`, 128), + repository: repositorySlug(scope['repository'], `${path}/scope/repository`), + paths: paths.map((item, index) => scopePattern(item, `${path}/scope/paths/${index}`)), + targetMatrix: targetMatrix(scope['targetMatrix'], `${path}/scope/targetMatrix`), + } + : { + taskpack: identifier(scope['taskpack'], `${path}/scope/taskpack`, 128), + repository: repositorySlug(scope['repository'], `${path}/scope/repository`), + paths: paths.map((item, index) => scopePattern(item, `${path}/scope/paths/${index}`)), + targetMatrix: targetMatrix(scope['targetMatrix'], `${path}/scope/targetMatrix`), + hardwareScope: parsedHardwareScope, + }; const entry: MemoryEntry = { version: 1, id: identifier(input['id'], `${path}/id`, 128), claimKey: identifier(input['claimKey'], `${path}/claimKey`, 128), claim: memoryClaim(input['claim'], `${path}/claim`), kind: kind as (typeof ENTRY_KINDS)[number], - scope: { taskpack: identifier(scope['taskpack'], `${path}/scope/taskpack`, 128), repository: repositorySlug(scope['repository'], `${path}/scope/repository`), - paths: paths.map((item, index) => scopePattern(item, `${path}/scope/paths/${index}`)), - targetMatrix: targetMatrix(scope['targetMatrix'], `${path}/scope/targetMatrix`) }, + scope: normalizedScope, sourceRef: { runId: identifier(sourceRef['runId'], `${path}/sourceRef/runId`, 128), lockHash: digestShape(sourceRef['lockHash'], `${path}/sourceRef/lockHash`), candidateDigest: digestShape(sourceRef['candidateDigest'], `${path}/sourceRef/candidateDigest`) }, sourceDigest: digestShape(input['sourceDigest'], `${path}/sourceDigest`), verifiedAtMs, diff --git a/packages/memory/src/selector.ts b/packages/memory/src/selector.ts index 07e875c..ad13ebd 100644 --- a/packages/memory/src/selector.ts +++ b/packages/memory/src/selector.ts @@ -24,6 +24,38 @@ function matrixMatches(entry: MemoryEntry, targetCell: MemorySelectorInput['targ return entry.scope.targetMatrix.id === targetCell.id && entry.scope.targetMatrix.platform === targetCell.platform && entry.scope.targetMatrix.variant === targetCell.variant; } +/** + * Directional hardware scope match for memory selection (entry scope vs current target scope). + * `driverConstraint` fails closed when the target omits it (preventing unverified driver transfers), + * while `operatorFamily` and `boundPipeline` are optional narrowers that match when unspecified on + * the target and exclude only explicit mismatches. + */ +function hardwareScopeMatches( + entryScope: MemoryEntry['scope']['hardwareScope'], + targetScope: MemorySelectorInput['hardwareScope'], +): boolean { + if (entryScope === undefined) return true; + if (targetScope == null) return false; + if (entryScope.accelerator !== targetScope.accelerator) return false; + if (entryScope.driverConstraint !== undefined && entryScope.driverConstraint !== targetScope.driverConstraint) { + return false; + } + if ( + entryScope.operatorFamily !== undefined + && targetScope.operatorFamily !== undefined + && entryScope.operatorFamily !== targetScope.operatorFamily + ) { + return false; + } + if ( + entryScope.boundPipeline !== undefined + && targetScope.boundPipeline !== undefined + && entryScope.boundPipeline !== targetScope.boundPipeline + ) { + return false; + } + return true; +} function exclusion(entry: MemoryEntry, reason: ExcludedMemoryEntry['reason'], detail: string): ExcludedMemoryEntry { return { entryId: entry.id, claimKey: entry.claimKey, reason, detail }; } @@ -34,6 +66,7 @@ function ownExclusion( currentCodeFingerprint: MemorySelectorInput['currentCodeFingerprint'], currentUpstreamVersions: MemorySelectorInput['currentUpstreamVersions'], targetCell: MemorySelectorInput['targetCell'], + hardwareScope: MemorySelectorInput['hardwareScope'], ): ExcludedMemoryEntry | null { if ( currentCodeFingerprint != null @@ -52,6 +85,9 @@ function ownExclusion( if (entry.scope.taskpack !== contract.spec.taskpack || entry.scope.repository !== contract.spec.target.repository || !matrixMatches(entry, targetCell)) { return exclusion(entry, 'scope_mismatch', 'entry scope does not match contract taskpack, repository, or target cell'); } + if (!hardwareScopeMatches(entry.scope.hardwareScope, hardwareScope)) { + return exclusion(entry, 'scope_mismatch', 'entry hardwareScope does not match target hardware'); + } const hasPassed = entry.evidenceRefs.some(reference => reference.observedStatus === 'passed'); const hasFailed = entry.evidenceRefs.some(reference => reference.observedStatus === 'failed'); if ((entry.kind === 'fact' || entry.kind === 'invariant') && (!hasPassed || hasFailed)) { @@ -60,6 +96,13 @@ function ownExclusion( if (entry.kind === 'fact' && entry.evidenceRefs.some(reference => reference.observedStatus === 'not_run' || reference.observedStatus === 'blocked')) { return exclusion(entry, 'hardware_or_gate_unproven', 'fact cites a not_run or blocked check as compatibility evidence'); } + if ( + entry.scope.hardwareScope !== undefined + && (entry.kind === 'fact' || entry.kind === 'invariant') + && !entry.evidenceRefs.some(reference => reference.level === 'hardware_execution' && reference.observedStatus === 'passed') + ) { + return exclusion(entry, 'hardware_or_gate_unproven', 'hardware-scoped fact or invariant requires a passed hardware_execution evidence reference'); + } return null; } function sanitizeRenderedClaim(claim: string): string { @@ -88,13 +131,13 @@ function renderMarkdown(taskpack: string, activeEntries: readonly MemoryEntry[]) } /** Excludes expired, superseded, drifted, and unproven entries; the returned snapshot is immutable. */ export function selectActiveMemory(input: MemorySelectorInput): ActiveMemorySnapshot { - const { store, contract, nowMs, currentCodeFingerprint, currentUpstreamVersions, targetCell } = input; + const { store, contract, nowMs, currentCodeFingerprint, currentUpstreamVersions, targetCell, hardwareScope } = input; const indexed = [...store.entries].sort(byId); const currentEntryIds = new Set(indexed.map(entry => entry.id)); const retiredOnly = store.retired.map(row => row.entry).filter(entry => !currentEntryIds.has(entry.id)); const invalid = new Map(); for (const entry of indexed) { - const reason = ownExclusion(entry, contract, currentCodeFingerprint, currentUpstreamVersions, targetCell); + const reason = ownExclusion(entry, contract, currentCodeFingerprint, currentUpstreamVersions, targetCell, hardwareScope); if (reason !== null) invalid.set(entry.id, reason); } const validSuccessorIds = new Set(indexed.filter(entry => !invalid.has(entry.id) && nowMs < entry.expiresAtMs).map(entry => entry.id)); diff --git a/packages/memory/src/types.ts b/packages/memory/src/types.ts index 727caa9..7eb4ec2 100644 --- a/packages/memory/src/types.ts +++ b/packages/memory/src/types.ts @@ -20,11 +20,19 @@ export interface MemoryEvidenceRef { readonly artifact: ArtifactRef; } +export interface HardwareMemoryScope { + readonly accelerator: string; + readonly driverConstraint?: string | undefined; + readonly operatorFamily?: string | undefined; + readonly boundPipeline?: string | undefined; +} + export interface MemoryEntryScope { readonly taskpack: string; readonly repository: string; readonly paths: readonly string[]; readonly targetMatrix: null | { readonly id: string; readonly platform: string; readonly variant: string }; + readonly hardwareScope?: HardwareMemoryScope | undefined; } export interface MemoryEntrySourceRef { @@ -90,7 +98,13 @@ export interface MemoryProposal { readonly operations: readonly MemoryOperation[]; } -export type MemoryGateName = 'memory-schema' | 'provenance' | 'scope' | 'redaction' | 'memory-review'; +export type MemoryGateName = + | 'memory-schema' + | 'provenance' + | 'scope' + | 'redaction' + | 'memory-review' + | 'hardware-evidence'; export type MemoryGateStatus = 'passed' | 'failed'; export type MemoryErrorCode = @@ -100,6 +114,7 @@ export type MemoryErrorCode = | 'MEMORY_SECRET_LEAK' | 'MEMORY_INJECTION_DETECTED' | 'MEMORY_CONFLICT_UNRESOLVED' + | 'MEMORY_HARDWARE_EVIDENCE_REQUIRED' | 'MEMORY_VERIFICATION_FAILED' | 'MEMORY_CAS_CONFLICT' | 'COMPACTION_UNSAFE_BOUNDARY' @@ -174,6 +189,7 @@ export interface MemorySelectorInput { readonly currentCodeFingerprint?: Digest | null | undefined; readonly currentUpstreamVersions?: Readonly> | null | undefined; readonly targetCell: null | { readonly id: string; readonly platform: string; readonly variant: string }; + readonly hardwareScope?: HardwareMemoryScope | null | undefined; readonly maxEntries?: number | undefined; readonly maxBytes?: number | undefined; } @@ -228,6 +244,7 @@ export interface MemoryFinalizerConfig { readonly checkUpstreamVersions?: boolean | undefined; readonly maxEntries?: number | undefined; readonly targetMatrix?: MemoryEntry['scope']['targetMatrix'] | undefined; + readonly hardwareScope?: HardwareMemoryScope | undefined; } export type SettledCycleContext = @@ -359,6 +376,7 @@ export interface CompactionSummaryInput { readonly currentCodeFingerprint?: Digest | null | undefined; readonly currentUpstreamVersions?: Readonly> | null | undefined; readonly targetCell: null | { readonly id: string; readonly platform: string; readonly variant: string }; + readonly hardwareScope?: HardwareMemoryScope | null | undefined; }; } diff --git a/packages/memory/src/verifier.ts b/packages/memory/src/verifier.ts index fe716a5..a24f549 100644 --- a/packages/memory/src/verifier.ts +++ b/packages/memory/src/verifier.ts @@ -1,17 +1,9 @@ import type { Evidence, VerificationResult } from '@loopwright/core'; -import { diagnostic, digestEqual, hasControlCharacter, incidentReferenceDigest, memoryProposalSchema, renderEntryMarkdown } from './schema.js'; +import { diagnostic, digestEqual, hardwareScopesOverlap, hasControlCharacter, incidentReferenceDigest, MEMORY_CREDENTIAL_PATTERNS, memoryProposalSchema, renderEntryMarkdown } from './schema.js'; import { compileScopePattern, isMemoryManagedPath, matchScopePattern, memoryDirectoryFor, normalizeMemoryRoot } from './store.js'; import type { MemoryDiagnostic, MemoryGateResult, MemoryGateName, MemoryOperation, MemoryProposal, MemoryVerificationInput, MemoryVerificationReport } from './types.js'; -const CREDENTIAL_PATTERNS: readonly { readonly source: RegExp; readonly label: string }[] = [ - { source: /ghp_[A-Za-z0-9]{20,}/, label: 'GitHub user token' }, - { source: /ghs_[A-Za-z0-9]{20,}/, label: 'GitHub server token' }, - { source: /github_pat_[A-Za-z0-9_]{20,}/, label: 'GitHub fine-grained token' }, - { source: /sk-[A-Za-z0-9_-]{20,}/, label: 'API key' }, - { source: /Bearer [A-Za-z0-9._~+/=-]{16,}/, label: 'bearer token' }, - { source: /-----BEGIN [A-Z ]*PRIVATE KEY-----/, label: 'private key' }, - { source: /AKIA[0-9A-Z]{16}/, label: 'AWS access key' }, -]; +const CREDENTIAL_PATTERNS = MEMORY_CREDENTIAL_PATTERNS; const INJECTION_PATTERNS: readonly { readonly source: RegExp; readonly label: string }[] = [ { source: /=== .*? ===/, label: 'sentinel header' }, { source: /^REQUIRED:/m, label: 'REQUIRED directive' }, @@ -192,6 +184,26 @@ function redactionGate(input: MemoryVerificationInput, proposal: MemoryProposal) } return gate('redaction', diagnostics); } +function hardwareEvidenceGate(proposal: MemoryProposal): MemoryGateResult { + const diagnostics: MemoryDiagnostic[] = []; + for (const [index, operation] of proposal.operations.entries()) { + if (operation.kind !== 'upsert') continue; + const entry = operation.entry; + if (entry.scope.hardwareScope === undefined) continue; + if (entry.kind !== 'fact' && entry.kind !== 'invariant') continue; + const hasPassingHardwareEvidence = entry.evidenceRefs.some( + reference => reference.level === 'hardware_execution' && reference.observedStatus === 'passed', + ); + if (!hasPassingHardwareEvidence) { + diagnostics.push({ + code: 'MEMORY_HARDWARE_EVIDENCE_REQUIRED', + path: `/proposal/operations/${index}/entry/evidenceRefs`, + detail: `${entry.kind} carrying hardwareScope (${entry.scope.hardwareScope.accelerator}) requires at least one passed hardware_execution evidence reference`, + }); + } + } + return gate('hardware-evidence', diagnostics); +} function conflictGate(input: MemoryVerificationInput, proposal: MemoryProposal): MemoryGateResult { const diagnostics: MemoryDiagnostic[] = []; const push = (path: string, detail: string) => diagnostics.push({ code: 'MEMORY_CONFLICT_UNRESOLVED', path, detail }); @@ -240,7 +252,8 @@ function conflictGate(input: MemoryVerificationInput, proposal: MemoryProposal): && base.scope.taskpack === upsert.entry.scope.taskpack && base.scope.repository === upsert.entry.scope.repository && (base.scope.targetMatrix === null || upsert.entry.scope.targetMatrix === null || (base.scope.targetMatrix.id === upsert.entry.scope.targetMatrix.id && base.scope.targetMatrix.platform === upsert.entry.scope.targetMatrix.platform - && base.scope.targetMatrix.variant === upsert.entry.scope.targetMatrix.variant)); + && base.scope.targetMatrix.variant === upsert.entry.scope.targetMatrix.variant)) + && hardwareScopesOverlap(base.scope.hardwareScope, upsert.entry.scope.hardwareScope); if (!overlapping) continue; const sharedKeys = Object.keys(base.validFor.upstreamVersions).filter(key => Object.hasOwn(upsert.entry.validFor.upstreamVersions, key)); const diverged = sharedKeys.length > 0 && sharedKeys.every(key => upsert.entry.validFor.upstreamVersions[key] !== base.validFor.upstreamVersions[key]); @@ -250,16 +263,28 @@ function conflictGate(input: MemoryVerificationInput, proposal: MemoryProposal): } return gate('memory-review', diagnostics); } -/** Deterministic five-gate verifier; never writes, never mutates its inputs. */ +/** Deterministic six-gate verifier; never writes, never mutates its inputs. */ export function verifyMemoryProposal(input: MemoryVerificationInput): MemoryVerificationReport { const schema = schemaGate(input); const gates: MemoryGateResult[] = [schema.result]; const proposal = schema.proposal; if (proposal === null) { - gates.push(skippedGate('provenance'), skippedGate('scope'), skippedGate('redaction'), skippedGate('memory-review')); + gates.push( + skippedGate('provenance'), + skippedGate('scope'), + skippedGate('redaction'), + skippedGate('memory-review'), + skippedGate('hardware-evidence'), + ); return { gates, satisfied: false }; } - gates.push(provenanceGate(input, proposal), scopeGate(input, proposal), redactionGate(input, proposal), conflictGate(input, proposal)); + gates.push( + provenanceGate(input, proposal), + scopeGate(input, proposal), + redactionGate(input, proposal), + conflictGate(input, proposal), + hardwareEvidenceGate(proposal), + ); return { gates, satisfied: gates.every(gate => gate.status === 'passed') }; } /** Re-checks a proposal after a rebase, verifying the regenerated patch text as well. */ diff --git a/packages/memory/test/finalizer-verifier.test.ts b/packages/memory/test/finalizer-verifier.test.ts index 42d710f..bbd3e43 100644 --- a/packages/memory/test/finalizer-verifier.test.ts +++ b/packages/memory/test/finalizer-verifier.test.ts @@ -593,7 +593,7 @@ describe('five-gate proposal verifier', () => { const report = verifyMemoryProposal(verificationInput(broken as unknown as MemoryProposal, (await loadMemoryStore(root, 'demo', 'org/repo')).index, fixture, outcome.patch ?? '')); assert.deepEqual(gateOf(report, 'memory-schema').codes, ['MEMORY_SCHEMA_INVALID']); assert.equal(report.satisfied, false); - for (const name of ['provenance', 'scope', 'redaction', 'memory-review']) assert.equal(gateOf(report, name).status, 'failed'); + for (const name of ['provenance', 'scope', 'redaction', 'memory-review', 'hardware-evidence']) assert.equal(gateOf(report, name).status, 'failed'); }); }); @@ -785,7 +785,7 @@ describe('five-gate proposal verifier', () => { const outcome = await finalize(fixture, root, finalizerConfig()); const report = verifyMemoryProposal(verificationInput(outcome.proposal!, (await loadMemoryStore(root, 'demo', 'org/repo')).index, fixture, '')); assert.equal(report.satisfied, true); - assert.equal(report.gates.length, 5); + assert.equal(report.gates.length, 6); }); }); diff --git a/packages/memory/test/hardware-scope.test.ts b/packages/memory/test/hardware-scope.test.ts new file mode 100644 index 0000000..92f7954 --- /dev/null +++ b/packages/memory/test/hardware-scope.test.ts @@ -0,0 +1,1118 @@ +import assert from 'node:assert/strict'; +import { createHash } from 'node:crypto'; +import { mkdir, mkdtemp, realpath, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { describe, it } from 'node:test'; +import { + admitTask, + bindSubject, + constructRunResult, + type ArtifactManifest, + type Digest, + type Evidence, + type EvidenceLevel, + type RunStatus, + type TaskContract, +} from '@loopwright/core'; +import { applyMemoryProposalCAS } from '../src/cas.js'; +import { finalizeRunMemory } from '../src/finalizer.js'; +import { + canonical, + hashDomain, + memoryEntrySchema, + parseEntryMarkdown, + renderEntryMarkdown, + storeDigestOf, + MemoryDiagnosticError, +} from '../src/schema.js'; +import { loadMemoryStore, memoryDirectoryFor } from '../src/store.js'; +import { selectActiveMemory } from '../src/selector.js'; +import { verifyMemoryProposal } from '../src/verifier.js'; +import type { + HardwareMemoryScope, + MemoryBudgetLedger, + MemoryEntry, + MemoryFinalizerConfig, + MemoryProposal, + MemoryStoreIndex, + MemoryVerificationInput, +} from '../src/types.js'; +import { + BASE_REVISION, + SOURCE_REVISION, + artifactOf, + digestOf, + inventoryMap, + refOf, + type RunFixture, +} from './run-fixtures.js'; + +function hex(seed: string): Digest { + return { algorithm: 'sha256', hex: createHash('sha256').update(seed).digest('hex') }; +} + +function makeContract( + allowedEvidenceLevels: readonly EvidenceLevel[] = ['local_execution'], + accelerator = 'sm_100a', +): TaskContract { + const isHardware = allowedEvidenceLevels.includes('hardware_execution'); + return { + apiVersion: 'loopwright.dev/v1alpha1', + kind: 'TaskContract', + spec: { + goal: 'hardware kernel optimization', + taskpack: 'demo', + target: { + repository: 'org/repo', + baseRevision: BASE_REVISION, + sourceRevision: SOURCE_REVISION, + matrix: isHardware + ? [ + { + id: 'cuda-b200', + platform: 'linux-x86_64', + variant: 'cuda', + hardware: { + accelerator, + isolationMode: 'whole_device', + deviceCount: 1, + }, + }, + ] + : null, + }, + scope: { writable: ['src/**'], protected: [] }, + roles: [{ id: 'coder', adapter: 'pi', provider: 'prov', model: 'model', thinking: 'off', tools: [] }], + trustedContext: { revision: 'rev.one', discovery: 'disabled', resources: [] }, + budgets: { + wallTimeMs: 60000, + totalTokens: 10000, + perCallOutputTokens: 2000, + maxModelCalls: 10, + maxConcurrency: 2, + maxFormatRepairs: 2, + maxImplementationRepairs: 3, + maxTransportRetries: 3, + enforcement: { + wallTime: 'soft_accounting', + tokens: 'soft_accounting', + modelCalls: 'soft_accounting', + concurrency: 'soft_accounting', + formatRepairs: 'soft_accounting', + implementationRepairs: 'soft_accounting', + transportRetries: 'soft_accounting', + }, + }, + steps: [{ id: 'work', kind: 'agent', uses: 'work', roleId: 'coder', dependsOn: [] }], + acceptance: { + required: ['check.bench'], + checks: [ + { + id: 'check.bench', + allowedEvidenceLevels: [...allowedEvidenceLevels], + ...(isHardware ? { targetCellId: 'cuda-b200' } : {}), + }, + ], + }, + }, + }; +} + +function buildHardwareRun(options: { + readonly status: RunStatus; + readonly level: EvidenceLevel; + readonly accelerator?: string; + readonly runId?: string; +}): RunFixture { + const contract = makeContract([options.level], options.accelerator ?? 'sm_100a'); + const runId = options.runId ?? 'run.hw.one'; + const admitted = admitTask(contract, { admissionId: 'admission.hw', runId }); + if (!admitted.ok) throw new Error(JSON.stringify(admitted.errors)); + const lock = admitted.value; + const candidate = artifactOf('candidate.bin', 'candidate-body'); + const manifest: ArtifactManifest = { + apiVersion: 'loopwright.dev/v1alpha1', + kind: 'ArtifactManifest', + metadata: { id: 'candidate' }, + spec: { entries: [refOf(candidate)] }, + }; + const bound = bindSubject(lock, manifest); + if (!bound.ok) throw new Error(JSON.stringify(bound.errors)); + const subject = bound.value; + const evidenceBytes = artifactOf('evidence-bench.bin', `evidence for ${runId} ${options.status}`); + const passed = options.status === 'completed' || options.status === 'no_change'; + const observedStatus = passed ? 'passed' : options.status === 'blocked' ? 'blocked' : 'failed'; + const hardwareProvenance = options.level === 'hardware_execution' + ? { + targetCellId: 'cuda-b200', + probeKind: 'physical' as const, + vendor: 'nvidia', + deviceModel: 'B200', + accelerator: options.accelerator ?? 'sm_100a', + isolationMode: 'whole_device' as const, + deviceCount: 1, + driverVersion: '570.124.06', + runtimeVersion: 'cuda-12.8', + workloadDigest: hex('workload'), + clockLockMode: 'locked' as const, + } + : undefined; + const evidence: Evidence = { + apiVersion: 'loopwright.dev/v1alpha1', + kind: 'Evidence', + metadata: { id: 'evidence.check.bench' }, + spec: { + checkId: 'check.bench', + observedStatus: observedStatus as Evidence['spec']['observedStatus'], + producerId: 'producer.hw', + method: 'method.bench', + level: options.level, + subject, + artifacts: [refOf(evidenceBytes)], + reason: passed ? null : `fixture ${options.status} observation`, + ...(hardwareProvenance === undefined ? {} : { hardwareProvenance }), + }, + }; + const claims = [ + { + checkId: 'check.bench', + status: observedStatus as 'passed' | 'failed' | 'blocked', + evidenceId: evidence.metadata.id, + reason: passed ? null : `fixture ${options.status} failure`, + }, + ]; + const built = constructRunResult( + { + trusted: { + expectedLock: lock, + candidateManifest: manifest, + eligibleEvidence: [evidence], + usage: [], + externalEffects: 'none', + noChange: null, + }, + candidate: { status: options.status, checks: claims, memory: { status: 'not_requested', reason: null } }, + }, + [candidate, evidenceBytes], + ); + if (!built.ok) throw new Error(JSON.stringify(built.errors)); + return { + lock, + result: built.value, + evidence: [evidence], + manifest, + artifactRefs: [refOf(candidate), refOf(evidenceBytes)], + }; +} + +function makeEntry(overrides: Partial = {}): MemoryEntry { + const base: MemoryEntry = { + version: 1, + id: 'entry.alpha', + claimKey: 'claim.alpha', + claim: 'Stable claim text.', + kind: 'fact', + scope: { taskpack: 'demo', repository: 'org/repo', paths: ['src/**'], targetMatrix: null }, + sourceRef: { runId: 'run.hw.one', lockHash: hex('lock'), candidateDigest: hex('candidate') }, + sourceDigest: hex('source'), + verifiedAtMs: 1000, + validFor: { + baseRevision: BASE_REVISION, + sourceRevision: SOURCE_REVISION, + codeFingerprint: hex('fingerprint'), + upstreamVersions: { npm: '1.0.0' }, + }, + expiresAtMs: 5000, + supersedes: [], + evidenceRefs: [ + { + evidenceId: 'evidence.check.bench', + checkId: 'check.bench', + level: 'local_execution', + observedStatus: 'passed', + artifact: { name: 'evidence-bench.bin', digest: hex('artifact'), byteLength: 10 }, + }, + ], + }; + return Object.freeze({ ...base, ...overrides }) as MemoryEntry; +} + +function makeStore(entries: readonly MemoryEntry[]): MemoryStoreIndex { + const base = { + version: 1 as const, + taskpack: 'demo', + repository: 'org/repo', + updatedAtMs: 1500, + entries, + retired: [], + }; + return { ...base, storeDigest: storeDigestOf(base) }; +} + +function proposalForEntry(fixture: RunFixture, store: MemoryStoreIndex, entry: MemoryEntry): MemoryProposal { + return { + version: 1, + proposalId: 'proposal.hw.one', + taskpack: 'demo', + repository: 'org/repo', + baseRevision: BASE_REVISION, + baseStoreDigest: store.storeDigest, + createdAtMs: 1500, + runId: fixture.lock.spec.runId, + lockHash: fixture.lock.spec.lockHash, + operations: [{ kind: 'upsert', entry }], + }; +} + +function verifyInputFor(fixture: RunFixture, store: MemoryStoreIndex, proposal: MemoryProposal): MemoryVerificationInput { + return { + proposal, + store, + lock: fixture.lock, + result: fixture.result, + incident: null, + evidence: fixture.evidence, + artifacts: new Map(fixture.artifactRefs.map(ref => [ref.name, { byteLength: ref.byteLength, digest: ref.digest }])), + candidateDigest: fixture.result.spec.subject.candidateDigest, + patch: '', + secretValues: [], + memoryWritable: [memoryDirectoryFor('demo')], + protectedPaths: [], + }; +} + +function entryBoundToFixture( + fixture: RunFixture, + overrides: { + readonly id?: string; + readonly claimKey?: string; + readonly kind?: MemoryEntry['kind']; + readonly hardwareScope?: HardwareMemoryScope; + readonly supersedes?: readonly string[]; + } = {}, +): MemoryEntry { + const ev = fixture.evidence[0]!; + return makeEntry({ + id: overrides.id ?? 'entry.hw.fact', + claimKey: overrides.claimKey ?? 'claim.hw.tma', + claim: 'Verified hardware kernel behavior.', + kind: overrides.kind ?? 'fact', + scope: { + taskpack: 'demo', + repository: 'org/repo', + paths: ['src/**'], + targetMatrix: null, + ...(overrides.hardwareScope === undefined ? {} : { hardwareScope: overrides.hardwareScope }), + }, + sourceRef: { + runId: fixture.lock.spec.runId, + lockHash: fixture.lock.spec.lockHash, + candidateDigest: fixture.result.spec.subject.candidateDigest, + }, + supersedes: overrides.supersedes ?? [], + evidenceRefs: [ + { + evidenceId: ev.metadata.id, + checkId: ev.spec.checkId, + level: ev.spec.level, + observedStatus: ev.spec.observedStatus, + artifact: ev.spec.artifacts[0]!, + }, + ], + }); +} + +describe('hardwareScope schema validation and v1 digest parity', () => { + it('omits hardwareScope when undefined so v1 canonical JSON, storeDigest, and proposalDigest remain byte-for-byte identical', () => { + const legacyRaw = { + version: 1, + id: 'entry.legacy', + claimKey: 'claim.legacy', + claim: 'Legacy v1 claim.', + kind: 'fact', + scope: { taskpack: 'demo', repository: 'org/repo', paths: ['src/**'], targetMatrix: null }, + sourceRef: { runId: 'run.one', lockHash: digestOf('lock'), candidateDigest: digestOf('cand') }, + sourceDigest: digestOf('src'), + verifiedAtMs: 1000, + validFor: { + baseRevision: BASE_REVISION, + sourceRevision: SOURCE_REVISION, + codeFingerprint: digestOf('fp'), + upstreamVersions: { npm: '1.0.0' }, + }, + expiresAtMs: 2000, + supersedes: [], + evidenceRefs: [ + { + evidenceId: 'ev.one', + checkId: 'check.one', + level: 'local_execution', + observedStatus: 'passed', + artifact: { name: 'artifacts/ev.json', digest: digestOf('art'), byteLength: 12 }, + }, + ], + }; + + const parsed = memoryEntrySchema(legacyRaw, '/entry'); + assert.equal(Object.hasOwn(parsed.scope, 'hardwareScope'), false); + assert.equal(canonical(parsed), canonical(legacyRaw)); + + const parsedWithUndefined = memoryEntrySchema( + { ...legacyRaw, scope: { ...legacyRaw.scope, hardwareScope: undefined } }, + '/entry', + ); + assert.equal(Object.hasOwn(parsedWithUndefined.scope, 'hardwareScope'), false); + assert.equal(canonical(parsedWithUndefined), canonical(legacyRaw)); + + const legacyStoreBase = { + version: 1 as const, + taskpack: 'demo', + repository: 'org/repo', + updatedAtMs: 1500, + entries: [legacyRaw as unknown as MemoryEntry], + retired: [], + }; + const parsedStoreBase = { ...legacyStoreBase, entries: [parsed] }; + assert.equal(storeDigestOf(parsedStoreBase).hex, storeDigestOf(legacyStoreBase).hex); + + const legacyProposal = { + version: 1, + proposalId: 'proposal.legacy', + taskpack: 'demo', + repository: 'org/repo', + baseRevision: BASE_REVISION, + baseStoreDigest: storeDigestOf(legacyStoreBase), + createdAtMs: 1500, + runId: 'run.one', + lockHash: digestOf('lock'), + operations: [{ kind: 'upsert', entry: legacyRaw }], + }; + const parsedProposal = { ...legacyProposal, operations: [{ kind: 'upsert', entry: parsed }] }; + assert.equal( + hashDomain('memory-proposal', parsedProposal).hex, + hashDomain('memory-proposal', legacyProposal).hex, + ); + + const md = renderEntryMarkdown(parsed); + const reparsed = parseEntryMarkdown(Buffer.from(md, 'utf8'), 'entry.legacy.md'); + assert.equal(canonical(reparsed), canonical(legacyRaw)); + }); + + it('round-trips valid hardwareScope and omits undefined optional fields', () => { + const entry = makeEntry({ + scope: { + taskpack: 'demo', + repository: 'org/repo', + paths: ['src/**'], + targetMatrix: null, + hardwareScope: { + accelerator: 'sm_100a', + driverConstraint: '>=570.0', + operatorFamily: 'flash_decode', + boundPipeline: 'tensor_cube', + }, + }, + }); + const parsed = memoryEntrySchema(entry, '/entry'); + assert.deepEqual({ ...parsed.scope.hardwareScope }, { + accelerator: 'sm_100a', + driverConstraint: '>=570.0', + operatorFamily: 'flash_decode', + boundPipeline: 'tensor_cube', + }); + const md = renderEntryMarkdown(parsed); + const reparsed = parseEntryMarkdown(Buffer.from(md, 'utf8'), 'entry.alpha.md'); + assert.equal(canonical(reparsed), canonical(parsed)); + + const minimal = memoryEntrySchema( + makeEntry({ + scope: { + taskpack: 'demo', + repository: 'org/repo', + paths: ['src/**'], + targetMatrix: null, + hardwareScope: { accelerator: 'ascend_910b', driverConstraint: undefined }, + }, + }), + '/entry', + ); + assert.equal(Object.hasOwn(minimal.scope.hardwareScope!, 'driverConstraint'), false); + assert.equal(Object.hasOwn(minimal.scope.hardwareScope!, 'operatorFamily'), false); + assert.equal(Object.hasOwn(minimal.scope.hardwareScope!, 'boundPipeline'), false); + assert.equal(minimal.scope.hardwareScope!.accelerator, 'ascend_910b'); + }); + + it('rejects malformed, prototype-polluting, lone-surrogate, unknown-key, and secret-bearing hardwareScope values', () => { + const base = makeEntry(); + const withRawScope = (hardwareScope: unknown) => ({ + ...base, + scope: { ...base.scope, hardwareScope }, + }); + + // null, non-object, missing/empty/whitespace accelerator + assert.throws(() => memoryEntrySchema(withRawScope(null)), MemoryDiagnosticError); + assert.throws(() => memoryEntrySchema(withRawScope('sm_100a')), MemoryDiagnosticError); + assert.throws(() => memoryEntrySchema(withRawScope({})), MemoryDiagnosticError); + assert.throws(() => memoryEntrySchema(withRawScope({ accelerator: '' })), MemoryDiagnosticError); + assert.throws(() => memoryEntrySchema(withRawScope({ accelerator: ' ' })), MemoryDiagnosticError); + assert.throws(() => memoryEntrySchema(withRawScope({ accelerator: 'a'.repeat(65) })), MemoryDiagnosticError); + + // unknown keys and prototype pollution keys + assert.throws(() => memoryEntrySchema(withRawScope({ accelerator: 'sm_100a', extra: 'nope' })), MemoryDiagnosticError); + const protoPayload = JSON.parse('{"accelerator":"sm_100a","__proto__":{"polluted":true}}') as unknown; + assert.throws(() => memoryEntrySchema(withRawScope(protoPayload)), MemoryDiagnosticError); + assert.throws(() => memoryEntrySchema(withRawScope({ accelerator: 'sm_100a', constructor: 'bad' })), MemoryDiagnosticError); + assert.throws(() => memoryEntrySchema(withRawScope({ accelerator: 'sm_100a', prototype: 'bad' })), MemoryDiagnosticError); + + // lone surrogates and non-ASCII / control characters + assert.throws(() => memoryEntrySchema(withRawScope({ accelerator: 'sm_\uD800' })), MemoryDiagnosticError); + assert.throws(() => memoryEntrySchema(withRawScope({ accelerator: 'sm_100a', driverConstraint: '>=570\n0' })), MemoryDiagnosticError); + assert.throws(() => memoryEntrySchema(withRawScope({ accelerator: 'sm_100a', operatorFamily: 'gemm\u0007' })), MemoryDiagnosticError); + assert.throws(() => memoryEntrySchema(withRawScope({ accelerator: 'sm_100a', boundPipeline: 'tensor_é' })), MemoryDiagnosticError); + + // secret/credential patterns fail closed with MEMORY_SECRET_LEAK + assert.throws( + () => memoryEntrySchema(withRawScope({ accelerator: 'sm_100a', driverConstraint: 'ghp_1234567890123456789012345' })), + (error: unknown) => error instanceof MemoryDiagnosticError && error.code === 'MEMORY_SECRET_LEAK', + ); + assert.throws( + () => memoryEntrySchema(withRawScope({ accelerator: 'sm_100a', operatorFamily: 'sk-1234567890123456789012345' })), + (error: unknown) => error instanceof MemoryDiagnosticError && error.code === 'MEMORY_SECRET_LEAK', + ); + }); +}); + +describe('6th verification gate: hardware-evidence', () => { + it('admits hardware-scoped fact and invariant backed by passed hardware_execution evidence', () => { + const fixture = buildHardwareRun({ status: 'completed', level: 'hardware_execution', accelerator: 'sm_100a' }); + const store = makeStore([]); + + for (const kind of ['fact', 'invariant'] as const) { + const entry = entryBoundToFixture(fixture, { + id: `entry.hw.${kind}`, + claimKey: `claim.hw.${kind}`, + kind, + hardwareScope: { accelerator: 'sm_100a', driverConstraint: '>=570.0', boundPipeline: 'tensor_cube' }, + }); + const report = verifyMemoryProposal(verifyInputFor(fixture, store, proposalForEntry(fixture, store, entry))); + assert.equal(report.gates.length, 6); + assert.equal(report.satisfied, true); + const hwGate = report.gates.find(g => g.gate === 'hardware-evidence'); + assert.ok(hwGate !== undefined); + assert.equal(hwGate.status, 'passed'); + assert.deepEqual(hwGate.diagnostics, []); + } + }); + + it('rejects hardware-scoped fact and invariant lacking passed hardware_execution evidence with MEMORY_HARDWARE_EVIDENCE_REQUIRED', () => { + const store = makeStore([]); + + for (const level of ['local_execution', 'synthetic_fixture', 'static_inspection'] as const) { + const fixture = buildHardwareRun({ status: 'completed', level, runId: `run.hw.${level}` }); + for (const kind of ['fact', 'invariant'] as const) { + const entry = entryBoundToFixture(fixture, { + id: `entry.${level}.${kind}`, + claimKey: `claim.${level}.${kind}`, + kind, + hardwareScope: { accelerator: 'sm_100a' }, + }); + const report = verifyMemoryProposal(verifyInputFor(fixture, store, proposalForEntry(fixture, store, entry))); + assert.equal(report.satisfied, false); + const hwGate = report.gates.find(g => g.gate === 'hardware-evidence'); + assert.ok(hwGate !== undefined); + assert.equal(hwGate.status, 'failed'); + assert.deepEqual( + hwGate.diagnostics.map(d => d.code), + ['MEMORY_HARDWARE_EVIDENCE_REQUIRED'], + ); + } + } + + // Failed hardware_execution evidence must also fail closed for fact/invariant + const failedHwFixture = buildHardwareRun({ status: 'failed', level: 'hardware_execution', runId: 'run.hw.failed' }); + const failedFact = entryBoundToFixture(failedHwFixture, { + id: 'entry.hw.failed.fact', + kind: 'fact', + hardwareScope: { accelerator: 'sm_100a' }, + }); + const failedReport = verifyMemoryProposal(verifyInputFor(failedHwFixture, store, proposalForEntry(failedHwFixture, store, failedFact))); + assert.equal(failedReport.satisfied, false); + const failedHwGate = failedReport.gates.find(g => g.gate === 'hardware-evidence'); + assert.ok(failedHwGate !== undefined); + assert.equal(failedHwGate.status, 'failed'); + assert.deepEqual( + failedHwGate.diagnostics.map(d => d.code), + ['MEMORY_HARDWARE_EVIDENCE_REQUIRED'], + ); + }); + + it('admits hardware-scoped failure_observation without requiring a passing hardware_execution ref', () => { + const failedLocal = buildHardwareRun({ status: 'failed', level: 'local_execution', runId: 'run.hw.trap' }); + const store = makeStore([]); + const trapEntry = entryBoundToFixture(failedLocal, { + id: 'entry.hw.trap', + claimKey: 'claim.hw.trap', + kind: 'failure_observation', + hardwareScope: { accelerator: 'ascend_910b', operatorFamily: 'matmul' }, + }); + const report = verifyMemoryProposal(verifyInputFor(failedLocal, store, proposalForEntry(failedLocal, store, trapEntry))); + assert.equal(report.satisfied, true); + const hwGate = report.gates.find(g => g.gate === 'hardware-evidence'); + assert.ok(hwGate !== undefined); + assert.equal(hwGate.status, 'passed'); + }); + + it('allows disjoint hardwareScope entries with the same claimKey without conflict in memory-review', () => { + const fixture = buildHardwareRun({ status: 'completed', level: 'hardware_execution', accelerator: 'sm_89' }); + const existingSm100a = entryBoundToFixture(fixture, { + id: 'entry.sm100a', + claimKey: 'claim.shared.tile', + kind: 'fact', + hardwareScope: { accelerator: 'sm_100a' }, + }); + const store = makeStore([existingSm100a]); + const newSm89 = entryBoundToFixture(fixture, { + id: 'entry.sm89', + claimKey: 'claim.shared.tile', + kind: 'fact', + hardwareScope: { accelerator: 'sm_89' }, + }); + const report = verifyMemoryProposal(verifyInputFor(fixture, store, proposalForEntry(fixture, store, newSm89))); + assert.equal(report.satisfied, true); + }); +}); + +describe('active memory selector hardwareScope filtering', () => { + const contract = makeContract(); + + function hwEntry( + id: string, + hardwareScope: HardwareMemoryScope | undefined, + overrides: Partial = {}, + ): MemoryEntry { + return makeEntry({ + id, + claimKey: `claim.${id}`, + scope: { + taskpack: 'demo', + repository: 'org/repo', + paths: ['src/**'], + targetMatrix: null, + ...(hardwareScope === undefined ? {} : { hardwareScope }), + }, + evidenceRefs: [ + { + evidenceId: `ev.${id}`, + checkId: 'check.bench', + level: hardwareScope === undefined ? 'local_execution' : 'hardware_execution', + observedStatus: 'passed', + artifact: { name: `artifacts/${id}.json`, digest: hex(id), byteLength: 10 }, + }, + ], + ...overrides, + }); + } + + it('isolates sm_100a, sm_89, and ascend_910b entries while keeping unscoped entries eligible everywhere', () => { + const unscoped = hwEntry('entry.unscoped', undefined); + const sm100a = hwEntry('entry.sm100a', { accelerator: 'sm_100a' }); + const sm89 = hwEntry('entry.sm89', { accelerator: 'sm_89' }); + const ascend = hwEntry('entry.ascend', { accelerator: 'ascend_910b' }); + const store = makeStore([unscoped, sm100a, sm89, ascend]); + + // Target sm_89: admits unscoped + sm_89; excludes sm_100a + ascend_910b + const forSm89 = selectActiveMemory({ + store, + contract, + nowMs: 1500, + currentCodeFingerprint: hex('fingerprint'), + currentUpstreamVersions: { npm: '1.0.0' }, + targetCell: null, + hardwareScope: { accelerator: 'sm_89' }, + }); + assert.deepEqual(forSm89.activeEntries.map(e => e.id), ['entry.sm89', 'entry.unscoped']); + assert.deepEqual( + forSm89.excludedEntries.map(e => [e.entryId, e.reason]), + [ + ['entry.ascend', 'scope_mismatch'], + ['entry.sm100a', 'scope_mismatch'], + ], + ); + + // Target ascend_910b: admits unscoped + ascend_910b + const forAscend = selectActiveMemory({ + store, + contract, + nowMs: 1500, + currentCodeFingerprint: hex('fingerprint'), + currentUpstreamVersions: { npm: '1.0.0' }, + targetCell: null, + hardwareScope: { accelerator: 'ascend_910b' }, + }); + assert.deepEqual(forAscend.activeEntries.map(e => e.id), ['entry.ascend', 'entry.unscoped']); + + // Omitting hardwareScope fails closed: excludes all hardware-scoped entries, keeps unscoped + const forUnscopedRun = selectActiveMemory({ + store, + contract, + nowMs: 1500, + currentCodeFingerprint: hex('fingerprint'), + currentUpstreamVersions: { npm: '1.0.0' }, + targetCell: null, + }); + assert.deepEqual(forUnscopedRun.activeEntries.map(e => e.id), ['entry.unscoped']); + assert.deepEqual( + forUnscopedRun.excludedEntries.map(e => [e.entryId, e.reason]), + [ + ['entry.ascend', 'scope_mismatch'], + ['entry.sm100a', 'scope_mismatch'], + ['entry.sm89', 'scope_mismatch'], + ], + ); + }); + + it('enforces driverConstraint fail-closed and optional operatorFamily/boundPipeline matching', () => { + const driverPinned = hwEntry('entry.driver.pinned', { + accelerator: 'sm_100a', + driverConstraint: '>=570.0', + }); + const driverAgnostic = hwEntry('entry.driver.any', { + accelerator: 'sm_100a', + }); + const gemmTensor = hwEntry('entry.gemm.tensor', { + accelerator: 'sm_100a', + operatorFamily: 'gemm', + boundPipeline: 'tensor_cube', + }); + const attnHbm = hwEntry('entry.attn.hbm', { + accelerator: 'sm_100a', + operatorFamily: 'attention', + boundPipeline: 'hbm', + }); + const store = makeStore([driverPinned, driverAgnostic, gemmTensor, attnHbm]); + + // Target omits driverConstraint: driverPinned must be excluded fail-closed! + const noDriverTarget = selectActiveMemory({ + store, + contract, + nowMs: 1500, + targetCell: null, + hardwareScope: { accelerator: 'sm_100a' }, + }); + assert.deepEqual(noDriverTarget.activeEntries.map(e => e.id), [ + 'entry.attn.hbm', + 'entry.driver.any', + 'entry.gemm.tensor', + ]); + assert.deepEqual( + noDriverTarget.excludedEntries.map(e => [e.entryId, e.reason]), + [['entry.driver.pinned', 'scope_mismatch']], + ); + + // Target has mismatched driverConstraint: driverPinned excluded + const wrongDriver = selectActiveMemory({ + store, + contract, + nowMs: 1500, + targetCell: null, + hardwareScope: { accelerator: 'sm_100a', driverConstraint: '>=550.0' }, + }); + assert.equal(wrongDriver.activeEntries.some(e => e.id === 'entry.driver.pinned'), false); + + // Target matches driverConstraint + operatorFamily + boundPipeline + const exactMatch = selectActiveMemory({ + store, + contract, + nowMs: 1500, + targetCell: null, + hardwareScope: { + accelerator: 'sm_100a', + driverConstraint: '>=570.0', + operatorFamily: 'gemm', + boundPipeline: 'tensor_cube', + }, + }); + assert.deepEqual(exactMatch.activeEntries.map(e => e.id), [ + 'entry.driver.any', + 'entry.driver.pinned', + 'entry.gemm.tensor', + ]); + assert.deepEqual( + exactMatch.excludedEntries.map(e => [e.entryId, e.reason]), + [['entry.attn.hbm', 'scope_mismatch']], + ); + }); + + it('excludes hardware-scoped facts lacking hardware_execution evidence while admitting hardware-scoped failure_observation', () => { + const unprovenFact = hwEntry('entry.unproven.fact', { accelerator: 'sm_100a' }, { + kind: 'fact', + evidenceRefs: [ + { + evidenceId: 'ev.local', + checkId: 'check.bench', + level: 'local_execution', + observedStatus: 'passed', + artifact: { name: 'artifacts/local.json', digest: hex('local'), byteLength: 10 }, + }, + ], + }); + const trapFailure = hwEntry('entry.trap.fail', { accelerator: 'sm_100a' }, { + kind: 'failure_observation', + evidenceRefs: [ + { + evidenceId: 'ev.fail', + checkId: 'check.bench', + level: 'local_execution', + observedStatus: 'failed', + artifact: { name: 'artifacts/fail.json', digest: hex('fail'), byteLength: 10 }, + }, + ], + }); + const store = makeStore([unprovenFact, trapFailure]); + + const snap = selectActiveMemory({ + store, + contract, + nowMs: 1500, + targetCell: null, + hardwareScope: { accelerator: 'sm_100a' }, + }); + assert.deepEqual(snap.activeEntries.map(e => e.id), ['entry.trap.fail']); + assert.deepEqual( + snap.excludedEntries.map(e => [e.entryId, e.reason]), + [['entry.unproven.fact', 'hardware_or_gate_unproven']], + ); + }); +}); + +describe('finalizer hardwareScope gating integration', () => { + function buildMixedHardwareRun(options: { + readonly runId: string; + readonly status: 'completed' | 'failed'; + readonly accelerator: string; + }): RunFixture { + const contract: TaskContract = { + ...makeContract(['hardware_execution'], options.accelerator), + spec: { + ...makeContract(['hardware_execution'], options.accelerator).spec, + acceptance: { + required: ['evolve-block-guard.v1', 'benchmark-gate.v1'], + checks: [ + { id: 'evolve-block-guard.v1', allowedEvidenceLevels: ['local_execution'] }, + { id: 'benchmark-gate.v1', allowedEvidenceLevels: ['hardware_execution'], targetCellId: 'cuda-b200' }, + ], + }, + }, + }; + const admitted = admitTask(contract, { admissionId: `admission.${options.runId}`, runId: options.runId }); + if (!admitted.ok) throw new Error(JSON.stringify(admitted.errors)); + const lock = admitted.value; + const candidate = artifactOf('candidate.bin', `candidate-${options.runId}`); + const manifest: ArtifactManifest = { + apiVersion: 'loopwright.dev/v1alpha1', + kind: 'ArtifactManifest', + metadata: { id: 'candidate' }, + spec: { entries: [refOf(candidate)] }, + }; + const bound = bindSubject(lock, manifest); + if (!bound.ok) throw new Error(JSON.stringify(bound.errors)); + const subject = bound.value; + + const passed = options.status === 'completed'; + const observedStatus = passed ? 'passed' : 'failed'; + const localArtifact = artifactOf('evidence-guard.bin', `guard-${options.runId}-${options.status}`); + const hwArtifact = artifactOf('evidence-bench.bin', `bench-${options.runId}-${options.status}`); + + const localEvidence: Evidence = { + apiVersion: 'loopwright.dev/v1alpha1', + kind: 'Evidence', + metadata: { id: 'evidence.evolve-block-guard.v1' }, + spec: { + checkId: 'evolve-block-guard.v1', + observedStatus, + producerId: 'producer.guard', + method: 'evolve-block-guard', + level: 'local_execution', + subject: structuredClone(subject), + artifacts: [refOf(localArtifact)], + reason: passed ? null : 'guard violation', + }, + }; + const hwEvidence: Evidence = { + apiVersion: 'loopwright.dev/v1alpha1', + kind: 'Evidence', + metadata: { id: 'evidence.benchmark-gate.v1' }, + spec: { + checkId: 'benchmark-gate.v1', + observedStatus, + producerId: 'producer.hw', + method: 'benchmark-gate', + level: 'hardware_execution', + subject: structuredClone(subject), + artifacts: [refOf(hwArtifact)], + reason: passed ? null : 'benchmark regression', + hardwareProvenance: { + targetCellId: 'cuda-b200', + probeKind: 'physical', + vendor: 'nvidia', + deviceModel: 'B200', + accelerator: options.accelerator, + isolationMode: 'whole_device', + deviceCount: 1, + driverVersion: '570.124.06', + runtimeVersion: 'cuda-12.8', + workloadDigest: hex('workload'), + clockLockMode: 'locked', + }, + }, + }; + const claims = [ + { + checkId: 'evolve-block-guard.v1', + status: observedStatus as 'passed' | 'failed', + evidenceId: localEvidence.metadata.id, + reason: passed ? null : 'guard violation', + }, + { + checkId: 'benchmark-gate.v1', + status: observedStatus as 'passed' | 'failed', + evidenceId: hwEvidence.metadata.id, + reason: passed ? null : 'benchmark regression', + }, + ]; + const built = constructRunResult( + { + trusted: { + expectedLock: lock, + candidateManifest: manifest, + eligibleEvidence: [localEvidence, hwEvidence], + usage: [], + externalEffects: 'none', + noChange: null, + }, + candidate: { status: options.status, checks: claims, memory: { status: 'not_requested', reason: null } }, + }, + [candidate, localArtifact, hwArtifact], + ); + if (!built.ok) throw new Error(JSON.stringify(built.errors)); + return { + lock, + result: built.value, + evidence: [localEvidence, hwEvidence], + manifest, + artifactRefs: [refOf(candidate), refOf(localArtifact), refOf(hwArtifact)], + }; + } + + it('omits hardwareScope on local_execution facts, retains it on hardware_execution facts and failure_observations, and passes verify + CAS', async () => { + const hardwareScope: HardwareMemoryScope = { + accelerator: 'sm_100a', + driverConstraint: '>=570.0', + operatorFamily: 'gemm', + boundPipeline: 'tensor_cube', + }; + const ledger: MemoryBudgetLedger = { + revision: 1, + remainingTokens: 1000, + remainingModelCalls: 5, + remainingWallMs: 60000, + }; + const makeConfig = (nowMs: number): MemoryFinalizerConfig => ({ + taskpack: 'demo', + memoryWritable: [memoryDirectoryFor('demo')], + onNoModelBudget: 'deterministic-observations-only', + nowMs, + ttlMs: 86_400_000, + upstreamVersions: { npm: '1.0.0' }, + hardwareScope, + }); + + const root = await mkdtemp(join(await realpath(tmpdir()), 'loopwright-hw-finalizer-')); + try { + await mkdir(join(root, 'src'), { recursive: true }); + await writeFile(join(root, 'src', 'kernel.cu'), '// kernel', { mode: 0o600 }); + + // 1. Failed hardware run: failure_observation entries retain hardwareScope (even for local_execution checks) + const failedRun = buildMixedHardwareRun({ runId: 'run.hw.fail', status: 'failed', accelerator: 'sm_100a' }); + const failedOutcome = await finalizeRunMemory({ + context: { + kind: 'summary', + repository: root, + summary: { + lock: failedRun.lock, + result: failedRun.result, + incident: null, + observations: [], + evidence: failedRun.evidence, + ledger, + candidateManifest: failedRun.manifest.spec.entries, + artifacts: failedRun.artifactRefs, + }, + }, + config: makeConfig(1000), + }); + assert.equal(failedOutcome.status, 'proposed'); + assert.ok(failedOutcome.proposal !== null); + assert.equal(failedOutcome.deterministicEntries.length, 2); + for (const entry of failedOutcome.deterministicEntries) { + assert.equal(entry.kind, 'failure_observation'); + assert.deepEqual({ ...entry.scope.hardwareScope }, hardwareScope); + } + + const emptyStore = (await loadMemoryStore(root, 'demo', 'org/repo')).index; + const failedReport = verifyMemoryProposal({ + proposal: failedOutcome.proposal, + store: emptyStore, + lock: failedRun.lock, + result: failedRun.result, + incident: null, + evidence: failedRun.evidence, + artifacts: inventoryMap(failedRun), + candidateDigest: failedRun.result.spec.subject.candidateDigest, + patch: failedOutcome.patch ?? '', + secretValues: [], + memoryWritable: [memoryDirectoryFor('demo')], + protectedPaths: [], + }); + assert.equal(failedReport.satisfied, true); + assert.deepEqual(failedReport.gates.flatMap(g => g.diagnostics), []); + + const failedCas = await applyMemoryProposalCAS({ + repository: root, + taskpack: 'demo', + proposal: failedOutcome.proposal, + lock: failedRun.lock, + result: failedRun.result, + incident: null, + evidence: failedRun.evidence, + artifacts: inventoryMap(failedRun), + candidateDigest: failedRun.result.spec.subject.candidateDigest, + secretValues: [], + memoryWritable: [memoryDirectoryFor('demo')], + protectedPaths: [], + targetBranch: 'main', + currentRevision: BASE_REVISION, + baseStore: emptyStore, + allowRebase: true, + nowMs: 1000, + }); + assert.equal(failedCas.applied, true); + + // 2. Completed hardware run with passing local_execution + passing hardware_execution checks + const completedRun = buildMixedHardwareRun({ runId: 'run.hw.pass', status: 'completed', accelerator: 'sm_100a' }); + const completedOutcome = await finalizeRunMemory({ + context: { + kind: 'summary', + repository: root, + summary: { + lock: completedRun.lock, + result: completedRun.result, + incident: null, + observations: [], + evidence: completedRun.evidence, + ledger, + candidateManifest: completedRun.manifest.spec.entries, + artifacts: completedRun.artifactRefs, + }, + }, + config: makeConfig(2000), + }); + assert.equal(completedOutcome.status, 'proposed'); + assert.ok(completedOutcome.proposal !== null); + assert.equal(completedOutcome.deterministicEntries.length, 2); + + const localFact = completedOutcome.deterministicEntries.find(e => e.claimKey === 'claim.check.evolve-block-guard.v1'); + const hwFact = completedOutcome.deterministicEntries.find(e => e.claimKey === 'claim.check.benchmark-gate.v1'); + assert.ok(localFact !== undefined); + assert.ok(hwFact !== undefined); + assert.equal(localFact.kind, 'fact'); + assert.equal(hwFact.kind, 'fact'); + assert.equal(Object.hasOwn(localFact.scope, 'hardwareScope'), false); + assert.deepEqual({ ...hwFact.scope.hardwareScope }, hardwareScope); + assert.equal(localFact.supersedes.length, 1); + assert.equal(hwFact.supersedes.length, 1); + + const storeBeforePass = (await loadMemoryStore(root, 'demo', 'org/repo')).index; + const completedReport = verifyMemoryProposal({ + proposal: completedOutcome.proposal, + store: storeBeforePass, + lock: completedRun.lock, + result: completedRun.result, + incident: null, + evidence: completedRun.evidence, + artifacts: inventoryMap(completedRun), + candidateDigest: completedRun.result.spec.subject.candidateDigest, + patch: completedOutcome.patch ?? '', + secretValues: [], + memoryWritable: [memoryDirectoryFor('demo')], + protectedPaths: [], + }); + assert.equal(completedReport.gates.length, 6); + assert.equal(completedReport.satisfied, true); + assert.deepEqual(completedReport.gates.flatMap(g => g.diagnostics), []); + + const completedCas = await applyMemoryProposalCAS({ + repository: root, + taskpack: 'demo', + proposal: completedOutcome.proposal, + lock: completedRun.lock, + result: completedRun.result, + incident: null, + evidence: completedRun.evidence, + artifacts: inventoryMap(completedRun), + candidateDigest: completedRun.result.spec.subject.candidateDigest, + secretValues: [], + memoryWritable: [memoryDirectoryFor('demo')], + protectedPaths: [], + targetBranch: 'main', + currentRevision: BASE_REVISION, + baseStore: storeBeforePass, + allowRebase: true, + nowMs: 2000, + }); + assert.equal(completedCas.applied, true); + + const finalStore = (await loadMemoryStore(root, 'demo', 'org/repo')).index; + assert.equal(finalStore.entries.length, 2); + const persistedLocal = finalStore.entries.find(e => e.claimKey === 'claim.check.evolve-block-guard.v1'); + const persistedHw = finalStore.entries.find(e => e.claimKey === 'claim.check.benchmark-gate.v1'); + assert.ok(persistedLocal !== undefined && Object.hasOwn(persistedLocal.scope, 'hardwareScope') === false); + assert.ok(persistedHw !== undefined && persistedHw.scope.hardwareScope?.accelerator === 'sm_100a'); + + // 3. A local_execution pass on gfx942 must NOT silently widen and clobber sm_100a's hardware-scoped benchmark fact + const gfxScope: HardwareMemoryScope = { accelerator: 'gfx942', driverConstraint: '>=6.2.0' }; + const gfxRun = buildMixedHardwareRun({ runId: 'run.gfx.pass', status: 'completed', accelerator: 'gfx942' }); + const gfxLocalOnlyEvidence = gfxRun.evidence.map(ev => + ev.spec.checkId === 'benchmark-gate.v1' + ? { ...ev, spec: { ...ev.spec, level: 'local_execution' as const } } + : ev, + ); + const gfxOutcome = await finalizeRunMemory({ + context: { + kind: 'summary', + repository: root, + summary: { + lock: gfxRun.lock, + result: gfxRun.result, + incident: null, + observations: [], + evidence: gfxLocalOnlyEvidence, + ledger, + candidateManifest: gfxRun.manifest.spec.entries, + artifacts: gfxRun.artifactRefs, + }, + }, + config: { ...makeConfig(3000), hardwareScope: gfxScope }, + }); + assert.equal( + gfxOutcome.deterministicEntries.some(e => e.claimKey === 'claim.check.benchmark-gate.v1'), + false, + 'local_execution pass on gfx942 must not emit hardware-universal fact clobbering sm_100a entry', + ); + assert.match(gfxOutcome.reason ?? '', /hardware_evidence_required_skipped:1/); + } finally { + await rm(root, { recursive: true, force: true }); + } + }); +}); diff --git a/packages/taskpack-runner/src/compile-taskpack.ts b/packages/taskpack-runner/src/compile-taskpack.ts index bedead1..e6db6fe 100644 --- a/packages/taskpack-runner/src/compile-taskpack.ts +++ b/packages/taskpack-runner/src/compile-taskpack.ts @@ -118,6 +118,15 @@ export type RunnerLocalCheckPlan = readonly startMarker: string; readonly endMarker: string; }; + } + | { + readonly id: string; + readonly implementation: 'evolve-block-guard.v1'; + readonly parameters: { + readonly files: readonly string[]; + readonly allowedBlockIds?: readonly string[]; + readonly maxBlockBytes?: number; + }; }; export interface CompileRunnerTaskpackOptions { @@ -406,7 +415,7 @@ export async function compileRunnerTaskpack(options: CompileRunnerTaskpackOption type CandidateCheckDef = { readonly id: string; readonly kind: 'check'; - readonly implementation: 'json-artifact.v1' | 'json-keys-guard.v1' | 'line-section-guard.v1' | 'gate.v1' | 'no-change.v1'; + readonly implementation: 'json-artifact.v1' | 'json-keys-guard.v1' | 'line-section-guard.v1' | 'evolve-block-guard.v1' | 'gate.v1' | 'no-change.v1'; readonly digest: { readonly algorithm: 'sha256'; readonly hex: string }; readonly parameters: Handler['parameters']; readonly allowedEvidenceLevels: readonly string[]; @@ -459,6 +468,24 @@ export async function compileRunnerTaskpack(options: CompileRunnerTaskpackOption }, allowedEvidenceLevels: ['local_execution'], }); + } else if (localCheck.implementation === 'evolve-block-guard.v1') { + candidateLocalChecks.push({ + id: localCheck.id, + kind: 'check', + implementation: 'evolve-block-guard.v1', + digest: installed['evolve-block-guard.v1'], + parameters: { + checkId: localCheck.id, + files: [...localCheck.parameters.files], + ...(localCheck.parameters.allowedBlockIds !== undefined + ? { allowedBlockIds: [...localCheck.parameters.allowedBlockIds] } + : {}), + ...(localCheck.parameters.maxBlockBytes !== undefined + ? { maxBlockBytes: localCheck.parameters.maxBlockBytes } + : {}), + }, + allowedEvidenceLevels: ['local_execution'], + }); } else { candidateLocalChecks.push({ id: localCheck.id, diff --git a/packages/taskpack-runner/test/taskpack-v2-parity.test.ts b/packages/taskpack-runner/test/taskpack-v2-parity.test.ts index 14b625f..7e99ff0 100644 --- a/packages/taskpack-runner/test/taskpack-v2-parity.test.ts +++ b/packages/taskpack-runner/test/taskpack-v2-parity.test.ts @@ -703,4 +703,110 @@ describe('Taskpack 2.0 runner parity alignment', () => { (err: unknown) => err instanceof RunnerTaskpackError && err.code === 'CONFIG_INVALID', ); }); + + it('compiles and enforces evolve-block-guard.v1 and Stage A static audit targetMatrix fields offline', async () => { + const baselineKernel = [ + '#include ', + 'static constexpr int ABI_VER = 1;', + '// EVOLVE-BLOCK-START: kernel_body', + 'int kernel_impl() { return 0; }', + '// EVOLVE-BLOCK-END: kernel_body', + '', + ].join('\n'); + const repo = await initGitRepo({ + 'src/kernel.cu': baselineKernel, + }); + cleanupRoots.push(repo.path); + + await withEnvAndDirs(async paths => { + const targetMatrix = [ + { + id: 'cuda-sm90-whole', + platform: 'linux/amd64' as const, + variant: 'cuda12', + hardware: { + accelerator: 'sm_90a', + isolationMode: 'whole_device' as const, + deviceCount: 1, + forbiddenSymbolPatterns: ['cublas', 'cudnn'], + maxRegisterCount: 64, + maxLocalSpillBytes: 0, + }, + }, + ]; + const bundle = await compileRunnerTaskpack({ + mode: 'candidate', + repository: 'example-org/runtime-runner', + baseRevision: repo.headSha, + sourceRevision: repo.headSha, + publication: { mode: 'disabled' }, + proposal: null, + scope: { writable: ['src/**'] }, + targetMatrix, + localChecks: [ + { + id: 'evolve-guard', + implementation: 'evolve-block-guard.v1', + parameters: { + files: ['src/kernel.cu'], + allowedBlockIds: ['kernel_body'], + maxBlockBytes: 4096, + }, + }, + ], + }); + + const compiledMatrix = bundle.config.spec.task.spec.target.matrix; + assert.ok(compiledMatrix !== null && compiledMatrix !== undefined); + assert.deepEqual(compiledMatrix[0]?.hardware?.forbiddenSymbolPatterns, ['cublas', 'cudnn']); + assert.equal(compiledMatrix[0]?.hardware?.maxRegisterCount, 64); + assert.equal(compiledMatrix[0]?.hardware?.maxLocalSpillBytes, 0); + + const { loaded, plan } = await loadAndCompile(bundle, paths); + const guardSlot = plan.verifierSlots.find(s => s.checkId === 'evolve-guard'); + assert.ok(guardSlot !== undefined); + assert.equal(guardSlot.handler.implementation, 'evolve-block-guard.v1'); + + // 1. Inside-block edit passes evolve-block-guard.v1 + const inBlockEdit = baselineKernel.replace('return 0;', 'return 42;'); + const passExec = await runCycleWithPorts( + { configuration: loaded, repository: repo.path, runRoot: paths.runRoot, runId: 'v2-evolve-guard-pass' }, + { + openAdapter: deterministicFakeAdapter({ + attempts: [{ + proposal: null, + edits: [{ path: 'src/kernel.cu', content: inBlockEdit }], + submission: { status: 'completed', reason: null }, + }], + }), + }, + ); + assert.equal(passExec.ok, true); + if (!passExec.ok || passExec.value.kind !== 'result') throw new Error('expected result'); + assert.equal(passExec.value.result.spec.status, 'completed'); + const passRow = passExec.value.result.spec.verification.spec.required.find(r => r.checkId === 'evolve-guard'); + assert.equal(passRow?.status, 'passed'); + + // 2. Single-character edit outside EVOLVE-BLOCK markers fails evolve-block-guard.v1 + const outsideEdit = baselineKernel.replace('ABI_VER = 1;', 'ABI_VER = 2;'); + const failExec = await runCycleWithPorts( + { configuration: loaded, repository: repo.path, runRoot: paths.runRoot, runId: 'v2-evolve-guard-fail' }, + { + openAdapter: deterministicFakeAdapter({ + attempts: [{ + proposal: null, + edits: [{ path: 'src/kernel.cu', content: outsideEdit }], + submission: { status: 'completed', reason: null }, + }], + }), + }, + ); + assert.equal(failExec.ok, true); + if (!failExec.ok || failExec.value.kind !== 'result') throw new Error('expected result'); + assert.equal(failExec.value.result.spec.status, 'exhausted'); + const failRow = failExec.value.result.spec.verification.spec.required.find(r => r.checkId === 'evolve-guard'); + assert.equal(failRow?.status, 'failed'); + assert.ok((failRow?.findings?.length ?? 0) >= 1); + }); + }); }); diff --git a/packages/taskpack/src/index.ts b/packages/taskpack/src/index.ts index 5b9ef6c..3b55071 100644 --- a/packages/taskpack/src/index.ts +++ b/packages/taskpack/src/index.ts @@ -477,6 +477,7 @@ export { buildMemoryProtectedPaths, finalizeLocalTurnkeyMemory, finalizeTurnkeyProposal, + projectMemoryHardwareScope, projectMemoryTargetMatrixCell, readRegularJsonBounded, resolveSafeRunDirectory, diff --git a/packages/taskpack/src/schema.ts b/packages/taskpack/src/schema.ts index e7b759c..090b611 100644 --- a/packages/taskpack/src/schema.ts +++ b/packages/taskpack/src/schema.ts @@ -1,5 +1,6 @@ import { posix } from 'node:path'; import { + digestArtifact, HANDOFF_LIMITS, isWritablePath, LIMITS, @@ -9,6 +10,7 @@ import { validateRelativePath, validateScopePattern, type HardwareTargetSpec, + type MetricBucketScope, type MetricThresholdRule, type OverlayLimits, type ResourceActivationPhase, @@ -18,6 +20,7 @@ import { type StepHandoffSelector, type StepHandoffSource, } from '@loopwright/core'; +import { SecretScrubber } from './scrubber.js'; import { STANDARD_PI_PROVIDER_ENV } from '@loopwright/agent-pi/catalog'; import { DECISION_PROVIDER_API_KEY_ENV } from '@loopwright/decisions'; import { @@ -1703,9 +1706,37 @@ function isValidDottedVersion(value: string): boolean { return true; } +const FORBIDDEN_SYMBOL_GLOB_RE = /[*?[\]]/; +const EVOLVE_BLOCK_MAX_FILES = 64; +const EVOLVE_BLOCK_MAX_ALLOWED_IDS = 64; +const EVOLVE_BLOCK_MAX_ID_LENGTH = 128; + +function isValidEvolveGuardPath(filePath: string): boolean { + if (typeof filePath !== 'string' || filePath.length < 1 || filePath.length > 1024) return false; + if (filePath.startsWith('/') || filePath.startsWith('\\')) return false; + if (!validateRelativePath(filePath).ok) return false; + if (!digestArtifact(filePath, new Uint8Array()).ok) return false; + const segments = filePath.split('/'); + if (segments.some(seg => seg.toLowerCase() === '.git')) return false; + if (segments[0]?.toLowerCase() === '.github' && segments[1]?.toLowerCase() === 'workflows') return false; + return true; +} + +function isValidEvolveBlockId(blockId: string): boolean { + return ( + typeof blockId === 'string' + && blockId.length >= 1 + && blockId.length <= EVOLVE_BLOCK_MAX_ID_LENGTH + && /^[\x21-\x7E]+$/.test(blockId) + && !blockId.includes('/*') + && !blockId.includes('*/') + ); +} + function validateHardwareTargetSpec(value: unknown, path: string): HardwareTargetSpec { const raw = requireNullProtoObject(value, path, [ 'accelerator', 'isolationMode', 'deviceCount', 'driverConstraint', 'topology', + 'forbiddenSymbolPatterns', 'maxRegisterCount', 'maxLocalSpillBytes', ]); const accelerator = requirePrintableAscii(raw['accelerator'], `${path}/accelerator`, 1, 64); const rawIsolation = raw['isolationMode']; @@ -1725,15 +1756,73 @@ function validateHardwareTargetSpec(value: unknown, path: string): HardwareTarge const topology = raw['topology'] === undefined ? undefined : requirePrintableText(raw['topology'], `${path}/topology`, 1, 128); + let forbiddenSymbolPatterns: readonly string[] | undefined; + if (raw['forbiddenSymbolPatterns'] !== undefined) { + const rawPatterns = raw['forbiddenSymbolPatterns']; + if (!Array.isArray(rawPatterns) || rawPatterns.length > LIMITS.forbiddenSymbolPatterns) { + manifestInvalid( + `hardware.forbiddenSymbolPatterns must contain 0..${LIMITS.forbiddenSymbolPatterns} entries`, + `${path}/forbiddenSymbolPatterns`, + ); + } + const seen = new Set(); + forbiddenSymbolPatterns = Object.freeze(rawPatterns.map((entry, idx) => { + const entryPath = `${path}/forbiddenSymbolPatterns/${idx}`; + const pattern = requirePrintableAscii(entry, entryPath, 1, LIMITS.forbiddenSymbolPattern); + if (FORBIDDEN_SYMBOL_GLOB_RE.test(pattern)) { + manifestInvalid('hardware.forbiddenSymbolPatterns entries must be glob-free literal substrings', entryPath); + } + if (seen.has(pattern)) { + manifestInvalid(`duplicate hardware.forbiddenSymbolPatterns entry "${pattern}"`, entryPath); + } + seen.add(pattern); + return pattern; + })); + } + const maxRegisterCount = raw['maxRegisterCount'] === undefined + ? undefined + : requireSafeIntInRange(raw['maxRegisterCount'], `${path}/maxRegisterCount`, 0, Number.MAX_SAFE_INTEGER); + const maxLocalSpillBytes = raw['maxLocalSpillBytes'] === undefined + ? undefined + : requireSafeIntInRange(raw['maxLocalSpillBytes'], `${path}/maxLocalSpillBytes`, 0, Number.MAX_SAFE_INTEGER); return Object.freeze({ accelerator, isolationMode: rawIsolation, ...(deviceCount === undefined ? {} : { deviceCount }), ...(driverConstraint === undefined ? {} : { driverConstraint }), ...(topology === undefined ? {} : { topology }), + ...(forbiddenSymbolPatterns === undefined ? {} : { forbiddenSymbolPatterns }), + ...(maxRegisterCount === undefined ? {} : { maxRegisterCount }), + ...(maxLocalSpillBytes === undefined ? {} : { maxLocalSpillBytes }), }); } +const BUCKET_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]*$/; +const DEFAULT_BUCKET_SCRUBBER = new SecretScrubber(); + +function validateMetricBucketScope(value: unknown, path: string): MetricBucketScope { + if (typeof value === 'string') { + if (value === 'aggregate' || value === 'all_buckets') return value; + manifestInvalid('metricThreshold.bucketScope must be "aggregate", "all_buckets", or { bucketId }', path); + } + const raw = requireNullProtoObject(value, path, ['bucketId']); + if (!Object.hasOwn(raw, 'bucketId')) { + manifestInvalid('metricThreshold.bucketScope object requires "bucketId"', `${path}/bucketId`); + } + const bucketId = raw['bucketId']; + if ( + typeof bucketId !== 'string' + || bucketId.length < 1 + || bucketId.length > LIMITS.bucketId + || FORBIDDEN_KEYS.has(bucketId) + || !BUCKET_ID_RE.test(bucketId) + || DEFAULT_BUCKET_SCRUBBER.containsSecret(bucketId) + ) { + manifestInvalid('metricThreshold.bucketScope.bucketId is invalid', `${path}/bucketId`); + } + return Object.freeze({ bucketId }); +} + function requireMetricKey(value: unknown, path: string): string { if (typeof value !== 'string' || value.length < 1 || value.length > LIMITS.metricKey) { manifestInvalid(`expected a metric key of 1..${LIMITS.metricKey} characters`, path); @@ -1758,7 +1847,7 @@ function validateMetricThresholdRule(value: unknown, path: string): MetricThresh } const kind = rawRecord['kind']; if (kind === 'bounds') { - const raw = requireNullProtoObject(value, path, ['kind', 'metric', 'min', 'max']); + const raw = requireNullProtoObject(value, path, ['kind', 'metric', 'min', 'max', 'bucketScope']); const metric = requireMetricKey(raw['metric'], `${path}/metric`); const min = raw['min'] === undefined ? undefined : requireFiniteNumber(raw['min'], `${path}/min`); const max = raw['max'] === undefined ? undefined : requireFiniteNumber(raw['max'], `${path}/max`); @@ -1768,15 +1857,19 @@ function validateMetricThresholdRule(value: unknown, path: string): MetricThresh if (min !== undefined && max !== undefined && min > max) { manifestInvalid('bounds metric threshold requires min <= max', path); } + const bucketScope = raw['bucketScope'] === undefined + ? undefined + : validateMetricBucketScope(raw['bucketScope'], `${path}/bucketScope`); return Object.freeze({ kind: 'bounds' as const, metric, ...(min === undefined ? {} : { min }), ...(max === undefined ? {} : { max }), + ...(bucketScope === undefined ? {} : { bucketScope }), }); } if (kind === 'comparative') { - const raw = requireNullProtoObject(value, path, ['kind', 'metric', 'baselineMetric', 'operator', 'threshold']); + const raw = requireNullProtoObject(value, path, ['kind', 'metric', 'baselineMetric', 'operator', 'threshold', 'bucketScope']); const metric = requireMetricKey(raw['metric'], `${path}/metric`); const baselineMetric = requireMetricKey(raw['baselineMetric'], `${path}/baselineMetric`); const operator = raw['operator']; @@ -1786,12 +1879,16 @@ function validateMetricThresholdRule(value: unknown, path: string): MetricThresh // Reject -0/NaN/Infinity on untrusted manifest input (stricter than @loopwright/core's -0 -> 0 normalization) // while matching @loopwright/core's allowance of finite negative comparative thresholds (e.g. -0.25). const threshold = requireFiniteNumber(raw['threshold'], `${path}/threshold`); + const bucketScope = raw['bucketScope'] === undefined + ? undefined + : validateMetricBucketScope(raw['bucketScope'], `${path}/bucketScope`); return Object.freeze({ kind: 'comparative' as const, metric, baselineMetric, operator, threshold, + ...(bucketScope === undefined ? {} : { bucketScope }), }); } manifestInvalid('metric threshold rule kind must be "bounds" or "comparative"', `${path}/kind`); @@ -3494,7 +3591,7 @@ function validateTaskpackManifestInternal( const checkIds = new Set(); const reservedIds = new Set(['scope', 'no-change', 'taskpack-author', 'taskpack-no-change']); const allowedLocalCheckImpls = schemaMode === 'v2' - ? ['json-artifact.v1', 'scope.v1', 'no-change.v1', 'command.v1', 'json-keys-guard.v1', 'line-section-guard.v1'] + ? ['json-artifact.v1', 'scope.v1', 'no-change.v1', 'command.v1', 'json-keys-guard.v1', 'line-section-guard.v1', 'evolve-block-guard.v1'] : ['json-artifact.v1', 'scope.v1', 'no-change.v1', 'command.v1']; const relativeToolchainPaths: string[] = []; @@ -3719,6 +3816,61 @@ function validateTaskpackManifestInternal( }), }); } + if (implementation === 'evolve-block-guard.v1') { + const paramPath = `/spec/verification/localChecks/${index}/parameters`; + const params = requireNullProtoObject(check['parameters'], paramPath, ['files', 'allowedBlockIds', 'maxBlockBytes']); + const rawFiles = params['files']; + if (!Array.isArray(rawFiles) || rawFiles.length < 1 || rawFiles.length > EVOLVE_BLOCK_MAX_FILES) { + manifestInvalid(`evolve-block-guard.v1 files must contain 1..${EVOLVE_BLOCK_MAX_FILES} repo-relative paths`, `${paramPath}/files`); + } + const seenFiles = new Set(); + const files = Object.freeze(rawFiles.map((entry, fIdx) => { + const fPath = `${paramPath}/files/${fIdx}`; + const file = requireString(entry, fPath, 1, 1024); + const folded = file.normalize('NFC').toLowerCase(); + if (!isValidEvolveGuardPath(file)) { + manifestInvalid(`evolve-block-guard.v1 file "${file}" must be a safe repo-relative path outside .git and .github/workflows`, fPath); + } + if (seenFiles.has(folded)) { + manifestInvalid(`duplicate evolve-block-guard.v1 file "${file}"`, fPath); + } + seenFiles.add(folded); + return file; + })); + let allowedBlockIds: readonly string[] | undefined; + if (params['allowedBlockIds'] !== undefined) { + const rawBlockIds = params['allowedBlockIds']; + if (!Array.isArray(rawBlockIds) || rawBlockIds.length < 1 || rawBlockIds.length > EVOLVE_BLOCK_MAX_ALLOWED_IDS) { + manifestInvalid(`evolve-block-guard.v1 allowedBlockIds must contain 1..${EVOLVE_BLOCK_MAX_ALLOWED_IDS} block IDs`, `${paramPath}/allowedBlockIds`); + } + const seenBlockIds = new Set(); + allowedBlockIds = Object.freeze(rawBlockIds.map((entry, bIdx) => { + const bPath = `${paramPath}/allowedBlockIds/${bIdx}`; + const blockId = requireString(entry, bPath, 1, EVOLVE_BLOCK_MAX_ID_LENGTH); + if (!isValidEvolveBlockId(blockId)) { + manifestInvalid(`evolve-block-guard.v1 block ID "${blockId}" is invalid`, bPath); + } + if (seenBlockIds.has(blockId)) { + manifestInvalid(`duplicate evolve-block-guard.v1 block ID "${blockId}"`, bPath); + } + seenBlockIds.add(blockId); + return blockId; + })); + } + let maxBlockBytes: number | undefined; + if (params['maxBlockBytes'] !== undefined) { + maxBlockBytes = requireSafeIntInRange(params['maxBlockBytes'], `${paramPath}/maxBlockBytes`, 1, Number.MAX_SAFE_INTEGER); + } + return Object.freeze({ + id: checkId, + implementation: 'evolve-block-guard.v1' as const, + parameters: Object.freeze({ + files, + ...(allowedBlockIds !== undefined ? { allowedBlockIds } : {}), + ...(maxBlockBytes !== undefined ? { maxBlockBytes } : {}), + }), + }); + } const parametersKey = Object.hasOwn(check, 'parameters') ? 'parameters' : ''; const record: { id: string; diff --git a/packages/taskpack/src/taskpack.ts b/packages/taskpack/src/taskpack.ts index 4518807..369a0e9 100644 --- a/packages/taskpack/src/taskpack.ts +++ b/packages/taskpack/src/taskpack.ts @@ -95,6 +95,7 @@ import { type Json, } from './schema.js'; import { SecretScrubber } from './scrubber.js'; +import { projectMemoryHardwareScope, projectMemoryTargetMatrixCell } from './turnkey-memory.js'; import { AUTHORIZED_ASSOCIATIONS, CANONICAL_TASKPACK_STEP_GATE_URL, @@ -1739,13 +1740,11 @@ export async function compileDeclarativeTaskpack(manifest: TaskpackManifest, bin const currentUpstreamVersions = checkUpstreamVersions ? buildUpstreamVersionsMap(bindings.upstreamRecords) : null; - const targetCell = effectiveTargetMatrix !== null && effectiveTargetMatrix.length === 1 - ? Object.freeze({ - id: effectiveTargetMatrix[0]!.id, - platform: effectiveTargetMatrix[0]!.platform, - variant: effectiveTargetMatrix[0]!.variant, - }) + const rawSingleTargetCell = effectiveTargetMatrix !== null && effectiveTargetMatrix.length === 1 + ? effectiveTargetMatrix[0]! : null; + const targetCell = projectMemoryTargetMatrixCell(rawSingleTargetCell); + const hardwareScope = projectMemoryHardwareScope(rawSingleTargetCell); const selectorContractStub = { apiVersion: 'loopwright.dev/v1alpha1', kind: 'TaskContract', @@ -1775,6 +1774,7 @@ export async function compileDeclarativeTaskpack(manifest: TaskpackManifest, bin currentCodeFingerprint, currentUpstreamVersions, targetCell, + ...(hardwareScope !== undefined ? { hardwareScope } : {}), maxEntries: maxPromptEntries, maxBytes: DEFAULT_MEMORY_MAX_PROMPT_BYTES, }); @@ -1796,6 +1796,7 @@ export async function compileDeclarativeTaskpack(manifest: TaskpackManifest, bin currentCodeFingerprint: null, currentUpstreamVersions: null, targetCell, + ...(hardwareScope !== undefined ? { hardwareScope } : {}), maxEntries: maxPromptEntries, maxBytes: clampedBytes, }); @@ -2516,7 +2517,8 @@ export async function compileDeclarativeTaskpack(manifest: TaskpackManifest, bin | 'gate.v1' | 'benchmark-gate.v1' | 'json-keys-guard.v1' - | 'line-section-guard.v1'; + | 'line-section-guard.v1' + | 'evolve-block-guard.v1'; readonly parameters: Record; readonly allowedEvidenceLevels: readonly ('local_execution' | 'external_service' | 'hardware_execution')[]; readonly targetCellId?: string | undefined; @@ -2572,6 +2574,42 @@ export async function compileDeclarativeTaskpack(manifest: TaskpackManifest, bin }); continue; } + if (declared.implementation === 'evolve-block-guard.v1') { + const files = declared.parameters?.['files']; + if (!Array.isArray(files) || files.length === 0 || !files.every(f => typeof f === 'string' && f.length > 0)) { + manifestInvalid('evolve-block-guard.v1 requires a non-empty parameters.files string array', `/spec/verification/localChecks/${declared.id}/parameters/files`); + } + const allowedBlockIds = declared.parameters?.['allowedBlockIds']; + if ( + allowedBlockIds !== undefined + && (!Array.isArray(allowedBlockIds) || allowedBlockIds.length === 0 || !allowedBlockIds.every(id => typeof id === 'string' && id.length > 0)) + ) { + manifestInvalid('evolve-block-guard.v1 parameters.allowedBlockIds must be a non-empty string array', `/spec/verification/localChecks/${declared.id}/parameters/allowedBlockIds`); + } + const maxBlockBytes = declared.parameters?.['maxBlockBytes']; + if ( + maxBlockBytes !== undefined + && (typeof maxBlockBytes !== 'number' || !Number.isSafeInteger(maxBlockBytes) || maxBlockBytes < 1) + ) { + manifestInvalid('evolve-block-guard.v1 parameters.maxBlockBytes must be a positive safe integer', `/spec/verification/localChecks/${declared.id}/parameters/maxBlockBytes`); + } + activeChecks.push({ + id: declared.id, + implementation: 'evolve-block-guard.v1', + parameters: { + checkId: declared.id, + files: [...files], + ...(allowedBlockIds !== undefined + ? { allowedBlockIds: [...allowedBlockIds] } + : {}), + ...(maxBlockBytes !== undefined + ? { maxBlockBytes } + : {}), + }, + allowedEvidenceLevels: ['local_execution'], + }); + continue; + } const parameters: Record = { checkId: declared.id }; if (declared.implementation === 'json-artifact.v1') { if (manifest.spec.proposal !== undefined) { @@ -3203,7 +3241,8 @@ function assemble(input: AssembleInput): CompiledTaskpack { | 'gate.v1' | 'benchmark-gate.v1' | 'json-keys-guard.v1' - | 'line-section-guard.v1', + | 'line-section-guard.v1' + | 'evolve-block-guard.v1', version: 1 as const, digest: { ...installed[check.implementation]! }, parameters: check.parameters as Readonly>, @@ -3492,6 +3531,11 @@ function assemble(input: AssembleInput): CompiledTaskpack { ...(cell.hardware.deviceCount !== undefined ? { deviceCount: cell.hardware.deviceCount } : {}), ...(cell.hardware.driverConstraint !== undefined ? { driverConstraint: cell.hardware.driverConstraint } : {}), ...(cell.hardware.topology !== undefined ? { topology: cell.hardware.topology } : {}), + ...(cell.hardware.forbiddenSymbolPatterns !== undefined + ? { forbiddenSymbolPatterns: [...cell.hardware.forbiddenSymbolPatterns] } + : {}), + ...(cell.hardware.maxRegisterCount !== undefined ? { maxRegisterCount: cell.hardware.maxRegisterCount } : {}), + ...(cell.hardware.maxLocalSpillBytes !== undefined ? { maxLocalSpillBytes: cell.hardware.maxLocalSpillBytes } : {}), }, } : {}), @@ -3554,6 +3598,13 @@ function assemble(input: AssembleInput): CompiledTaskpack { metric: rule.metric, ...(rule.min !== undefined ? { min: rule.min } : {}), ...(rule.max !== undefined ? { max: rule.max } : {}), + ...(rule.bucketScope !== undefined + ? { + bucketScope: typeof rule.bucketScope === 'string' + ? rule.bucketScope + : { bucketId: rule.bucketScope.bucketId }, + } + : {}), } : { kind: 'comparative' as const, @@ -3561,6 +3612,13 @@ function assemble(input: AssembleInput): CompiledTaskpack { baselineMetric: rule.baselineMetric, operator: rule.operator, threshold: rule.threshold, + ...(rule.bucketScope !== undefined + ? { + bucketScope: typeof rule.bucketScope === 'string' + ? rule.bucketScope + : { bucketId: rule.bucketScope.bucketId }, + } + : {}), } )), } diff --git a/packages/taskpack/src/turnkey-memory.ts b/packages/taskpack/src/turnkey-memory.ts index ca36c08..6d5326e 100644 --- a/packages/taskpack/src/turnkey-memory.ts +++ b/packages/taskpack/src/turnkey-memory.ts @@ -11,6 +11,7 @@ import { loadMemoryStore, MemoryDiagnosticError, resolveSettledCycleContext, + type HardwareMemoryScope, type MemoryCASResult, type MemoryFinalizerConfig, type MemoryProposal, @@ -88,6 +89,18 @@ export function projectMemoryTargetMatrixCell( }); } +/** Derive optional `HardwareMemoryScope` (`{ accelerator, driverConstraint? }`) when a matched matrix cell declares `hardware`. */ +export function projectMemoryHardwareScope( + cell: TargetMatrixCell | null | undefined, +): HardwareMemoryScope | undefined { + const hardware = cell?.hardware; + if (hardware === undefined) return undefined; + return Object.freeze({ + accelerator: hardware.accelerator, + ...(hardware.driverConstraint !== undefined ? { driverConstraint: hardware.driverConstraint } : {}), + }); +} + const MS_PER_DAY = 24 * 60 * 60 * 1000; export function buildMemoryProtectedPaths( @@ -580,6 +593,7 @@ export async function finalizeLocalTurnkeyMemory( ? options.targetMatrix : (manifestMatrix !== undefined && manifestMatrix !== null && manifestMatrix.length === 1 ? manifestMatrix[0]! : null); const targetMatrix = projectMemoryTargetMatrixCell(rawTargetMatrix); + const hardwareScope = projectMemoryHardwareScope(rawTargetMatrix); const expectedBindings: ExpectedSettledRunBindings = { runId: options.runId, @@ -600,6 +614,7 @@ export async function finalizeLocalTurnkeyMemory( checkCodeFingerprint, checkUpstreamVersions, targetMatrix, + ...(hardwareScope !== undefined ? { hardwareScope } : {}), upstreamVersions: buildUpstreamMemoryVersions(options.upstreamRecords as readonly UpstreamAcquisitionRecord[] | undefined), }; diff --git a/packages/taskpack/src/turnkey.ts b/packages/taskpack/src/turnkey.ts index b1b0d9b..ff47db7 100644 --- a/packages/taskpack/src/turnkey.ts +++ b/packages/taskpack/src/turnkey.ts @@ -6241,29 +6241,6 @@ export function makeAttemptRunId(baseRunId: string, attemptSeq: number): string return `${prefix.length > 0 ? prefix : 'run'}${suffix}`; } -async function withTemporaryProcessEnv( - overrides: Readonly>, - fn: () => Promise, -): Promise { - const previous = new Map(); - for (const [key, value] of Object.entries(overrides)) { - if (value === undefined) continue; - previous.set(key, process.env[key]); - process.env[key] = value; - } - try { - return await fn(); - } finally { - for (const [key, prior] of previous.entries()) { - if (prior === undefined) { - delete process.env[key]; - } else { - process.env[key] = prior; - } - } - } -} - function formatPiErrorDetail( error: { readonly code: string; readonly phase: string; readonly path?: string | undefined }, prefix = '', @@ -6272,7 +6249,7 @@ function formatPiErrorDetail( return `${prefix}${error.code} (${error.phase}${pathSuffix})`; } -function parsePositiveIntEnv(env: NodeJS.ProcessEnv, name: string): number | undefined { +function parsePositiveIntEnv(env: Readonly>, name: string): number | undefined { const raw = env[name]?.trim(); if (!raw || !/^\d+$/.test(raw)) return undefined; const parsed = Number(raw); @@ -6502,39 +6479,45 @@ export async function executeTurnkeyCycle( const startedMs = performance.now(); const scrubber = options.scrubber ?? new SecretScrubber(); const attemptRunId = makeAttemptRunId(options.runId, options.attemptSeq); - const envOverrides: Record = {}; + const effectiveEnv: Record = Object.create(null) as Record; + // Intentional isolation: when a caller supplies runtimeEnv it is authoritative over ambient + // process.env (preventing ambient secret leakage and concurrent process.env races), with an + // explicit read-only fallback for LOOPWRIGHT_ACTIVE_PROVIDER_TOKEN_ENV below. + const baseEnv = options.runtimeEnv ?? process.env; + for (const [key, value] of Object.entries(baseEnv)) { + if (value !== undefined) { + effectiveEnv[key] = value; + } + } let publisherHandle: Awaited>> | undefined; try { if (options.publisherFactory !== undefined) { publisherHandle = await options.publisherFactory(); const signEnv = publisherHandle.signingEnvName ?? 'LOOPWRIGHT_PUBLICATION_SIGNING_SECRET'; - envOverrides[signEnv] = publisherHandle.signingSecret; + effectiveEnv[signEnv] = publisherHandle.signingSecret; scrubber.register(publisherHandle.signingSecret); if (publisherHandle.authToken !== undefined) { const authEnv = publisherHandle.authEnvName ?? 'LOOPWRIGHT_PUBLICATION_AUTH_TOKEN'; - envOverrides[authEnv] = publisherHandle.authToken; + effectiveEnv[authEnv] = publisherHandle.authToken; scrubber.register(publisherHandle.authToken); } } - if (options.runtimeEnv !== undefined) { - for (const [key, value] of Object.entries(options.runtimeEnv)) { - if (value !== undefined && process.env[key] === undefined) { - envOverrides[key] = value; - } - } - } if (options.ephemeralEnv !== undefined) { for (const [key, value] of Object.entries(options.ephemeralEnv)) { - envOverrides[key] = value; + effectiveEnv[key] = value; scrubber.register(value); } } - const activeToken = process.env[LOOPWRIGHT_ACTIVE_PROVIDER_TOKEN_ENV] - ?? options.runtimeEnv?.[LOOPWRIGHT_ACTIVE_PROVIDER_TOKEN_ENV]; + if (effectiveEnv[LOOPWRIGHT_ACTIVE_PROVIDER_TOKEN_ENV] === undefined) { + const inheritedActiveToken = process.env[LOOPWRIGHT_ACTIVE_PROVIDER_TOKEN_ENV]; + if (typeof inheritedActiveToken === 'string' && inheritedActiveToken.length > 0) { + effectiveEnv[LOOPWRIGHT_ACTIVE_PROVIDER_TOKEN_ENV] = inheritedActiveToken; + } + } + const activeToken = effectiveEnv[LOOPWRIGHT_ACTIVE_PROVIDER_TOKEN_ENV]; if (typeof activeToken === 'string' && activeToken.length > 0) { - envOverrides[LOOPWRIGHT_ACTIVE_PROVIDER_TOKEN_ENV] = activeToken; scrubber.register(activeToken); } @@ -6545,14 +6528,13 @@ export async function executeTurnkeyCycle( let implRepairDispatches = 0; const totalTokenBudget = options.taskpack.config.spec.task.spec.budgets.totalTokens; let cumulativeTokens = 0; - const envSource = options.runtimeEnv ?? process.env; - const maxTurnsRaw = envSource['LOOPWRIGHT_MAX_TURNS']?.trim(); - const maxTurnsOverride = parsePositiveIntEnv(envSource, 'LOOPWRIGHT_MAX_TURNS'); + const maxTurnsRaw = effectiveEnv['LOOPWRIGHT_MAX_TURNS']?.trim(); + const maxTurnsOverride = parsePositiveIntEnv(effectiveEnv, 'LOOPWRIGHT_MAX_TURNS'); if (maxTurnsRaw && maxTurnsOverride === undefined) { options.onLog?.(scrubber.scrub(`warning: ignoring invalid LOOPWRIGHT_MAX_TURNS=${maxTurnsRaw}; expected positive integer`)); } - const maxRepairTurnsRaw = envSource['LOOPWRIGHT_MAX_REPAIR_TURNS']?.trim(); - const maxRepairTurnsOverride = parsePositiveIntEnv(envSource, 'LOOPWRIGHT_MAX_REPAIR_TURNS'); + const maxRepairTurnsRaw = effectiveEnv['LOOPWRIGHT_MAX_REPAIR_TURNS']?.trim(); + const maxRepairTurnsOverride = parsePositiveIntEnv(effectiveEnv, 'LOOPWRIGHT_MAX_REPAIR_TURNS'); if (maxRepairTurnsRaw && maxRepairTurnsOverride === undefined) { options.onLog?.(scrubber.scrub(`warning: ignoring invalid LOOPWRIGHT_MAX_REPAIR_TURNS=${maxRepairTurnsRaw}; expected positive integer`)); } @@ -6617,7 +6599,7 @@ export async function executeTurnkeyCycle( && (entry.id === 'taskpack-provider-token' || entry.environmentNames.includes(LOOPWRIGHT_ACTIVE_PROVIDER_TOKEN_ENV)), ); if ((hasExplicitMeta && matchesExplicitMeta) || (!hasExplicitMeta && matchesRegistryProviderBinding)) { - const active = process.env[LOOPWRIGHT_ACTIVE_PROVIDER_TOKEN_ENV]; + const active = effectiveEnv[LOOPWRIGHT_ACTIVE_PROVIDER_TOKEN_ENV]; if (typeof active === 'string' && active.length > 0) { return { bearerToken: active }; } @@ -6732,12 +6714,13 @@ export async function executeTurnkeyCycle( await mkdir(runRoot, { recursive: true, mode: 0o700 }); await chmod(runRoot, 0o700).catch(() => undefined); - const cycleOutcome = await withTemporaryProcessEnv(envOverrides, async () => { + const cycleOutcome = await (async () => { const loaded = await loadTrustedConfiguration({ configPath: options.taskpack.configPath, registryPath: options.taskpack.registryPath, registrySha256: options.taskpack.registrySha256, untrustedRoots: [options.repositoryRoot], + environment: name => (Object.hasOwn(effectiveEnv, name) ? effectiveEnv[name] : undefined), }); if (!loaded.ok) { return { @@ -6859,7 +6842,7 @@ export async function executeTurnkeyCycle( maxImplRepairs: options.taskpack.config.spec.task.spec.budgets.maxImplementationRepairs, maxModelCalls: options.taskpack.config.spec.task.spec.budgets.maxModelCalls, }; - }); + })(); const rawSummaryHolder = await mkdtemp(join(tmpdir(), 'loopwright-summary-')); await chmod(rawSummaryHolder, 0o700); diff --git a/packages/taskpack/src/types.ts b/packages/taskpack/src/types.ts index f71758d..441f442 100644 --- a/packages/taskpack/src/types.ts +++ b/packages/taskpack/src/types.ts @@ -2,6 +2,7 @@ import type { Digest, HardwareTargetSpec, MetricBoundsRule, + MetricBucketScope, MetricComparativeRule, MetricThresholdRule, OverlayLimits, @@ -26,6 +27,7 @@ export type { ClockSample, HardwareTargetSpec, MetricBoundsRule, + MetricBucketScope, MetricComparativeRule, MetricThresholdRule, PiCustomModelCompat, @@ -376,7 +378,8 @@ export type LegacyTaskpackCheckImplementation = 'json-artifact.v1' | 'scope.v1' export type TaskpackV2CheckImplementation = | LegacyTaskpackCheckImplementation | 'json-keys-guard.v1' - | 'line-section-guard.v1'; + | 'line-section-guard.v1' + | 'evolve-block-guard.v1'; export interface TaskpackCheckDeclaration { readonly id: string; diff --git a/packages/taskpack/test/evolution-taskpack.test.ts b/packages/taskpack/test/evolution-taskpack.test.ts new file mode 100644 index 0000000..d262be3 --- /dev/null +++ b/packages/taskpack/test/evolution-taskpack.test.ts @@ -0,0 +1,788 @@ +import assert from 'node:assert/strict'; +import { chmod, mkdir, mkdtemp, realpath, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { describe, it } from 'node:test'; +import { + compilePlan, + installedHandlerDigests, + loadTrustedConfiguration, + type ControllerIncident, +} from '@loopwright/controller'; +import { admitTask, digestArtifact, validateDocument } from '@loopwright/core'; +import { + canonical, + loadMemoryStore, + renderEntryMarkdown, + serializeMemoryStoreIndex, + storeDigestOf, + type MemoryEntry, + type MemoryStoreIndex, +} from '@loopwright/memory'; +import { + compileDeclarativeTaskpack, + DEFAULT_HOST_BUDGETS, + finalizeLocalTurnkeyMemory, + projectMemoryHardwareScope, + SecretScrubber, + serializePrettyYaml, + stageCompiledInstructionResources, + TaskpackError, + validateTaskpackManifest, + validateTaskpackV2Manifest, + type Json, + type TargetMatrixCell, +} from '../src/index.js'; + +const BASE_SHA = 'b'.repeat(40); +const ZERO_DIGEST = { algorithm: 'sha256' as const, hex: '0'.repeat(64) }; +const ARTIFACT_DIGEST = { algorithm: 'sha256' as const, hex: 'c'.repeat(64) }; + +async function withTempDir(fn: (dir: string) => Promise): Promise { + const base = await realpath(tmpdir()); + const dir = await mkdtemp(join(base, 'lw-tp-evo-')); + try { + await fn(dir); + } finally { + await rm(dir, { recursive: true, force: true }); + } +} + +function makeEvolutionManifestObject(overrides: { + readonly targetMatrix?: unknown; + readonly localChecks?: unknown; + readonly externalGates?: unknown; + readonly memory?: unknown; +} = {}): Record { + return { + apiVersion: 'loopwright.dev/v1alpha1', + kind: 'Taskpack', + metadata: { name: 'evo-kernel' }, + spec: { + goal: { + candidate: 'Optimize CUDA kernel inside EVOLVE-BLOCK regions.', + noChange: 'No kernel change needed.', + }, + scope: { + writable: ['src/**'], + protected: [], + }, + target: { + matrix: overrides.targetMatrix !== undefined + ? overrides.targetMatrix + : [ + { + id: 'h100-sxm', + platform: 'linux/amd64', + variant: 'cuda12', + hardware: { + accelerator: 'sm_90a', + isolationMode: 'whole_device', + deviceCount: 1, + driverConstraint: '>=550.54', + topology: 'nvlink', + forbiddenSymbolPatterns: ['cublas', 'at::native::'], + maxRegisterCount: 128, + maxLocalSpillBytes: 0, + }, + }, + ], + }, + verification: { + localChecks: overrides.localChecks !== undefined + ? overrides.localChecks + : [ + { + id: 'evolve-guard', + implementation: 'evolve-block-guard.v1', + parameters: { + files: ['src/kernel.cu'], + allowedBlockIds: ['gemm_main'], + maxBlockBytes: 8192, + }, + }, + ], + externalGates: overrides.externalGates !== undefined + ? overrides.externalGates + : [ + { + id: 'bench-h100', + implementation: 'benchmark-gate.v1', + gateId: 'Roofline Gate v1', + endpointId: 'bench-relay', + required: true, + targetCellId: 'h100-sxm', + heldOutWorkloadId: 'kernel.matmul.v1', + maxPreemptions: 2, + allowSyntheticHardwareProbe: true, + metricThresholds: [ + { kind: 'bounds', metric: 'max_ulp', max: 1, bucketScope: 'all_buckets' }, + { kind: 'bounds', metric: 'latency_us_p50', max: 250, bucketScope: { bucketId: 'bs1-isl4k' } }, + { + kind: 'comparative', + metric: 'goodput_rps', + baselineMetric: 'baseline_goodput_rps', + operator: 'min_ratio', + threshold: 1.1, + bucketScope: 'aggregate', + }, + ], + }, + ], + }, + publication: { mode: 'disabled' }, + memory: overrides.memory !== undefined + ? overrides.memory + : { + directory: '.loopwright/memory/evo-kernel', + apply: 'local-only', + onNoModelBudget: 'deterministic-observations-only', + }, + triggers: { + schedule: false, + workflowDispatch: true, + releasePublished: false, + commentCommands: [], + }, + }, + }; +} + +function makeMemoryEntry(overrides: { + readonly id: string; + readonly claimKey: string; + readonly claim: string; + readonly hardwareScope?: { readonly accelerator: string; readonly driverConstraint?: string }; + readonly targetMatrix?: { readonly id: string; readonly platform: string; readonly variant: string } | null; + readonly level?: 'local_execution' | 'hardware_execution'; +}): MemoryEntry { + const scope = overrides.hardwareScope !== undefined + ? { + taskpack: 'evo-kernel', + repository: 'local/kernel-repo', + paths: ['src/**'], + targetMatrix: overrides.targetMatrix ?? null, + hardwareScope: overrides.hardwareScope, + } + : { + taskpack: 'evo-kernel', + repository: 'local/kernel-repo', + paths: ['src/**'], + targetMatrix: overrides.targetMatrix ?? null, + }; + return Object.freeze({ + version: 1, + id: overrides.id, + claimKey: overrides.claimKey, + claim: overrides.claim, + kind: 'fact', + scope, + sourceRef: { + runId: 'run-seed-1', + lockHash: ZERO_DIGEST, + candidateDigest: ZERO_DIGEST, + }, + sourceDigest: ARTIFACT_DIGEST, + verifiedAtMs: 1_700_000_000_000, + validFor: { + baseRevision: BASE_SHA, + sourceRevision: BASE_SHA, + codeFingerprint: ZERO_DIGEST, + upstreamVersions: {}, + }, + expiresAtMs: 1_900_000_000_000, + supersedes: [], + evidenceRefs: [ + { + evidenceId: `ev-${overrides.id}`, + checkId: 'bench-h100', + level: overrides.level ?? (overrides.hardwareScope !== undefined ? 'hardware_execution' : 'local_execution'), + observedStatus: 'passed' as const, + artifact: { + name: `evidence-${overrides.id}.json`, + digest: ARTIFACT_DIGEST, + byteLength: 128, + }, + }, + ], + }); +} + +describe('evolve-block-guard.v1, Stage A static audit, bucketScope, and hardwareScope memory', () => { + it('validates and compiles evolve-block-guard.v1, Stage A static audit fields, and bucketScope through controller compilePlan', async () => { + await withTempDir(async dir => { + const repoRoot = join(dir, 'repo'); + await mkdir(join(repoRoot, 'src'), { recursive: true }); + await writeFile( + join(repoRoot, 'src', 'kernel.cu'), + '// EVOLVE-BLOCK-START: gemm_main\n__global__ void gemm() {}\n// EVOLVE-BLOCK-END: gemm_main\n', + 'utf8', + ); + + const manifest = validateTaskpackV2Manifest(makeEvolutionManifestObject() as Json); + const compiled = await compileDeclarativeTaskpack(manifest, { + mode: 'candidate', + executionMode: 'delegated', + repository: 'local/kernel-repo', + repositoryRoot: repoRoot, + baseRevision: BASE_SHA, + sourceRevision: BASE_SHA, + budgets: DEFAULT_HOST_BUDGETS, + gateEndpoints: [ + { + id: 'bench-relay', + url: 'http://127.0.0.1:42010/v1/benchmark/jobs', + signingCredentialRef: 'bench-signing', + authCredentialRef: null, + }, + ], + credentialEnvMap: { gate: 'BENCH_SIGNING_SECRET' }, + }); + + const installed = await installedHandlerDigests(); + const guardHandler = compiled.registry.spec.handlers.find(h => h.id === 'evolve-guard'); + assert.ok(guardHandler, 'expected evolve-block-guard.v1 handler in TrustedRegistry'); + assert.equal(guardHandler.implementation, 'evolve-block-guard.v1'); + assert.deepEqual(guardHandler.digest, installed['evolve-block-guard.v1']); + assert.deepEqual(guardHandler.parameters, { + checkId: 'evolve-guard', + files: ['src/kernel.cu'], + allowedBlockIds: ['gemm_main'], + maxBlockBytes: 8192, + }); + + const compiledHardware = compiled.config.spec.task.spec.target.matrix?.[0]?.hardware; + assert.deepEqual({ ...compiledHardware }, { + accelerator: 'sm_90a', + isolationMode: 'whole_device', + deviceCount: 1, + driverConstraint: '>=550.54', + topology: 'nvlink', + forbiddenSymbolPatterns: ['cublas', 'at::native::'], + maxRegisterCount: 128, + maxLocalSpillBytes: 0, + }); + + const compiledBenchCheck = compiled.config.spec.task.spec.acceptance.checks.find(c => c.id === 'bench-h100'); + assert.deepEqual( + JSON.parse(JSON.stringify(compiledBenchCheck?.metricThresholds)), + [ + { kind: 'bounds', metric: 'max_ulp', max: 1, bucketScope: 'all_buckets' }, + { kind: 'bounds', metric: 'latency_us_p50', max: 250, bucketScope: { bucketId: 'bs1-isl4k' } }, + { + kind: 'comparative', + metric: 'goodput_rps', + baselineMetric: 'baseline_goodput_rps', + operator: 'min_ratio', + threshold: 1.1, + bucketScope: 'aggregate', + }, + ], + ); + + const trustedDir = join(dir, 'trusted'); + const regDir = join(trustedDir, 'registry'); + const cfgDir = join(trustedDir, 'config'); + await mkdir(regDir, { recursive: true, mode: 0o700 }); + await mkdir(cfgDir, { recursive: true, mode: 0o700 }); + await chmod(trustedDir, 0o700); + const regPath = join(regDir, 'registry.yaml'); + const cfgPath = join(cfgDir, 'config.yaml'); + await writeFile(regPath, compiled.registryBytes, { mode: 0o600 }); + await writeFile(cfgPath, serializePrettyYaml(compiled.config), { mode: 0o600 }); + await stageCompiledInstructionResources(regDir, compiled.instructionResources ?? []); + + const prevSign = process.env['BENCH_SIGNING_SECRET']; + process.env['BENCH_SIGNING_SECRET'] = 'bench-signing-secret-t8'; + try { + const trusted = await loadTrustedConfiguration({ + configPath: cfgPath, + registryPath: regPath, + registrySha256: compiled.registrySha256, + untrustedRoots: [repoRoot], + }); + assert.equal(trusted.ok, true, trusted.ok ? '' : JSON.stringify(trusted.error)); + if (!trusted.ok) return; + const plan = await compilePlan(trusted.value); + assert.equal(plan.ok, true, plan.ok ? '' : JSON.stringify(plan.error)); + if (plan.ok) { + const evolveSlot = plan.value.verifierSlots.find(s => s.checkId === 'evolve-guard'); + assert.ok(evolveSlot, 'expected evolve-block-guard.v1 verifier slot in CompiledPlan'); + assert.equal(evolveSlot.handler.implementation, 'evolve-block-guard.v1'); + } + } finally { + if (prevSign === undefined) delete process.env['BENCH_SIGNING_SECRET']; + else process.env['BENCH_SIGNING_SECRET'] = prevSign; + } + }); + }); + + it('rejects invalid evolve-block-guard.v1, Stage A audit fields, and bucketScope declarations fail-closed', () => { + const assertInvalid = (raw: Record, message: string): void => { + assert.throws( + () => validateTaskpackV2Manifest(raw as Json), + (err: unknown) => err instanceof TaskpackError && err.code === 'TASKPACK_MANIFEST_INVALID', + message, + ); + }; + + // evolve-block-guard.v1 invalid cases + assertInvalid( + makeEvolutionManifestObject({ + localChecks: [{ id: 'g', implementation: 'evolve-block-guard.v1', parameters: { files: [] } }], + }), + 'empty files must fail', + ); + assertInvalid( + makeEvolutionManifestObject({ + localChecks: [{ id: 'g', implementation: 'evolve-block-guard.v1', parameters: { files: ['../escape.cu'] } }], + }), + 'parent traversal must fail', + ); + assertInvalid( + makeEvolutionManifestObject({ + localChecks: [{ id: 'g', implementation: 'evolve-block-guard.v1', parameters: { files: ['.github/workflows/ci.yml'] } }], + }), + '.github/workflows/ path must fail', + ); + assertInvalid( + makeEvolutionManifestObject({ + localChecks: [{ id: 'g', implementation: 'evolve-block-guard.v1', parameters: { files: ['src/Kernel.cu', 'src/kernel.cu'] } }], + }), + 'case-folded duplicate files must fail', + ); + assertInvalid( + makeEvolutionManifestObject({ + localChecks: [{ + id: 'g', + implementation: 'evolve-block-guard.v1', + parameters: { files: ['src/kernel.cu'], allowedBlockIds: [] }, + }], + }), + 'empty allowedBlockIds must fail', + ); + assertInvalid( + makeEvolutionManifestObject({ + localChecks: [{ + id: 'g', + implementation: 'evolve-block-guard.v1', + parameters: { files: ['src/kernel.cu'], allowedBlockIds: ['bad/*id'] }, + }], + }), + 'invalid block id must fail', + ); + assertInvalid( + makeEvolutionManifestObject({ + localChecks: [{ + id: 'g', + implementation: 'evolve-block-guard.v1', + parameters: { files: ['src/kernel.cu'], maxBlockBytes: 0 }, + }], + }), + 'zero maxBlockBytes must fail', + ); + assertInvalid( + makeEvolutionManifestObject({ + localChecks: [{ + id: 'g', + implementation: 'evolve-block-guard.v1', + parameters: { files: ['src/kernel.cu'], maxBlockBytes: -0 }, + }], + }), + '-0 maxBlockBytes must fail', + ); + assertInvalid( + makeEvolutionManifestObject({ + localChecks: [{ + id: 'g', + implementation: 'evolve-block-guard.v1', + parameters: { files: ['src/kernel.cu'], extra: true }, + }], + }), + 'unknown parameter key must fail', + ); + + // Stage A static audit invalid cases + assertInvalid( + makeEvolutionManifestObject({ + localChecks: [], + targetMatrix: [{ + id: 'h100-sxm', + platform: 'linux/amd64', + variant: 'cuda12', + hardware: { + accelerator: 'sm_90a', + isolationMode: 'whole_device', + forbiddenSymbolPatterns: ['cublas*'], + }, + }], + }), + 'glob in forbiddenSymbolPatterns must fail', + ); + assertInvalid( + makeEvolutionManifestObject({ + localChecks: [], + targetMatrix: [{ + id: 'h100-sxm', + platform: 'linux/amd64', + variant: 'cuda12', + hardware: { + accelerator: 'sm_90a', + isolationMode: 'whole_device', + forbiddenSymbolPatterns: ['cublas', 'cublas'], + }, + }], + }), + 'duplicate forbiddenSymbolPatterns must fail', + ); + assertInvalid( + makeEvolutionManifestObject({ + localChecks: [], + targetMatrix: [{ + id: 'h100-sxm', + platform: 'linux/amd64', + variant: 'cuda12', + hardware: { + accelerator: 'sm_90a', + isolationMode: 'whole_device', + maxRegisterCount: -1, + }, + }], + }), + 'negative maxRegisterCount must fail', + ); + assertInvalid( + makeEvolutionManifestObject({ + localChecks: [], + targetMatrix: [{ + id: 'h100-sxm', + platform: 'linux/amd64', + variant: 'cuda12', + hardware: { + accelerator: 'sm_90a', + isolationMode: 'whole_device', + maxLocalSpillBytes: 1.5, + }, + }], + }), + 'non-integer maxLocalSpillBytes must fail', + ); + + // bucketScope invalid cases + assertInvalid( + makeEvolutionManifestObject({ + localChecks: [], + externalGates: [{ + id: 'bench-h100', + implementation: 'benchmark-gate.v1', + gateId: 'Roofline Gate v1', + endpointId: 'bench-relay', + required: true, + targetCellId: 'h100-sxm', + heldOutWorkloadId: 'kernel.matmul.v1', + metricThresholds: [{ kind: 'bounds', metric: 'max_ulp', max: 1, bucketScope: 'some_buckets' }], + }], + }), + 'unknown bucketScope string must fail', + ); + assertInvalid( + makeEvolutionManifestObject({ + localChecks: [], + externalGates: [{ + id: 'bench-h100', + implementation: 'benchmark-gate.v1', + gateId: 'Roofline Gate v1', + endpointId: 'bench-relay', + required: true, + targetCellId: 'h100-sxm', + heldOutWorkloadId: 'kernel.matmul.v1', + metricThresholds: [{ kind: 'bounds', metric: 'max_ulp', max: 1, bucketScope: { bucketId: '__proto__' } }], + }], + }), + 'prototype bucketId must fail', + ); + + // Legacy v1 manifest rejects evolve-block-guard.v1 + const legacyManifest = { + ...makeEvolutionManifestObject({ externalGates: [] }), + spec: { + ...(makeEvolutionManifestObject({ externalGates: [] }).spec as Record), + proposal: { path: 'src/proposal.json', requiredFields: ['ok'], schemaVersion: 1 }, + }, + }; + assert.throws( + () => validateTaskpackManifest(legacyManifest as Json), + (err: unknown) => err instanceof TaskpackError && err.code === 'TASKPACK_MANIFEST_INVALID', + 'legacy v1 manifest must reject evolve-block-guard.v1', + ); + }); + + it('omits unset optional fields and preserves byte-identical TaskContract and TaskLock canonical digests', async () => { + await withTempDir(async dir => { + const repoRoot = join(dir, 'repo'); + await mkdir(join(repoRoot, 'src'), { recursive: true }); + await writeFile(join(repoRoot, 'src', 'kernel.cu'), '// kernel\n', 'utf8'); + + const legacyHardwareManifest = validateTaskpackV2Manifest( + makeEvolutionManifestObject({ + localChecks: [], + targetMatrix: [{ + id: 'h100-sxm', + platform: 'linux/amd64', + variant: 'cuda12', + hardware: { + accelerator: 'sm_90a', + isolationMode: 'whole_device', + deviceCount: 1, + }, + }], + externalGates: [{ + id: 'bench-h100', + implementation: 'benchmark-gate.v1', + gateId: 'Roofline Gate v1', + endpointId: 'bench-relay', + required: true, + targetCellId: 'h100-sxm', + heldOutWorkloadId: 'kernel.matmul.v1', + metricThresholds: [ + { kind: 'bounds', metric: 'latency_ms', max: 10 }, + ], + }], + }) as Json, + ); + + const compiled = await compileDeclarativeTaskpack(legacyHardwareManifest, { + mode: 'candidate', + executionMode: 'delegated', + repository: 'local/kernel-repo', + repositoryRoot: repoRoot, + baseRevision: BASE_SHA, + sourceRevision: BASE_SHA, + budgets: DEFAULT_HOST_BUDGETS, + gateEndpoints: [ + { + id: 'bench-relay', + url: 'http://127.0.0.1:42010/v1/benchmark/jobs', + signingCredentialRef: 'bench-signing', + authCredentialRef: null, + }, + ], + credentialEnvMap: { gate: 'BENCH_SIGNING_SECRET' }, + }); + + const hw = compiled.config.spec.task.spec.target.matrix?.[0]?.hardware as unknown as Record; + assert.equal(Object.hasOwn(hw, 'forbiddenSymbolPatterns'), false); + assert.equal(Object.hasOwn(hw, 'maxRegisterCount'), false); + assert.equal(Object.hasOwn(hw, 'maxLocalSpillBytes'), false); + const threshold = compiled.config.spec.task.spec.acceptance.checks.find(c => c.id === 'bench-h100') + ?.metricThresholds?.[0] as unknown as Record; + assert.equal(Object.hasOwn(threshold, 'bucketScope'), false); + + // Compare canonical TaskContract & TaskLock digests against a fresh copy stripped of any optional keys + const clonedContract = JSON.parse(JSON.stringify(compiled.config.spec.task)) as Json; + const revalidated = validateDocument(clonedContract, 'TaskContract'); + assert.equal(revalidated.ok, true); + if (!revalidated.ok) return; + assert.equal(canonical(compiled.config.spec.task), canonical(revalidated.value)); + const lockA = admitTask(compiled.config.spec.task, { admissionId: 'adm-parity', runId: 'run-parity' }); + const lockB = admitTask(revalidated.value, { admissionId: 'adm-parity', runId: 'run-parity' }); + assert.equal(lockA.ok && lockB.ok, true); + if (lockA.ok && lockB.ok) { + assert.equal(lockA.value.spec.contractHash.hex, lockB.value.spec.contractHash.hex); + assert.equal(lockA.value.spec.lockHash.hex, lockB.value.spec.lockHash.hex); + } + }); + }); + + it('projects hardwareScope for memory selection (sm_89 isolates sm_100a and ascend_910b) and local finalization', async () => { + const sm89Cell: TargetMatrixCell = { + id: 'l40s-sm89', + platform: 'linux/amd64', + variant: 'cuda12', + hardware: { + accelerator: 'sm_89', + isolationMode: 'whole_device', + deviceCount: 1, + driverConstraint: '>=550.54', + }, + }; + const sm89NoDriverCell: TargetMatrixCell = { + id: 'l40s-sm89', + platform: 'linux/amd64', + variant: 'cuda12', + hardware: { + accelerator: 'sm_89', + isolationMode: 'whole_device', + }, + }; + const legacyCell: TargetMatrixCell = { + id: 'cpu-x64', + platform: 'linux/amd64', + variant: 'default', + }; + + assert.deepEqual(projectMemoryHardwareScope(sm89Cell), { + accelerator: 'sm_89', + driverConstraint: '>=550.54', + }); + const noDriverScope = projectMemoryHardwareScope(sm89NoDriverCell); + assert.deepEqual(noDriverScope, { accelerator: 'sm_89' }); + assert.equal(Object.hasOwn(noDriverScope as unknown as Record, 'driverConstraint'), false); + assert.equal(projectMemoryHardwareScope(legacyCell), undefined); + assert.equal(projectMemoryHardwareScope(null), undefined); + assert.equal(projectMemoryHardwareScope(undefined), undefined); + + await withTempDir(async dir => { + const repoRoot = join(dir, 'repo'); + const runRoot = join(dir, 'runs'); + await mkdir(join(repoRoot, 'src'), { recursive: true }); + await mkdir(runRoot, { recursive: true, mode: 0o700 }); + await writeFile(join(repoRoot, 'src', 'kernel.cu'), '// kernel\n', 'utf8'); + + // Seed memory store with: unscoped entry, sm_89 matching entry, sm_100a entry, ascend_910b entry, and mismatched driver entry + const entries: MemoryEntry[] = [ + makeMemoryEntry({ + id: 'mem-unscoped', + claimKey: 'unscoped.rule', + claim: 'Shared repo invariant applies to all accelerators.', + }), + makeMemoryEntry({ + id: 'mem-sm89-match', + claimKey: 'sm89.shared-mem', + claim: 'sm_89 favors 48 KiB shared memory tiling.', + hardwareScope: { accelerator: 'sm_89', driverConstraint: '>=550.54' }, + }), + makeMemoryEntry({ + id: 'mem-sm100a-foreign', + claimKey: 'sm100a.tmem', + claim: 'sm_100a tensor memory pipeline rule.', + hardwareScope: { accelerator: 'sm_100a', driverConstraint: '>=570.0' }, + }), + makeMemoryEntry({ + id: 'mem-ascend-foreign', + claimKey: 'ascend.ub', + claim: 'ascend_910b unified buffer tiling rule.', + hardwareScope: { accelerator: 'ascend_910b' }, + }), + makeMemoryEntry({ + id: 'mem-sm89-driver-mismatch', + claimKey: 'sm89.driver-old', + claim: 'sm_89 legacy driver workaround.', + hardwareScope: { accelerator: 'sm_89', driverConstraint: '>=535.0' }, + }), + ]; + const baseIndex: Omit = { + version: 1, + taskpack: 'evo-kernel', + repository: 'local/kernel-repo', + updatedAtMs: 1_700_000_000_000, + entries, + retired: [], + }; + const seededIndex: MemoryStoreIndex = Object.freeze({ + ...baseIndex, + storeDigest: storeDigestOf(baseIndex), + }); + const memDir = join(repoRoot, '.loopwright', 'memory', 'evo-kernel'); + const entriesDir = join(memDir, 'entries'); + await mkdir(entriesDir, { recursive: true }); + await writeFile(join(memDir, 'index.json'), serializeMemoryStoreIndex(seededIndex), 'utf8'); + for (const entry of entries) { + await writeFile(join(entriesDir, `${entry.id}.md`), renderEntryMarkdown(entry), 'utf8'); + } + + const sm89Manifest = validateTaskpackV2Manifest( + makeEvolutionManifestObject({ + localChecks: [], + targetMatrix: [sm89Cell], + externalGates: [{ + id: 'bench-sm89', + implementation: 'benchmark-gate.v1', + gateId: 'Roofline Gate v1', + endpointId: 'bench-relay', + required: true, + targetCellId: 'l40s-sm89', + heldOutWorkloadId: 'kernel.matmul.v1', + }], + }) as Json, + ); + + const compiled = await compileDeclarativeTaskpack(sm89Manifest, { + mode: 'candidate', + executionMode: 'delegated', + repository: 'local/kernel-repo', + repositoryRoot: repoRoot, + baseRevision: BASE_SHA, + sourceRevision: BASE_SHA, + nowMs: 1_700_000_010_000, + budgets: DEFAULT_HOST_BUDGETS, + gateEndpoints: [ + { + id: 'bench-relay', + url: 'http://127.0.0.1:42010/v1/benchmark/jobs', + signingCredentialRef: 'bench-signing', + authCredentialRef: null, + }, + ], + credentialEnvMap: { gate: 'BENCH_SIGNING_SECRET' }, + }); + + assert.equal(compiled.activeMemory?.activeEntryCount, 2, JSON.stringify(compiled.activeMemory)); + assert.equal(compiled.activeMemory?.excludedEntryCount, 3, JSON.stringify(compiled.activeMemory)); + const memResource = (compiled.instructionResources ?? []).find(r => r.id.startsWith('memory.')); + assert.ok(memResource, 'expected staged active memory resource'); + const rendered = memResource.bytes.toString('utf8'); + assert.match(rendered, /mem-unscoped/); + assert.match(rendered, /mem-sm89-match/); + assert.doesNotMatch(rendered, /mem-sm100a-foreign/); + assert.doesNotMatch(rendered, /mem-ascend-foreign/); + assert.doesNotMatch(rendered, /mem-sm89-driver-mismatch/); + + // Finalize a local-only run with sm89Cell and verify persisted entry carries hardwareScope + const runId = 'run-sm89-hw-scope-1'; + const locked = admitTask(compiled.config.spec.task, { admissionId: 'adm-sm89-1', runId }); + assert.equal(locked.ok, true); + if (!locked.ok) return; + const runDir = join(runRoot, runId); + const artifactsDir = join(runDir, 'artifacts'); + await mkdir(artifactsDir, { recursive: true, mode: 0o700 }); + await writeFile(join(runDir, 'run.json'), JSON.stringify({ version: 1, identity: { lock: locked.value } }), 'utf8'); + const planBytes = Buffer.from(JSON.stringify({ stage: 'execution', note: 'sm89 timeout' }), 'utf8'); + const planRef = digestArtifact('plan-incident.bin', planBytes); + assert.equal(planRef.ok, true); + if (!planRef.ok) return; + await writeFile(join(artifactsDir, planRef.value.name), planBytes); + const incident: ControllerIncident = { + version: 1, + code: 'DEADLINE', + runId, + lockHash: locked.value.spec.lockHash, + stage: 'execution', + knownReferences: [planRef.value], + unavailable: ['candidate'], + cleanup: 'complete', + }; + await writeFile(join(artifactsDir, `incident-${runId}.bin`), JSON.stringify(incident), 'utf8'); + + const summary = await finalizeLocalTurnkeyMemory({ + runRoot, + runId, + repositoryRoot: repoRoot, + repositoryFullName: 'local/kernel-repo', + manifest: sm89Manifest, + baseRevision: BASE_SHA, + targetMatrix: sm89Cell, + nowMs: 1_700_000_020_000, + scrubber: new SecretScrubber(), + }); + assert.equal(summary.status, 'local_only', summary.reason ?? ''); + const reloaded = await loadMemoryStore(repoRoot, 'evo-kernel', 'local/kernel-repo', '.loopwright/memory'); + const incidentEntry = reloaded.index.entries.find(e => e.sourceRef.runId === runId); + assert.ok(incidentEntry, 'expected persisted incident memory entry'); + assert.deepEqual({ ...incidentEntry.scope.hardwareScope }, { + accelerator: 'sm_89', + driverConstraint: '>=550.54', + }); + }); + }); +}); diff --git a/packages/taskpack/test/turnkey-env-isolation.test.ts b/packages/taskpack/test/turnkey-env-isolation.test.ts new file mode 100644 index 0000000..3c0b8b6 --- /dev/null +++ b/packages/taskpack/test/turnkey-env-isolation.test.ts @@ -0,0 +1,370 @@ +import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; +import { chmod, mkdir, mkdtemp, realpath, rm, writeFile } from 'node:fs/promises'; +import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { describe, it } from 'node:test'; +import { openPiHostSessionAdapterV2 } from '@loopwright/agent-pi/host-session'; +import { + compileDeclarativeTaskpack, + DEFAULT_HOST_BUDGETS, + DEFAULT_LOCAL_COMMAND_GATE_ENV, + executeTurnkeyCycle, + LOOPWRIGHT_ACTIVE_PROVIDER_TOKEN_ENV, + SecretScrubber, + serializePrettyYaml, + stageCompiledInstructionResources, + startLocalCommandGateServer, + validateTaskpackV2Manifest, + type WrittenCompiledTaskpack, +} from '../src/index.js'; + +function initGitRepo(repoRoot: string): string { + spawnSync('git', ['init', '-b', 'main'], { cwd: repoRoot, stdio: 'ignore' }); + spawnSync('git', ['config', 'user.name', 'Loopwright Test'], { cwd: repoRoot, stdio: 'ignore' }); + spawnSync('git', ['config', 'user.email', 'test@loopwright.invalid'], { cwd: repoRoot, stdio: 'ignore' }); + spawnSync('git', ['add', '.'], { cwd: repoRoot, stdio: 'ignore' }); + spawnSync('git', ['commit', '-m', 'Initial commit'], { cwd: repoRoot, stdio: 'ignore' }); + return spawnSync('git', ['rev-parse', 'HEAD'], { cwd: repoRoot, encoding: 'utf8' }).stdout.trim(); +} + +function sseToolCall(model: string, id: string, name: string, args: Record): string { + return [ + `data: ${JSON.stringify({ + id: `chatcmpl-${id}`, + model, + choices: [{ + index: 0, + delta: { + role: 'assistant', + tool_calls: [{ index: 0, id, type: 'function', function: { name, arguments: JSON.stringify(args) } }], + }, + finish_reason: null, + }], + })}`, + '', + `data: ${JSON.stringify({ + id: `chatcmpl-${id}`, + model, + choices: [{ index: 0, delta: {}, finish_reason: 'tool_calls' }], + usage: { prompt_tokens: 40, completion_tokens: 10, total_tokens: 50 }, + })}`, + '', + 'data: [DONE]', + '', + '', + ].join('\n'); +} + +function sseStop(model: string, text: string): string { + return [ + `data: ${JSON.stringify({ + id: 'chatcmpl-final', + model, + choices: [{ index: 0, delta: { role: 'assistant', content: text }, finish_reason: 'stop' }], + usage: { prompt_tokens: 40, completion_tokens: 10, total_tokens: 50 }, + })}`, + '', + 'data: [DONE]', + '', + '', + ].join('\n'); +} + +function createBarrier(parties: number): () => Promise { + let arrived = 0; + let release!: () => void; + const gate = new Promise(resolve => { + release = resolve; + }); + return async () => { + arrived += 1; + if (arrived >= parties) { + release(); + } + await gate; + }; +} + +describe('executeTurnkeyCycle concurrent environment isolation', () => { + it('runs two parallel executeTurnkeyCycle calls with distinct ephemeralEnv secrets without clobbering each other or mutating process.env', async () => { + const base = await realpath(tmpdir()); + const holder = await mkdtemp(join(base, 'lw-tp-env-iso-')); + const prevActiveToken = process.env[LOOPWRIGHT_ACTIVE_PROVIDER_TOKEN_ENV]; + const prevGateSecret = process.env[DEFAULT_LOCAL_COMMAND_GATE_ENV]; + const hostGateSentinel = 'HOST_SENTINEL_GATE_SECRET_MUST_NOT_CHANGE_9876543210'; + + const tokenA = 'sk-island-A-provider-token-1111111111'; + const tokenB = 'sk-island-B-provider-token-2222222222'; + + const observedAuthHeaders: Record<'a' | 'b', string[]> = { a: [], b: [] }; + const turnCounters: Record<'a' | 'b', number> = { a: 0, b: 0 }; + const envSnapshotsDuringExec: Array<{ + readonly island: 'a' | 'b'; + readonly activeToken: string | undefined; + readonly gateSecret: string | undefined; + }> = []; + const fallbackTokens: Record<'a' | 'b', string | null> = { a: null, b: null }; + + const adapterBarrier = createBarrier(2); + + const sseServer = createServer((req: IncomingMessage, res: ServerResponse) => { + req.resume(); + req.on('end', () => { + const url = req.url ?? ''; + const island: 'a' | 'b' = url.startsWith('/island-a/') ? 'a' : 'b'; + const authHeader = typeof req.headers['authorization'] === 'string' ? req.headers['authorization'] : ''; + observedAuthHeaders[island].push(authHeader); + envSnapshotsDuringExec.push({ + island, + activeToken: process.env[LOOPWRIGHT_ACTIVE_PROVIDER_TOKEN_ENV], + gateSecret: process.env[DEFAULT_LOCAL_COMMAND_GATE_ENV], + }); + + const turn = turnCounters[island]++; + res.writeHead(200, { 'content-type': 'text/event-stream' }); + if (turn === 0) { + res.end(sseToolCall('mock-model', `call-${island}-0`, 'write', { + path: 'src/app.txt', + content: `updated-by-${island}\n`, + })); + } else { + res.end(sseStop('mock-model', JSON.stringify({ + version: 1, + status: 'completed', + checks: [], + reason: `island ${island} updated src/app.txt`, + }))); + } + }); + }); + + await new Promise(resolveListen => sseServer.listen(0, '127.0.0.1', () => resolveListen())); + const ssePort = (sseServer.address() as { port: number }).port; + + let gateServerA: Awaited> | undefined; + let gateServerB: Awaited> | undefined; + + try { + delete process.env[LOOPWRIGHT_ACTIVE_PROVIDER_TOKEN_ENV]; + process.env[DEFAULT_LOCAL_COMMAND_GATE_ENV] = hostGateSentinel; + + const setupIsland = async (island: 'a' | 'b') => { + const repoRoot = join(holder, `repo-${island}`); + const runRoot = join(holder, `runs-${island}`); + await mkdir(join(repoRoot, 'src'), { recursive: true }); + await mkdir(join(repoRoot, '.loopwright', 'checks'), { recursive: true }); + await mkdir(runRoot, { recursive: true, mode: 0o700 }); + await chmod(runRoot, 0o700); + await writeFile(join(repoRoot, 'src', 'app.txt'), 'initial\n', 'utf8'); + await writeFile( + join(repoRoot, '.loopwright', 'checks', 'verify.sh'), + [ + '#!/bin/sh', + 'set -eu', + `grep -q "updated-by-${island}" "$LOOPWRIGHT_CANDIDATE_DIR/src/app.txt"`, + `printf '{"detail":"verified-${island}"}\\n' > "$LOOPWRIGHT_CHECK_OUT"`, + ].join('\n') + '\n', + { mode: 0o755 }, + ); + const baseSha = initGitRepo(repoRoot); + + const modelsJsonPath = join(holder, `models-${island}.json`); + await writeFile( + modelsJsonPath, + JSON.stringify({ + providers: { + 'local-oai': { + baseUrl: `http://127.0.0.1:${ssePort}/island-${island}/v1`, + api: 'openai-completions', + apiKey: LOOPWRIGHT_ACTIVE_PROVIDER_TOKEN_ENV, + models: [{ id: 'mock-model', contextWindow: 128_000, maxTokens: 4_096 }], + }, + }, + }), + 'utf8', + ); + + const manifest = validateTaskpackV2Manifest({ + apiVersion: 'loopwright.dev/v1alpha1', + kind: 'Taskpack', + metadata: { name: `env-iso-${island}` }, + spec: { + goal: { candidate: `Update src/app.txt for island ${island}.`, noChange: 'Confirm no change.' }, + scope: { writable: ['src/**'], protected: [] }, + models: [{ provider: 'local-oai', id: 'mock-model', apiKeyEnv: LOOPWRIGHT_ACTIVE_PROVIDER_TOKEN_ENV }], + verification: { + localChecks: [ + { + id: 'verify-cmd', + implementation: 'command.v1', + parameters: { script: '.loopwright/checks/verify.sh', timeoutSeconds: 20 }, + }, + ], + externalGates: [], + }, + }, + }); + + const baseBindings = { + mode: 'candidate' as const, + repository: `local/island-${island}`, + repositoryRoot: repoRoot, + baseRevision: baseSha, + sourceRevision: baseSha, + budgets: DEFAULT_HOST_BUDGETS, + modelsJsonPath, + hostPolicy: { policyProfile: 'local' as const, allowPrivileged: false, allowWorkflowWrites: false }, + credentialEnvMap: { + provider: LOOPWRIGHT_ACTIVE_PROVIDER_TOKEN_ENV, + localCommandGate: DEFAULT_LOCAL_COMMAND_GATE_ENV, + }, + }; + + const preview = await compileDeclarativeTaskpack(manifest, baseBindings); + const gateServer = await startLocalCommandGateServer({ + runRoot, + repositoryRoot: repoRoot, + gates: preview.localCommandGates ?? [], + hostPolicy: { policyProfile: 'local', allowPrivileged: false, allowWorkflowWrites: false }, + runtimeEnv: { PATH: process.env['PATH'] ?? '/usr/bin:/bin' }, + }); + const compiled = await compileDeclarativeTaskpack(manifest, { + ...baseBindings, + gateEndpoints: [gateServer.endpointPlan], + }); + + const trustedDirectory = join(runRoot, `trusted-${island}`); + const regDir = join(trustedDirectory, 'registry'); + const cfgDir = join(trustedDirectory, 'config'); + await mkdir(regDir, { recursive: true, mode: 0o700 }); + await mkdir(cfgDir, { recursive: true, mode: 0o700 }); + await chmod(trustedDirectory, 0o700); + const registryPath = join(regDir, 'registry.yaml'); + const configPath = join(cfgDir, 'config.yaml'); + const configBytes = Buffer.from(serializePrettyYaml(compiled.config), 'utf8'); + await writeFile(registryPath, compiled.registryBytes, { mode: 0o600 }); + await writeFile(configPath, configBytes, { mode: 0o600 }); + await stageCompiledInstructionResources(regDir, compiled.instructionResources); + + const taskpack: WrittenCompiledTaskpack = { + ...compiled, + configBytes, + trustedDirectory, + registryPath, + configPath, + }; + return { repoRoot, gateServer, taskpack }; + }; + + const islandA = await setupIsland('a'); + gateServerA = islandA.gateServer; + const islandB = await setupIsland('b'); + gateServerB = islandB.gateServer; + + assert.notEqual(gateServerA.signingSecret, gateServerB.signingSecret); + + const makeWrappedAdapter = ( + island: 'a' | 'b', + postBarrierDelayMs: number, + ): NonNullable[0]['openHostSessionAdapter']> => + async (host, input, opts) => { + await adapterBarrier(); + envSnapshotsDuringExec.push({ + island, + activeToken: process.env[LOOPWRIGHT_ACTIVE_PROVIDER_TOKEN_ENV], + gateSecret: process.env[DEFAULT_LOCAL_COMMAND_GATE_ENV], + }); + + // Trigger the active-token fallback path in wrappedHost.resolveCredential using a mismatched destination. + const fallback = await host.resolveCredential({ + provider: input.policy.selection.provider, + model: input.policy.selection.model, + destination: 'https://mismatched.invalid/v1/chat/completions', + purpose: 'task', + runId: `env-iso-run-${island}`, + roleId: input.roleId, + stepId: input.stepId, + notAfterMonotonicMs: '1000', + signal: new AbortController().signal, + }); + fallbackTokens[island] = fallback.bearerToken; + + if (postBarrierDelayMs > 0) { + await new Promise(resolveDelay => setTimeout(resolveDelay, postBarrierDelayMs)); + } + return await openPiHostSessionAdapterV2(host, input, opts); + }; + + const [resA, resB] = await Promise.all([ + executeTurnkeyCycle({ + runId: 'env-iso-run-a', + attemptSeq: 0, + repositoryRoot: islandA.repoRoot, + taskpack: islandA.taskpack, + runtimeEnv: { PATH: process.env['PATH'] ?? '/usr/bin:/bin' }, + ephemeralEnv: { + [LOOPWRIGHT_ACTIVE_PROVIDER_TOKEN_ENV]: tokenA, + [DEFAULT_LOCAL_COMMAND_GATE_ENV]: gateServerA.signingSecret, + }, + scrubber: new SecretScrubber(), + policyProfile: 'local', + openHostSessionAdapter: makeWrappedAdapter('a', 0), + }), + executeTurnkeyCycle({ + runId: 'env-iso-run-b', + attemptSeq: 0, + repositoryRoot: islandB.repoRoot, + taskpack: islandB.taskpack, + runtimeEnv: { PATH: process.env['PATH'] ?? '/usr/bin:/bin' }, + ephemeralEnv: { + [LOOPWRIGHT_ACTIVE_PROVIDER_TOKEN_ENV]: tokenB, + [DEFAULT_LOCAL_COMMAND_GATE_ENV]: gateServerB.signingSecret, + }, + scrubber: new SecretScrubber(), + policyProfile: 'local', + // Delay island B slightly so island A finishes while island B is still verifying its gate HMAC. + openHostSessionAdapter: makeWrappedAdapter('b', 150), + }), + ]); + + assert.equal(resA.ok, true, `island A failed: ${resA.detail}`); + assert.equal(resA.status, 'completed'); + assert.equal(resB.ok, true, `island B failed: ${resB.detail}`); + assert.equal(resB.status, 'completed'); + + // Each island sent exclusively its own provider bearer token on the wire and via fallback. + assert.ok(observedAuthHeaders.a.length >= 2); + assert.ok(observedAuthHeaders.b.length >= 2); + assert.equal(observedAuthHeaders.a.every(h => h === `Bearer ${tokenA}`), true, JSON.stringify(observedAuthHeaders.a)); + assert.equal(observedAuthHeaders.b.every(h => h === `Bearer ${tokenB}`), true, JSON.stringify(observedAuthHeaders.b)); + assert.equal(fallbackTokens.a, tokenA); + assert.equal(fallbackTokens.b, tokenB); + + // Global process.env was never mutated during or after concurrent execution. + assert.ok(envSnapshotsDuringExec.length >= 4); + for (const snap of envSnapshotsDuringExec) { + assert.equal(snap.activeToken, undefined, `process.env.${LOOPWRIGHT_ACTIVE_PROVIDER_TOKEN_ENV} mutated during island ${snap.island}`); + assert.equal(snap.gateSecret, hostGateSentinel, `process.env.${DEFAULT_LOCAL_COMMAND_GATE_ENV} mutated during island ${snap.island}`); + } + assert.equal(process.env[LOOPWRIGHT_ACTIVE_PROVIDER_TOKEN_ENV], undefined); + assert.equal(process.env[DEFAULT_LOCAL_COMMAND_GATE_ENV], hostGateSentinel); + } finally { + if (prevActiveToken === undefined) { + delete process.env[LOOPWRIGHT_ACTIVE_PROVIDER_TOKEN_ENV]; + } else { + process.env[LOOPWRIGHT_ACTIVE_PROVIDER_TOKEN_ENV] = prevActiveToken; + } + if (prevGateSecret === undefined) { + delete process.env[DEFAULT_LOCAL_COMMAND_GATE_ENV]; + } else { + process.env[DEFAULT_LOCAL_COMMAND_GATE_ENV] = prevGateSecret; + } + await gateServerA?.close().catch(() => undefined); + await gateServerB?.close().catch(() => undefined); + await new Promise(resolveClose => sseServer.close(() => resolveClose())); + await rm(holder, { recursive: true, force: true }).catch(() => undefined); + } + }); +}); diff --git a/scripts/build.mjs b/scripts/build.mjs index d52ba8c..b4eb3bf 100644 --- a/scripts/build.mjs +++ b/scripts/build.mjs @@ -22,6 +22,7 @@ const PACKAGES = [ 'taskpack', 'github-app', 'hardware-runner', + 'evolution', 'cli', ]; diff --git a/scripts/check-docs.mjs b/scripts/check-docs.mjs index 55891a0..c05ccc3 100755 --- a/scripts/check-docs.mjs +++ b/scripts/check-docs.mjs @@ -669,7 +669,7 @@ export function checkPrettyYamlBlocks(relDoc, content, errors) { } } - const NAMED_METADATA_KINDS = new Set(["Taskpack", "TrustedRegistry"]); + const NAMED_METADATA_KINDS = new Set(["Taskpack", "TrustedRegistry", "EvolutionCampaign"]); const METADATA_FREE_KINDS = new Set([ "ControllerConfig", "TaskContract", diff --git a/scripts/generate-diagrams.mjs b/scripts/generate-diagrams.mjs index afbc8c2..5b1c144 100644 --- a/scripts/generate-diagrams.mjs +++ b/scripts/generate-diagrams.mjs @@ -939,6 +939,246 @@ ${pillsHtml} `; } +function renderHardwareRelayFlowSvg() { + const diagramName = "hardware-relay-flow.svg"; + const width = 1200; + const height = 1036; + + const headerTexts = [ + "LOOPWRIGHT / HARDWARE RUNNER", + "Hardware Relay and Network Boundaries", + "Three isolated network zones separate control plane credentials, relay DMZ routing, and private GPU clusters", + "ZONE 1 · CONTROL PLANE ZONE · OUTBOUND HTTPS ONLY", + "SIGNED BENCHMARK SUBMISSION · LOCAL CLI OR GITHUB ACTIONS", + "OUTBOUND HTTPS ONLY · HMAC JOB SUBMIT · NO WORKER TOKENS", + "ZONE 2 · RELAY DMZ BOUNDARY · HTTPS & CREDENTIAL ISOLATION", + "HARDWARE RELAY & CAS HUB · RELAY DMZ", + "HTTPS Endpoint · HMAC Auth · Monotonic Lease Fence · 1 MB CAS Store", + "Separates controller signing secrets from worker bearer tokens across distinct endpoints", + "CLUSTER FIREWALL · ZERO INBOUND PORTS · WORKER PULLS OVER HTTPS", + "ZONE 3 · PRIVATE GPU CLUSTER ZONE · OUTBOUND PULL & OFFLINE SANDBOX", + "OFFLINE DOCKER SANDBOX · ZERO NETWORK", + "GPU hosts open zero inbound ports and hold no signing secrets; controllers never read held-out suites." + ]; + for (const t of headerTexts) { + assertCleanSvgText(diagramName, "header/boundary", t); + } + + const domains = [ + { + title: "CAMPAIGN CLIENTS · Job Producers", + items: [ + { kicker: "LOCAL CLI", head: "Evolution campaigns", note: "Dispatches candidate jobs" }, + { kicker: "CI WORKFLOW", head: "GitHub Actions", note: "Runs with read scope" } + ] + }, + { + title: "SIGNED PAYLOAD · Controller Secret", + items: [ + { kicker: "BENCHMARK JOB", head: "Target pool routing", note: "Matches GPU capabilities" }, + { kicker: "HMAC SECRET", head: "Controller signing key", note: "Authenticates verdict receipts" } + ] + } + ]; + + const topDomainsHtml = domains + .map((dom, dIdx) => { + assertCleanSvgText(diagramName, `domain-${dIdx}`, dom.title); + const dx = dIdx === 0 ? 50 : 602; + const cardsHtml = dom.items + .map((it, iIdx) => { + assertCardWordLimit(diagramName, `domain-${dIdx}-card-${iIdx}`, [ + it.kicker, + it.head, + it.note + ]); + const ix = dx + 16 + iIdx * 266; + return [ + ``, + `${esc(it.kicker)}`, + `${esc(it.head)}`, + `${esc(it.note)}` + ].join(""); + }) + .join(""); + return [ + ``, + `${esc(dom.title)}`, + cardsHtml + ].join(""); + }) + .join(""); + + const wireXs = [179, 453, 727, 1001]; + const topWiresHtml = wireXs + .map((wx, idx) => { + const b1 = (-idx * 0.37).toFixed(2); + return [ + ``, + `` + ].join(""); + }) + .join(""); + + const bottomWiresHtml = wireXs + .map((wx, idx) => { + const b2 = (-(idx * 0.37 + 0.74)).toFixed(2); + return [ + ``, + `` + ].join(""); + }) + .join(""); + + const stageCards = [ + { + accent: "--indigo", + icon: "radar", + title: "01 · Worker Pull", + line1: "Zero inbound GPU ports", + line2: "Polls leases outbound" + }, + { + accent: "--teal", + icon: "layers", + title: "02 · Build Audit", + line1: "Offline zero-network compile", + line2: "Checks forbidden symbols" + }, + { + accent: "--amber", + icon: "chip", + title: "03 · GPU Bench", + line1: "Zero-network Docker sandbox", + line2: "Mounts holdout read-only" + }, + { + accent: "--emerald", + icon: "shield", + title: "04 · Verdict Receipt", + line1: "Returns signed HMAC", + line2: "Backs archive export" + } + ]; + + const stageCardsHtml = stageCards + .map((card, idx) => { + assertCardWordLimit(diagramName, `stage-card-${idx}`, [ + card.title, + card.line1, + card.line2 + ]); + const cx = 50 + idx * 274; + return [ + ``, + ``, + renderIcon(card.icon, cx + 16, 750, card.accent), + `${esc(card.title)}`, + `${esc(card.line1)}`, + `${esc(card.line2)}` + ].join(""); + }) + .join(""); + + const pills = [ + "Zone 1 to DMZ: outbound HTTPS job submit", + "Cluster firewall: zero inbound GPU ports", + "Stage A and B: offline zero-network Docker" + ]; + for (const pill of pills) { + assertCleanSvgText(diagramName, "pill", pill); + } + + const pillsHtml = pills + .map((pill, idx) => { + const px = 32 + idx * 384; + return [ + ``, + ``, + ``, + `${esc(pill)}` + ].join(""); + }) + .join(""); + + return ` +Hardware Relay and Network Boundaries +Three isolated network zones: Control Plane outbound HTTPS submit, Relay DMZ hub, and Private GPU Cluster behind a zero-inbound-ports firewall with offline zero-network Docker sandboxes. + + + + + + + + + +LOOPWRIGHT / HARDWARE RUNNER +Hardware Relay and Network Boundaries +Three isolated network zones separate control plane credentials, relay DMZ routing, and private GPU clusters +${renderLogoBadge(1126, 30, 42, 10)} + + +ZONE 1 · CONTROL PLANE ZONE · OUTBOUND HTTPS ONLY + +SIGNED BENCHMARK SUBMISSION · LOCAL CLI OR GITHUB ACTIONS +${topDomainsHtml} + +${topWiresHtml} + + +OUTBOUND HTTPS ONLY · HMAC JOB SUBMIT · NO WORKER TOKENS + + +ZONE 2 · RELAY DMZ BOUNDARY · HTTPS & CREDENTIAL ISOLATION + +${renderLogoBadge(52, 460, 48, 11)} +HARDWARE RELAY & CAS HUB · RELAY DMZ +HTTPS Endpoint · HMAC Auth · Monotonic Lease Fence · 1 MB CAS Store +Separates controller signing secrets from worker bearer tokens across distinct endpoints + +${bottomWiresHtml} + + +CLUSTER FIREWALL · ZERO INBOUND PORTS · WORKER PULLS OVER HTTPS + + +ZONE 3 · PRIVATE GPU CLUSTER ZONE · OUTBOUND PULL & OFFLINE SANDBOX + + +OFFLINE DOCKER SANDBOX · ZERO NETWORK +${stageCardsHtml} + +GPU hosts open zero inbound ports and hold no signing secrets; controllers never read held-out suites. +${pillsHtml} + +`; +} + for (const spec of DIAGRAMS) { const svg = renderBlueprintSvg(spec); const outPath = path.join(diagramsDir, spec.filename); @@ -954,4 +1194,10 @@ fs.writeFileSync( "utf8" ); -console.log(`Generated ${DIAGRAMS.length + 1} gpustack-style blueprint SVG diagrams.`); +fs.writeFileSync( + path.join(diagramsDir, "hardware-relay-flow.svg"), + renderHardwareRelayFlowSvg(), + "utf8" +); + +console.log(`Generated ${DIAGRAMS.length + 2} gpustack-style blueprint SVG diagrams.`); diff --git a/scripts/pack-npm.mjs b/scripts/pack-npm.mjs index d5443e5..008d858 100644 --- a/scripts/pack-npm.mjs +++ b/scripts/pack-npm.mjs @@ -18,6 +18,7 @@ const WORKSPACE_PACKAGES = [ 'taskpack', 'github-app', 'hardware-runner', + 'evolution', 'cli' ]; diff --git a/scripts/prepare-self-upgrade.mjs b/scripts/prepare-self-upgrade.mjs index a9594fd..833a31a 100755 --- a/scripts/prepare-self-upgrade.mjs +++ b/scripts/prepare-self-upgrade.mjs @@ -48,6 +48,7 @@ export const UNMANAGED_WORKSPACES = Object.freeze([ 'packages/memory', 'packages/taskpack-runner', 'packages/hardware-runner', + 'packages/evolution', ]); const DEFAULT_UPSTREAM_GROUPS = Object.freeze([ diff --git a/scripts/run-tests.mjs b/scripts/run-tests.mjs index e99ed62..ac806bb 100644 --- a/scripts/run-tests.mjs +++ b/scripts/run-tests.mjs @@ -23,6 +23,7 @@ const PACKAGES = [ 'taskpack', 'github-app', 'hardware-runner', + 'evolution', ]; const PACKAGE_SET = new Set(PACKAGES); diff --git a/specs/2026-11-23-evolutionary-campaigns-pareto-archive-and-bundle-export.md b/specs/2026-11-23-evolutionary-campaigns-pareto-archive-and-bundle-export.md new file mode 100644 index 0000000..5f46b26 --- /dev/null +++ b/specs/2026-11-23-evolutionary-campaigns-pareto-archive-and-bundle-export.md @@ -0,0 +1,613 @@ +# Spec: Evolutionary campaigns, Pareto archive, and bundle export + +Status: Shipped +Type: Feature + +## Summary + +Deliver evolutionary optimization across Loopwright for hardware kernels, continual compilation graphs, and speculative or runtime engine policies. Add `@loopwright/evolution` as the twelfth workspace package with an isolated `campaign.sqlite` archive (`islands`, MAP-Elites niches, lineage DAGs, `team_configs`, stepping-stone parent crossover, UCB1 model bandit routing, plateau-triggered bounded role and team-topology synthesis via `team-patch.v1`, and two-stage guarded portfolio synthesis) while keeping per-run `@loopwright/state` DDL and `D <= 256` controller checkpoints untouched. Add `evolve-block-guard.v1` mutable-region verification, Stage A static symbol and spill audits, Stage B bucketed multi-objective metrics and supervisor-distilled Roofline diagnostics, post-crash accelerator quarantine, three System-One advisory inner-loop filters in `@loopwright/decisions`, hardware-scoped memory in `@loopwright/memory`, and deterministic `evolution-bundle.v1` artifact exports. + +## Motivation + +### Goals + +Loopwright ships two-stage blind GPU/NPU verification (`benchmark-gate.v1` and `@loopwright/hardware-runner` in [`2026-11-21-hardware-execution-benchmark-gate-and-remote-runner.md`](2026-11-21-hardware-execution-benchmark-gate-and-remote-runner.md)) and deterministic section handoffs, conditional rules, and `RunEval` health telemetry ([`2026-11-21-multi-domain-suite-handoff-and-run-eval.md`](2026-11-21-multi-domain-suite-handoff-and-run-eval.md)). Seven architectural gaps still prevent Loopwright from driving non-convex evolutionary search for an evolving LLM inference engine: + +1. **Single-lineage pass/fail loops discard stepping stones**: + - [`packages/state/src/schema.ts`](../packages/state/src/schema.ts) models a singleton `run` row, and [`packages/controller/src/progress.ts`](../packages/controller/src/progress.ts) caps per-run checkpoints at `D <= 256`. + - Linear `implementationRepair` in [`packages/controller/src/controller.ts`](../packages/controller/src/controller.ts) overwrites or discards slower intermediate candidates that introduce necessary structural primitives (such as asynchronous tensor-memory pipelines or double-buffered unified-buffer tiling) before tile sizes are tuned. + - Single-run loops also cannot evolve per-shape specialists first and then synthesize a guarded multi-shape portfolio dispatcher verified on held-out workloads. + +2. **Fixed role topologies stall on cognitive and measurement plateaus**: + - [`packages/controller/src/compile.ts`](../packages/controller/src/compile.ts) freezes `roles[]` and `orderedDAG` inside each single-run `CompiledPlan`. Across generations, feeding different parent code into the same generic `optimizer` role still stalls when that role repeats a flawed micro-timing assumption, couples root-cause diagnosis with code rewriting, or hits `pingPong` / `toolRepeats` pathologies reported by [`packages/controller/src/run-eval.ts`](../packages/controller/src/run-eval.ts). + - Conversely, letting an unconstrained supervisor spawn arbitrary roles with unrestricted tools or shared mutable directories would violate Loopwright's non-delegable host authority model. + +3. **No mutable code-block fence or pre-GPU static spill/fallback gate**: + - `scope.v1` and `line-section-guard.v1` in [`packages/taskpack/src/types.ts`](../packages/taskpack/src/types.ts) guard whole files or static line headers, not inline mutable kernel blocks (`EVOLVE-BLOCK-START` / `EVOLVE-BLOCK-END`). + - [`packages/hardware-runner/src/evaluator.ts`](../packages/hardware-runner/src/evaluator.ts) seals Stage A binaries without auditing exported/imported ELF or PTX/SASS symbols for unauthorized high-level library fallbacks (`cublas`, `rocblas`, `aclnn`, `at::native`) or excessive register spills before spending Stage B GPU leases. + +4. **Flat scalar Stage B metrics lack bucketed Pareto objectives, Roofline diagnostics, and sticky-fault quarantine**: + - `parseEnvelopeMetrics` and `checkMetricThresholds` in [`evaluator.ts`](../packages/hardware-runner/src/evaluator.ts) validate flat `MetricsMap` scalars (`bounds` and `comparative`) without `(islBucket, batchBucket)` multi-objective matrices (`latencyUs`, `ttftP95Ms`, `itlP95Ms`, `goodputRps`, `peakMemBytes`, `maxUlp`, `tokenForceMaxDelta`). + - Stage B returns generic pass/deny findings without bounded, workload-redacted Roofline bottleneck summaries (`boundPipeline`, `rooflineHeadroom`, occupancy, L2 hit rate, bank conflicts, or warp/pipe stalls). + - [`packages/hardware-runner/src/worker.ts`](../packages/hardware-runner/src/worker.ts) lacks post-crash accelerator health probes to quarantine workers after sticky GPU/NPU faults (`Xid`, ECC errors, or HBM hangs). + +5. **System-One routing (`@loopwright/decisions`) cannot filter inner-loop mutations**: + - [`packages/decisions/src/nodes.ts`](../packages/decisions/src/nodes.ts) supports capability tiering, cycle alignment, soft compaction, and post-diff rule triage. It lacks pre-compile AST/token novelty rejection, bottleneck-driven DSL track routing, and smoke-to-full benchmark cascade escalation. + +6. **Memory drops accelerator micro-architecture scope and lacks an in-campaign scratchpad**: + - [`packages/memory/src/schema.ts`](../packages/memory/src/schema.ts), [`packages/taskpack/src/turnkey-memory.ts`](../packages/taskpack/src/turnkey-memory.ts), and [`packages/github-app/src/turnkey-memory.ts`](../packages/github-app/src/turnkey-memory.ts) project `target.matrix` down to `{ id, platform, variant }`, discarding `accelerator` and `driverConstraint`. Hardware-specific lessons (such as `sm_100a` tensor memory vs `sm_89` shared memory, or Ascend core-count tiling rules) risk cross-architecture misapplication, while mid-campaign discoveries have no ephemeral scratchpad between generations. + +7. **Publication supports pull requests only, not signed evolution artifact bundles**: + - `TaskpackPublicationDeclaration` in [`packages/taskpack/src/types.ts`](../packages/taskpack/src/types.ts) supports only `'pull_request' | 'disabled'`. Operators cannot export a deterministic bundle pairing sealed `.loopwright-verifier//*` binaries, guarded dispatch predicates (`dispatch-manifest.json`), and HMAC-signed `hardwareProvenance` + Pareto tables for downstream inference serving engines. + +Target users are kernel engineers, compiler and inference systems researchers, verification owners, and cluster operators. Success criteria: + +- Run multi-generation evolutionary campaigns in `@loopwright/evolution` using an isolated `campaign.sqlite` store while preserving byte-identical `@loopwright/state` `schema_digest` and `D <= 256` per-run `LocalRunStore` invariants. +- Retain stepping-stone individuals across islands and MAP-Elites niches, track multi-parent lineage DAGs, enforce `evolve-block-guard.v1` outside mutable blocks, and synthesize guarded multi-shape portfolios verified on held-out shards. +- Detect island plateaus (`stallGenerations`) and `RunEval` loop pathologies, invoke a read-only supervisor to synthesize `team-patch.v1` role DAGs strictly bounded by approved host archetype envelopes (`tools` subset, pinned models/resources, immutable scope and gates, `D <= 256`), and roll back unproductive `team_configs` automatically after `trialGenerations`. +- Enforce Stage A symbol/spill static audits, Stage B bucketed correctness and Token-Forcing losslessness gates, supervisor-sanitized Roofline diagnostic summaries, NSGA-II Pareto ranking, and worker GPU/NPU sticky-fault quarantine. +- Cut wasted hardware leases via advisory System-One novelty rejection, DSL track routing, and cascade budget escalation while keeping `verificationCertified: false`. +- Scope slow-loop `@loopwright/memory` entries to `{ accelerator, driverConstraint?, operatorFamily?, boundPipeline? }` backed by passing `hardware_execution` evidence, maintain fast-loop in-campaign scratchpads, and export deterministic `evolution-bundle.v1` artifacts (`dir` and `oci-layout`). + +### Non-Goals + +- Modifying the five-table per-run SQLite `DDL` (`format_version = 1`) in [`packages/state/src/schema.ts`](../packages/state/src/schema.ts) or altering `phaseSchedule` (`D <= 256`) in [`packages/controller/src/progress.ts`](../packages/controller/src/progress.ts). +- Mutating `roles[]` or `orderedDAG` mid-run inside an active `LocalRunStore`, or allowing the plateau supervisor to write candidate code, widen `tools` beyond host archetype profiles, relax `scope.writable` / `evolve-block-guard.v1`, or drop required acceptance checks. +- Introducing external database servers (PostgreSQL, Redis), multi-host distributed consensus, or web dashboards. +- Allowing `@loopwright/decisions` (`typesafe-jev` or other providers) to approve verification gates, override `metricThresholds`, or certify `Evidence`. +- Mounting `held_out_workloads` during Stage A compilation, exporting raw profiler databases (`*.ncu-rep`, `msprof` SQLite) or files from Stage B, or weakening socket-denying seccomp/seatbelt profiles. +- Injecting unverified human-written static optimization cookbooks into prompts without passing `hardware_execution` receipts. +- Adding any third-party runtime npm dependency across the workspace or changing the 23-row closure split (`18` `closedLocal`, `5` `unprovisionedExternal`) in [`packages/cli/src/closure.ts`](../packages/cli/src/closure.ts) without an `ExternalQualificationReceipt`. + +## Proposal + +Add `@loopwright/evolution` as the twelfth workspace package and extend `@loopwright/core`, `@loopwright/controller`, `@loopwright/hardware-runner`, `@loopwright/decisions`, `@loopwright/memory`, `@loopwright/taskpack`, `@loopwright/github-app`, and `@loopwright/cli`. Coordinate multi-generation island and MAP-Elites campaigns in an isolated `campaign.sqlite` database that dispatches standard fenced `LocalRunStore` runs per candidate evaluation. When an island stalls or hits `RunEval` loop pathologies, run a read-only supervisor to emit a capability-bounded `team-patch.v1` role DAG compiled into subsequent child `TaskContract` runs under a bounded `trialGenerations` rollback window. Guard mutable code regions and static binary invariants before Stage B benchmarking, collect bucketed multi-objective metrics and sanitized Roofline bottleneck diagnostics, maintain NSGA-II Pareto frontiers and hardware-scoped memories, and export verified `evolution-bundle.v1` packages with guarded dispatch manifests and signed provenance receipts. + +```yaml +apiVersion: loopwright.dev/v1alpha1 +kind: EvolutionCampaign +metadata: + name: flash-decode-sm90a +spec: + taskpack: .loopwright/taskpack.yaml + targetCellId: cuda-h100-whole + stages: + mode: specialist-then-portfolio # Optional single-target or specialist-then-portfolio + specialistBuckets: + - id: bs1-isl4k + heldOutWorkloadId: decode-bs1-4k + - id: bs16-isl8k + heldOutWorkloadId: decode-bs16-8k + portfolioHeldOutWorkloadId: decode-portfolio-holdout + population: + islands: 4 + migrationIntervalGenerations: 8 + maxMigrationElites: 1 + nicheAxes: + - id: bound_pipeline + kind: enum + values: [hbm, l2, smem_lds_ub, tensor_cube, vector_valu] + - id: occupancy_band + kind: numeric_bins + edges: [0, 25, 50, 75, 100] + sampling: + noveltyDecayLambda: 1.0 + mutationWeights: + diff_tune: 0.5 + full_rewrite: 0.3 + crossover: 0.2 + modelBandit: ucb1 # Optional deterministic-round-robin or ucb1 + maxCrossoversPerPrompt: 2 + teamEvolution: # Optional plateau-triggered bounded role and team synthesis + enabled: true + supervisorRoleId: supervisor + allowedArchetypeRoles: [probe-readonly, mutator-sandboxed, reviewer] + stallGenerations: 4 + minHypervolumeDelta: 0.001 + triggerOnRunEvalPathology: true + trialGenerations: 2 + maxTeamSize: 3 + maxTeamSteps: 4 + objectives: + - metric: latency_us_p50 + direction: minimize + - metric: goodput_rps + direction: maximize + - metric: peak_mem_bytes + direction: minimize + budgets: + maxGenerations: 40 + maxEvaluations: 160 + maxConcurrentEvaluations: 4 + targetRooflineHeadroom: 1.08 # Optional early-stop ratio >= 1.0 + scratchpadIntervalGenerations: 5 + export: + format: oci-layout # Optional dir or oci-layout + outputDir: .loopwright-out/bundles/flash-decode-sm90a +``` + +### User Stories + +#### Story 1 + +As a kernel and inference engine engineer, I want to run budget-bounded multi-generation evolutionary campaigns with isolated islands, hardware-behavior MAP-Elites grids, lineage DAGs, multi-parent crossover, and `evolve-block-guard.v1` region protection, so that slower structural stepping-stone mutations survive and synthesize into a guarded multi-shape operator portfolio. + +#### Story 2 + +As a verification owner, I want Stage A and Stage B hardware evaluation to enforce symbol/spill anti-cheat checks, bucketed multi-objective correctness and Token-Forcing bounds, supervisor-distilled Roofline bottleneck summaries, and post-crash accelerator quarantine, so that evolution receives actionable hardware guidance while library fallbacks, accuracy drift, and sticky GPU/NPU faults are blocked. + +#### Story 3 + +As a systems optimization engineer, I want campaigns to maintain an NSGA-II Pareto frontier over latency, Goodput, peak memory, and compile time while consulting `@loopwright/decisions` to reject cosmetic AST edits, route DSL tracks, and escalate smoke-tested candidates, so that GPU/NPU lease budgets focus on structurally novel improvements. + +#### Story 4 + +As a multi-silicon platform maintainer, I want campaigns to maintain an ephemeral in-campaign scratchpad every few generations while scoping committed `@loopwright/memory` facts and anti-patterns to exact accelerator micro-architectures and passing `hardware_execution` receipts, so that hardware-verified rules transfer cleanly without poisoning other chip generations. + +#### Story 5 + +As an inference serving operator, I want to export campaign winners as deterministic `evolution-bundle.v1` packages containing sealed binaries, a `dispatch-manifest.json` guarded routing table with baseline fallback, and HMAC-signed `hardwareProvenance` + Pareto receipts, so that downstream serving clusters verify compatibility tuples and hot-load specialized artifacts safely. + +#### Story 6 + +As a kernel and systems optimization engineer, I want stalled islands to invoke a read-only supervisor that diagnoses cognitive or measurement plateaus, synthesizes a capability-bounded multi-role team DAG (`team-patch.v1`) from approved host archetypes, and automatically rolls back unproductive teams after a bounded trial window, so that campaigns break through stagnation plateaus without privilege escalation or checkpoint overflow. + +### Core Features & Acceptance Criteria + +#### 1. `@loopwright/evolution` Campaign Store, Island + MAP-Elites Search, and Portfolio Synthesis (`packages/evolution`, `@loopwright/cli`, `scripts/`) + +- **Dedicated 12th workspace package and isolated `campaign.sqlite` authority**: + - Create `packages/evolution` (`@loopwright/evolution`) using built-in `node:sqlite` (`Node 26.x`) with zero new third-party runtime npm dependencies. + - Register `packages/evolution` across [`package.json`](../package.json), [`package-lock.json`](../package-lock.json), [`tsconfig.test.json`](../tsconfig.test.json), [`.opencodereview/rule.json`](../.opencodereview/rule.json), [`packages/cli/package.json`](../packages/cli/package.json), [`packages/cli/tsconfig.json`](../packages/cli/tsconfig.json), [`scripts/build.mjs`](../scripts/build.mjs), [`scripts/run-tests.mjs`](../scripts/run-tests.mjs), [`scripts/pack-npm.mjs`](../scripts/pack-npm.mjs), and `UNMANAGED_WORKSPACES` in [`scripts/prepare-self-upgrade.mjs`](../scripts/prepare-self-upgrade.mjs), [`.auto-sync/checks/verify.sh`](../.auto-sync/checks/verify.sh), [`.auto-sync/digests.lock.json`](../.auto-sync/digests.lock.json), and [`packages/github-app/test/self-upgrade-fixtures.ts`](../packages/github-app/test/self-upgrade-fixtures.ts). + - Persist campaign state in `/campaign.sqlite` (`journal_mode = DELETE`, `synchronous = FULL`, `busy_timeout = 250`, `STRICT` tables, `O_NOFOLLOW` non-symlink directory/file checks, monotonic `ClockSource` lease fencing, and `<= 1,000ms` clock-drift guard) with six tables (`campaign_meta`, `campaigns`, `islands`, `team_configs`, `individuals` carrying foreign key `team_config_id`, and `lineage_edges`) plus CAS-backed `scratchpad_snapshots`. Serialize all `campaign.sqlite` reads and writes through a single in-process coordinator queue inside `packages/evolution/src/store.ts` when `maxConcurrentEvaluations > 1` runs concurrent isolated child `/runs//` `LocalRunStore` instances. + - Keep [`packages/state/src/schema.ts`](../packages/state/src/schema.ts) (`DDL`, `format_version = 1`, `expectedSchema()`) and [`packages/controller/src/progress.ts`](../packages/controller/src/progress.ts) (`phaseSchedule`, `D <= 256`) completely unchanged. Each candidate evaluation executes inside its own fresh, fenced child `LocalRunStore` under `/runs//` and records only verified `ArtifactRef` / `Evidence` digests in `campaign.sqlite`. +- **Island isolation, hardware MAP-Elites niches, stepping-stone sampling, and UCB1 model bandit**: + - Parse and validate `kind: EvolutionCampaign` (`apiVersion: loopwright.dev/v1alpha1`, `<= 65,536` bytes) via null-prototype-safe YAML 1.2 core helpers from `@loopwright/taskpack`. + - Partition the population into `1..16` islands. Every `migrationIntervalGenerations`, copy up to `maxMigrationElites` non-rank-1 niche elites across ring neighbors as `role: 'inspiration'` references while keeping each island's rank-1 leader local (**Island Elitism**) to prevent premature convergence. + - Map each passing or soft-threshold individual into a deterministic MAP-Elites `nicheKey` over `1..4` declared `nicheAxes` (`enum` or `numeric_bins` derived from `hardwareDiagnostics` or `metrics`). Retain the Pareto-dominant or highest-scalarized individual per `(islandId, nicheKey)` alongside an append-only `individuals` history and `lineage_edges` DAG (`primary`, `crossover_donor`, `inspiration`, `portfolio_member`). + - Sample parents using novelty-decayed performance weights $w_i = \sigma(\lambda(F(P_i) - \alpha_0)) \cdot (1 + N(P_i))^{-1}$, where $\alpha_0$ is the island median scalarized fitness and $N(P_i)$ is `offspring_count`. Stage `1` primary parent plus up to `maxCrossoversPerPrompt` (`0..4`) donor/inspiration snapshots as read-only (`0o400`) `contextFiles` containing bounded code slices, `bucketMetrics`, and `hardwareDiagnostics`. + - Support deterministic round-robin or **UCB1 bandit** model selection across declared `Taskpack.spec.models[]` (`1..16` candidates), updating model rewards from truncated parent-relative improvement $r_u = \exp(\max(r - r_{\text{parent}}, 0)) - 1$ persisted in `campaign.sqlite`. +- **Two-stage `specialist-then-portfolio` orchestration and CLI commands**: + - Under `stages.mode: 'specialist-then-portfolio'`, run specialist campaigns per declared `specialistBuckets[]` entry first, then run a portfolio synthesis stage that mounts the winning specialist implementations and synthesizes a guarded portfolio entrypoint (`dispatch-manifest.json` + router glue) verified against `portfolioHeldOutWorkloadId` (which is never exposed during the specialist stage). + - Add `loopwright evolve check|run|resume|status|inspect|export` in [`packages/cli/src/arguments.ts`](../packages/cli/src/arguments.ts) and [`packages/cli/src/main.ts`](../packages/cli/src/main.ts) via lazy `await import('@loopwright/evolution')` (preserving zero top-level heavy runtime imports in `main.ts` and existing CLI exit codes `0`, `2..8`, `130/143`). +- **Acceptance criteria**: + - `@loopwright/state` `expectedSchema()` and all existing 11-package `TaskContract`/`TaskLock` digests remain unchanged. + - A slower structural stepping-stone individual occupying a distinct `(islandId, nicheKey)` (for example `bound_pipeline = tensor_cube`) is retained, sampled for crossover, and traced in `lineage_edges` to a Pareto-dominant descendant. + - Interrupted campaigns (`SIGTERM` or fenced child run preemption `BENCHMARK_PREEMPTED`) resume cleanly from `campaign.sqlite` without corrupting island archives or double-counting `maxEvaluations`. + +#### 2. Capability-Bounded Plateau Role and Team Synthesis (`@loopwright/evolution`, `@loopwright/core`) + +- **Event-driven plateau and `RunEval` pathology detection (zero steady-state overhead)**: + - Evaluate plateau triggers per island between generations only when `teamEvolution?.enabled === true` and remaining `maxEvaluations` / `maxGenerations` budgets cover at least `1` supervisor turn plus `1` child evaluation. + - Trigger a supervisor diagnosis turn when either condition holds on an island whose best `rooflineHeadroom` has not yet reached `targetRooflineHeadroom`: + 1. **Pareto stagnation**: `consecutiveNoGainGenerations >= stallGenerations` (`1..32`, default `4`), where per-generation island hypervolume delta stays `< minHypervolumeDelta` (`>= 0`, default `0.001`) and zero new MAP-Elites niches open. + 2. **Loop pathology**: `triggerOnRunEvalPathology === true` and `>= 2` consecutive child `RunEvalReport` artifacts ([`packages/controller/src/run-eval.ts`](../packages/controller/src/run-eval.ts)) record `pingPong` cycles or `toolRepeats` circuit-breaker trips (`consecutive_tool_errors` or `no_progress`). +- **Read-only, non-solving Supervisor isolation**: + - Execute `supervisorRoleId` inside an isolated read-only `LocalRunStore` run whose role permits `tools: ['read']` only (`write`, `edit`, `delete`, and `bash` forbidden; `scope.writable` untouched; zero `held_out_workloads` mounts). + - Stage only `SecretScrubber`-clean, read-only (`0o400`) diagnostic context artifacts: island score/hypervolume trajectory, bounded child `run-eval.json` summaries, sanitized `hardwareDiagnostics` + `findings`, latest `scratchpad` snapshot, and prior `team_configs` history (including `rolled_back` team diagnoses so failed team topologies are not repeated). + - Instruct and enforce that the supervisor diagnoses organizational or measurement blind spots and designs a specialist role workflow rather than authoring candidate kernel code. +- **Strict `team-patch.v1` schema and fail-closed Archetype Capability Envelope (`TEAM_ENVELOPE_VIOLATION`)**: + - Require the supervisor submission to parse strictly as JSON/YAML `kind: 'TeamPatch'` (`schemaVersion: 'team-patch.v1'`, `<= 32,768` bytes, null-prototype validation, zero free-form Markdown regex scraping): + - `diagnosis`: `{ readonly summary: string; readonly plateauCategory: 'measurement_mismatch' | 'coupled_responsibilities' | 'local_optimum_anchor' | 'resource_spill_trap' | 'correctness_ping_pong' | 'other'; readonly rationale: string }` (`<= 4,096` bytes total). + - `roles[]` (`1..maxTeamSize`, where `maxTeamSize` is capped at `1..4`): `{ readonly id: string; readonly archetypeRoleId: string; readonly purpose: 'task' | 'review'; readonly prompt: string; readonly model?: string; readonly thinking?: string; readonly tools: readonly string[]; readonly resourceIds?: readonly string[]; readonly timeoutSeconds?: number }`. + - `steps[]` (`1..maxTeamSteps`, where `maxTeamSteps` is capped at `1..6`, strict acyclic DAG): `{ readonly id: string; readonly roleId: string; readonly dependsOn: readonly string[]; readonly handoffs?: readonly StepHandoffSelector[]; readonly onRework?: ReworkPolicy }`. + - Validate every `team-patch.v1` against the **Archetype Capability Envelope** before compiling the child `TaskContract`, rejecting any violation fail-closed with `TEAM_ENVELOPE_VIOLATION` (retaining the incumbent `team_config_id` without crashing the campaign): + 1. **Approved archetype inheritance**: `role.archetypeRoleId` must appear in `teamEvolution.allowedArchetypeRoles[]` and resolve to a pre-approved role in the base `Taskpack` / host `TrustedRegistry.spec.roleProfiles`. + 2. **Monotonic tool narrowing (`tools <= archetype.tools`)**: every tool in `role.tools` must exist in `archetype.tools` (`write`, `edit`, `delete`, and `bash` are rejected on `purpose: 'review'` or read-only archetypes). No synthesized role can gain network, mount, MCP, or credential privileges beyond its host archetype. + 3. **Pinned models, resources, and timeouts**: optional `role.model` must match a declared entry in `Taskpack.spec.models[]`; optional `role.resourceIds` must be a subset of pre-hashed `TaskContract.spec.trustedContext.resources` (`discovery: 'disabled'` preserved); `timeoutSeconds` must not exceed the archetype's ceiling. + 4. **Isolated `StepHandoffSelector` relay and immutable gates**: parallel or sequential team roles exchange findings exclusively through deterministic SHA-256 `StepHandoffSelector` extracts (`handoffs` in [`packages/controller/src/handoff.ts`](../packages/controller/src/handoff.ts)), never through unisolated shared mutable directories. The compiler appends and locks the base `scope.writable`, `scope.protected`, `evolve-block-guard.v1`, and all required `acceptance.checks` (`benchmark-gate.v1`), and pre-verifies `checkpointCapacity(...)` (`D <= 256` in [`packages/controller/src/compile.ts`](../packages/controller/src/compile.ts)) before launching any child run. +- **`team_configs` credit assignment and automatic `trialGenerations` rollback (`campaign.sqlite`)**: + - Persist validated team topologies in `team_configs` (`team_config_id`, `island_id`, `parent_team_config_id`, `created_generation`, `status: 'baseline' | 'trial' | 'promoted' | 'rolled_back'`, `trial_budget_generations`, `trial_used_generations`, `diagnosis_json`, `patch_cas_digest`, `pareto_advances`, `niche_discoveries`) and bind `individuals.team_config_id` on every evaluated candidate. + - Admit newly synthesized teams in `status = 'trial'` with `trial_budget_generations = teamEvolution.trialGenerations` (`1..8`, default `2`). + - If any child evaluation under a `'trial'` `team_config_id` advances the island's Pareto hypervolume (`>= minHypervolumeDelta`) or discovers a higher-scoring MAP-Elites niche elite, transition `status -> 'promoted'` as the island's active team. + - If `trial_used_generations` reaches `trial_budget_generations` with zero Pareto or niche advance (not counting `BENCHMARK_PREEMPTED` runs), transition `status -> 'rolled_back'`, automatically restore `parent_team_config_id` (the prior promoted or baseline solo topology), and record the failed `team_config_id` in supervisor history to prevent re-proposing unproductive multi-agent overhead. +- **Acceptance criteria**: + - Islands that advance Pareto hypervolume within `stallGenerations` execute `0` supervisor runs. + - Any `team-patch.v1` requesting tools outside `archetype.tools`, referencing an undeclared model or unpinned resource, altering `scope`/`acceptance.required`, or exceeding `D <= 256` fails closed with `TEAM_ENVELOPE_VIOLATION` and keeps the incumbent team active. + - On a stalled island, the read-only supervisor emits a valid `probe-readonly -> mutator-sandboxed` `team-patch.v1` wired via `StepHandoffSelector`; `campaign.sqlite` promotes the team on a Pareto advance and automatically rolls back to the incumbent `team_config_id` when `trialGenerations` expire with zero improvement. + +#### 3. `evolve-block-guard.v1` Region Protection and Stage A Static Binary/Source Audits (`@loopwright/core`, `@loopwright/controller`, `@loopwright/taskpack`, `@loopwright/hardware-runner`) + +- **Deterministic mutable block check (`evolve-block-guard.v1`)**: + - Register `'evolve-block-guard.v1'` in `@loopwright/controller` (`handlers.ts`, `registry.ts`, `verifier-protocol.ts`) and `TaskpackV2CheckImplementation` in [`packages/taskpack/src/types.ts`](../packages/taskpack/src/types.ts). + - Parse paired `EVOLVE-BLOCK-START: ` and `EVOLVE-BLOCK-END: ` markers (`//`, `#`, or `/* ... */` single-line comments; `1..32` blocks per file; nested, duplicate, reordered, or unclosed markers fail closed). + - Verify that every byte outside matched mutable block interiors in guarded files matches the `baseRevision` (or carry-aligned baseline) SHA-256 digest exactly, locking function signatures, PyTorch/C++ registration bindings, and evaluation harness files while enforcing optional `maxBlockBytes` and `allowedBlockIds`. +- **Stage A static symbol denylist and register/spill ceiling audit (`@loopwright/hardware-runner`)**: + - Extend `HardwareTargetSpec` / `BenchmarkRequest` (optional fields omitted when unset so legacy canonical hashes stay unchanged) and `sealStageAOutputs` in [`packages/hardware-runner/src/evaluator.ts`](../packages/hardware-runner/src/evaluator.ts) with optional deterministic Stage A static audit rules: + - `forbiddenSymbolPatterns` (`0..64` exact prefixes or glob-free substrings, such as `cublas`, `cudnn`, `rocblas`, `miopen`, `aclnn`, `at::native::`, `torch_cuda`): inspect Stage A `.so`, `.o`, `.cubin`, `.ptx`, and `.sass` outputs using bounded binary symbol/section parsers or verified root-owned toolchain `nm`/`cuobjdump` binaries (`O_NOFOLLOW`, `1 MiB` output cap) before Stage B starts. + - `maxRegisterCount` and `maxLocalSpillBytes`: parse compiler/assembler resource reports or `.sass`/`.ptx` metadata emitted in Stage A and reject candidates exceeding hardware ceilings with `status: 'denied'`, `reason: 'STAGE_A_STATIC_AUDIT_FAILED'`, and structured line/symbol `findings` — consuming zero Stage B GPU runtime. +- **Acceptance criteria**: + - Mutating a single character outside `EVOLVE-BLOCK-START/END` markers, deleting a marker, or reordering block IDs fails `evolve-block-guard.v1` deterministically. + - A Stage A `.so`/`.cubin` linking `cublasGemmEx` or exceeding `maxLocalSpillBytes: 0` fails in Stage A with `STAGE_A_STATIC_AUDIT_FAILED` before Stage B mounts `held_out_workloads`. + +#### 4. Bucketed Multi-Objective Metrics, Roofline Diagnostic Distillation, and Device Quarantine (`@loopwright/core`, `@loopwright/controller`, `@loopwright/hardware-runner`, `@loopwright/evolution`) + +- **Backward-compatible `bucketMetrics` and `hardwareDiagnostics` on `Evidence` and Stage B envelopes**: + - Extend `Evidence.spec` in [`packages/core/src/evidence.ts`](../packages/core/src/evidence.ts) and `StageBResultEnvelope` in [`packages/hardware-runner/src/evaluator.ts`](../packages/hardware-runner/src/evaluator.ts) (keeping total Stage B stdout `<= 49,152` bytes and Relay `:complete` body `<= 65,536` bytes) with two optional, strictly typed structures: + - `bucketMetrics`: `1..64` entries `{ bucketId, dimensions?: Readonly>, metrics: MetricsMap }` (capped at `<= 16` numeric metrics and `<= 8` dimension keys per bucket so 64-bucket Stage B envelopes remain well below `49,152` bytes), supporting per-shape/per-load measurements (`latency_us_p50`, `latency_us_p95`, `ttft_ms_p95`, `itl_ms_p95`, `goodput_rps`, `peak_mem_bytes`, `compile_ms`, `max_ulp`, `token_force_max_delta`, `token_force_outlier_ratio`). + - `hardwareDiagnostics`: `{ boundPipeline: 'hbm' | 'l2' | 'smem_lds_ub' | 'tensor_cube' | 'vector_valu' | 'host_launch' | 'comm' | 'unknown', rooflineHeadroom?: number, achievedSolPct?: number, arithmeticIntensity?: number, occupancyPct?: number, registerCount?: number, sharedMemBytes?: number, localSpillBytes?: number, l2HitPct?: number, bankConflictPct?: number, topStallReasons?: readonly { readonly reason: string; readonly pct: number }[] }`. + - Validate every key and string with null-prototype guards, `PRINTABLE_ASCII_RE` enums/identifiers (preventing exfiltration of free-text `held_out_workloads` content through diagnostic fields), finite non-`-0` numbers, and `SecretScrubber` checks. Zero files may be exported from Stage B. + - Extend `metricThresholds` in [`packages/core/src/contracts.ts`](../packages/core/src/contracts.ts) and [`acceptance.ts`](../packages/core/src/acceptance.ts) with optional `bucketScope?: 'aggregate' | 'all_buckets' | { readonly bucketId: string }` so correctness bounds (such as `max_ulp <= 1` and `token_force_max_delta <= 0.02`) apply across every evaluated shape bucket before any candidate can pass. +- **NSGA-II Pareto frontier and hypervolume ranking (`@loopwright/evolution`)**: + - Gate admission into the fertile population on passing hard correctness rules; optionally retain compile-valid correctness-passing slow stepping stones in non-rank-1 niches while keeping correctness-failing candidates strictly as negative parent error feedback. + - Compute deterministic **NSGA-II non-dominated fronts (`paretoRank = 1..k`)**, crowding distance, and exact 2D/3D or Monte-Carlo-free bounded reference-point hypervolume contributions over declared campaign `objectives[]` (`minimize` / `maximize`). Break ties deterministically by lexicographic objective vector and `individualId`. +- **Post-crash accelerator health probe and worker quarantine (`@loopwright/hardware-runner`)**: + - After any Stage B timeout, signal kill (`SIGSEGV`, `SIGABRT`, `SIGBUS`), or non-zero exit in [`packages/hardware-runner/src/worker.ts`](../packages/hardware-runner/src/worker.ts), execute a trusted host health check via [`provenance.ts`](../packages/hardware-runner/src/provenance.ts) (`nvidia-smi`, `rocm-smi`, `npu-smi` query for fatal `Xid`, uncorrectable ECC, or unresponsive device state) **before** reporting completion or polling `/v1/runner/leases:acquire`. + - If the accelerator is wedged or degraded after a faulty candidate kernel, report candidate denial (or preempt if caused by external host loss) and transition the worker into local fail-closed quarantine (`WORKER_DEVICE_QUARANTINED`, exit code `3`) so subsequent healthy candidates in the Relay queue are never poisoned by a corrupted GPU/NPU context. +- **Acceptance criteria**: + - If any single bucket in `bucketMetrics` violates `max_ulp <= 1` under `bucketScope: 'all_buckets'`, both `evaluator.ts` and `@loopwright/core` `evaluateAcceptance` reject passing completion (`METRIC_THRESHOLD_FAILED`). + - Free-form or secret-bearing strings injected into `hardwareDiagnostics` fail Stage B envelope validation (`ARTIFACT_INVALID`), preserving blind Stage B non-exfiltration. + - A simulated sticky GPU fault after Stage B crash quarantines the unhealthy worker before it can pull another job from the Relay. + +#### 5. System-One (`@loopwright/decisions`) Inner-Loop Novelty Filter, Track Router, and Cascade Escalation (`@loopwright/decisions`, `@loopwright/evolution`) + +- **Three bounded advisory intents with deterministic fallbacks**: + - Add `'advise_mutation_novelty'`, `'route_evolution_strategy'`, and `'advise_cascade_escalation'` to `DECISION_ALLOWED_AUTHORITY_INTENTS` in [`packages/decisions/src/types.ts`](../packages/decisions/src/types.ts) while keeping all six `DECISION_FORBIDDEN_AUTHORITY_INTENTS` (`approve_gate`, `mint_evidence`, `bypass_sandbox`, `override_scope`, `publish_unverified`, `mutate_protected_workflow`) strictly forbidden (`DECISION_AUTHORITY_VIOLATION`): + 1. **`evaluateMutationNovelty`**: compute deterministic whitespace/comment-stripped token-shingle Jaccard similarity across `EVOLVE-BLOCK` slices against island history first. If similarity `=== 1.0`, reject immediately with `0` transport calls (`source: 'deterministic_heuristic'`, `action: 'reject_resample'`). In the soft high-similarity band (`[noveltyThreshold, 1.0)`), query System-One (`noul`) under configured `disclosurePolicy` to detect cosmetic variable renames or constant-folding clones before Stage A/B dispatch. + 2. **`routeEvolutionStrategy`**: accept sanitized structural metadata (operator kind, tensor rank, dtype, reduction/causal flags) and prior `hardwareDiagnostics` (`boundPipeline`, `rooflineHeadroom`, `occupancyPct`, `localSpillBytes`) to select `(trackId, mutationKind)` among campaign-declared tracks (for example `triton`, `cute`, `cuda_raw`, `ascend_tile`, `ascend_regbase`, `ascend_simt`), falling back to deterministic Roofline rules when System-One is disabled or low-confidence. + 3. **`evaluateCascadeEscalation`**: after a smoke-bucket check passes correctness, classify whether a candidate should `prune`, `confirm`, or `escalate` to the full multi-bucket / end-to-end engine benchmark gate, never bypassing full verification required for final publication or bundle export. +- **Acceptance criteria**: + - Byte-equivalent or whitespace/comment-only `EVOLVE-BLOCK` edits are rejected with `0` `benchmark-gate.v1` dispatches and `0` System-One network calls. + - Calling any decision helper with a forbidden authority intent throws `DecisionError('DECISION_AUTHORITY_VIOLATION')` with `authorityViolation: true`, and every new result stamps `advisoryOnly: true` and `verificationCertified: false`. + +#### 6. Fast-Loop Campaign Scratchpad and Hardware-Scoped Reviewed Memory (`@loopwright/evolution`, `@loopwright/memory`, `@loopwright/taskpack`, `@loopwright/github-app`) + +- **Deterministic in-campaign meta-scratchpad (`@loopwright/evolution`)**: + - Every `scratchpadIntervalGenerations` (`1..32`), synthesize a bounded (`<= 16 KiB`), `SecretScrubber`-clean Markdown/JSON scratchpad artifact in CAS (`scratchpad_snapshots`) from verified `campaign.sqlite` lineage deltas: top Pareto gains per niche (with exact speedup deltas and `boundPipeline` shifts) and top recurring failure/regression patterns (`STAGE_A_STATIC_AUDIT_FAILED`, ULP drift, spill regressions). + - Mount the latest scratchpad snapshot read-only (`0o400`) into subsequent child runs without mutating repository Git state or opening memory PRs mid-campaign. +- **Backward-compatible `hardwareScope` and `hardware_execution` evidence gate in `@loopwright/memory`**: + - Add optional `hardwareScope?: { readonly accelerator: string; readonly driverConstraint?: string; readonly operatorFamily?: string; readonly boundPipeline?: string }` to `MemoryEntry.scope` in [`packages/memory/src/schema.ts`](../packages/memory/src/schema.ts) and add `'MEMORY_HARDWARE_EVIDENCE_REQUIRED'` to `MemoryErrorCode` in [`packages/memory/src/types.ts`](../packages/memory/src/types.ts). + - Omit `hardwareScope` when undefined so every existing v1 `MemoryEntry`, `index.json`, `storeDigest`, and `proposalDigest` stays byte-for-byte identical. + - Enforce a 6th verification gate in `@loopwright/memory` proposal verification: any `upsert` of `kind: 'fact'` or `'invariant'` carrying `hardwareScope` **must** reference at least one `evidenceRef` with `level: 'hardware_execution'` and `observedStatus: 'passed'` (`MEMORY_HARDWARE_EVIDENCE_REQUIRED`), blocking unverified static lore. Verified regressions and dead-end traps (such as cross-core-count tiling mismatches or split-K atomic regressions) admit cleanly as `kind: 'failure_observation'`. + - Update [`packages/taskpack/src/turnkey-memory.ts`](../packages/taskpack/src/turnkey-memory.ts), [`packages/github-app/src/turnkey-memory.ts`](../packages/github-app/src/turnkey-memory.ts), and memory prompt selection (`selector.ts`) to preserve optional `hardwareScope` and filter active prompt entries by matching `target.matrix[].hardware.accelerator` and `driverConstraint` (preventing `sm_100a` entries from mounting on `sm_89` or `ascend_910b` runs). +- **Acceptance criteria**: + - Existing v1 memory stores load and hash to identical `storeDigest` values; a `hardwareScope` `fact` lacking a passing `hardware_execution` `evidenceRef` is rejected with `MEMORY_HARDWARE_EVIDENCE_REQUIRED`. + - Memory selection for `target.matrix` cell `sm_89` excludes `hardwareScope.accelerator = 'sm_100a'` entries while admitting unscoped repository entries and matching `sm_89` entries. + +#### 7. Deterministic `evolution-bundle.v1` Export and Guarded Dispatch Manifest (`@loopwright/evolution`, `@loopwright/taskpack`, `@loopwright/cli`) + +- **Signed, compatibility-pinned artifact bundle (`dir` and `oci-layout`)**: + - Implement `exportEvolutionBundle` in `@loopwright/evolution` and wire `loopwright evolve export --campaign --out [--format dir|oci-layout]` (plus `EvolutionCampaign.spec.export` auto-export on completion). + - Verify every exported binary and receipt from CAS (`O_NOFOLLOW`, `nlink === 1`, SHA-256 + `byteLength` match, `SecretScrubber` clean) before atomic directory staging: + 1. **`manifest.json` (`kind: EvolutionBundle`, `version: 1`)**: canonical compatibility tuple (`accelerator`, `isolationMode`, `deviceCount`, `driverVersion`, `driverConstraint`, `runtimeVersion`, `topology`, `workloadDigest`, optional `modelDigest` and parallelism tags), Pareto frontier summary across `(islBucket, batchBucket)`, lineage provenance (`campaignId`, `individualIds`, `baseRevision`, `lockHash`), and SHA-256 digests of all bundle members. + 2. **`dispatch-manifest.json` (`version: 1`)**: ordered guarded portfolio routing rules (`1..64` rules specifying `bucketId`, dimension min/max bounds, dtype/alignment predicates, target binary `blobs/sha256/` + entrypoint symbol, and mandatory `fallback: 'baseline'` semantics for uncovered shapes). + 3. **`receipts/.verdict.json`**: unmodified HMAC-signed `SignedBenchmarkVerdictReceipt`(s) binding `hardwareProvenance`, `bucketMetrics`, and Stage A `outputArtifacts` digests so downstream serving control planes can independently verify authenticity and ULP/Token-Forcing compliance before mounting. + 4. **`blobs/sha256/`** (and standard OCI Image Layout `oci-layout` + `index.json` when `--format oci-layout` is selected): sealed `.cubin`, `.so`, `.o` + host tiling libraries, compiled graph caches, and tuned runtime/speculative policy JSONs. + - Refuse bundle export (`EXPORT_UNVERIFIED_FORBIDDEN`) if any selected individual lacks a passing `hardware_execution` receipt (`probeKind: 'physical'` unless `--allow-synthetic-probe` is explicitly passed for offline testing) or if `portfolioHeldOutWorkloadId` failed under `specialist-then-portfolio` mode. +- **Acceptance criteria**: + - Exporting the same completed campaign twice produces byte-identical `manifest.json`, `dispatch-manifest.json`, and OCI `index.json` digests. + - Tampering with one byte of a Stage A `.cubin` blob or trying to export a `synthetic_fixture` receipt without `--allow-synthetic-probe` fails closed (`ARTIFACT_INVALID` or `EXPORT_UNVERIFIED_FORBIDDEN`). + +### Notes / Constraints / Caveats + +- Target Node.js `26.x` (`node:sqlite` built-in), strict ESM (`NodeNext`), explicit public parameter/return types, and zero `any` across all 12 workspace packages. +- Add **zero** new third-party runtime npm dependencies; reuse `@loopwright/taskpack` strict YAML 1.2 core helpers (`parseYamlDocument`, `readBoundedRegularFile`) in `@loopwright/evolution`. +- Validate all untrusted JSON, YAML, and SQLite JSON columns into `Object.create(null)` records with `Object.hasOwn`, rejecting lone UTF-16 surrogates, prototype keys, `NaN`, and `Infinity` (`-0` normalized to `0` only in `@loopwright/core`, rejected in campaign/runner config parsers). +- Maintain strict package layering: `@loopwright/evolution` may depend on `@loopwright/core`, `@loopwright/state`, `@loopwright/controller`, `@loopwright/decisions`, `@loopwright/memory`, `@loopwright/taskpack`, and `@loopwright/hardware-runner`, with zero imports from `@loopwright/github-app` or `@loopwright/cli`. +- Keep all specifications, code, documentation, and tests tool-neutral and free of off-repo filesystem paths or private hostnames. + +### Boundaries + +- **Always:** + - Isolate multi-generation campaign state in `/campaign.sqlite` inside `@loopwright/evolution`, keeping [`packages/state/src/schema.ts`](../packages/state/src/schema.ts) (`DDL`, `format_version = 1`) and [`packages/controller/src/progress.ts`](../packages/controller/src/progress.ts) (`D <= 256`) unchanged. + - Restrict the `teamEvolution` supervisor role to `tools: ['read']` only, enforce `team-patch.v1` archetype inheritance (`tools <= archetype.tools`, pinned models/resources, immutable scope/gates, `D <= 256` precheck), and automatically roll back `'trial'` `team_configs` that fail to advance within `trialGenerations`. + - Enforce `evolve-block-guard.v1` SHA-256 outside-block invariance and Stage A static symbol/spill audits before launching Stage B blind benchmarks. + - Require passing correctness bounds (`max_ulp`, `token_force_max_delta`, `metricThresholds`) across all configured buckets before admitting an individual into the fertile Pareto archive or `evolution-bundle.v1` export. + - Keep Stage B blind isolation intact (`held_out_workloads` read-only, `networkMode: 'none'`, socket-denying seccomp/seatbelt, zero exported files, and strict enum/numeric validation on `hardwareDiagnostics`). + - Quarantine workers (`WORKER_DEVICE_QUARANTINED`) if post-Stage-B accelerator health probes detect sticky GPU/NPU faults. + - Keep `@loopwright/decisions` strictly advisory (`advisoryOnly: true`, `verificationCertified: false`) with deterministic fallbacks when disabled or offline. + - Preserve the 23-row capability closure split (`18` `closedLocal`, `5` `unprovisionedExternal`) in [`packages/cli/src/closure.ts`](../packages/cli/src/closure.ts). +- **Ask first:** + - Before adding any third-party runtime npm dependency to any workspace package. + - Before altering per-run SQLite `DDL` in `@loopwright/state`, `storeDigest` canonicalization in `@loopwright/memory` for legacy v1 entries, or `phaseSchedule` in `@loopwright/controller`. + - Before changing the 23-row closure ledger dispositions or promoting `external-build-and-accelerator-matrix` without an `ExternalQualificationReceipt`. +- **Never:** + - Never allow candidate code to modify lines outside `EVOLVE-BLOCK` markers in guarded files or link forbidden fallback libraries (`cublas`, `rocblas`, `aclnn`, `at::native`) when `forbiddenSymbolPatterns` is active. + - Never allow the plateau supervisor to write candidate files, grant tools outside `archetype.tools`, share unisolated mutable directories across parallel roles, or weaken `scope.writable` / `acceptance.required`. + - Never export files or free-text `held_out_workloads` strings from Stage B through `hardwareDiagnostics` or `bucketMetrics`. + - Never admit a `hardwareScope` positive performance `fact` into `@loopwright/memory` without a passing `hardware_execution` `evidenceRef`. + - Never let `BENCHMARK_PREEMPTED` count as candidate fitness failure or `team_configs` trial consumption, and never export `synthetic_fixture` bundles without explicit `--allow-synthetic-probe` opt-in. + +### Risks and Mitigations + +- **Single fast local-optimum kernel dominating prompts and collapsing search diversity** -> Mitigation: partition archives into isolated islands with **Island Elitism** (rank-1 leaders stay local during migration), hardware MAP-Elites niches, and novelty-decayed parent sampling $w_i = s_i \cdot (1 + N(P_i))^{-1}$. +- **Supervisor-minted roles escalating privileges, clobbering shared workspaces, or burning budget on bloated teams** -> Mitigation: trigger supervisor turns only on deterministic plateaus/pathologies, validate `team-patch.v1` against host archetype envelopes (`TEAM_ENVELOPE_VIOLATION`, `maxTeamSize <= 4`, `D <= 256`), wire inter-role handoffs strictly via `StepHandoffSelector`, and auto-rollback `'trial'` teams after `trialGenerations` without gain. +- **Per-shape evolution overfitting target benchmarks and regressing 5x-3,000x on unseen shapes** -> Mitigation: support two-stage `specialist-then-portfolio` synthesis emitting explicit `dispatch-manifest.json` shape predicates with mandatory `baseline` fallback, gated on frozen `portfolioHeldOutWorkloadId` shards. +- **Reward hacking via library fallbacks, precision truncation, or single-step KV cache corruption** -> Mitigation: combine Stage A ELF/PTX/SASS symbol denylists with Stage B `all_buckets` ULP and `token_force_max_delta` checks. +- **Faulty TMA/async kernel triggering GPU `Xid` sticky errors and poisoning subsequent candidates** -> Mitigation: run out-of-band host accelerator health probes in `worker.ts` after every Stage B crash/timeout and quarantine unhealthy workers (`WORKER_DEVICE_QUARANTINED`) before acquiring new leases. +- **Exfiltrating private `held_out_workloads` via profiler outputs** -> Mitigation: forbid raw profiler file exports from Stage B and restrict `hardwareDiagnostics` to closed pipeline enums, bounded stall reason identifiers, and finite numeric percentages/counts validated by the supervisor. +- **Cross-architecture memory pollution (such as applying `sm_100a` TMEM idioms on `sm_89` or `ascend_910b`)** -> Mitigation: bind optional `hardwareScope` on `@loopwright/memory` entries, require passing `hardware_execution` receipts on positive facts, and filter active prompt memories by matching target cell hardware. +- **Static recipe lock-in degrading evolutionary ceiling** -> Mitigation: keep mid-campaign guidance in a dynamic CAS `scratchpad_snapshots` artifact computed strictly from measured in-campaign lineage deltas rather than unverified static prose. +- **Adding `'evolve-block-guard.v1'` updates `installedHandlerDigests()` across `@loopwright/controller` and invalidates hardcoded digest fixtures** -> Mitigation: resolve handler digests via `installedHandlerDigests()` in controller and taskpack tests while asserting byte-identical `TaskContract` and `TaskLock` digests on existing workflows that omit `evolve-block-guard.v1`. +- **Concurrent child evaluations (`maxConcurrentEvaluations > 1`) contending on `/campaign.sqlite` under `journal_mode = DELETE` and `synchronous = FULL`** -> Mitigation: serialize all `campaign.sqlite` mutations and queries through a single in-process coordinator queue in `packages/evolution/src/store.ts` while child runs write only to isolated `/runs//` stores, and execute `--pkg evolution` SQLite lock tests with `--concurrency 1`. +- **Wide `bucketMetrics` payloads (`64` buckets) overflowing the `49,152`-byte `MAX_STAGE_B_RESULT_BYTES` Stage B stdout envelope** -> Mitigation: cap each `bucketMetrics` entry at `<= 16` numeric metrics and `<= 8` dimension keys in both `@loopwright/core` and `@loopwright/hardware-runner` parsers so worst-case 64-bucket envelopes remain well below `49,152` bytes. +- **Registering a 12th workspace package breaking static CLI import guards (`runner-cli.test.ts`), `.opencodereview/rule.json` coverage checks (`docs-and-site.test.ts`), `npm-pack.test.ts` bundled counts, or self-upgrade unmanaged-workspace digests** -> Mitigation: land an atomic `T1` workspace prefactor updating all 12-package manifests and `.auto-sync/digests.lock.json` together, and load `@loopwright/evolution` strictly via lazy `await import('@loopwright/evolution')` inside `packages/cli/src/main.ts`. + +## Design Details + +### Commands + +Confirmed build and verification environment: +- **Primary mode**: Local deterministic offline and loopback execution on `macOS Darwin arm64` (`Darwin 25.6.0 arm64` verified) and `Linux x86_64/arm64`, using `Node.js v26.13.1` (built-in `node:sqlite`), `npm 11.20.0`, and `git 2.50+`. Automated suites run offline with `allowSyntheticHardwareProbe: true` and require zero external network calls or physical GPUs. +- **Optional live hardware smoke**: On-demand remote SSH checks when `LOOPWRIGHT_CUDA_SSH_HOST` or `LOOPWRIGHT_ROCM_SSH_HOST` is explicitly provisioned (`probeKind: 'physical'`). + +```bash +# Sync workspace links for the 12th package (@loopwright/evolution) and install cleanly +npm install --package-lock-only && npm ci + +# Build all 12 workspace packages, typecheck, and lint +npm run build +npm run typecheck +npm run lint + +# Validate connected docs and rebuild the Hugo site +npm run lint:docs +npm run site + +# Compile tests and run targeted package test suites +npx tsc -p tsconfig.test.json +node scripts/run-tests.mjs --pkg core +node scripts/run-tests.mjs --pkg controller +node scripts/run-tests.mjs --pkg decisions +node scripts/run-tests.mjs --pkg memory +node scripts/run-tests.mjs --pkg taskpack +node scripts/run-tests.mjs --pkg github-app +node scripts/run-tests.mjs --pkg hardware-runner +node scripts/run-tests.mjs --pkg evolution --concurrency 1 +node scripts/run-tests.mjs --pkg cli + +# Full 12-package test suite, tarball bundling check, and 23-row closure verification +npm test +node packages/cli/dist/main.js closure --verify-failures --json +``` + +### Project Structure + +```text +packages/ + core/src/ + contracts.ts # + bucketScope on MetricThresholdRule, Stage A static audit fields on HardwareTargetSpec + evidence.ts # + optional bucketMetrics (<= 64 buckets, <= 16 metrics/bucket) and hardwareDiagnostics on Evidence.spec + diagnostics.ts # + STAGE_A_STATIC_AUDIT_FAILED, TEAM_ENVELOPE_VIOLATION, EXPORT_UNVERIFIED_FORBIDDEN + acceptance.ts # Enforce bucketScope ('aggregate' | 'all_buckets' | { bucketId }) across bucketMetrics + controller/src/ + handlers.ts # Register 'evolve-block-guard.v1' in installedHandlerDigests() + registry.ts # Validate 'evolve-block-guard.v1' parameters (files, allowedBlockIds, maxBlockBytes) + verifier-protocol.ts # Execute deterministic EVOLVE-BLOCK-START/END outside-byte SHA-256 invariance check + benchmark-gate.ts # Forward Stage A static audit rules, bucketMetrics, and hardwareDiagnostics in receipts + decisions/src/ + types.ts # + advise_mutation_novelty, route_evolution_strategy, advise_cascade_escalation intents & types + nodes.ts # evaluateMutationNovelty (token-shingle + Jev), routeEvolutionStrategy, evaluateCascadeEscalation + memory/src/ + types.ts # + optional HardwareMemoryScope on MemoryEntry['scope'] and MEMORY_HARDWARE_EVIDENCE_REQUIRED + schema.ts # Validate optional hardwareScope (omitted when unset for v1 storeDigest parity) + verifier.ts # Enforce passing hardware_execution evidenceRef on hardwareScope fact/invariant upserts + selector.ts # Filter active prompt memories against target cell accelerator & driverConstraint + taskpack/src/ + types.ts # + 'evolve-block-guard.v1' check kind and optional hardwareScope projection plumbing + schema.ts # Validate evolve-block-guard.v1 and Stage A static audit declarations + turnkey-memory.ts # Preserve optional hardwareScope from matched hardware target.matrix cells + github-app/src/ + turnkey-memory.ts # Preserve optional hardwareScope on separate-pull-request memory proposals + hardware-runner/src/ + types.ts # + StageAStaticAuditSpec, BucketMetricEntry, HardwareDiagnosticsSummary, WORKER_DEVICE_QUARANTINED + evaluator.ts # Stage A forbidden-symbol/spill audit; Stage B bucketMetrics + sanitized hardwareDiagnostics parser + provenance.ts # Post-crash accelerator health check (Xid / ECC / unresponsive device detection) + worker.ts # Out-of-band post-crash health check and fail-closed worker quarantine before next lease poll + evolution/ # NEW 12th workspace package (@loopwright/evolution) + package.json # Built-in node:sqlite + workspace deps only (zero new third-party npm dependencies) + tsconfig.json # Composite NodeNext build config + src/ + index.ts # Public campaign runner, archive store, team supervisor, Pareto, sampler, and bundle APIs + types.ts # EvolutionCampaignManifest, TeamPatchV1, TeamConfigRecord, NicheKey, EvolutionBundle types + schema.ts # Strict null-prototype parser for EvolutionCampaign, team-patch.v1, and dispatch-manifest.json + store.ts # Single-writer fenced campaign.sqlite store (1,000ms clock guard, islands, team_configs, lineage_edges) + team-supervisor.ts # Plateau/RunEval trigger, read-only supervisor runner, archetype envelope compiler, trial rollback + pareto.ts # Deterministic NSGA-II non-dominated sorting, crowding distance, and hypervolume contribution + sampler.ts # Stepping-stone novelty-decayed parent sampler, multi-parent 0o400 context builder, UCB1 bandit + scratchpad.ts # Periodic deterministic CAS meta-scratchpad synthesizer (gains + dead-end anti-patterns) + campaign.ts # Async Proposal <-> Child LocalRunStore / benchmark-gate.v1 orchestrator + specialist/portfolio stages + bundle.ts # O_NOFOLLOW CAS-verified evolution-bundle.v1 exporter (dir and oci-layout + dispatch-manifest.json) + cli/src/ + arguments.ts # + loopwright evolve check|run|resume|status|inspect|export CLI grammar + main.ts # Lazy await import('@loopwright/evolution') subcommand handlers and deterministic exit codes + closure.ts # Add '@loopwright/evolution' to OWNER_PACKAGES; keep 18/5 closure split intact +docs/ & site/ # Update module map, configuration/operations/contribute guides, and Hugo site during build +``` + +### Code Style + +```ts +// Stepping-stone novelty-decayed parent weight and deterministic NSGA-II dominance in packages/evolution/src/pareto.ts +export interface ObjectiveDirectionSpec { + readonly metric: string; + readonly direction: 'minimize' | 'maximize'; +} + +export function dominatesObjectives( + candidate: Readonly>, + incumbent: Readonly>, + objectives: readonly ObjectiveDirectionSpec[], +): boolean { + if (objectives.length === 0) return false; + let strictlyBetterInAtLeastOne = false; + for (const obj of objectives) { + const a = candidate[obj.metric]; + const b = incumbent[obj.metric]; + if (a === undefined || b === undefined || !Number.isFinite(a) || !Number.isFinite(b)) { + return false; + } + if (obj.direction === 'minimize') { + if (a > b) return false; + if (a < b) strictlyBetterInAtLeastOne = true; + } else { + if (a < b) return false; + if (a > b) strictlyBetterInAtLeastOne = true; + } + } + return strictlyBetterInAtLeastOne; +} + +export function computeSteppingStoneSamplingWeight( + fitness: number, + islandMedianFitness: number, + offspringCount: number, + noveltyDecayLambda: number, +): number { + const scaled = Math.max(-60, Math.min(60, noveltyDecayLambda * (fitness - islandMedianFitness))); + const performanceScore = 1 / (1 + Math.exp(-scaled)); + const noveltyFactor = 1 / (1 + Math.max(0, offspringCount)); + return performanceScore * noveltyFactor; +} +``` + +Key conventions: +- Validate every untrusted YAML, JSON, and SQLite payload into `Object.create(null)` records with `Object.hasOwn`, zero `any`, and explicit collection/byte ceilings. +- Keep campaign SQLite storage isolated in `packages/evolution/src/store.ts` (`campaign.sqlite`) with single-writer coordinator serialization so single-run `LocalRunStore` invariants and `D <= 256` checkpoints remain unchanged. +- Verify `O_NOFOLLOW`, `nlink === 1`, SHA-256 digests, and `SecretScrubber` cleanliness on every parent handoff slice, `team-patch.v1` artifact, scratchpad snapshot, and exported `evolution-bundle.v1` blob. + +### Implementation Plan + +Parallel execution waves (`my-build evolutionary-campaigns-pareto-archive-and-bundle-export team`): +- **Wave 1 (Foundation Prefactor)**: `T1` +- **Wave 2 (Disjoint Leaf Packages)**: `T2` (`core`) || `T3` (`decisions`) || `T4` (`memory`) +- **Wave 3 (Runtime Gates & Evolution Core)**: `T5` (`controller`) || `T6` (`hardware-runner`) || `T7` (`evolution` store/pareto/sampler/scratchpad) +- **Wave 4 (Taskpack/App Wiring & Bundle Exporter)**: `T8` (`taskpack` + `github-app`) || `T9` (`evolution` bundle) +- **Wave 5 (Campaign & Plateau Supervisor Orchestration)**: `T10` (`evolution` supervisor + campaign) +- **Wave 6 (CLI Integration & Closure Matrix)**: `T11` (`cli` + `taskpack-runner` parity) +- **Wave 7 (Docs, Hugo Site & Full Verification)**: `T12` + +- [x] **T1 · 12-package workspace prefactor and `@loopwright/evolution` scaffold** + Blocked by: None + Owns: `package.json`, `package-lock.json`, `tsconfig.test.json`, `.opencodereview/rule.json`, `scripts/build.mjs`, `scripts/run-tests.mjs`, `scripts/pack-npm.mjs`, `scripts/prepare-self-upgrade.mjs`, `.auto-sync/checks/verify.sh`, `.auto-sync/digests.lock.json`, `packages/evolution/package.json`, `packages/evolution/tsconfig.json`, `packages/evolution/src/index.ts`, `packages/evolution/test/scaffold.test.ts`, `packages/cli/package.json`, `packages/cli/tsconfig.json`, `packages/cli/test/build-incremental.test.ts`, `packages/cli/test/npm-pack.test.ts`, `packages/cli/test/docs-and-site.test.ts`, `packages/github-app/test/self-upgrade-fixtures.ts` + Gate: review + Acceptance: `@loopwright/evolution` builds, typechecks, lints, packs as the 12th bundled workspace package with zero new third-party runtime dependencies, passes `.opencodereview/rule.json` coverage assertions, updates self-upgrade `UNMANAGED_WORKSPACES` and `.auto-sync/digests.lock.json`, and keeps `@loopwright/state` `expectedSchema()` byte-identical. + Verify: `npm run build && npm run typecheck && npm run lint && npx tsc -p tsconfig.test.json && node scripts/run-tests.mjs --pkg evolution --concurrency 1 && node --test build-test/packages/cli/test/build-incremental.test.js build-test/packages/cli/test/npm-pack.test.js build-test/packages/cli/test/docs-and-site.test.js build-test/packages/github-app/test/self-upgrade.test.js` + +- [x] **T2 · Core Stage A static audit contracts, `bucketScope` thresholds, `bucketMetrics`, and `hardwareDiagnostics`** + Blocked by: T1 + Owns: `packages/core/src/**`, `packages/core/test/**` + Gate: review + Acceptance: `HardwareTargetSpec` accepts optional `forbiddenSymbolPatterns` (`0..64`), `maxRegisterCount`, and `maxLocalSpillBytes` without altering legacy canonical digests when omitted; `Evidence.spec` validates bounded `bucketMetrics` (`1..64` buckets, `<= 16` numeric metrics and `<= 8` dimension keys per bucket) and closed-enum `hardwareDiagnostics` (rejecting free-text strings, `-0`/`NaN`/`Infinity`, prototype keys, and secrets); `evaluateAcceptance` enforces `bucketScope` (`'aggregate' | 'all_buckets' | { bucketId }`); `diagnostics.ts` exports `STAGE_A_STATIC_AUDIT_FAILED`, `TEAM_ENVELOPE_VIOLATION`, and `EXPORT_UNVERIFIED_FORBIDDEN`. + Verify: `npm run build && npm run typecheck && npx tsc -p tsconfig.test.json && node scripts/run-tests.mjs --pkg core` + +- [x] **T3 · System-One (`@loopwright/decisions`) novelty filter, strategy track router, and cascade escalation nodes** + Blocked by: T1 + Owns: `packages/decisions/src/**`, `packages/decisions/test/**` + Gate: review + Acceptance: `DECISION_ALLOWED_AUTHORITY_INTENTS` includes `'advise_mutation_novelty'`, `'route_evolution_strategy'`, and `'advise_cascade_escalation'` while all six `DECISION_FORBIDDEN_AUTHORITY_INTENTS` still throw `DecisionError('DECISION_AUTHORITY_VIOLATION')`; `evaluateMutationNovelty` rejects exact whitespace/comment-normalized token-shingle clones (`Jaccard === 1.0`) with `0` network calls and queries Jev `noul` in `[noveltyThreshold, 1.0)` under `disclosurePolicy`; `routeEvolutionStrategy` and `evaluateCascadeEscalation` stamp `advisoryOnly: true` and `verificationCertified: false` with deterministic offline fallbacks. + Verify: `npm run build && npm run typecheck && npx tsc -p tsconfig.test.json && node scripts/run-tests.mjs --pkg decisions` + +- [x] **T4 · Hardware-scoped reviewed memory (`hardwareScope`) and `hardware_execution` evidence gate** + Blocked by: T1 + Owns: `packages/memory/src/**`, `packages/memory/test/**` + Gate: review + Acceptance: `MemoryEntry.scope` supports optional `hardwareScope` (`accelerator`, optional `driverConstraint`, `operatorFamily`, `boundPipeline`) omitted when undefined so all legacy v1 `storeDigest` and `proposalDigest` fixtures remain byte-for-byte identical; `verifier.ts` enforces a 6th gate rejecting `hardwareScope` `fact`/`invariant` upserts that lack a passing `hardware_execution` `evidenceRef` (`MEMORY_HARDWARE_EVIDENCE_REQUIRED` in `packages/memory/src/types.ts`) while admitting `failure_observation`; `selector.ts` filters active prompt memories by matching target cell `accelerator` and `driverConstraint`. + Verify: `npm run build && npm run typecheck && npx tsc -p tsconfig.test.json && node scripts/run-tests.mjs --pkg memory` + +- [x] **T5 · Controller `evolve-block-guard.v1` verifier and `benchmark-gate.v1` Stage A/B receipt forwarding** + Blocked by: T2 + Owns: `packages/controller/src/**`, `packages/controller/test/**` + Gate: review + Acceptance: `handlers.ts`, `registry.ts`, and `verifier-protocol.ts` implement deterministic `'evolve-block-guard.v1'` (`1..32` `EVOLVE-BLOCK-START/END` pairs per file, rejecting nested/duplicate/reordered/unclosed markers, `maxBlockBytes` overflow, `allowedBlockIds` violations, or any single-byte mutation outside mutable blocks against `baseRevision` SHA-256); `benchmark-gate.ts` forwards Stage A static audit fields, `bucketMetrics`, and `hardwareDiagnostics` onto recorded `Evidence` while keeping `D <= 256` `phaseSchedule` untouched and resolving handler digests cleanly via `installedHandlerDigests()`. + Verify: `npm run build && npm run typecheck && npx tsc -p tsconfig.test.json && node scripts/run-tests.mjs --pkg controller` + +- [x] **T6 · Hardware-runner Stage A symbol/spill static audits, Stage B bucket/Roofline parser, and post-crash GPU quarantine** + Blocked by: T2 + Owns: `packages/hardware-runner/src/**`, `packages/hardware-runner/test/**` + Gate: review + Acceptance: `evaluator.ts` audits sealed Stage A `.so`/`.o`/`.cubin`/`.ptx`/`.sass` outputs (`O_NOFOLLOW`, `1 MiB` cap) and denies `forbiddenSymbolPatterns` (`cublas`, `rocblas`, `aclnn`, `at::native`) or `maxRegisterCount`/`maxLocalSpillBytes` breaches with `STAGE_A_STATIC_AUDIT_FAILED` before Stage B starts; Stage B parses bounded `bucketMetrics` + sanitized `hardwareDiagnostics` (`<= 49,152` bytes, zero exported files, `all_buckets` threshold enforcement); `provenance.ts` and `worker.ts` run post-crash/timeout accelerator health probes (`Xid`/ECC/hang) and fail closed into `WORKER_DEVICE_QUARANTINED` (exit code `3`) before polling `/v1/runner/leases:acquire`. + Verify: `npm run build && npm run typecheck && npx tsc -p tsconfig.test.json && node scripts/run-tests.mjs --pkg hardware-runner` + +- [x] **T7 · `@loopwright/evolution` schemas, fenced `campaign.sqlite` store, NSGA-II Pareto engine, UCB1 sampler, and CAS scratchpad** + Blocked by: T2 + Owns: `packages/evolution/src/types.ts`, `packages/evolution/src/schema.ts`, `packages/evolution/src/store.ts`, `packages/evolution/src/pareto.ts`, `packages/evolution/src/sampler.ts`, `packages/evolution/src/scratchpad.ts`, `packages/evolution/test/schema-and-store.test.ts`, `packages/evolution/test/pareto-and-sampler.test.ts`, `packages/evolution/test/scratchpad.test.ts` + Gate: review + Acceptance: Null-prototype parsers validate `EvolutionCampaign` (`<= 65,536` bytes), `team-patch.v1` (`<= 32,768` bytes), and `dispatch-manifest.json`; `store.ts` manages `/campaign.sqlite` (`journal_mode = DELETE`, `synchronous = FULL`, `STRICT` tables `campaign_meta`, `campaigns`, `islands`, `team_configs`, `individuals`, `lineage_edges`, `O_NOFOLLOW`, `1,000ms` clock-drift guard, and single-writer in-process coordinator serialization); `pareto.ts` computes deterministic NSGA-II ranks, crowding distances, and hypervolume deltas; `sampler.ts` implements **Island Elitism** ring migration, novelty-decayed stepping-stone parent weights, `0o400` multi-parent `contextFiles`, and UCB1 model bandit updates; `scratchpad.ts` writes `SecretScrubber`-clean `<= 16 KiB` CAS snapshots. + Verify: `npm run build && npm run typecheck && npx tsc -p tsconfig.test.json && node scripts/run-tests.mjs --pkg evolution --concurrency 1` + +- [x] **T8 · Taskpack and GitHub App `evolve-block-guard.v1` compilation, Stage A audit schema, and `hardwareScope` memory projection** + Blocked by: T4, T5 + Owns: `packages/taskpack/src/**`, `packages/taskpack/test/**`, `packages/github-app/src/turnkey-memory.ts`, `packages/github-app/test/turnkey-memory*.test.ts` + Gate: review + Acceptance: `Taskpack` schema and compiler accept `'evolve-block-guard.v1'` checks and optional Stage A static audit fields without changing `TaskContract` or `TaskLock` digests on existing v2 taskpacks that omit them; `turnkey-memory.ts` in both `@loopwright/taskpack` and `@loopwright/github-app` projects optional `hardwareScope` (`accelerator`, `driverConstraint`) from matched hardware `target.matrix` cells onto reviewed memory proposals and active memory selection. + Verify: `npm run build && npm run typecheck && npx tsc -p tsconfig.test.json && node scripts/run-tests.mjs --pkg taskpack && node scripts/run-tests.mjs --pkg github-app` + +- [x] **T9 · `@loopwright/evolution` deterministic `evolution-bundle.v1` exporter (`dir` and `oci-layout`)** + Blocked by: T7 + Owns: `packages/evolution/src/bundle.ts`, `packages/evolution/test/bundle.test.ts` + Gate: review + Acceptance: `exportEvolutionBundle` stages deterministic `dir` and `oci-layout` (`oci-layout` + `index.json` + `blobs/sha256/`) bundles containing `manifest.json` (`kind: EvolutionBundle`, `version: 1`), `dispatch-manifest.json` (`fallback: 'baseline'`), and unmodified HMAC-signed `receipts/.verdict.json` files after `O_NOFOLLOW`, `nlink === 1`, SHA-256/`byteLength`, and `SecretScrubber` checks; refuses unverified or `synthetic_fixture` receipts (`EXPORT_UNVERIFIED_FORBIDDEN`) unless `allowSyntheticProbe: true` is explicitly set; repeated exports produce byte-identical digests. + Verify: `npm run build && npm run typecheck && npx tsc -p tsconfig.test.json && node --test build-test/packages/evolution/test/bundle.test.js` + +- [x] **T10 · `@loopwright/evolution` plateau `team-supervisor.ts`, `specialist-then-portfolio` synthesis, and `campaign.ts` orchestrator** + Blocked by: T3, T6, T7, T8, T9 + Owns: `packages/evolution/src/team-supervisor.ts`, `packages/evolution/src/campaign.ts`, `packages/evolution/src/index.ts`, `packages/evolution/test/team-supervisor.test.ts`, `packages/evolution/test/campaign-e2e.test.ts` + Gate: review + Acceptance: `campaign.ts` orchestrates async multi-island generations over fenced child `LocalRunStore` runs (`/runs//`), integrating `@loopwright/decisions` pre-filters, periodic `scratchpad` mounts, graceful `SIGTERM` / `BENCHMARK_PREEMPTED` resume without double-counting `maxEvaluations`, and two-stage `specialist-then-portfolio` dispatch verification on `portfolioHeldOutWorkloadId`; `team-supervisor.ts` triggers `tools: ['read']` supervisor runs only on `stallGenerations` or consecutive `RunEval` `pingPong`/`toolRepeats` pathologies, enforces the fail-closed Archetype Capability Envelope (`TEAM_ENVELOPE_VIOLATION`, `tools <= archetype.tools`, `StepHandoffSelector` relays, `D <= 256` precheck), promotes advancing `'trial'` `team_configs`, and auto-rolls back stalled trials after `trialGenerations`. + Verify: `npm run build && npm run typecheck && npx tsc -p tsconfig.test.json && node scripts/run-tests.mjs --pkg evolution --concurrency 1` + +- [x] **T11 · CLI lazy-loaded `loopwright evolve` subcommands, offline parity check, and honest 23-row closure ledger** + Blocked by: T10 + Owns: `packages/cli/src/**`, `packages/cli/test/arguments.test.ts`, `packages/cli/test/closure-and-failure-matrix.test.ts`, `packages/cli/test/evolve-cli.test.ts`, `packages/taskpack-runner/test/**` + Gate: review + Acceptance: `loopwright evolve check|run|resume|status|inspect|export` parses cleanly in `arguments.ts` and executes via lazy `await import('@loopwright/evolution')` in `main.ts` (preserving `runner-cli.test.ts` zero-static-import invariant and exit codes `0`, `2..8`, `130/143`); `closure.ts` registers `'@loopwright/evolution'` in `OWNER_PACKAGES` while preserving the exact `18` `closedLocal` / `5` `unprovisionedExternal` split and `CLOSURE_FALSIFICATION_FORBIDDEN` guard. + Verify: `npm run build && npm run typecheck && npx tsc -p tsconfig.test.json && node scripts/run-tests.mjs --pkg cli && node scripts/run-tests.mjs --pkg taskpack-runner && node packages/cli/dist/main.js closure --verify-failures --json` + +- [x] **T12 · Connected documentation, Hugo site sync, skill references, and full 12-package verification** + Blocked by: T11 + Owns: `docs/**`, `site/**`, `README.md`, `AGENTS.md`, `.agents/skills/**`, `packages/cli/test/check-docs-rules.test.ts` + Acceptance: Connected user/contributor docs (`docs/getting-started/architecture.md`, `docs/contribute/internals.md`, configuration/operations guides, `README.md`, `AGENTS.md`, `.agents/skills/loopwright-overview/SKILL.md`), Pretty YAML examples, and Hugo `site/` pages document `@loopwright/evolution`, `EvolutionCampaign`, `evolve-block-guard.v1`, `teamEvolution`, `hardwareScope`, and `evolution-bundle.v1` with zero banned filler words, zero broken links, and green full-workspace CI checks. + Verify: `npm run lint:docs && npm run site && npm run lint && npm test` + +### Test Plan + +[ ] I/we understand 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 + +- Update hardcoded workspace package count assertions (`11 -> 12`) in [`packages/cli/test/build-incremental.test.ts`](../packages/cli/test/build-incremental.test.ts) and [`packages/cli/test/npm-pack.test.ts`](../packages/cli/test/npm-pack.test.ts), add `packages/evolution/**/*.ts` to [`.opencodereview/rule.json`](../.opencodereview/rule.json) for [`packages/cli/test/docs-and-site.test.ts`](../packages/cli/test/docs-and-site.test.ts), and sync `UNMANAGED_WORKSPACES` + [`.auto-sync/digests.lock.json`](../.auto-sync/digests.lock.json) in [`packages/github-app/test/self-upgrade-fixtures.ts`](../packages/github-app/test/self-upgrade-fixtures.ts) (`T1`). +- Ensure controller and taskpack test suites resolve handler digests dynamically through `installedHandlerDigests()` when `'evolve-block-guard.v1'` is registered (`T5`, `T8`). + +#### Unit tests + +- `@loopwright/core`: `2026-11-23` - `>= 90%` (`bucketMetrics` per-bucket `<= 16` metric / `<= 8` dimension bounds, `hardwareDiagnostics` enum/ASCII/secret rejection, `bucketScope` `'aggregate' | 'all_buckets' | { bucketId }` threshold enforcement, Stage A static audit optional hash invariance). +- `@loopwright/decisions`: `2026-11-23` - `>= 90%` (`evaluateMutationNovelty` zero-network `Jaccard === 1.0` reject and Jev soft-band `noul` triage, `routeEvolutionStrategy`, `evaluateCascadeEscalation`, `DECISION_AUTHORITY_VIOLATION` enforcement, `verificationCertified: false` invariant). +- `@loopwright/memory`: `2026-11-23` - `>= 90%` (`hardwareScope` v1 `storeDigest` backward parity, `MEMORY_HARDWARE_EVIDENCE_REQUIRED` 6th verification gate on `fact`/`invariant` vs `failure_observation` admission, `selector.ts` `accelerator`/`driverConstraint` filtering). +- `@loopwright/controller`: `2026-11-23` - `>= 90%` (`evolve-block-guard.v1` outside-byte SHA-256 invariance, nested/duplicate/reordered/unclosed marker rejection, `maxBlockBytes` and `allowedBlockIds`, `benchmark-gate.v1` receipt forwarding). +- `@loopwright/hardware-runner`: `2026-11-23` - `>= 90%` (Stage A `forbiddenSymbolPatterns` and `maxRegisterCount`/`maxLocalSpillBytes` `STAGE_A_STATIC_AUDIT_FAILED` denial prior to Stage B, `49,152`-byte Stage B `bucketMetrics` + `hardwareDiagnostics` parser, post-crash `WORKER_DEVICE_QUARANTINED` probe). +- `@loopwright/evolution`: `2026-11-23` - `>= 90%` (`EvolutionCampaign` and `team-patch.v1` null-prototype schemas, fenced single-writer `campaign.sqlite` store and `1,000ms` clock-drift guard, NSGA-II rank/crowding/hypervolume determinism, Island Elitism migration, novelty-decayed parent sampling + UCB1 bandit, `TEAM_ENVELOPE_VIOLATION` capability-envelope checks, `trialGenerations` promotion/auto-rollback, CAS `scratchpad`, `dir`/`oci-layout` `evolution-bundle.v1` byte-identical export and tamper rejection). +- `@loopwright/taskpack` & `@loopwright/github-app`: `2026-11-23` - `>= 90%` (`evolve-block-guard.v1` compilation, legacy `TaskLock` digest stability, `turnkey-memory.ts` `hardwareScope` projection). +- `@loopwright/cli`: `2026-11-23` - `>= 90%` (`loopwright evolve` argument grammar, lazy import compliance in `runner-cli.test.ts`, exit codes, 23-row `closure.ts` `18/5` ledger invariance). + +#### Integration tests + +- **Child `LocalRunStore` + `benchmark-gate.v1` + `evolve-block-guard.v1` loopback**: verify an outside-block edit fails `evolve-block-guard.v1` before hardware lease acquisition, a `cublasGemmEx` symbol fails Stage A with `STAGE_A_STATIC_AUDIT_FAILED` with zero Stage B runtime, and a single-bucket `max_ulp` breach fails `bucketScope: 'all_buckets'` (`METRIC_THRESHOLD_FAILED`). +- **Stepping-stone MAP-Elites crossover & preemption recovery**: verify a slower structural stepping stone in a distinct `bound_pipeline` niche survives, feeds a multi-parent crossover child to rank-1 Pareto dominance, and `BENCHMARK_PREEMPTED` / `SIGTERM` resumes cleanly without consuming `maxEvaluations` or `@loopwright/state` `D <= 256` checkpoints. +- **Plateau `team-patch.v1` synthesis, envelope denial, and `trialGenerations` rollback**: verify steady-progress islands run `0` supervisor turns; stalled or `pingPong` islands run a `tools: ['read']` supervisor, reject tool-widening patches with `TEAM_ENVELOPE_VIOLATION`, execute a valid `probe-readonly -> mutator-sandboxed` `StepHandoffSelector` relay, promote on Pareto gain, and roll back to `parent_team_config_id` when `trialGenerations` expire with zero advance. +- **Cross-silicon `hardwareScope` memory isolation**: verify an `sm_100a` `hardware_execution`-backed memory entry is selected for `sm_100a` runs and excluded from `sm_89` and `ascend_910b` runs. +- **Post-crash worker device quarantine**: verify a simulated sticky `Xid` fault after Stage B crash transitions `worker.ts` into `WORKER_DEVICE_QUARANTINED` before acquiring a second Relay lease. + +#### e2e tests + +- **Local loopback `specialist-then-portfolio` campaign to `evolution-bundle.v1` OCI export (`packages/evolution/test/campaign-e2e.test.ts` and `packages/cli/test/evolve-cli.test.ts`)**: run `loopwright evolve check`, `loopwright evolve run`, `loopwright evolve status`, `loopwright evolve inspect`, and `loopwright evolve export --format oci-layout --allow-synthetic-probe` end-to-end over a two-bucket specialist campaign plus `portfolioHeldOutWorkloadId` synthesis, asserting verified `manifest.json`, `dispatch-manifest.json` (`fallback: 'baseline'`), HMAC-signed `receipts/*.verdict.json`, and tampered-blob fail-closed rejection (`ARTIFACT_INVALID` / `EXPORT_UNVERIFIED_FORBIDDEN`). +- **Optional live accelerator SSH smoke (on-demand)**: when `LOOPWRIGHT_CUDA_SSH_HOST` or `LOOPWRIGHT_ROCM_SSH_HOST` is set, run a 2-generation physical-probe campaign and export an `evolution-bundle.v1` bundle without `--allow-synthetic-probe`. + +## Alternatives + +1. **Extend [`packages/state/src/schema.ts`](../packages/state/src/schema.ts) (`format_version = 2`) and [`packages/controller/src/progress.ts`](../packages/controller/src/progress.ts) to store multi-generation populations inside one `LocalRunStore`**: + - Rejected. Mutating the 5-table `DDL` breaks `expectedSchema()` across existing retained stores and requires lifting the `checkpoints <= 256` and `operations <= 2,048` single-run bounds that underpin deterministic crash-recovery audits. Storing campaign lineage in `/campaign.sqlite` while delegating each candidate evaluation to an unmodified child `LocalRunStore` preserves every existing single-run safety proof. +2. **Use greedy single-lineage hill-climbing instead of Island + MAP-Elites + stepping-stone parent decay**: + - Rejected. Kernel and compiler evolution landscapes are sharply non-convex; structural transitions (such as switching memory layouts or introducing warp specialization) often degrade latency for one generation before tile and barrier parameters are tuned. Greedy selection discards those stepping stones and collapses prompt diversity. +3. **Run an unconditional per-iteration supervisor emitting free-form Markdown `TEAM_CONFIG` over a shared mutable workspace or mutating `CompiledPlan` mid-run**: + - Rejected. Invoking a supervisor on every generation wastes tokens when the active role is still advancing, regex-scraped Markdown fails unpredictably on nested headings, shared working directories risk cross-agent file clobbering, and unrestricted role tools violate host authority boundaries. Triggering a read-only supervisor only on plateaus/pathologies, enforcing `team-patch.v1` archetype envelopes (`tools <= archetype.tools`), relaying outputs via `StepHandoffSelector`, and auto-rolling back unproductive `team_configs` after `trialGenerations` achieves plateau-breaking specialization safely. +4. **Export raw `ncu` / `rocprof` / `msprof` profiler files directly from Stage B to guide next-generation prompts**: + - Rejected. Multi-megabyte raw profiler archives bloat LLM context windows and create a covert exfiltration channel for private `held_out_workloads` tensor values and shapes. Distilling bounded numeric counters and closed pipeline/stall enums in the trusted supervisor preserves Stage B zero-file-export isolation. +5. **Seed prompts with large human-authored static optimization cookbooks instead of `hardware_execution`-verified memories and live campaign scratchpads**: + - Rejected. Empirical continual-compilation ablations show that generic static cookbooks anchor coding agents onto suboptimal templates and risk cross-architecture errors. Admitting only `hardware_execution`-backed `hardwareScope` facts, anti-pattern `failure_observation` entries, and live campaign delta scratchpads keeps guidance grounded in measured silicon behavior. +6. **Allow `@loopwright/decisions` (`typesafe-jev`) to score candidate fitness or approve `evolution-bundle.v1` exports without `benchmark-gate.v1`**: + - Rejected. Violates Loopwright's non-delegable verification invariant. System-One models can cheaply pre-filter cosmetic clones and route tracks, but only signed `hardware_execution` receipts may admit Pareto elites, hardware memories, or exported bundles. + +## Open Questions + +None. All user stories, isolated `campaign.sqlite` storage boundaries, plateau-triggered `team-patch.v1` archetype envelopes and `team_configs` trial rollback rules, anti-cheating Stage A/B rules, System-One advisory boundaries, hardware memory scopes, `evolution-bundle.v1` export contracts, and the 12-task `T1`-`T12` implementation and KEP test plans are confirmed. diff --git a/tsconfig.test.json b/tsconfig.test.json index 3dafe06..bd53e03 100644 --- a/tsconfig.test.json +++ b/tsconfig.test.json @@ -29,6 +29,8 @@ "packages/github-app/src/**/*.ts", "packages/github-app/test/**/*.ts", "packages/hardware-runner/src/**/*.ts", - "packages/hardware-runner/test/**/*.ts" + "packages/hardware-runner/test/**/*.ts", + "packages/evolution/src/**/*.ts", + "packages/evolution/test/**/*.ts" ] }