Skip to main content

capsule_runtime/
types.rs

1use std::{
2    collections::{HashMap, HashSet},
3    path::PathBuf,
4    sync::Arc,
5};
6
7use murmur_artifact::{
8    ArtifactImplementation, ArtifactRuntime, ContextConfig, HookConfig, InferenceConfig,
9    LifecycleConfig, LifecycleOverride, Registry,
10};
11use wasmtime::{component::Component, Engine};
12
13use crate::{
14    bindings::host::murmur::tool::run::ToolResult,
15    formation::FormationId,
16    formation_credentials::FormationMember,
17    hooks::ShellDispatchInfo,
18    limits::{EpochTicker, ExecutionLimits},
19    network_policy::{HookCapabilityGrant, ToolCapabilityGrant},
20    spawn_credential::{SpawnApproval, SpawnCredential},
21};
22
23pub(crate) struct DispatchOutcome {
24    pub result: ToolResult,
25    pub shell: Option<ShellDispatchInfo>,
26    /// Set instead of [`Self::shell`] when the command outran its grace period and was demoted
27    /// to the background. The two are never both `Some`: a demoted command has no exit code yet,
28    /// which is exactly why `HookEvent::Shell` does not fire for one.
29    pub detached: Option<crate::detached::DetachedDispatchInfo>,
30    /// True when the dispatch was served by reading a skill.md file rather than running
31    /// a binary or WASM component. Used by the agent loop to write a `skill_call` trace
32    /// event instead of a `tool_call` event.
33    pub is_skill: bool,
34    /// The fence source `result.data` was wrapped under, or `None` when the result carries no
35    /// fence. Set by [`crate::runtime::CapsuleStoreState::dispatch_agent_tool_async`] on the
36    /// same branch that applies the fence, so the label and the wrapping cannot drift: a caller
37    /// reading this never re-derives a source name by parsing the content back.
38    ///
39    /// `Some("tool:<name>")` on every non-skill outcome, `Some("skill:<name>")` on a skill whose
40    /// `murmur.lock` origin is `runtime`, and `None` on an operator-declared skill and on every
41    /// outcome that leaves the private unfenced dispatch — that is,
42    /// [`crate::runtime::CapsuleStoreState::dispatch_submit_plan`]'s route, whose step output is
43    /// fenced later as one field of a report.
44    pub fence_source: Option<String>,
45    /// Set when this dispatch failed in a way that ends the *session* rather than just this
46    /// tool call — today only a `sealed` composed-root construction failure
47    /// ([`crate::shell::ShellExecError::session_fatal`]). `result` still describes the failed
48    /// call so the trace records what was attempted; the agent turn loop then returns this
49    /// error instead of feeding the failure back to the model for another turn.
50    ///
51    /// A dispatch that merely failed leaves this `None`: a capsule reacting to a broken tool
52    /// call is ordinary, whereas a capsule continuing to run after its declared containment
53    /// boundary stopped being establishable is the silent-degradation failure mode the whole
54    /// containment-class mechanism exists to prevent.
55    pub fatal: Option<crate::errors::RuntimeError>,
56    /// The runtime's own words about this call, appended by
57    /// [`crate::runtime::CapsuleStoreState::dispatch_agent_tool_async`] after the fence's closing
58    /// marker, so the model reads them as the runtime's rather than as the tool's data.
59    ///
60    /// `Some` on these outcomes:
61    ///
62    /// * a `call-member` call that started, carrying [`crate::member_call::started_note`];
63    /// * an accepted `end-without-answer`;
64    /// * a pull through `pull-artifact`, and a `remove-artifact` that removed something, each
65    ///   saying when the tool list changes;
66    /// * a shell call that finished and whose failure was attributed to a
67    ///   `capabilities.resources` limit, carrying [`crate::resources::resource_limit_line`].
68    ///
69    /// `None` on every other outcome. The unfenced route of
70    /// [`crate::runtime::CapsuleStoreState::dispatch_submit_plan`] never reads it.
71    pub runtime_note: Option<String>,
72}
73
74impl DispatchOutcome {
75    pub(crate) fn tool(result: ToolResult) -> Self {
76        Self {
77            result,
78            shell: None,
79            detached: None,
80            is_skill: false,
81            fence_source: None,
82            fatal: None,
83            runtime_note: None,
84        }
85    }
86
87    pub(crate) fn skill(result: ToolResult) -> Self {
88        Self {
89            result,
90            shell: None,
91            detached: None,
92            is_skill: true,
93            fence_source: None,
94            fatal: None,
95            runtime_note: None,
96        }
97    }
98}
99
100#[derive(Debug, Clone, PartialEq, Eq)]
101pub struct ArtifactRequest {
102    pub name: String,
103    pub version: String,
104    pub runtime: ArtifactRuntime,
105    /// Optional local source path (skill artifacts only). When set, the runtime resolves the
106    /// skill's `skill.md` directly from this path and skips registry resolution entirely.
107    /// Relative paths resolve against `StageRequest::manifest_dir`.
108    pub source: Option<String>,
109    /// Per-artifact capability grant copied verbatim from this artifact's entry in the
110    /// capsule operator's own manifest (`murmur_artifact::RuntimeArtifact::capabilities`).
111    /// Consumed for `runtime: hook` (default-deny baseline, `None` = deny everything) and for
112    /// `runtime: tool`/`runtime: driver` (ceiling baseline, `None` = the capsule-wide policy
113    /// unchanged); the manifest parser rejects the key on `runtime: skill`. Never sourced
114    /// from the artifact's own bundled `murmur.yaml`, so an artifact cannot self-grant.
115    pub capabilities: Option<murmur_artifact::Capabilities>,
116    /// What the runtime does when this hook's async job queue is full, copied verbatim from
117    /// `on_overflow:` on this artifact's entry in the capsule operator's own manifest — the
118    /// same operator-only sourcing rule `capabilities` above follows. Consumed for
119    /// `runtime: hook` and inert for every other role (the manifest parser rejects the key
120    /// there); inert too for a hook that turns out to be `execution_mode: blocking`, which is
121    /// never queued.
122    pub on_overflow: murmur_artifact::HookOverflowPolicy,
123    /// This artifact's operator-declared `config:` block, copied verbatim from its entry in the
124    /// capsule operator's own manifest (`murmur_artifact::RuntimeArtifact::config`) — the same
125    /// operator-only sourcing rule `capabilities` above follows, so an artifact pulled from a
126    /// registry cannot configure itself.
127    ///
128    /// Lowered to compact JSON at staging by [`crate::artifact_config::lower_artifact_config`] and
129    /// delivered to this artifact alone as [`crate::artifact_config::ARTIFACT_CONFIG_ENV`]. `None`
130    /// means the variable is absent from the guest environment. Consumed for `runtime: hook`,
131    /// `runtime: tool` and `runtime: driver`; the manifest parser rejects the key on
132    /// `runtime: skill`, and a native tool warns `W-SEC-015` because it reads no per-artifact
133    /// environment at all.
134    pub config: Option<serde_yaml::Value>,
135    /// This artifact's operator-declared `gateway:` block, copied verbatim from its entry in the
136    /// capsule operator's own manifest (`murmur_artifact::RuntimeArtifact::gateway`) — the same
137    /// operator-only sourcing rule `capabilities` above follows. Built into the artifact's
138    /// credential gateway at staging, which is also where the artifact's own `upstream_auth:`
139    /// declaration is read; an artifact without this block is never asked for one.
140    pub gateway: Option<murmur_artifact::ArtifactGateway>,
141}
142
143/// What `murmur.lock` pins one artifact at, already narrowed to this host.
144#[derive(Debug, Clone, PartialEq, Eq)]
145pub struct LockExpectation {
146    pub name: String,
147    pub resolved_version: String,
148    /// The hash the resolved payload must have. Selected by the caller from the lock entry's
149    /// `sha256` for the platform staging runs on, so it is whichever of `any` or
150    /// `platforms.<platform>` applies to this host.
151    pub sha256: String,
152    /// Who wrote the lock entry. A [`murmur_artifact::LockOrigin::Runtime`] pin stages only as a
153    /// tool or skill without a `gateway:` block; staging refuses anything else with
154    /// [`crate::RuntimeError::RuntimeOriginNotDeclarable`].
155    pub origin: murmur_artifact::LockOrigin,
156}
157
158/// What staging actually resolved, for the caller to write back into `murmur.lock`.
159#[derive(Debug, Clone, PartialEq, Eq)]
160pub struct ResolvedLockArtifact {
161    pub name: String,
162    pub resolved_version: String,
163    /// Hash of the payload that was resolved on this host.
164    pub sha256: String,
165    /// Which platform the resolved payload is filed under, `None` for a platform-independent
166    /// one. Decides whether the lock entry pins `sha256.any` or `sha256.platforms.<platform>`.
167    pub platform: Option<String>,
168}
169
170#[derive(Debug, Clone, PartialEq, Eq, Default)]
171pub struct CapabilityPolicy {
172    pub network_allow: Vec<String>,
173    /// From `capabilities.peer_fetch.allow`: the peers this capsule may redeem a peer-file handle
174    /// against. Empty by default, which is deny — and which is also why no `fetch-peer-file` tool
175    /// manifest is written and the capsule's model never sees the tool exists.
176    ///
177    /// A separate list from [`Self::network_allow`], enforced with the same rule matcher but
178    /// never merged into it. Ingesting a peer's bytes lands a file in this capsule's own workdir,
179    /// so it is a prompt-injection surface and deserves its own operator control; a destination
180    /// in `network.allow` is not redeemable unless it also appears here, and declaring it here
181    /// does not widen `network.allow`.
182    pub peer_fetch_allow: Vec<String>,
183    /// From `capabilities.network.unix_sockets`. `false` by default, which makes the shell
184    /// subprocess tree's `socket(AF_UNIX, ...)` calls fail with `EACCES` at the kernel level on
185    /// both Linux tiers — `network_allow` above governs IP destinations only and would otherwise
186    /// leave a local daemon socket (`/var/run/docker.sock` — host root) completely unmediated.
187    /// `true` simply omits that seccomp rule; it is capsule-wide, not per-socket-path. See
188    /// `sandbox::denied_socket_domains`.
189    pub unix_sockets_allowed: bool,
190    pub filesystem_scope: Option<String>,
191    /// From `capabilities.filesystem.workdir_exec`. `false` by default, which withholds the
192    /// Landlock `Execute` right from the workdir's own `PathBeneath` rule — see
193    /// `sandbox::linux_enforce::workdir_access_rights`. With it withheld the kernel refuses to exec
194    /// anything under the workdir on the resolved path itself, so `shell_allow` is enforced
195    /// completely: a binary copied or compiled into the workdir cannot run under *any* name.
196    ///
197    /// `true` gives the right back for compile-and-run workflows and accepts, explicitly, that
198    /// `shell_allow` is then unenforceable for anything inside the workdir. That is why this field
199    /// is the one *grant* in this struct that also lowers the session's achieved containment class
200    /// (see `crate::containment::achieved_containment_class`) — nothing else here can.
201    pub workdir_exec_allowed: bool,
202    /// From `capabilities.filesystem.read_only`: workdir subtrees the capsule may read but must
203    /// not write, in the same vocabulary [`Self::filesystem_scope`] uses. Empty by default, which
204    /// is the whole workdir writable.
205    ///
206    /// Carried here as the declared strings and lowered once at staging into
207    /// `crate::protected_paths::ProtectedPaths`, which is what the dispatch check consults — so a
208    /// malformed entry refuses the launch rather than one call at a time. Unlike every other field
209    /// here this one grants nothing: it can only subtract from what the workdir preopen already
210    /// allows.
211    pub read_only_paths: Vec<String>,
212    pub shell_allow: Vec<String>,
213    pub spawn_allow: Vec<String>,
214    pub shell_strip_env: Vec<String>,
215    pub shell_baseline_env: Vec<String>,
216    /// Typed interpreter-runtime grants from `capabilities.shell.interpreter_runtime`: each
217    /// names an already-allowlisted binary and the exact host directories outside the workdir
218    /// its import machinery needs, with a per-directory `list_dir` enumerability flag. Empty
219    /// unless the manifest declares them. Consumed on `KernelFull` to add narrow Landlock
220    /// grants (see `sandbox::resolve_interpreter_runtime_grants`) and to fire `W-SEC-009`.
221    pub shell_interpreter_runtime: Vec<murmur_artifact::InterpreterRuntimeGrant>,
222    /// Typed staged-runtime grants from `capabilities.shell.staged_runtime`: each names an
223    /// already-allowlisted binary, the absolute host path of a pinned runtime tree, and the `pin`
224    /// identifying that tree's build. Empty unless the manifest declares them.
225    ///
226    /// Consumed at staging to enforce that declaring one requires an effective `sealed` floor (see
227    /// `crate::staged_runtime::check_staged_runtime_floor`) and to render the `staged runtime`
228    /// section of `--explain-scope`. Per-binary mutually exclusive with
229    /// [`Self::shell_interpreter_runtime`], which the manifest parser already guarantees.
230    pub shell_staged_runtime: Vec<murmur_artifact::StagedRuntimeGrant>,
231    /// Host env var names a WASM guest may observe, from `capabilities.env.allow`. Empty by
232    /// default: a guest sees only the runtime's own `MURMUR_*` injection unless the manifest
233    /// names a variable here. `shell_strip_env` and the credential patterns still apply on
234    /// top, so a credential-shaped name declared here is stripped anyway.
235    pub env_allow: Vec<String>,
236    /// Execution limits applied to every guest store in the session. Always fully
237    /// resolved — `capability_policy_from_runtime_manifest` substitutes a default for
238    /// each field `capabilities.limits` omits, so there is no "unset" state here and a
239    /// silent manifest yields [`ExecutionLimits::default`] rather than no limits.
240    pub limits: ExecutionLimits,
241    /// OS-level bounds applied to every *native subprocess* the session spawns — rlimits, the
242    /// Linux cgroup v2 scope, and the workdir-size ceiling. Resolved on exactly the same terms
243    /// as `limits` above (each omitted `capabilities.resources` field replaced by its default,
244    /// no "unset" state), but a completely different subject: `limits` bounds a WASM guest
245    /// inside its wasmtime store, this bounds the processes the host forks. See
246    /// [`crate::resources`].
247    pub resources: crate::resources::HostResourceLimits,
248    /// The containment class this capsule asked for, from `capabilities.containment`.
249    ///
250    /// Unlike every other field here it is a *requirement*, not a grant — and unlike
251    /// `StageRequest::declared_containment_floor` it is only the manifest's own vote, before the
252    /// workspace config and `--containment` are folded in. `stage_session` overwrites it with the
253    /// combined floor as soon as that is known, so anything reading it off a `StagedSession` sees
254    /// the effective value; the manifest-only value exists so a `CapabilityPolicy` built straight
255    /// from a manifest is still self-consistent.
256    ///
257    /// Read by `sandbox::ShellEnforcement::resolve` to decide whether a sealed-capable host
258    /// actually installs a composed root for this session — a capsule that declared `scoped` must
259    /// keep getting `scoped`'s mechanism. See `sandbox::applied_tier`.
260    pub containment_floor: murmur_artifact::ContainmentClass,
261    /// Whether the capsule's own top-level `capabilities.state` block was declared.
262    ///
263    /// Not a grant, and the only field here that is not: a durable state store is granted per
264    /// *artifact*, so a capsule-wide declaration reaches nothing at all. It is recorded so
265    /// `stage_session` can say that once (`W-SEC-014`) instead of leaving an operator to discover
266    /// an empty directory, and it is read by nothing else.
267    pub state_declared: bool,
268    /// Recorded for the same reason [`Self::state_declared`] is, and applied just as little: the
269    /// `murmur:conversation/read` grant is per artifact, so a capsule-wide declaration reaches
270    /// nothing and `stage_session` says so once (`W-SEC-016`).
271    pub conversation_declared: bool,
272    /// From `capabilities.plan.submit`: whether this capsule's model is offered the
273    /// runtime-provided `submit-plan` tool. `false` by default, which is deny — and which is also
274    /// why no `submit-plan` tool manifest is written and the capsule's model never sees the tool
275    /// exists.
276    ///
277    /// It grants no reach of its own: every step of a submitted plan runs through this same
278    /// session's tool dispatch, its shell allowlist and its spawn grant, so a plan reaches exactly
279    /// what the model could already call one call at a time.
280    pub plan_submit: bool,
281    /// From `capabilities.install.skill`: the entries naming which skill artifacts a pull
282    /// (`manage.pull` or the `pull-artifact` tool) may install into this session, verbatim and in
283    /// declaration order. Empty by default, which is deny. With [`Self::install_tool`] also
284    /// empty, every pull is refused.
285    ///
286    /// A pulled skill gains no grant of its own; see `install_grant`.
287    pub install_skill: Vec<String>,
288    /// From `capabilities.install.tool`: the entries naming which tool artifacts, WASM or native,
289    /// a pull may install, verbatim and in declaration order. Empty by default, which is deny.
290    ///
291    /// A pulled tool joins the session's dispatch allowlist and dispatches on this policy's own
292    /// ceiling; it gains no grant of its own.
293    pub install_tool: Vec<String>,
294    /// From `capabilities.install.from`: `true` for `[stores, sources]`, under which a pull the
295    /// stores cannot answer is fetched from the scope's GitHub source. `false` by default.
296    pub install_from_sources: bool,
297    /// `capabilities.limits.deadline_seconds` exactly as the manifest declared it — `None`
298    /// when it declared nothing. Retained undefaulted alongside the fully-resolved `limits`
299    /// above purely so hook calls can apply their own, lower default without mistaking an
300    /// explicit `600` for silence. See [`Self::hook_limits`].
301    pub declared_deadline_seconds: Option<u64>,
302}
303
304impl CapabilityPolicy {
305    /// Execution limits for hook lifecycle calls — [`Self::limits`] with the hook-specific
306    /// deadline default substituted when the manifest declared none.
307    ///
308    /// A hook call is one bounded piece of work, so it does not inherit the capsule-wide
309    /// ten-minute budget that exists for a capsule's whole `run`: a wedged hook would
310    /// otherwise stall the session for most of that, every event. An explicitly declared
311    /// `deadline_seconds` still wins, for hooks as for every other guest.
312    #[must_use]
313    pub fn hook_limits(&self) -> ExecutionLimits {
314        self.limits.for_hook_calls(self.declared_deadline_seconds)
315    }
316}
317
318#[derive(Debug, Clone, PartialEq, Eq)]
319pub struct InstalledArtifactSummary {
320    pub name: String,
321    pub version: String,
322    pub runtime: ArtifactRuntime,
323    pub implementation: Option<ArtifactImplementation>,
324    /// Who pinned the artifact: its `murmur.lock` entry's origin, both for an artifact staged
325    /// from the lock and for one `manage.pull()` installed mid-session. An artifact staged
326    /// without a lock, and a `source:` skill, are [`murmur_artifact::LockOrigin::Operator`].
327    pub origin: murmur_artifact::LockOrigin,
328}
329
330#[derive(Clone)]
331pub(crate) struct StagedHookArtifact {
332    pub name: String,
333    pub version: String,
334    pub component: Component,
335    /// Behavioral contract (binding/execution_mode/commit_policy) from the hook artifact's
336    /// *own* bundled manifest. Carries no capability information — see `grant`.
337    pub config: HookConfig,
338    /// What this hook is allowed to do, lowered and validated at staging time from the
339    /// operator's own manifest entry. Applied identically by all three hook instantiation
340    /// paths in `hooks.rs`; `HookCapabilityGrant::default()` is full default-deny.
341    pub grant: HookCapabilityGrant,
342    /// What to do when this hook's async job queue is full — from the operator's manifest
343    /// entry (via [`ArtifactRequest::on_overflow`]), on the same terms as `grant` and never
344    /// from `config`. Read only when `config.execution_mode` is `Async`; a blocking hook has
345    /// no queue to overflow.
346    pub on_overflow: murmur_artifact::HookOverflowPolicy,
347    /// This hook's own credential gateway, when its operator entry declares `gateway:`. Attached
348    /// to every store the hook is instantiated on, `on-stage` included. Filled once the session's
349    /// gateways are staged, before any hook runs.
350    pub gateway: Option<Arc<crate::credential_gateway::CredentialGateway>>,
351}
352
353/// How `mur run --resume` puts the loaded conversation in front of the model.
354///
355/// `Full` is often the cheaper of the two: a verbatim reload can land on the provider's own
356/// prompt cache, while compaction changes the prefix from the first altered token, guarantees a
357/// cache miss, and costs an inference call to produce the summary. `Compact` is the answer when
358/// the conversation would not fit the context window at all.
359#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
360pub enum ResumeMode {
361    #[default]
362    Full,
363    Compact,
364}
365
366/// One operator act: continue *this* conversation, whatever the capsule's own
367/// `lifecycle.conversation` policy says about carrying one between tasks.
368///
369/// Sugar over [`StageRequest::context_id`], never a second load path: the CLI resolves a session
370/// address to the context id that session ran under and fills both this and `context_id`. What
371/// this adds is the override — the record is loaded even under `lifecycle.conversation:
372/// stateless` — and the provenance the trace records.
373#[derive(Debug, Clone)]
374pub struct ResumeRequest {
375    /// The prior session's id, recorded verbatim as `session_start.resumed_from`.
376    pub from_session: String,
377    pub mode: ResumeMode,
378}
379
380#[derive(Debug, Clone)]
381pub struct StageRequest {
382    pub manifest_dir: PathBuf,
383    pub capsule_name: String,
384    pub capsule_version: String,
385    /// The full `<scope>/<name>` the capsule was resolved by, for one launched by name
386    /// (`mur run --capsule`). The session registers with mur-roost and reports its completion
387    /// under it. `None` for a capsule run from a project directory, which is `local/<capsule_name>`.
388    pub capsule_artifact: Option<String>,
389    pub capsule_component_bytes: Vec<u8>,
390    pub artifacts: Vec<ArtifactRequest>,
391    pub allowlisted_tools: HashSet<String>,
392    pub lock_expectations: Option<Vec<LockExpectation>>,
393    pub capability_policy: CapabilityPolicy,
394    pub inference: Option<InferenceConfig>,
395    /// The global config file a `${NAME}` in an artifact's `gateway.api_key` is looked up in first, as
396    /// `credentials.NAME`, and re-read from while the session runs. `None` looks in the launching
397    /// environment only.
398    pub credentials_file: Option<PathBuf>,
399    /// Whether `inference` above had its system-prompt declaration replaced by the caller
400    /// (`mur run --system-prompt`) rather than read from the manifest. Purely a provenance
401    /// signal for the trace: the override itself is already applied to `inference`, which by
402    /// this point is indistinguishable from a manifest that declared the same prompt inline.
403    /// `true` even when the override cleared the prompt to nothing.
404    pub system_prompt_overridden: bool,
405    pub context: Option<ContextConfig>,
406    /// Context id every `task.md` task of this launch runs under, from `mur run --context`.
407    /// `None` mints a fresh one per task. Validated by `stage_session` as one path segment: it is
408    /// a directory name in the conversation record path.
409    pub context_id: Option<String>,
410    /// `mur run --resume <session>`, already resolved: `context_id` above holds the context that
411    /// session ran under, and this carries the session's own id and the mode. `None` is every
412    /// ordinary launch. `stage_session` refuses a resume whose context kept no record on disk,
413    /// and a `--resume-mode compact` with no hook bound to `on-compaction`.
414    pub resume: Option<ResumeRequest>,
415    /// `mur run --forget-session`: drop the harness session `context_id` names before this
416    /// launch's first task, so that task starts a new conversation under the same context id.
417    /// `false` on every ordinary launch. `stage_session` refuses it for a capsule whose transport
418    /// keeps no harness session.
419    pub forget_session: bool,
420    /// OTLP/HTTP endpoint for span export; None = no external OTel emission.
421    pub otel_endpoint: Option<String>,
422    /// JSON-serialized EvalConfig injected into hook WASI env as MURMUR_EVAL_CONFIG.
423    pub eval_config_json: Option<String>,
424    /// Dataset case identifier injected as MURMUR_CASE_ID when running a dataset.
425    pub case_id: Option<String>,
426    /// Dataset identifier injected as MURMUR_DATASET_ID when running a dataset.
427    pub dataset_id: Option<String>,
428    /// Lifecycle config from the manifest (None = use LifecycleConfig::default()).
429    pub lifecycle: Option<LifecycleConfig>,
430    /// Optional override applied on top of lifecycle (e.g. from CLI flags or mur-roost).
431    pub lifecycle_override: Option<LifecycleOverride>,
432    /// Trace config from the manifest (None = defaults apply: input captured, output not).
433    pub trace: Option<murmur_artifact::TraceConfig>,
434    /// Optional user project directory to mount as the capsule's accessible workspace.
435    /// When set, session artifacts go into `<workdir>/.murmur/<session_id>/`.
436    /// When None, uses the default temp dir (existing behavior).
437    pub workdir: Option<std::path::PathBuf>,
438    /// Address to bind the HTTP server on. Defaults to "127.0.0.1" for local runs.
439    /// Use "0.0.0.0" when deploying to a VM so the capsule is reachable externally.
440    pub bind_addr: String,
441    /// Internal port from `network.internal_port` in the manifest. When `Some`, the runtime
442    /// binds strictly to this port and errors if it is already in use. When `None`, the OS
443    /// assigns a port.
444    pub internal_port: Option<u16>,
445    /// Minimum containment class this session must achieve, already combined across every
446    /// source that asked for one (manifest / workspace config / `--containment`) by taking the
447    /// strongest. Required rather than optional: "nobody declared anything" is
448    /// [`ContainmentClass::Advisory`], an explicit floor every host clears, not an absence.
449    /// `stage_session` refuses to stage when the host cannot meet it.
450    pub declared_containment_floor: murmur_artifact::ContainmentClass,
451    /// The manifest's top-level `exports:` block. `None` — and `Some` with no `files:` — means
452    /// the resource plane is not declared and every request to it is denied.
453    ///
454    /// Carried beside `capability_policy` rather than inside it: an export is a disclosure the
455    /// operator makes, not a capability the guest holds, and nothing derived from this field ever
456    /// reaches the achieved containment class.
457    pub exports: Option<murmur_artifact::Exports>,
458    /// The manifest's top-level `control:` block. `None` means the session has no control
459    /// surface: no token is minted and every request under `/control` is answered `404`.
460    ///
461    /// Beside `exports` and on the same terms: what a controller may change is not a capability
462    /// the guest holds, and nothing derived from it reaches the containment class.
463    pub control: Option<murmur_artifact::ControlConfig>,
464    /// The manifest's `network.authentication` block. `None` is a public door, which answers every
465    /// caller that reaches the port; `Some` makes staging mint this session's door key and tokens.
466    pub door_authentication: Option<murmur_artifact::NetworkAuthentication>,
467    /// The approval a delegated child was handed by its parent, presented once at registration.
468    ///
469    /// `None` for every top-level launch, which the daemon admits against its own `--spawn-allow`
470    /// instead. Unlike [`StagedSession::spawn_credential`], this exists before staging: it names
471    /// an artifact rather than a session, and the parent already held it when it started this
472    /// process.
473    pub spawn_grant: Option<SpawnApproval>,
474    /// `spend.machine_tokens_per_day` from the operator's effective `config.yaml`. `Some` makes
475    /// staging open the shared daily spend ledger for a `transport: http` session with a driver,
476    /// and refuse when it cannot; `None` — every launch that does not read the operator config —
477    /// keeps no ledger and is not counted.
478    pub machine_tokens_per_day: Option<u64>,
479    /// The formation this session is a member of.
480    ///
481    /// `None` is the ordinary case: a session nobody placed in a formation, including a
482    /// standalone capsule that delegates and every child it spawns. `mur run` sets it from
483    /// [`crate::formation::FormationId::from_env`], which reads what the launcher of a formation's
484    /// members, or a member's runtime for its child, put in the environment.
485    pub formation_id: Option<FormationId>,
486    /// What this session's formation launcher handed it: its roster name, what its door checks a
487    /// formation token with, and the tokens and addresses of the members it may call.
488    ///
489    /// `Some` only for a session `mur run --roster` launched as a member: `mur run` reads it from
490    /// the channel [`crate::formation_credentials::FormationMember::from_env`] names, and refuses
491    /// the launch when that cannot be read. The door verifies formation tokens with it, every WASM
492    /// guest is handed its callees' names, and the runtime's egress resolves and authorizes calls
493    /// to them. No native process and no delegated child is handed any of it.
494    pub formation_member: Option<Arc<FormationMember>>,
495    /// Where a pull the stores cannot answer is fetched from, for a capsule granted
496    /// `capabilities.install.from: [stores, sources]`. `None` fetches from no source: every pull
497    /// is answered by the stores alone.
498    pub source_supply: Option<Arc<dyn crate::artifact_supply::SourceSupply>>,
499    /// The `(st_dev, st_ino)` the accessible workdir must have, compared with `fstat` of the
500    /// directory `stage_session` opens at [`Self::workdir`] before anything is written beneath
501    /// it; a mismatch refuses the launch with [`crate::RuntimeError::WorkdirIdentityMismatch`].
502    /// Set by a delegating parent through `mur run --workdir-identity`, for the child directory it
503    /// created. `None` checks nothing.
504    pub expected_workdir_identity: Option<(u64, u64)>,
505    /// The manifest file this launch read, copied into the runtime directory under its own file
506    /// name: `--manifest`, or the project's `murmur.yaml`. `None` for a launch that read none from
507    /// disk — an installed capsule run by name — which copies nothing.
508    pub manifest_file: Option<PathBuf>,
509}
510
511/// The `transport: process` driver this session runs its harness through, compiled and described
512/// once at staging.
513///
514/// Not a tool: it is granted nothing, never enters `tool_components`, and is reached only by the
515/// process runner, which instantiates a fresh [`crate::process_driver::ProcessDriver`] from
516/// `component` per harness run.
517pub struct StagedProcessDriver {
518    pub(crate) name: String,
519    pub(crate) version: String,
520    pub(crate) component: Component,
521    pub(crate) description: crate::process_driver::Description,
522    /// The absolute path of the executable to spawn, already resolved and checked.
523    pub(crate) binary: PathBuf,
524    /// Where [`Self::binary`]'s name came from, for diagnostics and the trace: `inference.command`
525    /// or the process driver's `describe()`.
526    pub(crate) binary_source: String,
527}
528
529pub struct StagedSession {
530    pub session_id: String,
531    /// The session directory's host path, for display and subprocess arguments. The runtime reads
532    /// and writes beneath it only through [`Self::session_root`].
533    pub workdir: PathBuf,
534    /// User project directory (or session dir if no --workdir). WASM tools see this at ".".
535    /// The runtime reads and writes beneath it only through [`Self::accessible_root`].
536    pub accessible_workdir: std::path::PathBuf,
537    /// [`Self::accessible_workdir`], held open.
538    pub accessible_root: crate::workdir_fs::WorkdirRoot,
539    /// [`Self::workdir`], held open, reached from [`Self::accessible_root`] with no link followed.
540    /// The same root as `accessible_root` without `--workdir`.
541    pub session_root: crate::workdir_fs::WorkdirRoot,
542    /// The session's runtime directory, `~/.murmur/sessions/<session-id>/runtime`: the value of
543    /// `$MURMUR_RUNTIME_DIR`, holding `MURMUR.md`, `task.md`, `murmur.yaml`, `tools/` and
544    /// `plans/`. Removed when the session ends; the runtime reads and writes beneath it only
545    /// through [`Self::runtime_root`].
546    pub runtime_dir: PathBuf,
547    /// [`Self::runtime_dir`], held open, sharing [`Self::accessible_root`]'s refusal latch.
548    pub runtime_root: crate::workdir_fs::WorkdirRoot,
549    /// The three held directories beneath the session's runtime directory, with the records
550    /// directory beside them.
551    pub(crate) runtime_dirs: crate::runtime_dir::RuntimeDirRoots,
552    /// The session's records directory, `~/.murmur/records/<workdir root>/<session-id>`: the
553    /// value of `$MURMUR_RECORDS_DIR`, holding `trace.jsonl`, `blobs/`, `logs/`,
554    /// `completion.json` and `hooks/`. Kept after the session ends; the runtime reads and writes
555    /// beneath it only through [`Self::records_root`].
556    pub records_dir: PathBuf,
557    /// [`Self::records_dir`], held open, sharing [`Self::accessible_root`]'s refusal latch.
558    pub records_root: crate::workdir_fs::WorkdirRoot,
559    /// The file name the launched manifest was copied into the runtime directory under, which
560    /// the `[Capsule]` notice and `MURMUR.md` name. `None` when the launch read no manifest file.
561    pub(crate) manifest_file_name: Option<String>,
562    /// Owns the runtime directory: dropping it removes the directory, so it is held until the
563    /// session ends — `launch` takes it and drops it on return, and a `StagedSession` dropped
564    /// unlaunched drops it with itself.
565    pub(crate) runtime_dir_guard: Option<crate::runtime_dir::RuntimeDir>,
566    pub(crate) manifest_dir: PathBuf,
567    pub(crate) capsule_name: String,
568    pub(crate) capsule_version: String,
569    /// [`StageRequest::capsule_artifact`], or `local/<capsule_name>` for a project run.
570    pub(crate) capsule_artifact: String,
571    pub(crate) capsule_url: String,
572    pub resolved_lock_artifacts: Vec<ResolvedLockArtifact>,
573    pub(crate) installed_artifacts: Vec<InstalledArtifactSummary>,
574    /// Each staged artifact's full name, by the tool name the session knows it by.
575    pub(crate) artifact_full_names: std::collections::HashMap<String, String>,
576    pub(crate) inference: Option<InferenceConfig>,
577    /// Every credential gateway of the session, built at staging from each artifact entry's
578    /// `gateway:` block and the artifact's own `upstream_auth:` declaration. Empty when no entry
579    /// declares one.
580    pub(crate) gateways: crate::credential_gateway::GatewayTable,
581    /// This session's spend account, built at staging from `inference.max_session_tokens` and
582    /// [`StageRequest::machine_tokens_per_day`]. Always present: a session with no ceiling gets a
583    /// meter that admits everything, so every driver call has an admission to open.
584    pub(crate) spend: Arc<crate::spend::SpendMeter>,
585    /// What a controller has changed on this session, built at staging from
586    /// [`StageRequest::control`]. `None` for a capsule with no `control:` block, which mints no
587    /// control token and answers `404` under `/control`.
588    pub(crate) control: Option<Arc<crate::control_plane::ControlState>>,
589    /// Copied from [`StageRequest::door_authentication`], which the cards are built from.
590    pub(crate) door_authentication: Option<murmur_artifact::NetworkAuthentication>,
591    /// This session's door key and tokens, minted at staging when
592    /// [`Self::door_authentication`] is declared. The key never leaves this value.
593    pub(crate) door_auth: Option<Arc<crate::door_auth::DoorAuth>>,
594    /// Copied from [`StageRequest::system_prompt_overridden`] — the only record left that the
595    /// prompt in `inference` came from `--system-prompt` and not from the manifest. Passed to
596    /// `TraceWriter::open`, which turns it into `session_start.system_prompt_source`.
597    pub(crate) system_prompt_overridden: bool,
598    pub(crate) context: Option<ContextConfig>,
599    /// Copied from [`StageRequest::context_id`] and already validated. Read by `launch_session`,
600    /// which uses it in place of a freshly minted id for every `task.md` task.
601    pub(crate) context_id: Option<String>,
602    /// Copied from [`StageRequest::resume`] and already checked. Read by `launch_session`, which
603    /// turns it into `session_start.resumed_from` and the agent loop's record-load override.
604    pub(crate) resume: Option<ResumeRequest>,
605    /// Copied from [`StageRequest::forget_session`] and already checked against the transport.
606    /// Read by `launch_session` as a one-shot: the launch's first task carries the forget, and no
607    /// later task of the same launch does.
608    pub(crate) forget_session: bool,
609    pub(crate) engine: Engine,
610    /// The compiled-form cache handle built for [`Self::engine`] and the capsule's writable root.
611    /// A mid-session pull compiles through it, so a pulled component is stored and
612    /// looked up under the same name a staged one is.
613    pub(crate) compiled_forms: crate::compiled_forms::CompiledForms,
614    /// `None` for manifest-only agent capsules; `Some` for script capsules with a WASM component.
615    pub(crate) capsule_component: Option<Component>,
616    pub(crate) tool_components: HashMap<String, Component>,
617    /// What each native tool installed at staging needs to start, keyed by tool name. Derived
618    /// from the image the runtime wrote; see [`crate::sandbox::NativeEntrypoint`].
619    pub(crate) native_entrypoints: HashMap<String, crate::sandbox::NativeEntrypoint>,
620    /// The process driver, for a `transport: process` session that named one. `None` on every
621    /// other transport.
622    pub(crate) process_driver: Option<Arc<StagedProcessDriver>>,
623    /// Per-artifact narrowing for the tool/driver dispatch path, keyed by artifact name and
624    /// lowered at staging time from the operator's own manifest entries. Holds an entry only
625    /// for artifacts that actually declared a `capabilities:` block — a name absent from this
626    /// map (the overwhelmingly common case) runs on the full capsule ceiling, exactly as
627    /// before per-artifact narrowing existed.
628    pub(crate) artifact_grants: HashMap<String, ToolCapabilityGrant>,
629    pub(crate) hook_components: Vec<StagedHookArtifact>,
630    pub(crate) allowlisted_tools: HashSet<String>,
631    pub(crate) capability_policy: CapabilityPolicy,
632    pub(crate) otel_endpoint: Option<String>,
633    pub(crate) eval_config_json: Option<String>,
634    pub(crate) case_id: Option<String>,
635    pub(crate) dataset_id: Option<String>,
636    /// Resolved lifecycle config (manifest + override already applied).
637    pub(crate) lifecycle: LifecycleConfig,
638    /// How much of each turn's driver request this session's trace keeps (resolved from the
639    /// manifest's `trace:` block, or [`murmur_artifact::TraceCapture::default`] when it has
640    /// none).
641    pub(crate) trace_capture: murmur_artifact::TraceCapture,
642    /// What bounds this workdir's session directories, from the manifest's `trace.retain` block.
643    /// `None` — the overwhelmingly common case — prunes nothing, ever.
644    pub(crate) trace_retain: Option<murmur_artifact::TraceRetainConfig>,
645    /// Address the HTTP server is bound to (copied from StageRequest::bind_addr).
646    pub(crate) bind_addr: String,
647    /// Internal port from the manifest (copied from StageRequest::internal_port).
648    pub(crate) internal_port: Option<u16>,
649    /// Floor this session was staged against (copied from
650    /// StageRequest::declared_containment_floor).
651    pub(crate) declared_containment_floor: murmur_artifact::ContainmentClass,
652    /// The complete effective grant set this session was staged with — the same report
653    /// `mur run --explain-scope --json` prints, built by `containment::scope_report_for_tier`
654    /// from this session's own policy, declared floor and single host probe. Written verbatim to
655    /// `trace.jsonl`'s `session_start` as `effective_grants`, and the source of the
656    /// `containment_declared`/`containment_achieved`/`workdir_exec` fields alongside it, so the
657    /// summary and the full report cannot disagree.
658    ///
659    /// Replaces a former separate `achieved_containment` field: what the host actually provided
660    /// is `scope_report.achieved_containment`, and keeping a second copy beside it only created a
661    /// way for the two to drift.
662    pub(crate) scope_report: crate::containment::ScopeReport,
663    /// The single host reading this session was staged against, taken at the top of
664    /// `runtime::stage_session`. `launch_session` passes it to `sandbox::ShellEnforcement::resolve`
665    /// rather than taking a new one, so the mechanisms installed at launch are the ones
666    /// [`Self::scope_report`] already claims.
667    pub(crate) host_probe: crate::sandbox::HostProbe,
668    /// The declared read-only surface, lowered and validated by `stage_session` — a malformed
669    /// entry refuses the launch there rather than surfacing at the first call. Empty for every
670    /// capsule that declared no `capabilities.filesystem.read_only`.
671    pub(crate) protected_paths: crate::protected_paths::ProtectedPaths,
672    /// What each staged tool's own `input_schema` declared about where its inputs go, lowered by
673    /// `stage_session` from the manifests it wrote into `<runtime dir>/tools/`. Empty for a capsule
674    /// that declared no `read_only`, which reads no schema at all, and for one whose tools
675    /// annotated nothing.
676    pub(crate) tool_annotations: crate::tool_annotations::ToolAnnotationMap,
677    /// The declared read-only file surface, with its root already checked against this session's
678    /// accessible workdir by `stage_session` — a root that resolves outside it refuses the launch
679    /// rather than being served. `None` means no resource plane.
680    pub(crate) exports_files: Option<murmur_artifact::FileExport>,
681    /// The declared peer-handoff surface, with its root already checked against this session's
682    /// accessible workdir and its `max_ttl` already checked against `lifecycle.after_task` by
683    /// `stage_session`. `None` means no peer plane: nothing mints, and `/resources/peer/` answers
684    /// `no_peer_plane`.
685    pub(crate) exports_peer_files: Option<murmur_artifact::PeerFilesExport>,
686    /// Whether the door serves a task a peer capsule's runtime sends, read from the manifest's
687    /// own `exports.peer_tasks` by [`murmur_artifact::Exports::accepts_peer_tasks`]. `false`
688    /// answers every peer-origin request on the door with `403 peer_not_accepted`.
689    pub(crate) accepts_peer_tasks: bool,
690    /// Registry used to resolve this session's artifacts, retained so a pull can
691    /// resolve additional artifacts at runtime after staging has completed.
692    pub(crate) registry: Arc<dyn Registry>,
693    /// Copied from [`StageRequest::source_supply`]: where a runtime pull the stores cannot answer
694    /// is fetched from. `None` unless the capsule declared `capabilities.install.from: [stores,
695    /// sources]` and the launcher supplied one.
696    pub(crate) source_supply: Option<Arc<dyn crate::artifact_supply::SourceSupply>>,
697    /// Keeps this session's epoch ticker running: without it no epoch deadline set on any
698    /// store built from `engine` can ever fire. Held here (rather than detached) so ticking
699    /// stops when the session's `StagedSession` drops. `launch_session` moves the other
700    /// fields out one by one, which leaves this one in place until the session returns.
701    pub(crate) _epoch_ticker: EpochTicker,
702    /// The credential this session presents when it asks `mur-roost` to spawn a capsule.
703    ///
704    /// `None` for every session that cannot delegate, which is nearly all of them. Set by the
705    /// caller between `stage_session` and `launch_session` rather than carried in
706    /// [`StageRequest`]: the credential names a session id, and `stage_session` is what mints one,
707    /// so it cannot exist before staging returns.
708    pub(crate) spawn_credential: Option<SpawnCredential>,
709    /// Copied from [`StageRequest::spawn_grant`]. Read by `launch_session`, which presents it at
710    /// `POST /register` and never again — an approval covers one launch.
711    pub(crate) spawn_grant: Option<SpawnApproval>,
712    /// The handle the spawning capsule's launcher injected, read once per process at staging.
713    ///
714    /// `None` for every capsule nobody delegated. Its `session_id` and `delegation_id` become
715    /// `session_start.spawned_by` and `session_start.delegation_id`; its `report_to` — present
716    /// only for a parent that wants a completion — is what `launch_session`'s reporting guard
717    /// posts to. Read here rather than at each of those two points so one process reads
718    /// `MURMUR_SPAWNER` once and both readers see the same value.
719    pub(crate) spawner: Option<crate::delegation::SpawnerHandle>,
720    /// Copied from [`StageRequest::formation_id`]. Hooks see it as `MURMUR_FORMATION_ID` and the
721    /// delegation plane hands it to every child this session spawns.
722    pub(crate) formation_id: Option<FormationId>,
723    /// Copied from [`StageRequest::formation_member`].
724    pub(crate) formation_member: Option<Arc<FormationMember>>,
725    /// This member's formation lifeline, attached after staging by
726    /// [`StagedSession::attach_formation_lifeline`]. A process property rather than a staged
727    /// one, so it never travels on [`StageRequest`].
728    #[cfg(unix)]
729    pub(crate) formation_lifeline: Option<crate::lifeline::FormationLifeline>,
730    /// This delegated child's spawner lifeline, attached after staging by
731    /// [`StagedSession::attach_spawner_lifeline`]. A process property on the same terms as
732    /// [`Self::formation_lifeline`].
733    #[cfg(unix)]
734    pub(crate) spawner_lifeline: Option<crate::lifeline::SpawnerLifeline>,
735}
736
737impl StagedSession {
738    /// Writes `bytes` as the task input, `task.md` in the runtime directory, which the capsule's
739    /// commands can read and not change. A launch with one finds nothing to import from the
740    /// workdir.
741    pub fn write_task_input(&self, bytes: &[u8]) -> Result<(), crate::workdir_fs::WorkdirError> {
742        self.runtime_root.write_file(
743            crate::runtime::TASK_INPUT_FILE,
744            bytes,
745            crate::workdir_fs::DEFAULT_FILE_MODE,
746        )
747    }
748
749    /// Writes `bytes` as `rel` in the accessible workdir before launch, the folder the capsule's
750    /// tools see as their working directory. A link at `rel` is refused rather than written
751    /// through, and missing parent directories are created.
752    pub fn write_workdir_file(
753        &self,
754        rel: &str,
755        bytes: &[u8],
756    ) -> Result<(), crate::workdir_fs::WorkdirError> {
757        self.accessible_root
758            .write_file(rel, bytes, crate::workdir_fs::DEFAULT_FILE_MODE)
759    }
760
761    /// Hands this session the credential it will present to the spawning daemon.
762    pub fn set_spawn_credential(&mut self, credential: SpawnCredential) {
763        self.spawn_credential = Some(credential);
764    }
765
766    /// The credential this session presents, if it was granted one.
767    pub fn spawn_credential(&self) -> Option<&SpawnCredential> {
768        self.spawn_credential.as_ref()
769    }
770
771    /// The grant set this session was staged with, as written to the trace.
772    pub fn scope_report(&self) -> &crate::containment::ScopeReport {
773        &self.scope_report
774    }
775
776    /// Every door token this session minted, operator first, then the declared credentials by
777    /// name. Empty for a capsule that declares no `network.authentication`.
778    pub fn door_tokens(&self) -> Vec<(String, crate::door_auth::DoorToken)> {
779        self.door_auth
780            .as_ref()
781            .map(|auth| auth.tokens().to_vec())
782            .unwrap_or_default()
783    }
784
785    /// The formation this session is a member of, or `None` for a session nobody placed in one.
786    pub fn formation_id(&self) -> Option<&FormationId> {
787        self.formation_id.as_ref()
788    }
789
790    /// Hand this session the lifeline its process was launched with. Honoured only by
791    /// [`crate::launch_session_handling_sigterm`] on an agent capsule: every other launch of a
792    /// session holding one is refused with [`crate::RuntimeError::FormationLifelineUnreadable`]
793    /// before anything is instantiated.
794    #[cfg(unix)]
795    pub fn attach_formation_lifeline(&mut self, lifeline: crate::lifeline::FormationLifeline) {
796        self.formation_lifeline = Some(lifeline);
797    }
798
799    /// Hand this session the spawner lifeline its process was launched with. Honoured only by
800    /// [`crate::launch_session_handling_sigterm`], for an agent and a script capsule alike: every
801    /// other launch of a session holding one is refused with
802    /// [`crate::RuntimeError::SpawnerLifelineUnreadable`] before anything is instantiated.
803    #[cfg(unix)]
804    pub fn attach_spawner_lifeline(&mut self, lifeline: crate::lifeline::SpawnerLifeline) {
805        self.spawner_lifeline = Some(lifeline);
806    }
807}
808
809#[derive(Debug, Clone, PartialEq, Eq)]
810pub struct LaunchResult {
811    pub session_id: String,
812    pub workdir: PathBuf,
813    /// The session's records directory, where its trace is, kept after the session.
814    pub records_dir: PathBuf,
815    /// How a launch that reports no error ended.
816    pub ending: LaunchEnding,
817}
818
819/// How a launch that reports no error ended. A launch whose task did not complete for any other
820/// reason is a [`crate::RuntimeError::TaskDidNotComplete`], not an ending.
821#[derive(Debug, Clone, Copy, PartialEq, Eq)]
822pub enum LaunchEnding {
823    /// Every task the launch ran completed, or it ran none: `session_end.exit_status` `ok`.
824    Completed,
825    /// The session's formation ended while it was running a task, and the wind-down that followed
826    /// cancelled that task: `session_end.exit_status` `formation_ended`.
827    FormationEnded,
828}
829
830impl LaunchEnding {
831    /// The `exit_status` `session_end` and `on-session-end` carry for this ending.
832    pub fn as_str(self) -> &'static str {
833        match self {
834            Self::Completed => "ok",
835            Self::FormationEnded => "formation_ended",
836        }
837    }
838}
839
840pub fn capability_policy_from_runtime_manifest(
841    manifest: &murmur_artifact::RuntimeManifest,
842) -> CapabilityPolicy {
843    let caps = manifest.capabilities.as_ref();
844    let network_allow = caps
845        .and_then(|c| c.network.as_ref())
846        .map(|network| network.allow.clone())
847        .unwrap_or_default();
848    // Absent `capabilities.peer_fetch` block means denied, on the same terms — and separately
849    // from `network.allow`, which this deliberately does not read.
850    let peer_fetch_allow = caps
851        .and_then(|c| c.peer_fetch.as_ref())
852        .map(|peer_fetch| peer_fetch.allow.clone())
853        .unwrap_or_default();
854
855    // Absent `capabilities.network` block, or absent key within it, both mean denied.
856    let unix_sockets_allowed = caps
857        .and_then(|c| c.network.as_ref())
858        .is_some_and(|network| network.unix_sockets);
859
860    // Absent `capabilities.plan` block, or `submit: false` within it, both mean denied.
861    let plan_submit = caps
862        .and_then(|c| c.plan.as_ref())
863        .is_some_and(|plan| plan.submit);
864
865    // Absent `capabilities.install` block means both lists are empty, which is deny.
866    let install = caps.and_then(|c| c.install.as_ref());
867    let install_skill = install.map(|i| i.skill.clone()).unwrap_or_default();
868    let install_tool = install.map(|i| i.tool.clone()).unwrap_or_default();
869    let install_from_sources = install.is_some_and(|i| i.from.sources());
870
871    // Recorded, never applied: see `CapabilityPolicy::state_declared`.
872    let state_declared = caps.is_some_and(|c| c.state.is_some());
873    let conversation_declared = caps.is_some_and(|c| c.conversation.is_some());
874
875    let filesystem_scope = caps
876        .and_then(|c| c.filesystem.as_ref())
877        .and_then(|filesystem| filesystem.scope.clone());
878    // Absent `capabilities.filesystem` block, or absent key within it, both mean denied — the same
879    // shape as `unix_sockets_allowed` above, for the same reason: the widening has to be declared.
880    let workdir_exec_allowed = caps
881        .and_then(|c| c.filesystem.as_ref())
882        .is_some_and(|filesystem| filesystem.workdir_exec);
883    // Absent block, absent key and an empty list are one declaration: nothing is protected.
884    let read_only_paths = caps
885        .and_then(|c| c.filesystem.as_ref())
886        .map(|filesystem| filesystem.read_only.clone())
887        .unwrap_or_default();
888
889    let shell_allow = caps
890        .and_then(|c| c.shell.as_ref())
891        .map(|shell| shell.allow.clone())
892        .unwrap_or_default();
893    let shell_strip_env = caps
894        .and_then(|c| c.shell.as_ref())
895        .and_then(|shell| shell.strip_env.clone())
896        .unwrap_or_default();
897    let shell_baseline_env = caps
898        .and_then(|c| c.shell.as_ref())
899        .and_then(|shell| shell.baseline_env.clone())
900        .unwrap_or_default();
901    let shell_interpreter_runtime = caps
902        .and_then(|c| c.shell.as_ref())
903        .map(|shell| shell.interpreter_runtime.clone())
904        .unwrap_or_default();
905    let shell_staged_runtime = caps
906        .and_then(|c| c.shell.as_ref())
907        .map(|shell| shell.staged_runtime.clone())
908        .unwrap_or_default();
909
910    let spawn_allow = caps
911        .and_then(|c| c.spawn.as_ref())
912        .map(|spawn| spawn.allow.clone())
913        .unwrap_or_default();
914
915    let env_allow = caps
916        .and_then(|c| c.env.as_ref())
917        .map(|env| env.allow.clone())
918        .unwrap_or_default();
919
920    let limits = ExecutionLimits::resolve(caps.and_then(|c| c.limits.as_ref()));
921    let declared_deadline_seconds = caps
922        .and_then(|c| c.limits.as_ref())
923        .and_then(|l| l.deadline_seconds);
924
925    let resources = crate::resources::resolve(caps.and_then(|c| c.resources.as_ref()));
926
927    CapabilityPolicy {
928        network_allow,
929        peer_fetch_allow,
930        unix_sockets_allowed,
931        filesystem_scope,
932        workdir_exec_allowed,
933        read_only_paths,
934        shell_allow,
935        spawn_allow,
936        shell_strip_env,
937        shell_baseline_env,
938        shell_interpreter_runtime,
939        shell_staged_runtime,
940        env_allow,
941        limits,
942        resources,
943        containment_floor: caps.and_then(|c| c.containment).unwrap_or_default(),
944        state_declared,
945        conversation_declared,
946        plan_submit,
947        install_skill,
948        install_tool,
949        install_from_sources,
950        declared_deadline_seconds,
951    }
952}
953
954#[cfg(test)]
955mod tests {
956    use super::*;
957
958    fn policy_for(manifest_yaml: &str) -> CapabilityPolicy {
959        let manifest = murmur_artifact::RuntimeManifest::from_yaml_str(manifest_yaml)
960            .expect("manifest fixture must parse");
961        capability_policy_from_runtime_manifest(&manifest)
962    }
963
964    /// `read_only` reaches the policy in declaration order, trimmed, with empty entries already
965    /// dropped by the manifest parser — and a capsule that declares none gets an empty list, which
966    /// is what makes the dispatch check free for it.
967    #[test]
968    fn read_only_paths_are_carried_through_and_default_to_empty() {
969        let declared = policy_for(
970            r#"
971name: cap
972version: 0.1.0
973capabilities:
974  filesystem:
975    read_only:
976      - tests
977      - "  bench/fixtures  "
978      - "   "
979"#,
980        );
981        assert_eq!(declared.read_only_paths, vec!["tests", "bench/fixtures"]);
982
983        let silent = policy_for(
984            "name: cap
985version: 0.1.0
986",
987        );
988        assert!(silent.read_only_paths.is_empty());
989
990        let no_key = policy_for(
991            r#"
992name: cap
993version: 0.1.0
994capabilities:
995  filesystem:
996    scope: work
997"#,
998        );
999        assert!(no_key.read_only_paths.is_empty());
1000    }
1001
1002    /// A manifest that sets no deadline gives hook calls the hook-specific default while the
1003    /// capsule's own guests keep the capsule-wide one — one manifest, two budgets.
1004    #[test]
1005    fn a_silent_manifest_gives_hook_calls_the_lower_deadline() {
1006        let policy = policy_for(
1007            r#"
1008name: cap
1009version: 0.1.0
1010artifacts: []
1011"#,
1012        );
1013
1014        assert_eq!(
1015            policy.limits.deadline_seconds,
1016            crate::limits::DEFAULT_DEADLINE_SECONDS
1017        );
1018        assert_eq!(
1019            policy.hook_limits().deadline_seconds,
1020            crate::limits::HOOK_DEFAULT_DEADLINE_SECONDS
1021        );
1022        // The default policy a hand-built fixture gets must agree with the silent-manifest one.
1023        assert_eq!(
1024            CapabilityPolicy::default().hook_limits().deadline_seconds,
1025            crate::limits::HOOK_DEFAULT_DEADLINE_SECONDS
1026        );
1027    }
1028
1029    /// An explicit `deadline_seconds` applies to every guest, hooks included — the hook
1030    /// default only fills a silence.
1031    #[test]
1032    fn an_explicit_deadline_applies_to_hook_calls_too() {
1033        let policy = policy_for(
1034            r#"
1035name: cap
1036version: 0.1.0
1037artifacts: []
1038capabilities:
1039  limits:
1040    deadline_seconds: 120
1041"#,
1042        );
1043
1044        assert_eq!(policy.declared_deadline_seconds, Some(120));
1045        assert_eq!(policy.limits.deadline_seconds, 120);
1046        assert_eq!(policy.hook_limits().deadline_seconds, 120);
1047    }
1048
1049    /// `capabilities.shell.staged_runtime` lowers onto the policy verbatim — binary, source path
1050    /// and pin all survive, since the pin is what a human later compares across two hosts.
1051    #[test]
1052    fn staged_runtime_grants_lower_onto_the_policy() {
1053        let policy = policy_for(
1054            r#"
1055name: cap
1056version: 0.1.0
1057artifacts: []
1058capabilities:
1059  containment: sealed
1060  shell:
1061    allow:
1062      - python3
1063    staged_runtime:
1064      - binary: python3
1065        source_path: /opt/testbed/conda/envs/django__django
1066        pin: conda-4.10.3/python-3.9.19
1067"#,
1068        );
1069
1070        assert_eq!(
1071            policy.shell_staged_runtime,
1072            vec![murmur_artifact::StagedRuntimeGrant {
1073                binary: "python3".to_string(),
1074                source_path: "/opt/testbed/conda/envs/django__django".to_string(),
1075                pin: "conda-4.10.3/python-3.9.19".to_string(),
1076            }]
1077        );
1078        // The two mechanisms stay separate all the way down: lowering one must not populate the
1079        // other.
1080        assert!(policy.shell_interpreter_runtime.is_empty());
1081    }
1082
1083    /// A shell block that declares no staged runtime lowers to an empty list, not to a default
1084    /// grant of any kind.
1085    #[test]
1086    fn absent_staged_runtime_lowers_to_empty() {
1087        let policy = policy_for(
1088            r#"
1089name: cap
1090version: 0.1.0
1091artifacts: []
1092capabilities:
1093  shell:
1094    allow:
1095      - bash
1096"#,
1097        );
1098
1099        assert!(policy.shell_staged_runtime.is_empty());
1100    }
1101
1102    /// The default every existing manifest gets. Three separate "nothing was declared" shapes —
1103    /// no `capabilities:` at all, no `filesystem:` within it, and a `filesystem:` that only sets
1104    /// `scope` — must all lower to denied, because each one is a real manifest in the wild and any
1105    /// of them silently keeping workdir `Execute` would reopen the rename-to-an-allowed-basename
1106    /// bypass this default exists to close.
1107    #[test]
1108    fn workdir_exec_denied_for_every_shape_of_undeclared() {
1109        for manifest_yaml in [
1110            r#"
1111name: cap
1112version: 0.1.0
1113artifacts: []
1114"#,
1115            r#"
1116name: cap
1117version: 0.1.0
1118artifacts: []
1119capabilities:
1120  network:
1121    allow:
1122      - https://api.anthropic.com
1123"#,
1124            r#"
1125name: cap
1126version: 0.1.0
1127artifacts: []
1128capabilities:
1129  filesystem:
1130    scope: workdir
1131"#,
1132        ] {
1133            let policy = policy_for(manifest_yaml);
1134            assert!(
1135                !policy.workdir_exec_allowed,
1136                "an undeclared workdir_exec must lower to denied: {manifest_yaml}"
1137            );
1138        }
1139    }
1140
1141    #[test]
1142    fn workdir_exec_denied_when_declared_false() {
1143        let policy = policy_for(
1144            r#"
1145name: cap
1146version: 0.1.0
1147artifacts: []
1148capabilities:
1149  filesystem:
1150    workdir_exec: false
1151"#,
1152        );
1153
1154        assert!(!policy.workdir_exec_allowed);
1155    }
1156
1157    #[test]
1158    fn workdir_exec_allowed_when_declared_true() {
1159        let policy = policy_for(
1160            r#"
1161name: cap
1162version: 0.1.0
1163artifacts: []
1164capabilities:
1165  filesystem:
1166    scope: workdir
1167    workdir_exec: true
1168"#,
1169        );
1170
1171        assert!(policy.workdir_exec_allowed);
1172        // The two filesystem keys stay independent: lowering one must not disturb the other.
1173        assert_eq!(policy.filesystem_scope.as_deref(), Some("workdir"));
1174    }
1175
1176    /// A manifest with no `capabilities:` block at all denies unix sockets — the field must not
1177    /// pick up any implicit widening from the "nothing declared" path.
1178    #[test]
1179    fn unix_sockets_denied_when_capabilities_block_is_absent() {
1180        let policy = policy_for(
1181            r#"
1182name: cap
1183version: 0.1.0
1184artifacts: []
1185"#,
1186        );
1187
1188        assert!(!policy.unix_sockets_allowed);
1189    }
1190
1191    /// A declared `network:` block that never mentions the key still denies.
1192    #[test]
1193    fn unix_sockets_denied_when_network_block_omits_the_key() {
1194        let policy = policy_for(
1195            r#"
1196name: cap
1197version: 0.1.0
1198artifacts: []
1199capabilities:
1200  network:
1201    allow:
1202      - https://api.anthropic.com
1203"#,
1204        );
1205
1206        assert!(!policy.unix_sockets_allowed);
1207        assert_eq!(
1208            policy.network_allow,
1209            vec!["https://api.anthropic.com".to_string()]
1210        );
1211    }
1212
1213    #[test]
1214    fn unix_sockets_denied_when_declared_false() {
1215        let policy = policy_for(
1216            r#"
1217name: cap
1218version: 0.1.0
1219artifacts: []
1220capabilities:
1221  network:
1222    unix_sockets: false
1223"#,
1224        );
1225
1226        assert!(!policy.unix_sockets_allowed);
1227    }
1228
1229    #[test]
1230    fn unix_sockets_allowed_when_declared_true() {
1231        let policy = policy_for(
1232            r#"
1233name: cap
1234version: 0.1.0
1235artifacts: []
1236capabilities:
1237  network:
1238    unix_sockets: true
1239"#,
1240        );
1241
1242        assert!(policy.unix_sockets_allowed);
1243    }
1244
1245    /// The opt-in is independent of the IP allowlist in both directions: a non-empty `allow`
1246    /// does not imply unix sockets, and `unix_sockets: true` does not imply any IP destination.
1247    #[test]
1248    fn unix_sockets_opt_in_is_independent_of_the_ip_allowlist() {
1249        let policy = policy_for(
1250            r#"
1251name: cap
1252version: 0.1.0
1253artifacts: []
1254capabilities:
1255  network:
1256    unix_sockets: true
1257    allow:
1258      - https://api.anthropic.com
1259"#,
1260        );
1261
1262        assert!(policy.unix_sockets_allowed);
1263        assert_eq!(
1264            policy.network_allow,
1265            vec!["https://api.anthropic.com".to_string()]
1266        );
1267    }
1268
1269    /// `CapabilityPolicy::default()` is what the sandbox tests and every `..Default::default()`
1270    /// call site start from; it must deny, not inherit whatever a future field ordering implies.
1271    #[test]
1272    fn default_capability_policy_denies_unix_sockets() {
1273        assert!(!CapabilityPolicy::default().unix_sockets_allowed);
1274    }
1275}