# Saved configuration selection

This module implements runtime, resource, execution, storage, network-policy, keyed secret/listener and gateway-input selection stages, plus runtime binding preparation of PR3's saved-config resolver. Production capture and restore do not yet publish or activate this document. The host runtime can enforce deferred command requirements attached to a destination during reservation. The required saved-config extension remains unsupported until the complete consumer and capture paths are integrated in this PR.

`select_runtime_defaults` accepts validated portable runtime metadata, the existing sparse `SandboxSpecPatch`, structural clear selectors and trusted operation facts. It returns the surviving lower-priority saved overlay, unresolved binding consumers, unknown fields and full-resume script identity obligations. The explicit destination patch stays separate, so this stage cannot copy destination credentials or scripts into portable metadata.

Native collection replacement and merge are distinct. An empty merge preserves saved environment entries; an empty replacement removes the optional saved map. Per-key merge removes only the overridden source entries. The generated `replaces_*` patch accessors expose existing replacement intent without changing patch application or serialization. Config-file decoding retains its released merge behavior.

Clears are validated against the original source before any are applied. Repeating a key clear or combining it with a whole-map clear is order-independent. Missing keys and unavailable map contents produce a redacted error; clearing the whole optional field can discard unknown contents. Map keys containing dots remain literal keys.

Fresh disk boot discards optional defaults. Fresh full resume still retains captured init, hostname, script backing and clock evidence. This stage rejects a new initial command or init/hostname overrides during full resume. Script replacements retain the original evidence and return identity proof obligations, including empty whole-map replacement; they are never approved merely because this selector succeeds. No script is executed here.

The approved saved-snapshot rule clears saved CMD when an explicit entrypoint differs from the recorded literal entrypoint and no explicit CMD is supplied. An identical recorded literal entrypoint retains CMD; an unavailable or binding-backed entrypoint cannot prove equality, so an explicit replacement resets inherited CMD. Explicit CMD, including an empty vector, always wins. `reset_inherited_cmd` must also block older image CMD fallback during final assembly. Fresh mode already discards saved CMD, and existing image-only merging remains unchanged. The internal policy-choice switch has been removed; launch integration is still required.

Integration must still resolve bindings at their actual consumer's activation time, enforce mandatory destination/security policy, preserve captured resource compatibility, validate full-state script backing, and apply the original destination patch in its existing order. Saved generated hostnames require destination identity regeneration. Optional-field clears must be reconciled with image and legacy defaults during final assembly. These responsibilities are not fulfilled by returning a surviving overlay, and import/inspect success does not authorize execution.

## Resource and execution selection

`select_resource_defaults` reuses optional active allocations for disk boot and checks the combination of explicit values and retained saved maxima. It keeps unknown observations distinct. Full resume takes construction geometry separately from the already checked execution closure, accepts only the existing equal-geometry overrides and refuses resource clears or THP overrides. Full preparation checks the saved construction CPU count, memory allocation and their respective maxima against independent checkpoint geometry, including in fresh mode. Live allocations may differ after hotplug. Fresh mode cannot discard that geometry. Host CPU placement and source profile names never enter the required geometry patch. Complete document validation must precede selection, and final assembly must still validate destination defaults, host capabilities and managed limits.

`select_execution_defaults` handles user labels, ordered rlimit replacement and independent lifetime fields. Lifetime output distinguishes omitted defaults from unknown values, concrete zero and concrete unlimited (`Value(None)`). Clearing or overriding one duration leaves the other unchanged. The output contains no elapsed timers or ephemeral ownership. These settings affect new processes and new destination timers; full-resume processes retain their captured state.

Security admission takes destination baseline and mandatory minimum from trusted destination policy, never from the artifact. A saved weaker profile requires explicit destination intent, and explicit intent cannot bypass the mandatory minimum. Unknown disk-boot policy requires a choice, a clear or fresh mode. Full resume requires independently established captured security evidence, retains existing refusal of profile overrides, checks recorded/captured consistency and rejects incompatible destination policy even in fresh mode. The selector does not obtain that evidence or install enforcement itself; activation remains disabled until capture and all consumer paths supply and enforce the complete contract.

## Storage and IPC selection

`select_storage_inputs` matches native destination mounts by canonical guest path and socket routes by `(port, socket_type)`. It retains every other required source resource, including when the explicit list is empty or mode is fresh. A shared binding ID stays required until every corresponding mount/route consumer has a destination mapping. Destination host paths and endpoints remain separate from saved metadata, keep their original path-resolution policy, and are not opened or created by selection. Duplicate destination identities reject with value-safe errors; parent mounts precede children.

Authoritative owned backing is retained even when the saved mount section is omitted or unknown. It cannot be replaced by an explicit mount, and new disk-boot owned mounts are checked for collisions with captured and other new owned IDs. Legacy external guest paths remain requirements; an empty tmpfs or new owned volume does not satisfy missing external backing. Contradictory complete saved and legacy inventories reject. Missing/unknown metadata is never inferred to be a complete inventory from a partial destination mapping.

Full resume rejects new resources when the recorded inventory is complete, new backing provisioning, obvious filesystem/block conflicts, incompatible known disk format/filesystem, changed mount flags/ownership, and tmpfs geometry changes. Every successful full plan still requires authoritative physical identity and captured-topology validation. Named-volume kind, file/directory identity, open handles, unresolved filesystem probes and real socket compatibility cannot be proved from a path match. The full checker must inspect all captured resources even when the saved inventory is incomplete.

Saved metadata relaxation, host permission mirroring and root-symlink following produce field-specific approval requirements; they are not granted by the artifact. Explicit mappings retain their own input provenance and must still satisfy mandatory destination policy. Narrow existing missing-resource or filesystem-identity waivers belong to later operation admission and must not erase owned state or turn absent resources into new empty backing. The output is a plan with unresolved bindings/approvals, not an activation-ready configuration.

## Network policy selection

`select_network_policy_defaults` emits a native lower-priority policy patch for NIC intent, ordered rules, DNS protection/timeouts, TLS inspection/verification, connection caps, per-direction rate limits, NAT64 classification and denial responses. Explicit sparse inputs mask only the fields they supply; ordered rule, bypass, scoped-verification and prefix lists replace in full. False, zero and empty values are preserved. The source section validates before fresh mode or overrides can mask malformed records.

Known absence, builtin default and unavailable observation remain distinct from an omitted source field. `absent_fields` records concrete missing rate directions/messages that a native sparse patch cannot express; `defaulted_fields` preserves recorded builtin choices. `cleared_fields` records explicit structural clears. The policy assembler processes these operations before the explicit layer, rather than applying only `defaults` and accidentally reviving an inherited message or rate limit. Combined network assembly preserves those results alongside resource inputs; mandatory destination-policy enforcement remains a later gate.

The destination supplies its inspection baseline. Selected saved TLS/DNS/QUIC relaxations, bypass scopes, reduced intercepted ports and relaxed authority return individual approval obligations. Explicit destination values mask the corresponding saved obligation but still need mandatory-policy enforcement after full assembly; the absence of an obligation is not an authorization result. Debug output excludes saved policy/message values and destination endpoints.

Fresh disk boot discards these optional policy defaults. Full resume retains recorded NIC presence and rejects conflicting overrides or a presence clear; even matching or unknown values still require independently checked captured NIC, identity, trust and connection state. Ordinary host policy selection cannot establish that evidence, and fresh mode cannot waive it.

This stage neither fulfills nor drops DNS/proxy/CA/listener/secret bindings. The separate input selectors and binding-demand planner below feed resource preparation, destination enforcement and full-state checks. Its output contains no host resolver endpoints, source addresses, trust-file paths, credentials, secret entries, allocated guest identity, source profile names or certificate cache state. The complete feature remains disabled until these stages and every activation/exec path are integrated.

## Binding demand and supply gaps

`plan_binding_demand` combines selected typed consumers with a separately established captured-execution inventory. Cold init, script backing, gateway, trust, listener, mount and IPC uses require inputs before their selected activation; a new-command use is immediate for run and otherwise retained for future exec. Shared IDs keep the strongest timing and every consumer. Full resume does not replay init, but keeps its bindings for a later cold boot. Captured requirements remain immediate even when fresh mode or explicit command overrides removed the corresponding launch default. An unavailable captured inventory is not treated as a checked empty inventory.

`BindingDemandPlan::supply_gaps` checks destination value kinds and reports missing immediate, future-command and later-cold-boot inputs without storing any credential values. These sets can overlap: satisfying an immediate shared input does not erase the future requirement from the plan. Unknown input IDs, kind conflicts, malformed identifiers and oversized combined inventories fail with value-safe diagnostics; debug output prints counts only. The original typed inventory still needs complete-document validation, and pending next-start bindings must never be passed as selected active requirements.

This is planning/admission metadata, not an authorization to execute. Gateway consumers must come from the selected effective network configuration, never a blanket declaration that all recorded settings are active. Binding materialization, keyed network selection, physical identity checks, mandatory policy, coherent capture and persistent deferred enforcement still need integration. Every exec and later cold boot must re-evaluate its requirements against its actual explicit inputs. The required extension and production capture/launch/exec paths remain disabled until the entire contract is implemented.

## Keyed secret selection

`select_secret_inputs` matches already selected substitution requirements against explicit destination entries by the exact environment key. A new value for one key does not drop another key or its binding, including when both share one logical ID. Explicit empty collections do not erase selected requirements; optional clears/mode selection happen before this step, and independently established captured uses still join binding demand afterward. Combined duplicate placeholders reject, so replacing one key cannot accidentally redirect another surviving placeholder to a different secret.

Full resume rejects a changed known placeholder for an existing key and always retains a captured-state proof obligation. New explicit entries are destination policy/future-command defaults, never instructions to rewrite the environment of captured processes. Missing or unknown source metadata stays unknown even when explicit inputs exist. Recorded builtin policy, absent global passthrough and explicit empty policy are kept distinct for final assembly.

Selected destination `SecretEntry` values remain local inputs and are not serialized into portable metadata. The global-default patch contains no secret entries. Debug/errors omit credential values, source names and placeholders; saved TLS-identity relaxations produce field-specific approval obligations. An explicit relaxation still requires mandatory destination-policy admission. No host credential source is read, no gateway policy is installed, and no captured connection is authorized by selection alone. Binding materialization, listener/proxy/trust preparation, assembly, coherent capture and all activation/exec enforcement remain required before enabling the saved-config workflow.

## Listener and gateway input selection

`select_listener_inputs` preserves each logical listener/transport identity, including multiple listeners targeting one guest service. A logical destination binding supplies its host address/port without copying source-host ownership. Native port inputs match a remaining saved guest service/transport only when the match is unambiguous on both sides; ambiguous mappings require logical binding IDs. Binding one listener does not erase another, and supplying TCP alone does not satisfy UDP sharing its ID. Additional native listeners remain separate. Exact destination collisions use parsed IP identity; port-zero requests remain unallocated inputs. Actual bind admission, wildcard/dual-stack conflicts, host policy and captured connections still need checking.

`select_gateway_inputs` separates resource inputs from policy defaults. Explicit ordered DNS and CA lists replace the corresponding selected requirements, including empty lists, while policy-only patches leave those requirements intact. Shared CA bindings retain unsupplied scoped/guest-trust consumers. An explicit host-trust boolean cannot establish a particular recorded certificate's identity. Explicit proxy clear stays distinct from omission and cannot arise implicitly from missing credentials. Interception certificate/key inputs retain the engine's all-or-neither contract; auto-generation intent is a destination input, never proof of compatibility with captured trust.

Both selectors run without sockets, DNS resolution, filesystem reads or credential lookup. Paths and credential sources remain destination inputs with their existing resolution policy. Unknown and builtin defaults remain distinct; original metadata and cross-field binding kinds are checked before overrides can hide malformed requirements. Full resume always retains a separate compatibility obligation, and independently established captured uses must still join binding demand after selected defaults are replaced. None of these outputs authorizes guest activation or serializes destination secrets into snapshot metadata. Whole-destination input composition is described below. Materialization, coherent capture/retention, admission and every activation/exec consumer remain unfinished.

## Runtime input preparation

`prepare_runtime_inputs` resolves selected text bindings into transient, redacted consumer inputs. It preserves complete argv ordering, empty arguments and exact environment keys, with no shell expansion, host lookup or script wrapping. If a future-command binding is missing, the whole corresponding field stays deferred; it never returns a shortened argv or a partially populated environment as ready. Initial commands, cold-boot init and script backing require their selected inputs immediately. Full resume can retain init requirements for a later cold boot without replaying PID 1.

Inline scripts retain their validated exact bytes and mode. A destination input supplying an excluded script body must also provide explicit permission bits; preparation never assumes the ordinary startup writer's `0755` mode. Script bytes and mode remain separate from ordinary runtime script strings so later materialization can preserve them exactly. Full-resume overrides and empty script-map replacements still carry their captured-backing identity obligations. This internal input contract does not yet add a public CLI binding syntax.

Resolved destination text uses zeroizing buffers and is never converted into portable literal metadata. The retained configuration keeps its original binding references for later exec, cold boot and capture provenance. Debug output and errors omit values and binding IDs. Omitted, builtin-default, unknown, explicit-empty and unresolved states remain distinguishable. Expanded input budgets count each use of a shared binding, preventing small metadata from expanding into unbounded arguments, environment or scripts.

This pure preparation step performs no file writes or guest execution. The complete assembler must still enforce combined selected/captured demand, mandatory destination policy, generated hostname identity and full-state compatibility, and persist deferred requirements for every later consumer. Supplying an init/env value here cannot discharge a separate captured-process requirement. Last-active configuration retention and coherent capture remain prerequisites; the production writer, launch and exec paths remain disabled.

## Native runtime assembly

`prepare_runtime_configuration` composes runtime selection, binding preparation and native runtime/env/init assembly. The lower input must already contain the resolved destination/image defaults; do not run image-default merging again on its output. Structural clears suppress the named lower fallback before explicit inputs apply. Complete saved env/script maps replace their lower maps, followed by the existing native destination per-key merge or full replacement. A changed entrypoint uses explicit empty CMD to prevent the image CMD from returning; ordinary image-only merging remains unchanged.

The result keeps native command defaults private until `command_defaults()` verifies that all selected command fields are available. Unknown or deferred values cannot expose an apparently usable image fallback or incomplete environment. Future command overrides reselect and reprepare from retained references. `cold_boot_init()` independently checks init availability and returns its resolved path/args/env for cold boot only; full resume must not replay that init. Generated hostnames are cleared for disk boot and retained as evidence for full-state identity checking.

Exact script backing stays in a separate bytes/mode map; native runtime script strings remain empty so the ordinary 0755 writer cannot silently change recorded permissions. Explicit native script replacement retains its existing 0755 behavior, and full-resume replacement still carries captured-backing proof obligations. Prepared binding buffers remain zeroizing; copies converted to existing native configuration types follow those types' ordinary local secret handling. Neither assembled plans nor retained portable metadata serialize destination credentials, but this is not a claim that every native string is zeroized.

This completes runtime field composition only. It does not assemble the other policy/resource sections, install backing, enforce mandatory policy, persist deferred requirements, capture last-active state or activate a guest. The production workflow and required-extension support remain disabled until those remaining paths are complete.

## Native network policy assembly

`prepare_network_policy_configuration` composes known portable policy fields over resolved destination defaults, followed by the explicit policy patch. Recorded builtin defaults and concrete absence reset the corresponding lower fallback. Structural clears run before explicit values, so false, zero, empty lists/messages and independent rate directions retain their meanings. Omitted source fields leave lower defaults intact; unavailable source observations cannot masquerade as known destination policy.

The plan keeps its native policy private. `apply_policy_to` refuses unknown selected policy before changing any destination field, then updates policy only while preserving separately prepared DNS endpoints, CA/key paths, proxy inputs, listeners, interface identity and secret entries. Neither lower nor explicit resource/credential inputs are copied into the policy plan. Errors and Debug omit policy values and destination inputs.

Recorded builtin TLS defaults retain approval obligations when they weaken the destination baseline; a default marker is not authorization. Literal saved relaxations retain their existing obligations, and full resume retains independent captured-network compatibility checks even in fresh mode. Applying policy does not discharge those obligations or enforce mandatory destination constraints. This completes policy-field composition only; resource preparation, full assembly, coherent capture/retention and all activation/exec gates remain required before enabling the saved-config feature.

## Native resource and execution assembly

`prepare_resource_configuration` composes sparse destination/image defaults, selected saved resources and explicit inputs. An omitted maximum follows the final boot allocation, matching existing SDK behavior; a configured maximum remains a ceiling and the assembled allocation must fit it. A recorded builtin maximum or explicit maximum clear removes the lower ceiling. Unknown source observations cannot borrow a pending allocation from lower defaults, and `resources()` refuses until they are resolved. Full resume uses independently checked construction geometry, retains THP/guest-policy compatibility obligations and never imports source host placement or profile names.

`prepare_execution_configuration` composes user labels, process limits, guest security and fresh lifetime durations. Complete saved label maps suppress obsolete lower user labels; native explicit merges and replacements retain their established meanings. Destination identity labels and ephemeral ownership survive application unchanged. Reserved identity keys in source or explicit user labels are rejected even when fresh mode or overrides would hide them. Unknown execution defaults prevent any destination mutation. Process limits preserve ordering and full-width unlimited sentinels, and zero durations remain distinct from unlimited durations. This sets configuration only: limits apply through the existing cold-boot/new-process mechanisms, and full resume must not rewrite captured processes or reuse source elapsed timer counters.

These plans expose no portable serialization of destination inputs, and their diagnostics redact values. They complete resource and execution field composition, not runtime activation: destination capacity/policy admission, captured-state validation, binding/backing preparation, coherent last-active capture, and every launch/exec consumer remain required. The saved-config writer and required-extension support stay disabled until the complete workflow is implemented.

## Gateway binding preparation

`prepare_gateway_configuration` turns selected resolver, certificate, interception-identity and proxy bindings into destination-only native inputs. Ordered resolver and trust lists remain ordered. A certificate shared by upstream, scoped and guest trust consumers is supplied once but retained for each consumer. Explicit resource replacements and empty lists mask only their own requirements; builtin choices reset lower resource defaults. Unknown observations prevent application before any destination mutation, and every missing immediate input refuses preparation. Proxy protocol and credential shape must agree; missing credentials never select an unauthenticated fallback.

