Skip to content

feat(controller): add command.v1 direct checks, exec roles, and snapshots - #61

Merged
thxCode merged 26 commits into
mainfrom
spec/managed-controller-in-process-execution
Dec 2, 2026
Merged

thxCode merged 26 commits into
mainfrom
spec/managed-controller-in-process-execution

Conversation

@thxCode

@thxCode thxCode commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

What type of PR is this?

/kind feature
/area core
/area controller
/area cli
/area docs
/area site

Summary

  • Why. Enable unattended Managed Controller runs inside an already isolated host (such as a single-accelerator Pod Security Admission restricted Pod with no Docker socket, no loopback relay, and no controller model calls), and make evolutionary campaign state portable across hosts without sharing SQLite clock or lease state.
  • Managed Controller command.v1 (direct) and host_execution evidence. Added host.localChecks.backend: direct attestation in TrustedRegistry, command.v1 check handler validation (scope.protected directory enforcement, committed executable bit, #! check, timeout fit), LocalCheck process-group execution with binding/proof markers and crash recovery (EVIDENCE_UNAVAILABLE), rework detail extraction, and verifier-receipts.json export in inspect.
  • exec role adapter and usage ledger. Added adapter: exec role profiles and consumer: exec in-memory vault bindings, runExecRole allowlisted environment and process-group teardown, Cycle.#execDispatch (intent/permit, CLEANUP_FAILED invariants, DEADLINE vs CANCELLED pre-receipt lease renewal, exit 3 DAG halt guarded by scope.v1, no format repair, and fail-closed RECOVERY_REQUIRED recovery without re-dispatch), and exec usage aggregation from settled exec-outcome artifacts into RunResult, usage.json, and run-eval.json without mutating frozen LocalRunStore.requests.
  • Portable campaign-snapshot.v1 and CLI. Added writeCampaignSnapshot, verifyCampaignSnapshot, importCampaignSnapshot, and snapshot_provenance in @loopwright/evolution with fresh local authority and clock-basis reset on import, plus loopwright evolve export --snapshot, evolve check --bundle, and evolve import (--receipt-secret-env optional when zero signed receipts exist and fail-closed otherwise, --allow-synthetic-probe, --allow-host-attested).
  • In-process hardware gate feasibility probe (blocked_external). Recorded the Pod Security Admission restricted namespace probe verdict (namespaces_blocked: RuntimeDefault seccomp denies clone(CLONE_NEWUSER)) with tracked sanitized JSONL evidence under packages/hardware-runner/test/fixtures/bwrap-namespace-probe/evidence/. Added optional hardwareProvenance.isolation (docker | host_attested) with fail-closed refusal of host_attested in benchmark-gate.v1 and opt-in gating in evolution commands; loopwright runner inline and deviceOwnership: host are intentionally not implemented in this version.
  • Closure matrix, ADR, and documentation. Expanded CLOSURE_CAPABILITY_LEDGER from 23 to 26 rows (20 closed_local, 6 unprovisioned_external), added ADR 0003 (Linux SQLite Profiles), added public pages Managed Controller in Isolated Host and Campaign Snapshots, and synced all public, contribute, reference, and Hugo site indexes.
  • Verification scope. Verified deterministically on local macOS arm64 (Node 26) across all workspace packages and Hugo site export. Physical CUDA qualification and live container/Pod host qualification remain external boundaries honestly recorded in the closure ledger and walkthrough.

Related Issues

None.

Verification

  • npm run build passed cleanly
  • npm run typecheck passed cleanly
  • npm run lint passed cleanly
  • npm run lint:docs passed cleanly (37 docs pages, 47 linked sources, 0 errors)
  • npm run site built and verified with zero broken links (20 HTML pages, 17 Markdown exports, 6 reference files)
  • Focused and package test suites passed (core 146/146, state 143/143, controller 424/424, taskpack 80/80, evolution 56/57 with 1 Linux-only skip, hardware-runner 67/70 with 3 Linux/Docker-only skips, cli 105/105, closure --verify-failures 14/14)
  • OS sandbox diagnostics verified (bwrap-namespace-probe.test.ts records namespaces_blocked under PSA restricted)
  • Verified .github/workflows/ maintains least-privilege permissions and remains protected against untrusted taskpack/sandbox writes (zero workflow changes)
  • Signed-off-by: Full Name <email> Developer Certificate of Origin (DCO) included on all commits

Does this PR introduce a user-facing change?

Added Managed Controller `command.v1` checks (`host.localChecks.backend: direct`, `host_execution` evidence), the `exec` role adapter with `consumer: exec` credentials and `LOOPWRIGHT_USAGE_OUT` accounting, and portable `campaign-snapshot.v1` export/check/import CLI commands (`loopwright evolve export --snapshot`, `evolve check --bundle`, `evolve import`) with fresh-authority import across hosts. Recorded the `namespaces_blocked` feasibility probe for in-process `benchmark-gate.v1` under PSA `restricted` and added fail-closed `hardwareProvenance.isolation` handling (`runner inline` and `deviceOwnership: host` are not implemented in this version).

- Add command.v1 as a Managed Controller check under an explicit direct backend
- Add the exec role adapter so loopwright run completes DAGs with local commands
- Phase two: portable campaign snapshots and an in-process benchmark gate
- Record boundaries, risks, alternatives, and open questions

Signed-off-by: thxCode <thxcode0824@gmail.com>
…n review

- Add the task DAG and test plan for command.v1 under direct and the exec adapter
- Move the direct attestation into the registry and add the host_execution evidence level
- Settle unknown exec and check outcomes without re-dispatch and import campaigns with a fresh authority
- Fold the 26 review findings into features, boundaries, risks, and tests

Signed-off-by: thxCode <thxcode0824@gmail.com>
- exec role binds pi.agent.v1 handler; dispatch follows adapter
- controller sets LOOPWRIGHT_USAGE_OUT inside attempt scratch
- exec timeoutMs obeys the command.v1 drain-reserve fit rule
- T5 follows T2; T1, T2, T9, T11 start together

Signed-off-by: thxCode <thxcode0824@gmail.com>
- HardwareProvenance isolation is optional; absent means a docker-era receipt
- T9 owns core evidence.ts and evolution schema.ts for the parser
- T11 only produces the field; T9 lands the type first

Signed-off-by: thxCode <thxcode0824@gmail.com>
- write, verify, import campaign-snapshot.v1 with fresh authority
- snapshot_provenance table and single-transaction importCampaignState
- HardwareProvenance.isolation optional; export refuses host_attested
- move shared bundle helpers into internal bundle-fs.ts
- T9 spec check-off; F4 members, Owns widenings, Open Question 3

Task 9 of managed-controller-in-process-execution.

Signed-off-by: thxCode <thxcode0824@gmail.com>
… exec profiles

- registry accepts command.v1 check handler and exec role profile
- config refuses missing direct attestation and unfit timeouts
- host_execution evidence level and capability; RoleAdapterKind gains exec
- named limits for captureBytes, exec command entries, localChecks timeout
- T2 spec check-off; T3/T4 Owns notes for exports, handlers, errors

Task 2 of managed-controller-in-process-execution.

Signed-off-by: thxCode <thxcode0824@gmail.com>
- export EXEC_LIMITS and LOCAL_CHECK_LIMITS for the exec runner
- export handlerCapability for registry consumers
- unblocks T5; satisfies the T3 index.ts export item

Task 5 of managed-controller-in-process-execution.

Signed-off-by: thxCode <thxcode0824@gmail.com>
…-workspace.ts

- move materializeAttemptWorkspace and scanCandidateDirectory verbatim
- step.ts imports them; export two helpers the moved bodies call
- prune imports only the moved bodies used; document the module cycle
- T1 spec check-off

Task 1 of managed-controller-in-process-execution.

Signed-off-by: thxCode <thxcode0824@gmail.com>
…environment

- runExecRole spawns the command in its own process group
- allowlist-only environment; credentials via SecretResolver, never process.env
- bounded scrubbed capture; exit 0/3/other/timeout/cancel mapping with group kill
- optional usage file parse with exact refusal codes
- T5 spec check-off; F2 list separators recorded

Task 5 of managed-controller-in-process-execution.

Signed-off-by: thxCode <thxcode0824@gmail.com>
- probe script and restricted-profile Pod manifest for bubblewrap namespaces
- recorded verdict namespaces_blocked on kind/containerd 2.3 with PSA restricted
- seccomp versus AppArmor differential recorded; no Landlock ABI on the node
- no feature code: F5 stays behind the probe; spec records blocked_external

Task 11 of managed-controller-in-process-execution.

Signed-off-by: thxCode <thxcode0824@gmail.com>
- core contract: env names, env name rule, strict CHECK_OUT parser
- LocalCheck mirrors Gate.run: intent, permit, binding with pgid, proof, receipt
- candidate workspace via T1 helpers; F1 environment; process-group kill on timeout
- host_execution evidence; restore settles blocked/EVIDENCE_UNAVAILABLE, never re-dispatches
- T3 spec check-off; T4 Owns widened with retained.ts and acceptance.ts

Task 3 of managed-controller-in-process-execution.

Signed-off-by: thxCode <thxcode0824@gmail.com>
…to end

- compile resolves script directory digest into the slot under planDigest
- two-phase owner acquire keeps runs without command.v1 byte-identical
- dispatch through LocalCheck; rework detail; recovery settles blocked, no re-dispatch
- inspect exports verifier-receipts.json; acceptance, lease, run-eval branches
- T4 spec check-off; F1 receipt export wording and resume re-verification

Task 4 of managed-controller-in-process-execution.

Signed-off-by: thxCode <thxcode0824@gmail.com>
…n parity

Address Phase 1 review findings across @loopwright/core and @loopwright/controller:
- Fix LocalCheck.restore double-restore on interrupted operations (removing the
  silent early return in recovery-cycle.test.ts and adding crash-before-binding
  coverage), attach spawn exit/error/stderr listeners synchronously before
  binding-marker fsync, cap stderr to a rolling 16 KiB tail, settle aborted
  dispatches cleanly with DEADLINE vs CANCELLED mapping, and preserve
  holdLocalActivity and attemptDir on CLEANUP_FAILED.
- Enforce canonical path containment and readBoundedFile on exec-role usageOut,
  expose ExecRoleOutcome.usageReported, raise parseUsage collection limit to
  LIMITS.requests (1024), cap exec.timeoutMs at 3,600,000 ms, wait on exit with
  unconditional process-group cleanup via shared process-group.ts, and check
  timedOut before exit.code.
- Reject exec blocks on pi/delegated profiles, enforce full directory protection
  and #! shebang admission for command.v1 scripts, sanitize control characters
  in rework detail, widen retained lease headroom and safePath whitelist, align
  SecretScrubber/CredentialVault.scrub patterns, export HandlerCapability, and
  accept optional docker isolation (refusing host_attested) in benchmark-gate.ts.

Signed-off-by: thxCode <thxcode0824@gmail.com>
…ding, and import atomicity

Address Phase 2 review findings across @loopwright/evolution:
- Secret-scan scratchpads, textual CAS blobs, and all text members on snapshot
  export, verify, and import, threading resolved.scrubber into document parsers.
- Raise snapshot manifest parsing/canonicalization caps to 16,384 members
  (131,072 nodes) aligned with MAX_SNAPSHOT_MANIFEST_BYTES while keeping default
  parser limits unchanged.
- Allow signed finite negative scalarFitness values, topologically sort
  team_configs with cycle rejection, and wrap legacy snapshot_provenance
  migration in BEGIN IMMEDIATE with IF NOT EXISTS.
- Bind receipted individuals' status, metrics, bucketMetrics, and
  hardwareDiagnostics to their signed verdict receipt, reject unreceipted
  hardwareProvenance and unreferenced manifest members, stage absent stateDir
  imports atomically with O_EXCL empty-dir claiming, include isolation in bundle
  compatibility checks, deduplicate bundle-fs helpers, and add negative tests.

Signed-off-by: thxCode <thxcode0824@gmail.com>
…space diagnostics

Relocate sanitized probe JSONL transcripts into tracked fixture evidence under
packages/hardware-runner/test/fixtures/bwrap-namespace-probe/evidence/, remove
agent scratch paths and internal task tags from tracked files, replace the
nonexistent /sys/kernel/security/landlock/abi sysfs read with unprobed, fix the
SECCOMP_RET_ERRNO | EPERM comment, and align the Ubuntu 6.8+ AppArmor
unprivileged_userns differential notes.

Signed-off-by: thxCode <thxcode0824@gmail.com>
…o boundaries

Update specs/2026-11-30-managed-controller-in-process-execution.md with the
pre-T6 design review findings and confirmed gpustack-operator <-> loopwright <->
forgevo alignment:
- Clarify exec.env literal values, 3,600,000 ms exec.timeoutMs ceiling, same-UID
  trust boundary, T6 DAG/recovery/cleanup requirements, and T7 usage aggregation
  from settled exec-outcome artifacts without mutating frozen LocalRunStore.requests.
- Align F4/T10 snapshot continuation on evolve resume with optional
  --receipt-secret-env when no individual carries a signed receipt, and correct
  T11 Landlock/AppArmor diagnostic wording.
- Record the three-layer boundary and explicitly deferred/rejected items in
  Alternatives (decoupled snapshot manifests, single-archive packing in forgevo,
  F5 blocked_external under PSA restricted, and evolve CLI composition boundary).

Signed-off-by: thxCode <thxcode0824@gmail.com>
…h, capture, and recovery

- Add exec compilation branch in compile.ts (no runtime profile, provider credential, or context guard; refuses mixed exec+pi/delegated plans and exec review/compaction steps; validates exec credentialRefs strictly against vault bindings).
- Add CredentialVault.resolveExecCredential for consumer: exec bindings and include exec timeoutMs in resolveStoreLeaseMs and exec dispatches in countDelegatedBudgets.
- Share synthesizedStepOutput and removeTree across step, capture, local-check, controller, and recovery; extend captureDelegatedRole and add captureExecRole for single confirmed exec local_write operations.
- Implement Cycle.#execDispatch with binding/proof markers, holdLocalActivity, process-group confirmation, CLEANUP_FAILED invariants, DEADLINE vs CANCELLED mapping with pre-receipt store.renew, exit-3 blocked DAG halt (guarded by scope.v1), upstream failed pruning, and no format repair.
- Refuse exec plans in stepNext/reopenStepContext (CAPABILITY_UNSUPPORTED) and settle interrupted exec operations fail-closed as exec_unknown / RECOVERY_REQUIRED in recovery.ts while discarding attempt directories.
- Add compile, end-to-end integration, and crash-recovery tests (417/417 controller tests passing) and check off T6 in the spec.

Signed-off-by: thxCode <thxcode0824@gmail.com>
…in run-eval

- Add collectExecUsage and deterministic core-identifier-safe request ID namespacing in exec-role.ts, reading settled exec-outcome artifacts without mutating frozen LocalRunStore.requests.
- Preserve provenance: 'unknown' (never zero) when usageReported is false, artifacts are unreadable, or exec settles as exec_unknown; preserve complete reported zero for explicit empty usage files; enforce LIMITS.requests bounds.
- Wire exec usage aggregation into evaluateControllerAcceptance (acceptance.ts), Cycle acceptance paths (controller.ts), and inspectRun / usage.json (inspect.ts).
- Update run-eval.ts to exclude exec operations from tool ops, classify exec attempts separately from pi/delegated, keep toolTelemetry and circuitBreaker honestly unavailable for pure-exec runs, and aggregate exec tokens/cost into step, role, and total breakdowns.
- Add core usage boundary tests and controller exec-usage integration tests (146/146 core, 424/424 controller passing) and check off T7 in the spec.

Signed-off-by: thxCode <thxcode0824@gmail.com>
…lated-host docs

- Expand CLOSURE_CAPABILITY_LEDGER to 26 rows (20 closed_local, 6 unprovisioned_external): add command.v1 direct and exec role adapter as closed_local and in-process benchmark-gate hardware as blocked_external with tracked probe evidence; update closureExitCode and CLI tests.
- Add ADR 0003 (Linux SQLite profiles) superseding ADR 0001's darwin/arm64-only host sentence with CI runner evidence and Linux fullfsync semantics.
- Add Managed Controller in Isolated Host public walkthrough (YAML verified via loopwright check) and update controller-and-registry, task-contract, cli, coding-agents, closure-matrix, docs/README.md, site navigation/index/home, check-docs.mjs, page-map.md, and docs/site CLI tests.
- Check off T8 in the spec; all 36 docs pages, Hugo site exports, 100/100 CLI tests, and closure --verify-failures (14/14) pass.

Signed-off-by: thxCode <thxcode0824@gmail.com>
…Hash verification, and add docs

- Add evolve export --snapshot, evolve check --bundle, evolve import, --receipt-secret-env (optional when zero signed receipts, fail-closed otherwise), and --allow-host-attested in packages/cli/src/{arguments,main}.ts.
- Drop expectedLockHash: campaign.lockHash in packages/evolution/src/snapshot.ts (matching bundle.ts) so real evolve campaigns with per-candidate child TaskContract lockHashes export and import cleanly while preserving HMAC signature, candidateDigest, targetCellId, and receipt field bindings.
- Add packages/cli/test/evolve-snapshot.test.ts covering grammar, signed synthetic_fixture round-trip/tamper/secret-hygiene, direct-mode receipt: null without --receipt-secret-env, host_attested gating, and real evolve resume on a lower monotonic clock without EVOLUTION_CLOCK_DRIFT.
- Add Campaign Snapshots public configuration page and sync docs/contribute/internals.md (snapshot_provenance), docs/operations/cli.md, docs/README.md, scripts/check-docs.mjs, site navigation/index/home, page-map.md, and docs/site CLI tests.
- Check off T10 in the spec; all 37 docs pages, Hugo site exports, 56/57 evolution tests (1 skipped), and 105/105 CLI tests pass.

Signed-off-by: thxCode <thxcode0824@gmail.com>
…hardwareProvenance.isolation

- Document in docs/operations/cli.md that loopwright runner inline and deviceOwnership: host are not implemented in this version due to the recorded namespaces_blocked probe under PSA restricted, pointing isolated-Pod users to command.v1 (direct) and adapter: exec.
- Document optional hardwareProvenance.isolation (docker | host_attested) fail-closed semantics in docs/configuration/task-contract.md.
- Expand the in-process-benchmark-gate-hardware blocked_external explanation in docs/contribute/closure-matrix.md and update docs/README.md index entries.
- Check off T12 in the spec; lint:docs (37 pages, 0 errors), Hugo site (20 HTML / 17 Markdown, 0 broken links), and docs/closure tests pass.

Signed-off-by: thxCode <thxcode0824@gmail.com>
- Add command.v1, host.localChecks, exec role profiles, and consumer: exec to controller-and-registry-schema.md.
- Update cli-and-action-reference.md for the 26-row closure matrix, evolve import, --snapshot, and --bundle.
- Add exec adapter, host_execution, and hardwareProvenance.isolation to taskpack-and-contract-schema.md and README.md.
- Advance specs/2026-11-30-managed-controller-in-process-execution.md Status to Shipped.

Signed-off-by: thxCode <thxcode0824@gmail.com>
@gpustack-code-review

gpustack-code-review Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

🔍 OpenCodeReview found 1 issue(s) in this PR.

  • ✅ Successfully posted inline: 0 comment(s)
  • 📋 Routed to summary by policy: 1 comment(s)

bug · low

📄 packages/core/src/scrubber.ts (L20-L21)

⚠️ GitHub could not post this as an inline comment: Routed to summary (severity low · category bug)

The trailing generic pattern has no minimum-length guard, unlike the registered-forms branch (MIN_FORM_LENGTH = 8). Both optional inner groups in the -----BEGIN ... alternative mean a string ending in the bare header -----BEGIN (no 'PRIVATE KEY', no key material) is fully replaced with [scrubbed], and ghp_ (4 chars) or sk-ant- (7 chars) with an empty body also match. These prefixes contain no secret material, so this over-redacts benign trailing text and is inconsistent with the documented >= 8 truncation-prefix contract. Consider requiring at least a partial token body, e.g. gh[pousr]_[A-Za-z0-9]{4,} and requiring the 'PRIVATE KEY' keyword (or at least -----BEGIN P) before matching.

💡 Suggested Change

Before:

const TRAILING_GENERIC_SECRET_PATTERN =
  /(?:gh[pousr]_[A-Za-z0-9]*|github_pat_[A-Za-z0-9_]*|sk-(?:ant-|proj-)[A-Za-z0-9_-]*|(?<![0-9A-Za-z])AKIA[0-9A-Z]{4,}|-----BEGIN (?:(?:RSA |EC |DSA |OPENSSH |ENCRYPTED )?PRIVATE KEY(?:-{0,5})?)?)$/;

After:

const TRAILING_GENERIC_SECRET_PATTERN =
  /(?:gh[pousr]_[A-Za-z0-9]{4,}|github_pat_[A-Za-z0-9_]{4,}|sk-(?:ant-|proj-)[A-Za-z0-9_-]{4,}|(?<![0-9A-Za-z])AKIA[0-9A-Z]{4,}|-----BEGIN (?:(?:RSA |EC |DSA |OPENSSH |ENCRYPTED )?PRIVATE KEY-{0,5})?)$/;

Reviewed 4bf83cf..0aaf5a5 only; earlier commits in this PR were reviewed in a previous run.

Comment on lines +491 to +494
for (const item of execUsage) {
usage.push(item);
}
if (usage.length > LIMITS.requests) refuse('OUTPUT_LIMIT', '', 'verification');

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
The new bound usage.length > LIMITS.requests conflates two different budgets. usage now mixes model request records with exec entries synthesized by collectExecUsage (one unknown entry per exec operation that did not report usage, plus per-op reported lists each capped at LIMITS.requests). A run that is legitimately within its model-request budget can be refused OUTPUT_LIMIT in the verification phase purely because of the number of exec attempts — e.g. 700 model requests + 400 exec steps that report no usage (CI commands, linters) fails even though neither budget was individually exceeded. If the intent is a hard cap on the combined result payload, consider a dedicated limit for exec entries (e.g. EXEC_LIMITS.usageEntries) or counting exec ops separately, so the refusal maps to the budget actually breached.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changed (false positive): LIMITS.requests (1024) is @loopwright/core's hard requestsSchema ceiling (packages/core/src/usage.ts:17), and mixed pi + exec plans are refused at admission (packages/controller/src/compile.ts:150). Checking usage.length > LIMITS.requests here surfaces OUTPUT_LIMIT cleanly instead of an opaque RECOVERY_REQUIRED inside constructRunResult.

Comment on lines +211 to +216
for (const profile of registry.spec.roleProfiles) {
if (profile.adapter !== 'exec' || profile.exec === undefined) continue;
if (configuration.spec.controls.drainReserveMs + profile.exec.timeoutMs > finalTask.spec.budgets.wallTimeMs) {
refuse('CONFIG_SCHEMA', '/registry/spec/roleProfiles');
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
This loop refuses the configuration when ANY registry role profile with adapter: 'exec' has a timeout that doesn't fit, even if that profile is never selected by this task's roles (profiles are bound per-role via spec.profiles.roles[].profileRef, see compile.ts:339). A shared registry carrying an exec profile with a large timeoutMs for some other task/campaign will now hard-refuse every configuration whose wallTimeMs is smaller, with no way to fix it from the config side other than raising the task budget. Same concern applies to the command.v1 handler loop above if a handler is not referenced by this task's steps. Consider resolving the profiles/handlers actually used by finalTask (e.g. via the planned roles or step handlerRefs) and validating only those against drainReserveMs/wallTimeMs, mirroring how /spec/registry binding is already scoped to this configuration.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changed (intentional spec contract): loadConfiguration intentionally validates registry-wide command.v1 and exec timeout fit against drainReserveMs and wallTimeMs before compilePlan binds profiles (verified in packages/controller/test/config-local-checks.test.ts).

Comment on lines +2306 to +2316
} finally {
if (groupClean && workspacePresent) {
await removeTree(attemptDir, 'execution');
workspacePresent = false;
}
if (groupClean && !workspacePresent) {
done();
} else if (this.#cleanup === 'complete') {
this.#cleanup = 'pending';
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · medium
In the finally block, done() (the release callback for owner.holdLocalActivity()) is only invoked on the groupClean && !workspacePresent branch. If groupClean is true but removeTree(attemptDir, 'execution') throws (its phase parameter suggests it can refuse with a ControllerFailure, e.g. on an I/O or recovery error), the thrown error replaces the original failure AND done() is never called — the owner's local-activity hold leaks for the lifetime of the process, blocking later acquisition attempts even though the workspace is actually gone or partially gone. Similarly, when groupClean is false but #cleanup was already 'pending', nothing records that done() is still outstanding. Consider wrapping the removal in a try/catch that still releases the hold (or defers it explicitly to the incident cleanup path) so a cleanup failure cannot strand the owner lease.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changed (intentional fail-closed invariant): matching packages/controller/src/local-check.ts:506, when removeTree fails with CLEANUP_FAILED, keeping done() held prevents owner.release() from relinquishing the lease while cleanup is unresolved.

Comment on lines 161 to +163
const formBuffers = deriveSecretFormBuffers(tokens.values());
const scrubber = new SecretScrubber();
for (const token of tokens.values()) scrubber.register(token);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maintainability · medium
The secret-form derivation logic (raw, JSON-escaped, \/-escaped, URL-encoded, base64) is now duplicated between deriveSecretFormBuffers here and SecretScrubber.register in @loopwright/core, and the two generic-pattern lists already diverge (the scrubber replaces a wider set such as AZURE_API_KEY/AWS_SECRET_ACCESS_KEY than the credential checker detects). Over time this drift means scrub() and assertClean() disagree on what counts as a leak: a string can be scrubbed in one place yet pass assertClean in another (or vice versa). Consider centralizing the form derivation (and ideally the pattern list) in SecretScrubber / core and have the vault reuse it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changed (out of scope): CredentialVault operates on streaming Buffer chunks whereas SecretScrubber operates on UTF-8 strings. The redundant regexes in packages/core/src/scrubber.ts were cleaned up in this round; unifying the streaming vault matcher is left out of scope.

Comment thread packages/controller/src/exec-role.ts Resolved
Comment thread packages/evolution/src/snapshot.ts Resolved
Comment thread packages/evolution/src/snapshot.ts Resolved
Comment thread packages/evolution/src/snapshot.ts Resolved
Comment on lines +2174 to +2175
assertDriverConstraint(campaign.driverConstraint, '/driverConstraint');
const manifest = parseEvolutionCampaignDocument(campaign.manifest);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bug · high
importCampaignState validates campaign.manifestDigest only syntactically (assertDigest) but never checks that it equals the digest of the manifest content actually persisted. The INSERT writes canonicalizeJson(manifest) into manifest_json and campaign.manifestDigest.hex into manifest_digest_hex, so a caller of this public store API (outside the snapshot verify path, which separately checked the snapshot's own digests) can supply a mismatched pair, and every downstream consumer that trusts manifest_digest_hex (e.g. lock/lockHash binding, getCampaign hydration) will silently disagree with the stored manifest. Compute sha256Hex(Buffer.from(canonicalizeJson(manifest))) and reject on mismatch before the INSERT.

Suggestion:

Suggested change
assertDriverConstraint(campaign.driverConstraint, '/driverConstraint');
const manifest = parseEvolutionCampaignDocument(campaign.manifest);
const manifest = parseEvolutionCampaignDocument(campaign.manifest);
const manifestText = canonicalizeJson(manifest);
if (sha256Hex(Buffer.from(manifestText, 'utf8')) !== campaign.manifestDigest.hex) {
throw new EvolutionError(
'EVOLUTION_SCHEMA_INVALID',
'manifestDigest does not match the campaign manifest content',
'/manifestDigest',
);
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changed (false positive): campaign.manifestDigest hashes the raw YAML source file bytes (see createCampaign in packages/evolution/src/store.ts:1094 and packages/evolution/test/snapshot.test.ts:280), not canonicalizeJson(manifest). Comparing it against sha256Hex(canonicalizeJson(manifest)) would reject every real YAML campaign import.

Comment thread packages/evolution/src/store.ts Resolved
…solation parity

Signed-off-by: thxCode <thxcode0824@gmail.com>
…dispatch, capture, and recovery

Signed-off-by: thxCode <thxcode0824@gmail.com>
…ipt binding, and import atomicity

Signed-off-by: thxCode <thxcode0824@gmail.com>
@thxCode

thxCode commented Dec 1, 2026

Copy link
Copy Markdown
Contributor Author

Address PR Review — Round 1 Summary

Triaged all 36 OpenCodeReview findings (17 inline threads + 19 summary-routed items) and the Linux CI failure (ubuntu-24.04 / ubuntu-24.04-arm shard 3/3) against the source before applying fixes. Zero upgrade compatibility risks were identified.

Fixed (engineering issues & CI)

  • Linux CI (packages/controller/test/local-check.test.ts:228): Filtered optional shell-injected environment keys (PWD, SHLVL, _) before comparing child env keys so both Ubuntu /bin/sh (dash) and macOS /bin/sh (bash) pass deterministically.
  • T5 (packages/core/src/scrubber.ts, packages/controller/src/exec-role.ts:394): Added SecretScrubber.scrubTruncated(value) to scrub any trailing >= 8-char prefix of a registered secret form at stream truncation boundaries, applied when stdout.truncated / stderr.truncated is true, with unit tests in scrubber.test.ts and exec-role.test.ts.
  • T6 (packages/controller/src/local-check.ts:404, packages/controller/src/exec-role.ts:390): Disarmed the abort event listener immediately after exited resolves (before confirmProcessGroupGone and drainStream) to prevent late aborts from signaling an already-cleaned PGID.
  • T7 (packages/controller/src/local-check.ts:510): Extracted shared #settleFailClosed used by both #settleAbortedDispatch and #settle so abort and recovery settlement cannot drift.
  • T9 (packages/controller/src/controller.ts:2175): Removed the redundant second confirmProcessGroupGone(outcome.pgid, 'execution') call after runExecRole already confirmed the process group gone.
  • T11 (packages/controller/src/recovery.ts:243): Removed dead !isRecord(parsedProof) and cross-checked parsedProof.pgid against the binding pgid (confirming any positive proof pgid gone when binding was absent), with regression tests in recovery-owner.test.ts.
  • T13 (packages/evolution/src/snapshot.ts:214): Added optional verifyReceiptSignature?: ReceiptSignatureVerifier to CampaignSnapshotCommonOptions (symmetric with bundle.ts, still strictly fail-closed when neither secret nor callback is supplied), with tests in snapshot.test.ts.
  • T14 (packages/evolution/src/snapshot.ts:1029): Enforced bytes.byteLength <= MAX_SNAPSHOT_MEMBER_BYTES in writeCampaignSnapshot's pushText so export cannot emit oversized members its own verifier rejects.
  • T15 (packages/evolution/src/snapshot.ts:1661): Cleaned up claimed files via removeImportedFilesInExistingDir(stateDir) unconditionally on populateImportedStore failure after the O_EXCL ownership claim + post-claim empty check succeeded, with regression test.
  • T17 (packages/evolution/src/store.ts:2175): Asserted campaign.name === manifest.metadata.name in importCampaignState so exported campaign names and manifest metadata cannot silently diverge, with regression test.
  • Summary-routed S2, S12, S14, S15, S16, S17, S18, S19: Threaded collectionLimit into yaml() in parser.ts; removed subsumed duplicate secret regexes in scrubber.ts; capped exec.env values at 16384 chars in registry.ts; rejected : in contextFiles/scopeWritable before colon-joining and added field paths to parseExecOutcomeUsage in exec-role.ts; ran assertCleanSecretText in peekReceiptStatus and PRINTABLE_ASCII_RE on manifest mediaType in snapshot.ts; replaced hardcoded 16_384 with SCRATCHPAD_MAX_BYTES in store.ts.

Not changed (false positives, intentional boundaries, and low-priority style nits)

  • T1 (packages/controller/src/acceptance.ts:494): False positive — LIMITS.requests (1024) is @loopwright/core's hard requestsSchema ceiling (packages/core/src/usage.ts:17), and mixed pi + exec plans are refused at admission (compile.ts:150).
  • T2 (packages/controller/src/config.ts:216): Intentional fail-closed registry-wide fit check at loadConfiguration per spec and verified by config-local-checks.test.ts.
  • T3 (packages/controller/src/controller.ts:2316): Intentional fail-closed holdLocalActivity() retention on CLEANUP_FAILED, matching local-check.ts:506 so another owner cannot acquire while cleanup is unresolved.
  • T4 (packages/controller/src/credentials.ts:163): Pre-existing streaming Buffer vs string scrubber boundary; left out of scope for this PR.
  • T8 (packages/controller/src/local-check.ts:580) & T10 (packages/controller/src/recovery.ts:220): False positive on proposed fix — POSIX PIDs do not exist prior to spawn(), and granting untrusted children write access to the controller's private 0o600 artifacts directory would violate the trust boundary. The sub-millisecond spawn-to-fsync window, fail-closed recovery, attempt-directory discard, and Pod-exit backstop are documented in the spec.
  • T12 (packages/controller/src/recovery.ts:460): Intentional fail-closed design per spec (controller.ts:2323 shortcut:): interrupted exec attempts without published role_post settle RECOVERY_REQUIRED without re-running or silently re-adopting.
  • T16 (packages/evolution/src/store.ts:2175): False positive — campaign.manifestDigest hashes raw YAML file bytes (see createCampaign at store.ts:1094 and snapshot.test.ts:280), not canonicalizeJson(manifest). Rejecting on canonicalizeJson mismatch would break every real campaign import.
  • Summary-routed S13 (packages/controller/src/compile.ts:132): False positive — Git trees cannot represent empty directories, so every directory in a baseline Git tree contains at least one tracked blob.
  • Summary-routed S1, S3–S11: Low-severity style/maintainability suggestions kept out of this fixup pass to avoid drive-by churn (S11's ?? slot.id fallback is intentionally tested by local-check.test.ts:236).

Verification

  • npm run build, npx tsc -p tsconfig.test.json --incremental false, npm run typecheck, npm run lint: 0 errors.
  • @loopwright/core, @loopwright/evolution --concurrency 1, focused @loopwright/controller (local-check*, exec-role*, exec-usage, recovery*, exec-profile, config-local-checks), and @loopwright/cli (evolve-snapshot): all green.
  • Landed as DCO-signed --fixup commits on top of the PR branch so incremental review stays intact.

Comment thread packages/core/src/scrubber.ts Resolved
…solation parity

Signed-off-by: thxCode <thxcode0824@gmail.com>
@thxCode

thxCode commented Dec 1, 2026

Copy link
Copy Markdown
Contributor Author

Address PR Review — Round 2 Summary

Triaged both Round 2 incremental OpenCodeReview findings (c027f83..4bf83cf, 1 inline thread + 1 summary-routed item). Zero upgrade compatibility risks.

Fixed

  • Inline thread (packages/core/src/scrubber.ts:65) & summary item (packages/core/src/scrubber.ts:64-65): Added TRAILING_GENERIC_SECRET_PATTERN to SecretScrubber.scrubTruncated so trailing partial generic token formats (gh[pousr]_, github_pat_, sk-ant-, sk-proj-, AKIA with >= 4 chars after prefix, and -----BEGIN ... PRIVATE KEY) cut mid-token at a capture boundary are redacted even when unregistered or cut below 8 total characters, while retaining MIN_FORM_LENGTH = 8 for opaque registered secrets to avoid false-positive redactions on short plain text. Added focused unit tests in packages/core/test/scrubber.test.ts.

Verification

  • npm run build, npx tsc -p tsconfig.test.json --incremental false, npm run typecheck, npm run lint: 0 errors.
  • @loopwright/core and packages/controller/test/exec-role.test.js: all passed.
  • Landed as a DCO-signed --fixup commit on top of the PR branch.

@thxCode
thxCode merged commit f6e1ec5 into main Dec 2, 2026
15 checks passed
@thxCode
thxCode deleted the spec/managed-controller-in-process-execution branch December 2, 2026 00:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant