Skip to content

ADR-0008: Runtime and environment preparation

Status: Accepted — 2026-09-23. The project owner approved this decision. Acceptance establishes the architectural contract; it does not establish a completed implementation or successful execution of outstanding checks.

English | Русский

Refinement — 2026-09-24: ADR-0013 uses the same lazy preparation for CLI and MCP calls; listing tools never prepares a runtime. ADR-0014 applies bounded authority/accounting to preparation, and ADR-0015 separately checks whether the resulting environment can be used under required execution restrictions. The provider remains a trusted registered integration, not an installer supplied by an extension.

Extensions can require different runtime implementations and versions. A branded CLI must connect its own runtime manager without making extension authors depend on that manager. Downloading a language runtime, preparing dependencies and starting a command are separate responsibilities; confusing them causes hidden installation, global version changes and unreliable cleanup.

This ADR defines the RuntimeProvider boundary separated from the executor by ADR-0001. It consumes ADR-0006 requirements and the pinned release from ADR-0007; both are accepted. Invocation order, contextual help and final outcomes retain ADR-0002/0004 rules.

  • Authors request a runtime; the CLI owner chooses how it is supplied.
  • Prepare only when execution requires it and policy allows it.
  • Different extension versions coexist without changing the user’s global environment.
  • Record exact choices and limitations instead of assuming every manager gives identical guarantees.
OptionBenefitLimitation
Use whatever executable is on PATHMinimal setupUndeclared version/implementation and machine-dependent dispatch
Let each extension install its own environmentAuthor flexibilityPublisher code controls installation and can alter shared state
Require one runtime managerFewer integrationsExcludes existing company tooling and platform requirements
Trusted provider contract with exact resolutionReplaceable management and consistent execution boundaryEach adapter must declare and verify its real guarantees

The core resolves an extension’s runtime requirement against the owner’s catalog, obtains an explicit preparation plan from a trusted provider, and uses only a verified environment result. Lazy preparation is a core capability, not an installer supplied by the extension or a promise to download anything requested.

The simple configuration from ADR-0009 can use native extensions or an approved preinstalled-runtime provider. Installing a runtime manager is optional; automatic preparation is required only when a selected extension needs an absent environment and the owner enables that facility. Adding manager integration preserves the same requirement/result contract.

ElementMeaning
Extension requirementFamily, implementation, explicit version scheme and constraint, target/ABI requirements and declared dependency inputs
Owner runtime catalogApproved implementations, version policy, platforms, provider bindings and required integrity/reproduction guarantees
Provider registrationTrusted implementation/version, supported operations, manager/backend identity and controlled configuration
ResolutionExact selected runtime/build/target and dependency inputs; no mutable latest alias in the executable result
Local environment recordVerified paths, restricted environment additions, ownership and reference state for that machine

The owner registers a built-in provider or a trusted library adapter when assembling the CLI. An adapter can use mise, proto, asdf, nvm, Homebrew, an internal service or preinstalled runtimes. These are integration options, not mandatory dependencies or a claim of equal platform support. Adding an approved configuration for an existing adapter need not require rebuilding the CLI; new adapter code does. An extension cannot register a manager plugin or nominate an arbitrary installer.

Resolution intersects extension requirements, owner policy, target compatibility and provider support. A family does not imply an implementation: CPython and another Python implementation, or Lua and LuaJIT, are not silently interchangeable. Version comparison uses its declared scheme, not lexical order or a universal SemVer assumption; Python has its own specified version rules. Python version specifiers.

The core chooses one provider under explicit owner policy and pins it with the plan. No matching combination means the requirement is unsupported; a supported but uninstalled runtime can be prepared. Ambiguous provider/target selection fails or follows an explicit owner priority, never installation order. An unavailable selected build does not authorize switching versions or bootstrapping a different manager.

The selected rukh.runtime/1 profile uses the following comparisons. A requirement names its scheme explicitly; an adapter cannot reinterpret it using its manager’s default. Published package versions and runtime versions are distinct. The selected implementation and target must match before comparing versions.

SchemeAccepted constraint and comparison
semverComplete SemVer 2.0 versions; either one exact version or explicit lower/upper bounds with inclusive flags. No npm-style shorthand. Pre-releases require an explicit allowPrerelease; build metadata does not order versions but remains part of exact build identity
pep440A comma-separated intersection of Python specifiers using ==, !=, <, <=, >, >=, ~= with the normalization and comparison rules of the Python specification; === is excluded. Pre-release admission is explicit; no implicit “only pre-releases available” fallback
numeric-tripletExactly three nonnegative decimal components, each at most 2^31-1; numeric tuple order and explicit bounds or exact match. No suffixes, leading zeroes or inferred missing components
opaqueExact case-sensitive version/build identifier only; no ranges, ordering or inferred compatibility

SemVer follows its defined precedence; Python follows its version specifiers. A requirement cannot mix schemes. Empty intersections fail. Among permitted candidates, an existing exact resolution for the same active profile binding and extension requirement is reused after verification; an explicit refresh or first resolution selects the greatest permitted version. Equal-precedence builds require an exact owner-approved build choice, not registry order. opaque always needs that exact choice. Re-resolution never changes an invocation already pinned to a plan.

The local resolution record binds activeProfileRevision, release digest, requirement ID, provider identity/configuration digest and exact environment selection. It is mutable machine state outside the immutable release envelope. A profile migration may reuse it only after validating the new requirements and authority. Expired approval or a missing selected build reports an error until an explicit permitted new resolution; it is not permission for automatic version fallback.

These are logical operations in the selected rukh.runtime/1 contract, not a released SDK. Each request carries a core-created request ID, a pinned owner/profile context, a deadline and cancellation signal; none is taken from extension-supplied identity. Resolve/Inspect/Acquire for a command bind its invocation; support inspection and collection can use an explicit owner-maintenance scope. A shared Prepare uses its own preparation-activity context and fixed plan budget, with separately authorized invocation waiters as defined below. It does not impersonate its first waiter. Each response echoes the request ID and contains one typed result or error. The core rejects a stale, duplicate, differently bound or oversized result before use.

OperationResult and side-effect boundary
Describe supportSupported families, implementations, targets, version schemes, facilities and guarantees; no installation
ResolveExact candidate and preparation plan using approved metadata; identifies sources, writes, dependencies and any required installation authority
InspectDetermine whether the selected environment exists and is usable; no installation, activation scripts or project hooks
PreparePerform the explicitly authorized plan under fixed limits; publish readiness only after complete verification
Acquire / releaseHold or release a reference to a verified environment for an invocation; not automatic deletion of shared tools
CollectRemove only unreferenced provider-owned environments under owner policy, separately from command completion
DataRequired fields and invariants
Support recordproviderId, adapter version, contract version, supported platforms/implementations/schemes, preparation facilities and individually declared guarantees. Configuration comes from the pinned owner profile
Resolution requestRequirement, exact release/descriptor digests, target constraints, activeProfileRevision, provider binding/configuration digest, ownership domain and required guarantees. It does not carry arbitrary URLs, shell commands or credentials from invocation data
Preparation planplanId, planDigest, provider/adapter/backend identity, exact runtime version/build/target, dependency artifact digests, approved sources and expected sizes, managed destination identity, declared writes/network effects, required preparation action and limits. An explicit ready result still names the same selection
Environment resultenvironmentKey, exact plan identity, verified absolute executable and managed dependency paths, allowed environment additions, ownership (managed or borrowed), integrity evidence, guarantees and readiness record. No shell command string or mutable alias is an executable result
Acquired referenceCore-issued opaque referenceId, environment key, invocation/owner binding and verification evidence. It protects use; it is not an access grant or a transferable credential
Errorcode, request/plan identity, safe message and affected requirement; uncertain side effects and cleanup state when relevant. No secret values or unrestricted internal exception data

planId is an opaque core identity in the request wrapper. planDigest is SHA-256 of the exact core-serialized UTF-8 PlanBody after structural validation. That immutable body contains the profile version, selection, declared effects and limits; it excludes planDigest itself, planId, request correlation, absolute deadlines, cancellation state and authorization handles. There is no self-referential hash. Adapters confirm those exact body bytes and cannot substitute another plan. Sources use approved bindings; connection secrets stay in core-owned credential references and never enter the body. environmentKey hashes a versioned, length-prefixed tuple of provider/adapter/backend identity, relevant configuration digest, ownership domain, runtime/build/target and dependency digests. It excludes invocation ID and machine paths. The core owns encoding and compares the full tuple as well as the key; concatenated strings and a version string alone are insufficient. Sharing across ownership domains requires an explicit owner-approved shared domain with equivalent trust and permissions, not an implicit cache hit.

Prepare accepts the plan and a core-held authorization binding for its exact effects; the adapter cannot manufacture that approval. Acquire atomically checks readiness and selected identity and creates a reference before collection can remove the environment. Release is idempotent for that reference and cannot free another invocation’s reference. Missing or unverifiable ready state yields an error, not automatic repair during Acquire; a permitted repair requires a new plan. describe uses only Inspect/Acquire on an existing exact resolution and never performs network resolution or preparation.

Error codeCore behavior
unsupported_requirement, insufficient_guarantee, ambiguous_selectionrejected before extension code; report the unmet requirement without trying another mapping
preparation_deniedrejected before extension code; preparation does not start
resolution_unavailable, environment_missing, integrity_failed, plan_changed, provider_failed, resource_exhaustedexecution_failed unless cancellation was already accepted. A previously known static incompatibility remains rejected; these codes describe failure of the selected preparation path
cancelled, deadline_exceededCore-owned cancellation rules apply. A provider’s report alone cannot invent a user cancellation; a provider-local timeout before the invocation deadline is provider_failed
cleanup_incompletePrevent a normal success and retain protective ownership; accepted cancellation keeps its result with cleanup diagnostics

No error automatically repeats a command, switches providers or reruns an uncertain preparation effect. A user-requested retry starts a new attempt; inspection can reconcile existing files without executing installation again. Base help never calls these operations, and ineligible contextual help retains ADR-0002’s base-help behavior rather than creating a failing preparation attempt.

Resolution may need approved network metadata; it is not a promise of no I/O. Static help, command listing and base completion use declarations and support metadata and never invoke preparation. Contextual describe uses an already ready environment and cannot trigger installation. A native executable needs no language-runtime preparation unless its declared executor mapping explicitly requires an engine.

The sequence shows an execute invocation. Authorization gates use the core boundary; arrows do not prescribe remote broker traffic per call. A failed resolution, acquisition or final launch check ends that path without launch. Reference release during finalization requires confirmed end of use; incomplete cleanup retains the reference.

Accepted lazy environment preparation
Accepted lazy environment preparationThe core checks a pinned command before asking a trusted provider for an exact plan. Preparation requires authorization. Only a verified acquired environment reaches the executor; failures and cancellation never start the command.ExecutorCore access checksTrusted runtimeproviderRukh coreExecutorCore access checksTrusted runtimeproviderRukh coreopt[Allowed and invocation active]opt[Missing environment]opt[Final checks pass]alt[Environment ready and invocation active][Denied, failed or cancelled]Pin invocation andcheck static requirementsResolve environmentand inspect availabilityExact plan or ready environmentCheck permissionfor preparationAllow, deny or unavailablePrepare exact planwithin limitsVerified environmentor preparation errorAcquire environment referenceVerified handleRecheck launch settingsand required accessLaunch using pinned environmentCompletion evidenceRelease after confirmedend of useFinalize without command launchAccepted lazy environment preparationThe core checks a pinned command before asking a trusted provider for an exact plan. Preparation requires authorization. Only a verified acquired environment reaches the executor; failures and cancellation never start the command.ExecutorCore access checksTrusted runtimeproviderRukh coreExecutorCore access checksTrusted runtimeproviderRukh coreopt[Allowed and invocation active]opt[Missing environment]opt[Final checks pass]alt[Environment ready and invocation active][Denied, failed or cancelled]Pin invocation andcheck static requirementsResolve environmentand inspect availabilityExact plan or ready environmentCheck permissionfor preparationAllow, deny or unavailablePrepare exact planwithin limitsVerified environmentor preparation errorAcquire environment referenceVerified handleRecheck launch settingsand required accessLaunch using pinned environmentCompletion evidenceRelease after confirmedend of useFinalize without command launch

ADR-0002’s static input/compatibility and mandatory pre-launch access checks precede preparation. The plan is bound to the pinned invocation and release. If an actual source, target or side effect changes, a provider must return a new plan for validation and authorization rather than continue under the old decision. After preparation, the core checks concrete launch representation and access again. Cancellation stops admission and bounds provider cleanup; a late success cannot revive the invocation.

The result records runtime family/implementation, exact version/build, target OS/architecture/ABI, provider and backend identities, origin and integrity evidence. It also binds dependency-lock/bundle digests and the relevant provider configuration identity. Absolute executables and local paths belong to machine state; portable records retain identities, not those paths. The executor invokes the approved executable directly with an argument vector and a controlled environment.

Runtime installation and extension dependencies are different plans. Prefer verified dependency bundles or locked artifacts installed by an owner-approved preparer. Ordinary automatic preparation does not execute extension-supplied build scripts or dependency lifecycle hooks. Packages needing such work must supply prepared artifacts or use a separate explicitly authorized build workflow; an installer hook must not disguise extension execution as harmless metadata preparation.

An environment may require creation at its final managed path. Python virtual environments, for example, are not generally portable by moving directories. Construct such an environment at a unique final location, keep it unavailable while preparing, and publish a readiness record only after verification. An interrupted directory is incomplete, never a ready cache hit. Python virtual environments.

GuaranteeRequirement
Version accuracyThe reported implementation and version match the selected requirement; no implicit substitution
Content identityRecord build/artifact digests where the adapter can establish them; absence is an explicit limitation
ReproductionExact reacquisition requires pinned runtime and dependency artifacts, not just a version string or manager lockfile
CoexistencePreparing one selection must not switch or modify another active environment
OwnershipDistinguish Rukh-managed environments from borrowed system or user-managed tools

A provider declares these guarantees individually, and the owner may reject insufficient ones. A preinstalled-only adapter is valid if it can satisfy the required guarantees; it must report external mutability where it cannot prevent changes. A manager lock may depend on its backend’s precision, so the core verifies the adapter’s evidence rather than assuming uniform behavior. mise lock behavior.

Providers use controlled working directories and explicit configuration. Project files cannot silently enable manager plugins, hooks or tasks. A shell-based manager adapter may use a trusted fixed shell integration internally, but the executor does not evaluate returned shell text. Environment additions are checked against owner rules and cannot replace IPC handles, broker identity, permissions or inject general login credentials. Global PATH, shell profiles and system-default runtimes are not modified by ordinary preparation. A plan requiring unsupported global changes or privileges is rejected; no hidden elevation occurs.

The preparation key is the full environment identity defined above; the local resolution record points to it. One preparation writer publishes a ready environment per key. Waiters can share the verified result, not a half-written directory. Cancelling one waiter does not cancel another caller’s valid ownership; shared work has a bounded owner and is cancelled when no authorized demand remains. A waiter joins only after its own effect authorization and plan checks; one caller’s permission never authorizes another.

Writer ownership is acquired atomically with a fencing generation. Its journal records the plan, owned paths, supervised workers and readiness state before mutation. A successor cannot publish with an old generation. An expired heartbeat or missing PID alone does not prove that the previous writer stopped: uncertain workers keep their staging and protective references until supervised termination or reconciliation establishes the end of use. Restart validates records and artifact evidence; incomplete directories are quarantined, never treated as ready or rerun blindly. This is environment recovery, not resuming a finished invocation.

A live trusted core/provider preparation activity owns shared work, its approved effects and its original fixed deadline. Every waiter has its own invocation deadline and permission to join that exact plan. Ending one wait releases only that waiter’s demand; the activity may continue for other authorized waiters without inheriting the first invocation’s identity or expired deadline. Joining never extends the activity deadline. If demand ends, its owner cancels and cleans up within the activity’s fixed cleanup budget. Loss of the activity owner fails or reconciles waiting requests within their budgets and retains uncertainty; it does not transfer ownership or repeat installation automatically. The baseline coalesces work inside one live core. Cross-process joining requires explicitly declared coordinator support; otherwise another process receives bounded resource_exhausted/busy behavior and may later inspect an already completed environment. This facility is preparation ownership, not background execution of an extension.

Ready publication and reference acquisition share one storage transaction boundary. Collection marks an unreferenced owned environment deleting under that boundary, preventing new acquisition, then removes only validated owned paths. Successful removal commits removed; interrupted removal remains unavailable and is reconciled on restart. A failed or cancelled installation never publishes ready state. Borrowed tools are inspected and rechecked before launch, but references cannot prevent their external owner from replacing them; that declared limitation must satisfy owner policy, otherwise the provider is rejected.

These are design defaults, not measured optimal values or ADR-0001 process-startup limits. Invocation work and waiting use the smaller of their own budget and the invocation deadline. A shared preparation activity has its own fixed authorized plan budget; individual waiter deadlines do not terminate other authorized demand. Release, reconciliation and cleanup are exceptions to the work deadline: they use the remaining fixed finalization budget, not a newly expired invocation deadline. The invocation deadline remains active through final outcome commitment; finalization has a fixed budget which cancellation or deadline expiry never restarts. The first accepted cancellation cause is retained. Invocation-owned provider cleanup uses the remaining core-finalization budget, at most 5 seconds, rather than adding another period after it; an independently shared activity also has a fixed 5-second cleanup budget once its own finalization begins.

ResourceBaseline limit
Resolve / inspect / acquire metadata work30 seconds / 5 seconds / 5 seconds; no retry on an uncertain result
One preparation plan15 minutes elapsed; transfer inactivity 60 seconds; progress never extends the total deadline
Concurrent work2 preparation writers per profile, 16 queued distinct plans, 64 authorized waiters per environment key; excess admission returns resource_exhausted
Plan and result metadata256 KiB of UTF-8 each; depth 32; 4,096 members/elements; at most 64 source artifacts and 128 environment additions
Download / expanded files2 GiB total downloaded and 4 GiB expanded per plan; at most 100,000 files; declared expected sizes checked before transfer and actual sizes during processing
Managed cache10 GiB per ownership domain, including reservations and staging. Referenced or uncertain resources are never deleted to make room; insufficient space refuses admission
Readiness and referencesDurable transaction records; explicit final owner reconciliation, no TTL-based removal of a reference to potentially running code
DiagnosticsAt most 128 bounded records per plan, 4 KiB each; secrets removed; logs cannot delay cancellation or become command stdout

Capacity is reserved before writing. Providers may require less; tighter owner limits apply. A larger profile must be explicitly declared and tested, and does not relax integrity, cancellation or ownership rules. An adapter that cannot honor a budget reports unsupported support before preparation. Trusted library calls must cooperate with cancellation; operations requiring forceful stopping run in an owner-controlled supervised helper. The initial contract does not promise to terminate arbitrary code inside the core’s address space, and such a blocking adapter is not conforming.

The state view concerns a managed environment, not a command process. A referenced ready environment cannot be collected.

Accepted managed environment lifecycle
Accepted managed environment lifecycleAn exact plan enters preparation and becomes ready only after verification. Invocation references keep it available. Failed preparation is isolated; collection of ready environments requires no retained references and owner policy.Exact planPreparing, not availableReady and verifiedIn use by invocationsIncomplete, isolatedDeletion reserved, unavailableRemovedPreparation authorizedVerify and publish readinessFailure or cancelled ownerAcquire referenceOther references acquired orreleasedLast reference releasedNo references, reserve alloweddeletionEnd of use confirmed, cleanupallowedInterrupted cleanup, reconcileownershipOwned paths removed andrecord committedAccepted managed environment lifecycleAn exact plan enters preparation and becomes ready only after verification. Invocation references keep it available. Failed preparation is isolated; collection of ready environments requires no retained references and owner policy.Exact planPreparing, not availableReady and verifiedIn use by invocationsIncomplete, isolatedDeletion reserved, unavailableRemovedPreparation authorizedVerify and publish readinessFailure or cancelled ownerAcquire referenceOther references acquired orreleasedLast reference releasedNo references, reserve alloweddeletionEnd of use confirmed, cleanupallowedInterrupted cleanup, reconcileownershipOwned paths removed andrecord committed

Command finalization releases references only after confirmed end of use; it does not uninstall a shared runtime. If execution or cleanup remains uncertain, a protective reference survives final outcome commitment until reconciled. Cleanup never removes borrowed tools or unrelated user directories. Updates create another environment when identity changes and retain the previous one while referenced. Runtime/dependency updates are deliberate new resolutions, not a silent response to a command failure. Process lifetime, stopping and outcome commitment remain with the core/executor under ADR-0004.

Preparation authority and execution restrictions

Section titled “Preparation authority and execution restrictions”

Preparation effects use their own exact authorized plan and finite activity budget. A shared preparation retains its separate context with an owner-controlled payer/accounting policy selected before it starts; each waiter must be authorized to consume the result. Joining another waiter neither transfers that waiter’s broader authority nor silently duplicates or removes a charge. Task-requested preparation costs remain attributable under ADR-0014; sponsoring them from an explicitly approved owner budget is a policy choice, not an accidental escape from task limits. A provider that cannot establish a required finite maximum cost is unsupported for that budget profile.

The command’s eventual confinement does not automatically confine the provider. Its download endpoints, writes, credentials and any trusted helper require their own admitted scope; protected preparation effects use ADR-0016 where the selected policy requires that contract. The provider cannot expand its plan because the extension will later be restricted.

The environment result supplies the identities and guarantees needed by ADR-0015’s executor gate. A borrowed or externally mutable runtime is insufficient when the required executable/dependency binding cannot be preserved through startup and use. Neither a verified path at inspection time nor a manager name proves immutability or confinement. Failure to meet required guarantees stops before extension startup, without switching to a weaker executor or altering the shared environment. The checks below do not establish confined runtime support.

  • Teams declare language requirements without requiring users to manage versions manually or choose the same tool manager.
  • Providers can be replaced without changing command declarations, but each adapter must validate platform, isolation and identity guarantees.
  • Environment separation prevents dependency/version interference; it is not an OS sandbox or a grant of rights.

The project owner accepted this decision on 2026-09-23. The following list remains required implementation verification, not a claim that these checks passed at acceptance.

For implementation verification, implement the selected provider/result schemas, comparisons, budgets and transaction/recovery rules, then check:

  1. Native, script and incompatible requirements follow the right path; base help and contextual describe cause no installation.
  2. One external-manager adapter and one preinstalled/internal adapter satisfy the same contract, with unsupported guarantees rejected rather than invented.
  3. Two incompatible versions coexist; mutable aliases, project hooks and changed plans cannot alter a pinned invocation or global defaults.
  4. Concurrent preparation, cancellation and crash recovery never expose incomplete environments or collect referenced/borrowed tools.
  5. Dependency hooks are not hidden execution; changed artifacts, missing exact builds and final launch/access failures preserve ADR-0002/0004 outcomes without command retry.

These checks have not been run for ADR-0008. Using mise to maintain this documentation repository does not validate a Rukh runtime adapter.

Diagram

Drag to move · + / − to zoom · 0 to fit · Esc to closeDrag to move and pinch to zoom

100%