The plan retains logical source requirements and full-state compatibility obligations. It neither opens files nor resolves credential sources, and preserves path spellings for the existing destination path-resolution layer. Guest trust files remain a separate installation obligation; a host-trust boolean does not satisfy them. Native network validation, file/certificate loading, secret-source resolution, mandatory destination policy and authoritative full-resume identity checks must still run before activation. Debug/error output redacts values, resolved destination inputs are not serialized into portable metadata, and expanded shared bindings have a total size budget. The saved-config workflow remains disabled until coherent capture and every enforcement/consumer path are integrated.

## Substitution binding preparation

`prepare_secret_configuration` composes the complete selected placeholder inventory into native substitution entries. Each surviving saved binding requires destination material or a destination-owned credential source; keyed explicit overrides replace only their own entries. Shared binding values expand per consumer without changing each consumer's placeholder, allowed hosts, substitution locations, passthrough rules or violation policy. Explicit empty lists do not erase selected requirements. Recorded builtin inventory resets lower entries, and unknown inventory refuses before destination mutation.

Inline destination material is held in zeroizing values. Environment and store references remain unresolved for the existing destination resolver; preparation never reads the source host or copies credentials into the portable record. Missing/extra bindings, ambiguous value-plus-source inputs and excessive expanded credentials fail with redacted errors. Empty explicit material stays distinct from a missing source. Global policy preserves recorded absence and explicit empty-list semantics.

The immutable selection retains logical requirements, field-specific TLS identity approvals and independent full-resume placeholder/connection obligations. Preparation is not policy authorization or proof that a destination credential is available. Credential resolution, mandatory policy, captured-state checks, coherent capture/retention and every activation/exec consumer remain required; the saved-config writer and public activation stay disabled.

## Storage and IPC binding preparation

`prepare_storage_configuration` converts selected guest resources into native destination mount and socket inputs. Bind files/directories, existing named directory/disk volumes, external images and stream/datagram endpoints have distinct binding kinds. A logical binding can supply several consumers while each retains its own guest path, flags, quota and socket port. Explicit per-resource mappings replace only their own consumer; empty lists and fresh mode cannot discard other required backing.

Named bindings never imply creation, ensure-exists or resizing. Recorded capacities, quotas and backing kinds remain in the immutable selection for actual resource admission. Authoritative owned-volume configuration is reconstructed from the captured inventory, and its IDs remain explicit private-materialization obligations; these native owned entries must not provision empty replacement data. Legacy external mounts without a recorded logical binding still require explicit destination mappings.

Preparation preserves path spelling, including non-UTF-8 and symlink/parent components, without opening files, resolving source-host state or provisioning resources. Missing, extra or wrong-kind bindings fail with redacted diagnostics; shared input expansion is bounded. Unknown inventory cannot partially replace destination mounts or routes. Destination inputs remain outside portable metadata, and supplying a path never grants a saved relaxation or proves full-resume identity.

This completes native storage-reference preparation, not backing restoration or whole-config activation. The shared destination path resolver, physical resource checks, mandatory policy and individual approvals, private owned-payload materialization, captured mount/socket identity checks and every activation consumer remain required. The saved-config writer and required-extension activation remain disabled.

`prepare_listener_configuration` similarly turns complete listener selection into native port inputs. Every surviving selected listener must have a destination; an explicit mapping for one shared consumer cannot discard another transport/service. Known builtin/empty inventories replace lower ports, whereas unknown or unrecorded inventories cannot mutate destination networking. Ephemeral port zero and independent TCP/UDP listeners retain their native meanings. Socket allocation, mandatory destination policy and full-resume NIC/connection checks remain required; preparation opens no listener and does not authorize traffic.

## Combined configuration preparation

`prepare_saved_configuration` coordinates the family preparers against one validated immutable document, descriptor, destination patch and restore context. It validates original metadata and legacy projections before fresh mode, clears or explicit overrides can mask them. Only selected active fields contribute default demand; pending fields remain validated but cannot supply defaults or add activation requirements. Full resume additionally requires independently established geometry, guest policy and captured binding inventory, which optional selection cannot discard.

The destination supplies one typed binding registry. A text binding shared by future command defaults and host substitution has one value, while replacing only the command field preserves the substitution requirement. Logical listener inputs participate before matching explicit native listeners, so they can disambiguate repeated guest service identities. The registry is bounded before copying shared material, rejects unused or incompatible inputs, and retains captured-only inputs for subsequent physical identity checks.

An unresolved environment/store credential source can prepare a host substitution reference but is never ready command text. Future command/init requirements remain explicit gaps; an immediate command/init/script consumer refuses until its text is resolved. Empty supply gaps establish only logical input coverage, not credential resolution, backing identity or permission to activate. The returned plans retain each family's unknown, approval, materialization and full-state obligations, and no partial result escapes a preparation failure.

The network and whole-destination input assemblers below build on this combined preparation without enabling the feature. Effective-consumer admission, file/credential loading, policy and identity enforcement, persistent deferred defaults, coherent last-active capture and every launch/exec integration remain required. The writer and activation path stay disabled.

## Combined native network inputs

`SavedConfigurationPlan::network_inputs()` combines the prepared policy, gateway references, listener inventory and secret substitution inputs into one native network value. It validates every family before returning anything; unknown policy/resource/secret/listener observations cannot produce an apparently complete partial configuration. Resolved destination interface defaults and sparse explicit overrides remain inputs to the later allocator and captured-identity checker, never portable source identity.

Native optional containers retain their meaning: in saved mode, a recorded builtin DNS/TLS/secret section produces an absent container unless an explicit destination section is supplied; a recorded concrete section or explicit empty section remains present. Fresh mode keeps the presence of destination DNS/TLS policy defaults, even when the artifact recorded a builtin choice. Policy fields and resource siblings are composed together before restoring this presence, so resolver/CA/proxy inputs cannot erase policy and policy defaults cannot erase supplied resources. Guest trust certificates remain separately available through the gateway plan because `NetworkSpec` has no guest-certificate-file field.

Composition performs no file loading, credential lookup, DNS resolution, socket allocation or activation. It retains the original approval, full-state and binding obligations in the immutable plan; an unresolved substitution source does not make a future command binding ready. Its returned value is input to destination admission and must never be exported as the portable saved document. The whole-destination assembler below retains those obligations. Materialization, policy/full-state/deferred enforcement, capture/retention and all public launch/exec consumers remain required before enabling the saved-config writer and required extension.

## Whole-destination inputs

`SavedConfigurationPlan::into_destination_inputs()` composes runtime, resources, execution metadata, network and storage/IPC inputs into `SavedDestinationInputs`. It owns both the native inputs and the same immutable preparation plan. It has no serialization or consuming conversion into a bare `SandboxSpec`; consumers must retain the plan through materialization, admission and persistence. The read-only `spec_inputs()` view is not proof that all future defaults are ready and must not be passed directly to launch.

Destination-only fields (name, root source, requested patches, pull/deployment policy, ephemeral ownership and reserved identity labels) are pinned from the original destination inputs. Saved metadata does not supply them. The assembler does not reapply the whole raw patch afterward, which could revive removed CMD, discard bound resource inventories or route exact scripts through the ordinary writer. Root/dependency compatibility, patch eligibility and all existing destination validation still need enforcement before side effects.

Unknown immediate inputs refuse before any candidate escapes. Hostname, clock and script backing are checked for the current activation. A new initial command also requires complete command defaults; cold boot requires init inputs. Full resume keeps its captured PID 1 and never places a cold-boot init request in native activation inputs. Future command/init requirements remain on the owned plan when they are not needed now; an empty native field does not resolve a missing binding or unknown observation. Each later command/boot must use the plan's availability checks and retained references. Exact script bytes and modes remain separate from ordinary runtime script strings.

Composition grants no approval, opens no files or sockets, resolves no credentials and admits no captured backing. Full-state, mandatory policy, saved relaxation, host-resource and deferred requirements all survive unchanged. Coherent capture/retention, actual backing materialization, mandatory enforcement, durable deferred requirements and every public launch/exec path remain required; portable capture and activation stay disabled.

## Local registered-script backing

On Unix, `capture_runtime_scripts` observes registered files below an already pinned runtime directory with the portable schema’s limits. It delegates to the filesystem crate’s `CapturedRuntimeScripts`, which is reusable by the runtime inside its checkpoint pause without introducing a runtime-to-SDK dependency. It holds inode references and reads exact bounded UTF-8 bytes plus guest-visible ownership and permissions using the filesystem backend's strict metadata overlays. Host `stat` permissions alone are insufficient: a guest can have mode `0000` while the host retains owner access. Script and runtime directory metadata are retained too. Symlinked files/directories, special files, incompatible virtual types, privileged mode bits and oversized inputs refuse; diagnostics omit names, paths and content.

The caller must hold the coherent source mutation/capture guard. Revalidation checks directory identity and metadata, file identity, content, timestamps and guest metadata, but cannot create atomicity across concurrent writers by itself. These observations are not serializable and are not the portable document: capture exclusions/binding substitution, source generation and full-state closure checks still apply. Unregistered runtime files and arbitrary captured open handles are not covered.

`stage_exact` writes a separate temporary runtime directory beneath a caller-owned private staging parent, with no replacement of an existing runtime. It preserves exact bytes and guest metadata, verifies them, and revalidates the source before returning. Host permissions remain private independently of guest modes. Relative staging parents are pinned to the call-time directory without collapsing symlink/parent components. Dropping the returned directory cleans it up even after cwd changes; late failure or observed source change discards the staged files. Nothing is executed or installed. This is local capture/staging infrastructure, not archive restoration, source-deleted support, or launch integration. Windows metadata support, portable backing evidence, capture sanitization, runtime ownership transfer, full-state admission and durable consumer integration remain required; feature activation stays disabled.

`RuntimeConfigurationPlan::stage_disk_scripts` materializes selected portable or destination-bound bytes without a surviving source directory. It writes exact UTF-8 content and selected guest modes, with root ownership for newly created guest files and directories, while host permissions remain private. Names, duplicates, count/byte limits and privileged mode bits are checked before filesystem effects; verification reopens the staged filenames and checks their bytes, metadata and directory identity. Input failure, staging failure or an observed change discards the complete temporary directory. Relative staging parents retain call-time symlink/parent semantics through cleanup.

This is cold-boot preparation, not a full-resume backing repair or an activation permit. Full-resume plans refuse even when their selected script inventory is empty or matches recorded content. Unavailable inputs refuse, destination bindings remain separate from the portable record, and ordinary script wrapping is not rerun. Adopting the staged directory into runtime ownership, coherent capture, complete destination admission, full-state handle identity, Windows support and public launch integration remain required before feature activation.

## Live-source selection under runtime ownership

The runtime's `RetentionJournal::select_live_configuration` borrows a confirmed source from the in-process journal and checks it against one catalog query for the latest run, owning PID, sandbox/run identities, live status and active configuration. It retains the original database connection and catalog pathname identity; revalidation also checks the durable journal generation, owner and source. Missing legacy evidence and interrupted transitions remain unknown. Desired next-start configuration is selected separately from the same catalog statement, never used as active fallback; malformed-document diagnostics do not expose content.

The full/disk checkpoint coordinator now selects this evidence after VM pause while retaining executor mutation authority and revalidates it before publication. Opt-in capture writes a bounded private receipt under the source sandbox's `last-active/captures`, bound to the checkpoint identity and full root or disk-generation fingerprint, and returns only a digest. The client must independently select the source sandbox and verify the immutable capture before reading its receipt. Catalog disagreement or missing evidence stays unknown; direct catalog writers are not blocked and an edit that was subsequently undone is not detected. A receipt preserves the runtime-confirmed configuration, not guest resource-convergence evidence.

Rust and TypeScript checked control clients probe the actual peer before dispatch; JSON uses independently verified runtime identity and fresh capability discovery. Omitted options retain existing capture behavior. Private receipt files are outside the portable checkpoint tree and never substitute for the sanitization rules above. Live SDK receipt consumption is described below. Active/pending portable projection, source-aware metadata/secret handoffs, script/backing capture and all materialization/enforcement consumers remain required. Portable saved-config emission and activation stay disabled.

## SDK checkpoint receipt consumption

The live snapshot capture path now requests a private receipt when the selected runtime advertises `configuration_capture`. Before dispatch it records independent catalog file, sandbox incarnation and run identity from the verified control session. After validating the immutable full closure or sealed disk generation, it verifies the receipt digest, capture identity/root and source owner before decoding local `SandboxConfig`. Parse diagnostics never include raw values. A later configuration generation cannot invalidate earlier immutable capture evidence.

Confirmed source values supply the existing user, clock and mount metadata projections for installed and archive-only captures. This is not the portable config writer: no raw retained source enters an archive, and no saved security or host binding becomes destination authority. Older runtimes receive the original requests and do not acquire retention dependencies. Unknown evidence currently preserves legacy metadata behavior; it is not a confirmed active-config fallback and must be represented explicitly when the complete portable projection is enabled. Production integration of active/pending sanitization, script backing, destination admission and deferred-exec enforcement remain required before the feature is complete.

## Stopped-source consumption

Stopped disk capture now selects the runtime retention module's confirmed last-active source under lifecycle ownership, uses its mount inventory for the cut, and revalidates owner, generation and source after copying. The worker retains ownership even if its caller cancels. Pending desired edits remain separate; a later run, contradictory catalog evidence or changed terminal receipt prevents stale publication. Missing legacy evidence remains unknown without writing retention files; malformed records produce value-safe errors.

Both installed and archive-only paths use the selected source for their existing user/mount projections, after checking source image/root agreement. This is not full portable configuration capture: raw retained values stay private, historical unknowns still follow legacy metadata behavior, and production integration of active/pending projection, sanitization, bindings, script backing and complete launch/exec enforcement remains unfinished. Portable emission and activation remain disabled.

## Reproducing live init evidence

`scripts/smoke/cli/saved-init-evidence.py` exercises builtin, explicit-path and auto init with a current agent, including resource modification, stop/start, stopped disk capture and restart through a released CLI. Pass `--binary`, `--old`, `--agent`, `--firmware`, `--image` (an existing Alpine image archive), `--output` (a new directory) and `--temp-root`. It does not pull an image. Candidate Mac binaries must already be signed with the VM entitlement. The fixture deliberately force-stops the init cases rather than treating the test init as a graceful-shutdown service.

The output keeps the original failure and cleanup evidence plus owner-only `*-source.json` records read from the actual stopped journal. These are not runtime capture receipts. Set `MSB_RUNTIME_INIT_CAPTURE_FIXTURES` to that output and run `cargo test -p microsandbox --lib runtime_capture_live_init_records -- --ignored --nocapture`. The regression checks both the guest-observed executable and retained auto/path intent, including the existing auto-init inheritance of image PATH. Separate older-agent receipt fixtures exercise unknown-init handling. Neither test claims that portable saved-config emission or restore activation is enabled.

## Captured resource and execution sections

The guarded `RuntimeCaptureSource` can project resource and execution sections from the same retained raw configuration. `project_resources` takes `ResourceCaptureObservation`, whose fields reuse `SavedValue`: only positively observed capacity or an explicit unknown reason is accepted. Requested, image, platform and default values cannot be presented as effective capacity. Converging remains distinct from unavailable observation. The caller must still obtain fresh observations under the capture guard; this helper neither queries the guest nor proves freshness. Static maxima and THP require recorded field presence, and host CPU placement/profile names are excluded.

`project_execution` preserves recorded guest security, ordered sandbox-wide rlimits, zero/unlimited durations and ordinary user labels. It drops reserved system labels and ephemeral ownership; it does not copy elapsed counters or per-invocation limits. `ExecutionCaptureControls` can omit all labels or exact keys before their portable values are cloned and validated. Invalid, overlapping or unmatched selectors fail without echoing keys or values. A partial historical lifetime record remains unknown rather than inventing an unlimited missing duration. These are source projection stages, not destination security approval or runtime activation.

Current raw serialization omits some default-valued/absent fields. Absence remains unknown unless matching private field-presence evidence establishes the specific setting, as described below. Production capture orchestration, pending-source projection, binding/exclusion controls for other families, full-state backing and immediate/deferred destination enforcement are still required before saved-config emission or activation.


## Network source projection

`RuntimeCaptureSource::project_network` projects network policy from the same guarded retained source, preserving rule/listener/resolver order, explicit zero and false, configured rate parameters and recorded default selection. It excludes source interface allocation, host listener ownership, resolver/proxy endpoints, proxy authentication material, CA paths/keys and secret values/source references. `NetworkCaptureBindings` supplies logical destination requirements; missing, extra or unused bindings fail with value-safe errors. Enabled interception still needs an identity requirement when its CA was generated. Host-trust requirements need an independently established backing inventory; the source boolean cannot identify certificate contents.

Raw field presence is checked inside DNS, TLS, secret, HTTP, policy, rate and proxy sections before typed defaults become portable values. Absent or incomplete sections remain `Unknown(NotRecorded)`; explicit recorded null is distinct and retains default intent. Existing TCP-count and TLS aliases remain accepted. Matching private presence evidence can establish known absent top-level sections; it cannot certify missing descendants of present objects. `NetworkCaptureControls::omit_http` removes the complete optional response default before cloning or validating custom text. Other public capture exclusions and production capture orchestration remain separate work.

These helpers neither authorize a destination security relaxation nor prove guest identity, trust backing, observation freshness or full-resume compatibility. They do not read host files, resolve secrets or dispatch network operations. Existing destination selection/approval and backing checks still apply. Portable emission and activation remain disabled.


## Storage source projection

`RuntimeCaptureSource::project_storage` projects complete recorded mount and vsock inventories under the source guard. External mount evidence is keyed by canonical guest path; bind root kind and named-volume backing must be independently observed. Named-volume creation intent never establishes active storage kind or capacity. Host paths, source-local volume names and socket/pipe endpoints are replaced with logical destination requirements without opening or resolving them. Guest mount flags, quotas, formats and socket semantics remain explicit.

Owned mounts refer to the captured descriptor's authoritative owned-volume inventory; capture validates exact reference membership and never substitutes fresh external backing. Portable mounts are sorted into canonical parent-before-child order without modifying the retained source or normalizing host paths. Duplicate guest/socket identities, reserved socket ports, missing/extra/wrong-kind bindings and incompatible cross-kind binding reuse fail with value-safe errors.

A missing or partially recorded mount list stays unknown as a whole, preserving the distinction from an explicitly empty list. Missing nested mount options and missing socket types cannot become today's defaults. Current serializers omit unset UID/GID overrides; absent evidence therefore remains unknown, as with other optional source fields. An unknown projection does not erase authoritative owned backing. Production capture orchestration and destination/full-state backing admission remain required; this helper does not enable portable emission or activation.


## Capture document assembly

`RuntimeCaptureSource::project_document` composes every active section from the same raw source adapter, with caller-supplied resource/backing observations from that capture cut. `PendingCaptureSource::from_recorded` accepts the independently selected next-start raw record and its logical network/storage bindings, without active init or script observations. The assembler classifies all pending sections itself and applies runtime controls across both sources, derives one exact binding inventory from the resulting references, and rejects incompatible sharing across runtime/network/storage or active/pending sections. Pending targets and pending-only requirements never supply active defaults or activation demand. Aggregate bounds, observed active capacity/generation, legacy user/clock consistency and captured owned-volume membership are checked before returning the document. Full-state omission protection is selected from the descriptor scope, not a separate caller boolean.

`CapturedSandboxConfiguration::project_document` invokes that assembler using its retained immutable raw source, init/script observations and confirmed generation. It does not reread mutable catalog intent or current retention files. This method is deliberately unused by production writers while publication/activation remain gated. Callers must still supply the matching descriptor, coherent resource/trust/backing observations and a pending source selected under that same guard. Pending resources remain configured targets, scripts/init remain declarations, and requested owned storage never borrows active payload IDs. Label selectors are validated against the union of recorded active/pending keys and then applied only where present; a pending-only match is valid, while unmatched, reserved or overlapping selectors fail without echoing keys. Whole-label and HTTP-response omission apply to both sources before portable literal validation. Logical bindings are checked against their own source and unified only after projection, so pending requirements cannot become active demand.

Producer version is generated by the SDK. Source-name provenance is opt-in and is independent of the captured guest hostname: omitting that provenance field is not a blanket identity-redaction control. Runtime hostname exclusions retain their disk/full rules. No new extension is emitted or advertised, no catalog/launch contract changes, and no destination materialization or activation is enabled. Public controls, production capture orchestration, full-state closure and immediate/deferred enforcement remain required.

## Source-derived network requirements

The retained capture adapter derives network binding references from its immutable active record and separately selected pending record. Generated IDs contain only a fixed active/pending namespace, field name and ordinal; they contain no source endpoint, credential, host environment name, path or digest of those values. Ordered resolvers, listeners and CA requirements preserve their recorded order. Empty configured proxy credentials still require authentication bindings, and enabled TLS interception requires an identity even when the source generated its CA automatically. Duplicate source secret keys and oversized inventories refuse with value-safe errors.

Incomplete historical sections generate no requirements and remain unknown during projection. The helper does not establish guest trust from `trust_host_cas`: callers must supply independently established trust requirements, and projection still rejects a missing or inconsistent inventory. Active and pending requirements use separate identifiers, preventing a pending endpoint from being substituted for captured active policy. This completes source-to-requirement assembly, not resource identity proof or authorization. Production portable emission, destination admission and activation remain gated.

## Pending runtime and resource intent

`RuntimeCaptureSource::pending_input` classifies the recorded next-start init and script declarations without using guest init observations or materialized script bytes. `requested_handoff` records `auto` or the configured guest path plus supplemental arguments/environment; a script `declaration` records desired content without claiming a mode or backing digest. Both require configured origin. Missing raw fields remain unknown, explicit null init is a known default, and an explicit empty script map remains empty. The same private environment/CMD provenance checks prevent host-derived values and detached invocation from becoming portable defaults. Runtime exclusions and bindings apply before declaration bytes enter the portable document.

`project_pending_resources` records present CPU/memory targets as configured values while active capture still requires independent observed capacity. Pending intent never supplies missing active values. Document validation and both runtime selection/preparation entry points reject pending-only init/script forms as active input, including when fresh mode, clears or explicit replacements would otherwise discard them. Declaration payloads share the active/pending script budget and binding inventory. These are internal capture stages; production orchestration and portable emission/activation remain unfinished.

## Pending storage intent

`project_pending_storage` retains complete recorded next-start mount and socket requirements without borrowing the active descriptor's owned payload IDs. Requested owned directory/disk storage uses `requested_owned`, preserving capacity/quota and guest policy with configured origin. It is a declaration, not a promise that backing exists or was captured. External mounts and routes still require independently classified logical bindings; source paths, volume names and transient named-volume provisioning are excluded.

Document validation and active storage selection reject requested-owned declarations before saved/fresh mode or explicit replacements can discard them. Pending references contribute to the document binding inventory but never active restore demand. Incomplete optional-policy evidence keeps the whole mount inventory unknown; a missing required storage kind remains a malformed-record error. Current serializers can omit default mount UID/GID fields. Matching private presence evidence can establish that both overrides were absent; historical omissions without that evidence remain unknown. No filesystem lookup, provisioning, payload publication or activation is performed by this projector.

## Private default-presence evidence

Fresh configurations retain an optional host-private `field_presence` hint for declared THP, known absent network sections and mount ownership defaults. Mount entries contain only kind and canonical guest path; they certify that both UID/GID overrides are absent, not backing identity, effective ownership or host policy. No source host path, volume name or credential is copied into the hint. An explicit mount addition certifies only that addition; reconstruction does not certify older siblings.

Decode and persistence discard evidence that no longer matches the associated value. Missing parent objects, changed mount kind/path/ownership, unknown hint forms and historical omissions remain unknown. The raw mount options object and its other policy fields must still be recorded. Older writers may drop the optional hint; new readers do not recreate it during restart. Active capture additionally requires the existing exact-source and runtime-generation guards, so a legacy rewrite cannot make stale retained evidence authoritative. This changes no catalog schema, required launch field or existing runtime operation. Portable saved-config publication/activation remains gated.

## Pending selection at capture

For captures with confirmed last-active evidence, the live runtime selects raw next-start configuration alongside active catalog/run validation and seals it into the private capture receipt. Stopped capture retains next-start intent before the disk cut while holding lifecycle ownership. Both paths keep that exact value after later desired-only edits. Active provenance is independently revalidated; desired settings never become active evidence.

The retained capture object builds pending projection input from its own selected document. Assembly rejects omitted or substituted input when pending evidence was recorded, and rejects invented input when an older receipt omitted it. Missing legacy evidence remains unknown. These records remain host-private, use redacted errors, and are not copied into archives. Production resource/backing acquisition, full-state closure and all destination consumers still gate portable emission.

## Full-capture script metadata and offline staging

The draft portable `active.script_backing` section retains observed guest UID/GID/mode for the runtime and scripts directories and every registered script. It must match the sanitized observed inventory and inline modes. Pending intent cannot contain this evidence; missing historical evidence stays unknown. Full capture projects it from the existing private receipt, while disk capture keeps fresh-boot directory ownership separate. Binding an excluded body does not retain its digest in this metadata.

`SavedConfigurationPlan::stage_full_scripts` stages exact selected inline content and captured guest metadata after source deletion. It checks the original inline digests and modes before filesystem effects; changed, bound or unknown identity refuses. The filesystem primitive retains inode pins while verifying file bytes, guest metadata and directory identity, with whole-directory cleanup on failure. Existing `stage_disk_scripts` remains a separate root-owned cold-boot operation.

The returned temporary directory grants no resume permission. Captured filesystem state must still admit every handle and unregistered runtime resource, with complete destination policy and ownership transfer before launch. The tests prove one registered open-handle reconstruction and refusal of unaccounted backing; they are not a complete runtime-share or VM-resume qualification. Production emission, full-state closure, binding-backed identity proof and activation integration remain unfinished.

## Pending selectors and init provenance

A pending script-key match cannot authorize full-state omission when active script backing is unknown/default. Known absence permits pending-only sanitation, while disk capture keeps its separate omission rules. This check runs before copying or hashing source content.

Pending init records the original `auto` choice from validated private provenance, even after image resolution has replaced the configured command with a concrete path. Explicit-path provenance retains that path; a non-null historical init without provenance stays unknown because the resolved spelling alone cannot identify the original choice. Explicit null remains a known no-handoff default. Neither pending intent nor these preparation fixes changes existing boot behavior or supplies active observation.

## Linked runtime scripts

Registered script evidence refuses backing whose host link count is not one. The portable representation recreates independent files and cannot preserve hard-link aliases, including aliases outside the scripts directory. Initial observation and later revalidation keep those cases unknown; existing snapshot operations still succeed with unavailable optional backing evidence. Exact staging also rejects an alias introduced before its final verification and removes the temporary output. No receipt fields, catalog schemas, runtime capabilities or released capture interfaces change.

This checks registered-file relationships only. Unregistered runtime files and cached filesystem handles still need full-state closure validation; a successful script observation is not permission to resume a VM.

## Deferred command bindings

When a whole saved command field is explicitly unknown, destination preparation requires the caller to replace or clear it before launch. This applies to the environment, entrypoint, CMD, user, shell and working directory. A partial environment merge cannot establish the missing map. Fresh disk settings discard optional source defaults. An older snapshot with no portable configuration continues through its historical restore path.

A restore that launches no new command can prepare a destination with unresolved command bindings. The plan keeps the logical binding for each affected environment key and for the saved entrypoint and CMD. Resolved sibling environment keys remain available. An immediate command still requires its inputs during preparation.

The local reservation transaction saves these references beside the sandbox record. Each runtime loads them in the transaction that inserts its run record, before guest activation. An older runtime attempting to insert a run for that destination receives an upgrade error. Deleting the destination deletes the references. Catalog readers and unrelated sandbox starts work with the same database.

The host relay checks foreground, streaming and attached commands before forwarding an exec to the guest. The detached-job manager checks the same requirements before recording a job. A capable SDK sends explicit environment keys and command origin on the negotiated path. Picking a saved default supplies no evidence of an argv override. Older SDKs can connect and stop or restart the sandbox on a capable runtime. A command that needs unresolved bindings receives a pre-start error. A per-command override applies only to that invocation.

The capture and restore activation paths still need to connect validated portable configuration to reservation. The cross-platform smoke test in `scripts/smoke/cli/deferred-command-bindings.py` restores a real disk, then seeds only the private requirements row. It checks that refused foreground and detached commands leave no guest file or registered job, an explicit override admits one invocation, and the guard survives restart.

The active storage projection uses the captured runtime’s guest mount paths, backing kinds and byte quotas. It retains file and directory bind kinds and distinguishes unlimited, zero and positive quotas for named directories. A partial or contradictory observation makes the entire mount inventory unknown. Socket requirements and descriptor-owned volumes are checked independently. Explicit mount selections must agree with the observed backing. A separately negotiated live receipt can record a named disk’s virtual capacity in bytes. The runtime reads the admitted virtio device at the checkpoint pause and records only its guest mount path and capacity. Stopped captures and older storage-only receipts have no block observation. Non-integral or out-of-range MiB capacities remain unknown in the portable representation.

Pending disk-image declarations can identify a destination binding by the guest mount’s position. If the next start requests a bind of unknown kind or a named volume of unknown backing, its entire pending mount list stays unknown. Independently recorded socket routes keep their own bindings.

A bind mount that inherited its source host's default budget records the observed active quota in MiB. A pending declaration with an omitted quota retains that omission. An unlimited, unobserved or unrepresentable active bind quota makes the mount inventory unknown.

## Restored execution limits

A full restore with nondefault guest execution limits installs those five limits on the new sandbox. The destination runtime reads the policy on every start and requires the guest to confirm it before accepting commands. An older CLI can start that destination using a capable runtime. An older runtime receives an upgrade error on start. Ordinary sandboxes and restored sandboxes with built-in limits can still start on otherwise compatible runtimes. Removing the destination removes its policy.

## Capacity at checkpoint capture

A runtime and client can negotiate CPU and memory evidence for their private capture receipt. A guest advertising freeze-time observation samples the CPU and memory drivers while the workload is frozen. The host matches the reply to that freeze request and compares each sample with the corresponding VM device while the VM is paused. CPU requires agreement on the exact online and enforced count. Memory requires the same address range and agreement on plugged, requested and onlined capacity. The recorded MiB value includes boot memory. CPU and memory can converge independently.

An ordinary pause, a stopped capture, a capture without a guest flush or an older peer can leave this evidence absent. An optional guest read has a 100 ms budget with at most one outstanding worker. A late read cannot supply evidence for another cut. Missing evidence stays unknown and the normal checkpoint operation can complete.
