diff --git a/crates/sessions/docs/COMPOSITION.md b/crates/sessions/docs/COMPOSITION.md
index 1bd14ebd7b..e63c8097ad 100644
--- a/crates/sessions/docs/COMPOSITION.md
+++ b/crates/sessions/docs/COMPOSITION.md
@@ -42,14 +42,13 @@ pending item into one `ContributionResponse`, and the client
batches every verdict into one `ContributionVerdict`.
> **Status note.** The shared gate pipeline (`compose_contribution`,
-> with `gate_vars` + `gate_patches`) exists in `core::compose` and
-> drives Phase 1 today via `UserComposer::compose`. Phases 2–4 are
-> not yet wired: the daemon doesn't yet emit a `ContributionResponse`
-> for unresolved items, and the client doesn't yet have a Phase 3
-> handler that runs the gate to produce a `ContributionVerdict`.
-> `SessionComposer::compose` is a placeholder until those land. The
-> hooks-driven gate code is positioned to run on the client (from the
-> Phase 3 handler), not on the daemon.
+> with `gate_vars` + `gate_patches`) lives in `core::compose`. Phase
+> 1 runs it via `UserComposer::compose` and Phase 3 runs it via
+> `client::handler::handle_response`. Phases 2 and 4 (daemon-side
+> routing) are not yet wired: `SessionComposer::compose` errors with
+> `HookRequired` instead of batching pending items into a
+> `ContributionResponse`, and there is no `SubmitVerdict` handler
+> yet to apply verdicts and assemble the final `Composition`.
## Phases in detail
@@ -77,11 +76,22 @@ items the policy can't decide are collected as
### Phase 3 — Client gates the pending items
-The client receives the `ContributionResponse` and runs the gate
-pipeline over the pending batch: resolves any inherit vars, expands
-patch sources, applies the user policy, and prompts via local
-`PolicyHooks` when needed. Result: one `ContributionVerdict`,
-shipped back to the daemon via `SubmitVerdict`.
+The client receives the `ContributionResponse` and runs
+`client::handler::handle_response` over the pending batch: resolves
+any `Inherit`/`InheritWithDefault` vars against the client env
+(`ResolvedVar::resolve_with`), expands patch sources against the
+already-gated vars from Phase 1 plus anything approved in this
+batch, applies the user policy, and prompts via local `PolicyHooks`
+when the policy can't decide. Result: one `ContributionVerdict`,
+shipped back to the daemon via `SubmitVerdict`. Lifecycle hooks in
+the response are dropped — there's no per-hook policy, so the
+verdict schema has no slot for them; the daemon installs them as
+declared.
+
+**Verdict ordering.** Per-domain verdicts are not in pending-item
+order: items the policy auto-decides are emitted in input order,
+items routed through the hook land at the end. The daemon must
+correlate by `id`, not slice position.
### Phase 4 — Daemon assembles and hands off
@@ -99,10 +109,14 @@ pass through unchanged.
## The shared client-side gate pipeline
-The same pipeline runs in two distinct phases — once in Phase 1 to
-compose loadouts, once in Phase 3 to generate verdicts on the
-daemon's pending items. Patches add a filesystem walk up front;
-vars don't.
+The two phases share `Policy::check`, the hook prompt protocol, and
+the `UseRule` re-check. They differ in what happens once an item is
+`Decided`: Phase 1 (`gate_vars`/`gate_patches` in `core::compose`)
+treats `Denied` as fatal and silently drops `Ignored`; Phase 3
+(`gate_pending_vars`/`gate_pending_patches` in `client::handler`)
+emits a per-item `WireVarVerdict`/`WirePatchVerdict` for every
+outcome — the wire schema requires one verdict per pending id.
+Patches add a filesystem walk up front; vars don't.
```mermaid
flowchart TD
@@ -120,7 +134,7 @@ flowchart TD
P1 -->|NeedsApproval| P2
P1 -->|decided items| P3
- P1 -.->|"policy.deny matched (Pass 1)"| DE
+ P1 -.->|"policy.deny matched (Phase 1 only;
Phase 3 emits a per-item Denied verdict)"| DE
P2 -->|"Decided{decisions, updated_policy}
install updated_policy if Some"| P3
P2 -.->|Abort| AE
@@ -140,12 +154,16 @@ Below, in numbered prose:
(the raw policy is preserved for round-trip).
2. **Pass 1 — Categorize.** Each item runs through `Policy::check`,
which steps through:
- - `ignore` matches? → `Ignored`; drop silently.
- - `deny` matches? → `Denied`; surface `ComposeError::Denied`
- regardless of origin.
+ - `ignore` matches? → `Ignored`. Phase 1 drops silently;
+ Phase 3 emits an `Ignored` verdict.
+ - `deny` matches? → `Denied`, regardless of origin. Phase 1
+ surfaces `ComposeError::Denied`; Phase 3 emits a `Denied`
+ verdict.
- `Source::UserLoadout`? → `Allowed` (auto-pass the allow step;
the user doesn't need to allow-list their own loadout).
- - `allow` matches? → `Allowed`; push.
+ - `allow` matches? → `Allowed`. Phase 1 pushes; Phase 3 emits
+ an `Approved` verdict and adds the var to the in-batch
+ expansion context.
- Otherwise → `NeedsApproval`; defer to Pass 2.
3. **Pass 2 — Prompt.** Call `hooks.on_*_unapproved(policy_copy,
&[Unapproved])`. The hook returns either `Abort` (→
@@ -201,9 +219,14 @@ overload:
`Contribution::merge`. There is no public way to push raw
primitives — every item must carry a known `Source`.
- **Env lookup lives on the composer.** Both composers default to
- `std::env::var`; `with_env(...)` pins a custom closure for tests.
- Each `add` threads the lookup into `contribute`. The patch gate
- reads `HOME` via the same closure as tilde fallback.
+ `std::env::var` for the `contribute()` step and accept
+ `with_env(...)` to pin a custom closure for tests. The
+ difference is in patch-source `~` expansion: `UserComposer`
+ passes its `env("HOME")` as the tilde fallback, but
+ `SessionComposer` passes `None` — daemon-side `~/...` patterns
+ must resolve against a `HOME` carried in the client's wire
+ vars, never against the daemon's process env. Phase 3's
+ `handle_response` reads `HOME` from the client env it was given.
- **Source travels end-to-end.** Every primitive carries its `Source`
through every gate and into the final `Composition`, so downstream
layers (audit, inspection commands, error reporting) can attribute
@@ -221,7 +244,9 @@ overload:
decidable: ignored, denied, or auto-allowed).
- **Patches fan out before policy check.** A single `Patch` with a
glob source becomes N `PatchFile`s; each is checked independently.
- A `Denied` on any one file kills the whole composition.
+ In Phase 1 a `Denied` on any one file aborts the composition;
+ in Phase 3 each file gets its own `WirePatchVerdict` so a Denied
+ doesn't abort, it just rejects that file.
- **Hook gets narrow policy by value.** The gate hands the hook an
owned `VarsPolicy` or `PatchPolicy` — never `&mut UserPolicy`. To
add a rule, the hook returns the modified copy in
@@ -233,11 +258,14 @@ overload:
made. The daemon doesn't re-gate them.
- **Source `~` is expanded at gate time; dest has no `~` to expand.**
Patch source `FileSet` patterns and `PatchPolicy` patterns expand
- `~` against a resolved `HOME` — loadout-declared session var first,
- else the composer's `env("HOME")`. `PatchDest` is always relative
- to the sandbox user's home; `~` and absolute paths are rejected at
- construction. Patterns retain their `~` form in returned policies,
- so save/load is lossless.
+ `~` against a resolved `HOME` — a session var named `HOME` first,
+ else the client-side fallback (`UserComposer`'s `env("HOME")` in
+ Phase 1, `handle_response`'s `env("HOME")` in Phase 3). The
+ `SessionComposer` (Phase 2/4 daemon side) has no fallback —
+ daemon `~/...` patterns must resolve from the client's wire vars.
+ `PatchDest` is always relative to the sandbox user's home; `~`
+ and absolute paths are rejected at construction. Patterns retain
+ their `~` form in returned policies, so save/load is lossless.
- **`Contribution::merge` is pure aggregation today.** Two
contributors pushing the same var name both survive into the
`Composition`. Conflict resolution (precedence, dedup,
@@ -248,5 +276,12 @@ overload:
- **Terminating failure modes:** `Denied` (explicit policy reject),
`Aborted` (hook returned `Abort`), `HookContract` (application
bug — wrong decision count, or `UseRule` to a still-undecidable
- item), `PatchWalk` (IO-level filesystem walk failures),
- `Expansion` (malformed `$VAR` / `~` pattern, or undefined var).
+ item), `HookRequired` (non-user-origin item reached the daemon
+ composer with no hook to prompt — placeholder until Phase 2
+ routing lands), `PatchWalk` (IO-level filesystem walk failures),
+ `Expansion` (malformed `$VAR` / `~` pattern, or undefined var),
+ `VarResolution` (a Phase 3 pending `Inherit` var couldn't be
+ resolved against the client env), `InvalidPendingPatchDest` (a
+ Phase 3 pending patch destination violates `PatchDest`
+ invariants), `InvalidWireItem` (a wire-form item failed
+ conversion back to its domain type).
diff --git a/crates/sessions/src/client/handler.rs b/crates/sessions/src/client/handler.rs
new file mode 100644
index 0000000000..bdff98cf46
--- /dev/null
+++ b/crates/sessions/src/client/handler.rs
@@ -0,0 +1,406 @@
+//! Client-side handler for the daemon's [`ContributionResponse`].
+//!
+//! Sits between the initial [`UserComposer`] phase and the daemon's
+//! final assembly (see `docs/COMPOSITION.md` for the full picture):
+//! the daemon has emitted pending items the client must gate against
+//! the user's policy. This module turns the pending batch into a
+//! [`ContributionVerdict`] to ship back via `SubmitVerdict`.
+//!
+//! For each pending var: build a [`PendingVar`] (resolving the spec
+//! against the env closure), then run the user's [`VarsPolicy`]
+//! check. Approved vars are added to the var-expansion context for
+//! subsequent patch processing in the same call.
+//!
+//! For each pending patch: expand the source pattern against the
+//! gated vars (from the loadout phase) combined with this batch's
+//! newly approved pending vars, walk the filesystem, and check each
+//! matched file against the user's [`PatchPolicy`]. One
+//! [`WirePatchVerdict`] is emitted per matched file.
+//!
+//! Lifecycle hooks in the response are dropped — there is no
+//! per-hook policy, so the verdict schema has no slot for them. The
+//! daemon will install them as the source declared. To reject a
+//! hook the user aborts the whole session.
+//!
+//! **Verdict ordering.** Per-domain verdicts are *not* emitted in
+//! the order pending items arrived: items the policy can auto-decide
+//! are emitted in input order, but anything routed through the hook
+//! lands at the end. The daemon must correlate by `id`, not slice
+//! position.
+//!
+//! [`UserComposer`]: crate::client::composer::UserComposer
+//! [`PendingVar`]: crate::core::compose::PendingVar
+
+use crate::core::compose::{
+ ComposeError, ComposeOptions, HookDomain, PendingPatchFile, PendingVar, SessionVar,
+ expand_patch_sources,
+};
+use crate::core::decision::{CheckOutcome, Decision, ItemDecision};
+use crate::core::enumerate::enumerate_patch_files;
+use crate::core::hooks::{PolicyHooks, Unapproved};
+use crate::core::policy::{ExpandedPatchPolicy, PatchPolicy, UserPolicy, VarsPolicy};
+use crate::core::primitives::{Patch, PatchDest};
+use crate::core::source::{Provenanced, ProvenancedPatch, Source};
+use crate::wire::policy::{WirePatchVerdict, WireVarVerdict};
+use crate::wire::primitives::{WirePendingPatch, WirePendingVar};
+use crate::wire::request::{ContributionResponse, ContributionVerdict};
+
+/// Gate the daemon's pending items against `policy`, prompting via
+/// `hooks` for anything the policy can't auto-decide, and emit a
+/// [`ContributionVerdict`] to ship back.
+///
+/// `gated_vars` is the client's already-gated var set from the
+/// loadout phase; pending patch sources reference both those and any
+/// vars approved in this same response.
+///
+/// # Errors
+///
+/// See [`ComposeError`]. In particular:
+/// - [`ComposeError::Aborted`] when a hook returns
+/// [`HookResult::Abort`]; the caller should send a `SessionAbort`
+/// RPC with [`AbortReason::UserCancelled`](crate::wire::request::AbortReason::UserCancelled).
+/// - [`ComposeError::VarResolution`] when an `Inherit`-shaped
+/// pending var can't be resolved against the env.
+/// - [`ComposeError::Expansion`] / [`ComposeError::PatchWalk`] for
+/// pattern / filesystem failures.
+/// - [`ComposeError::InvalidPendingPatchDest`] when a pending
+/// patch's destination violates `PatchDest` invariants.
+/// - [`ComposeError::HookContract`] when the hook returns
+/// ill-formed decisions.
+///
+/// [`HookResult::Abort`]: crate::core::hooks::HookResult::Abort
+pub fn handle_response(
+ response: ContributionResponse,
+ gated_vars: &[SessionVar],
+ policy: UserPolicy,
+ hooks: &dyn PolicyHooks,
+ options: ComposeOptions,
+ env: &dyn Fn(&str) -> Result,
+) -> Result {
+ let session_id = response.session_id;
+ let (vars_policy, patches_policy) = policy.into_parts();
+
+ let var_out = gate_pending_vars(response.vars, vars_policy, hooks, env)?;
+
+ let combined_vars: Vec =
+ gated_vars.iter().cloned().chain(var_out.approved).collect();
+
+ let patch_verdicts = gate_pending_patches(
+ response.patches,
+ patches_policy,
+ hooks,
+ options,
+ &combined_vars,
+ env,
+ )?;
+
+ Ok(ContributionVerdict {
+ session_id,
+ vars: var_out.verdicts,
+ patches: patch_verdicts,
+ })
+}
+
+// =====================================================================
+// Vars
+// =====================================================================
+
+/// Two-output result of processing a single pending var: the wire
+/// verdict the daemon receives, and an optional [`SessionVar`] to
+/// chain into patch expansion (only present when the decision was
+/// `Allowed`).
+struct VarOutcome {
+ verdict: WireVarVerdict,
+ approval: Option,
+}
+
+/// Output of [`gate_pending_vars`]: the wire-form verdicts and the
+/// approved vars to feed into patch expansion.
+struct VarGateOutput {
+ verdicts: Vec,
+ approved: Vec,
+}
+
+impl VarGateOutput {
+ fn with_capacity(n: usize) -> Self {
+ Self {
+ verdicts: Vec::with_capacity(n),
+ approved: Vec::new(),
+ }
+ }
+
+ fn push(&mut self, outcome: VarOutcome) {
+ if let Some(sv) = outcome.approval {
+ self.approved.push(sv);
+ }
+ self.verdicts.push(outcome.verdict);
+ }
+}
+
+fn gate_pending_vars(
+ pending: Vec,
+ policy: VarsPolicy,
+ hooks: &dyn PolicyHooks,
+ env: &dyn Fn(&str) -> Result,
+) -> Result {
+ // Resolve every wire item to its domain form. Fails fast on the
+ // first env-lookup miss for an `Inherit` spec.
+ let pending: Vec = pending
+ .into_iter()
+ .map(|w| PendingVar::from_wire(w, env))
+ .collect::>()?;
+
+ // Pass 1: classify. Items the policy can auto-decide flow into
+ // `out`; items that need approval queue up for the hook.
+ let (mut out, unapproved) = partition_var_classifications(
+ pending.len(),
+ pending.into_iter().map(|p| classify_var(&policy, p)),
+ );
+ if unapproved.is_empty() {
+ return Ok(out);
+ }
+
+ // Pass 2: prompt.
+ let view: Vec> = unapproved
+ .iter()
+ .map(|p| Unapproved {
+ item: p.name(),
+ source: p.provenanced().source(),
+ })
+ .collect();
+ let (decisions, policy) = crate::core::compose::prompt_var_hook(hooks, policy, &view)?;
+
+ // Pass 3: apply the hook's decisions. UseRule re-routes back
+ // through the classifier, which can't legally re-produce
+ // `Pending` (the hook is the last word).
+ for (p, d) in unapproved.into_iter().zip(decisions) {
+ out.push(apply_var_decision(&policy, p, d)?);
+ }
+ Ok(out)
+}
+
+/// Drain `classifications` into the finished `VarGateOutput` and a
+/// queue of items that still need a hook decision.
+fn partition_var_classifications(
+ capacity: usize,
+ classifications: impl IntoIterator- ,
+) -> (VarGateOutput, Vec) {
+ let mut out = VarGateOutput::with_capacity(capacity);
+ let mut unapproved = Vec::new();
+ for c in classifications {
+ match c {
+ VarClassification::Decided(outcome) => out.push(outcome),
+ VarClassification::Pending(p) => unapproved.push(p),
+ }
+ }
+ (out, unapproved)
+}
+
+/// Apply a hook's `ItemDecision` to a single pending var. `AllowOnce`
+/// produces an outcome directly; `UseRule` routes back through the
+/// classifier and treats a still-undecidable result as a hook
+/// contract violation.
+fn apply_var_decision(
+ policy: &VarsPolicy,
+ pending: PendingVar,
+ decision: ItemDecision,
+) -> Result {
+ match decision {
+ ItemDecision::AllowOnce => {
+ let approval = SessionVar::from_provenanced(pending.provenanced().clone());
+ Ok(VarOutcome {
+ verdict: pending.into_approved_verdict(),
+ approval: Some(approval),
+ })
+ }
+ ItemDecision::UseRule => match classify_var(policy, pending) {
+ VarClassification::Decided(outcome) => Ok(outcome),
+ VarClassification::Pending(p) => Err(ComposeError::use_rule_undecided(
+ HookDomain::Var,
+ format!("variable `{}`", p.name()),
+ )),
+ },
+ }
+}
+
+/// Result of running a single pending var through the policy.
+enum VarClassification {
+ /// Policy reached a verdict.
+ Decided(VarOutcome),
+ /// Policy couldn't decide; pending is returned for the hook batch.
+ Pending(PendingVar),
+}
+
+fn classify_var(policy: &VarsPolicy, pending: PendingVar) -> VarClassification {
+ // The eager `to_owned()` is forced by `Decision::Ignored`: that
+ // arm consumes the item without handing it back, so the name has
+ // to be captured before `policy.check` takes ownership. The other
+ // arms could reach the name through the returned `pv`.
+ let name = pending.name().to_owned();
+ let (id, pv) = pending.into_parts();
+ match policy.check(&name, pv) {
+ CheckOutcome::Decided(Decision::Allowed(pv)) => {
+ let approval = Some(SessionVar::from_provenanced(pv.clone()));
+ VarClassification::Decided(VarOutcome {
+ verdict: PendingVar::reassemble(id, pv).into_approved_verdict(),
+ approval,
+ })
+ }
+ CheckOutcome::Decided(Decision::Denied(pv)) => VarClassification::Decided(VarOutcome {
+ verdict: PendingVar::reassemble(id, pv).into_denied_verdict(),
+ approval: None,
+ }),
+ CheckOutcome::Decided(Decision::Ignored) => VarClassification::Decided(VarOutcome {
+ verdict: WireVarVerdict::Ignored { id, name },
+ approval: None,
+ }),
+ CheckOutcome::NeedsApproval(pv) => {
+ VarClassification::Pending(PendingVar::reassemble(id, pv))
+ }
+ }
+}
+
+// =====================================================================
+// Patches
+// =====================================================================
+
+fn gate_pending_patches(
+ pending: Vec,
+ policy: PatchPolicy,
+ hooks: &dyn PolicyHooks,
+ options: ComposeOptions,
+ combined_vars: &[SessionVar],
+ env: &dyn Fn(&str) -> Result,
+) -> Result, ComposeError> {
+ if pending.is_empty() {
+ return Ok(Vec::new());
+ }
+ let home_fallback = env("HOME").ok();
+ let home_fallback = home_fallback.as_deref();
+
+ let mut expanded_policy = policy.expand_with(combined_vars, home_fallback)?;
+
+ // Pass 1: walk each pending patch's source pattern, classify
+ // every matched file. Unapproved files batch into one queue so
+ // the hook prompts once per response.
+ let (mut verdicts, unapproved) = enumerate_and_classify_patches(
+ pending,
+ &expanded_policy,
+ combined_vars,
+ home_fallback,
+ options.follow_symlinks,
+ )?;
+ if unapproved.is_empty() {
+ return Ok(verdicts);
+ }
+
+ // Pass 2: prompt. If the hook updated the policy, re-expand
+ // before applying decisions.
+ let view: Vec> = unapproved
+ .iter()
+ .map(|p| Unapproved {
+ item: p.file().user_facing().as_utf8_path(),
+ source: p.file().source(),
+ })
+ .collect();
+ let (decisions, policy, policy_updated) =
+ crate::core::compose::prompt_patch_hook(hooks, policy, &view)?;
+ if policy_updated {
+ expanded_policy = policy.expand_with(combined_vars, home_fallback)?;
+ }
+
+ // Pass 3: apply.
+ for (pending, decision) in unapproved.into_iter().zip(decisions) {
+ verdicts.push(apply_patch_decision(&expanded_policy, pending, decision)?);
+ }
+ Ok(verdicts)
+}
+
+/// Walk every pending patch's source pattern, run each matched file
+/// through the policy, and partition into finished verdicts vs files
+/// that need the hook.
+fn enumerate_and_classify_patches(
+ pending: Vec,
+ policy: &ExpandedPatchPolicy,
+ combined_vars: &[SessionVar],
+ home_fallback: Option<&str>,
+ follow_symlinks: bool,
+) -> Result<(Vec, Vec), ComposeError> {
+ let mut verdicts: Vec = Vec::new();
+ let mut unapproved: Vec = Vec::new();
+ for p in pending {
+ let id = p.id;
+ let provenance: Source = p.source.into();
+ let dest = PatchDest::try_new(p.destination.as_utf8_path().to_path_buf())
+ .map_err(|source| ComposeError::InvalidPendingPatchDest { source })?;
+ let pp = ProvenancedPatch::new(Patch::new(p.source_pattern, dest), provenance);
+ let expanded = expand_patch_sources(vec![pp], combined_vars, home_fallback)?;
+ let files = enumerate_patch_files(expanded, follow_symlinks)?;
+ for pf in files {
+ match classify_patch_file(policy, PendingPatchFile::new(id, pf)) {
+ PatchClassification::Decided(verdict) => verdicts.push(verdict),
+ PatchClassification::Pending(p) => unapproved.push(p),
+ }
+ }
+ }
+ Ok((verdicts, unapproved))
+}
+
+/// Apply a hook's `ItemDecision` to a single pending patch file.
+fn apply_patch_decision(
+ policy: &ExpandedPatchPolicy,
+ pending: PendingPatchFile,
+ decision: ItemDecision,
+) -> Result {
+ match decision {
+ ItemDecision::AllowOnce => Ok(pending.into_approved_verdict()),
+ ItemDecision::UseRule => match classify_patch_file(policy, pending) {
+ PatchClassification::Decided(verdict) => Ok(verdict),
+ PatchClassification::Pending(p) => Err(ComposeError::use_rule_undecided(
+ HookDomain::Patch,
+ format!("path `{}`", p.file().target_path.as_str()),
+ )),
+ },
+ }
+}
+
+/// Result of running a single matched file through the patch policy.
+enum PatchClassification {
+ /// Policy reached a verdict.
+ Decided(WirePatchVerdict),
+ /// Policy couldn't decide; file is returned for the hook batch.
+ Pending(PendingPatchFile),
+}
+
+fn classify_patch_file(
+ policy: &ExpandedPatchPolicy,
+ pending: PendingPatchFile,
+) -> PatchClassification {
+ let (id, pf) = pending.into_parts();
+ // Save the target path before `policy.check` consumes the file;
+ // the Ignored arm doesn't get the file back and needs the path
+ // to construct a verdict that the daemon can correlate.
+ let saved_target = pf.target_path.clone();
+ let link = pf
+ .link_path
+ .as_ref()
+ .map(|p| p.as_utf8_path().to_path_buf());
+ let target = pf.target_path.as_utf8_path().to_path_buf();
+ match policy.check(link.as_deref(), &target, pf) {
+ CheckOutcome::Decided(Decision::Allowed(pf)) => {
+ PatchClassification::Decided(PendingPatchFile::new(id, pf).into_approved_verdict())
+ }
+ CheckOutcome::Decided(Decision::Denied(pf)) => {
+ PatchClassification::Decided(PendingPatchFile::new(id, pf).into_denied_verdict())
+ }
+ CheckOutcome::Decided(Decision::Ignored) => {
+ PatchClassification::Decided(WirePatchVerdict::Ignored {
+ id,
+ host_path: saved_target,
+ })
+ }
+ CheckOutcome::NeedsApproval(pf) => {
+ PatchClassification::Pending(PendingPatchFile::new(id, pf))
+ }
+ }
+}
diff --git a/crates/sessions/src/client/mod.rs b/crates/sessions/src/client/mod.rs
index 0ee3b91c0b..c507e3da68 100644
--- a/crates/sessions/src/client/mod.rs
+++ b/crates/sessions/src/client/mod.rs
@@ -1 +1,2 @@
pub mod composer;
+pub mod handler;
diff --git a/crates/sessions/src/core/compose.rs b/crates/sessions/src/core/compose.rs
index 16c556ab34..1cdcff175c 100644
--- a/crates/sessions/src/core/compose.rs
+++ b/crates/sessions/src/core/compose.rs
@@ -16,10 +16,14 @@ use crate::core::decision::{CheckOutcome, Decision, ItemDecision};
use crate::core::enumerate::{ExpandedProvenancedPatch, PatchFile, enumerate_patch_files};
use crate::core::hooks::{HookResult, PolicyHooks, Unapproved};
use crate::core::policy::{PatchPolicy, UserPolicy, VarsPolicy};
-use crate::core::primitives::{ResolvedPatch, ResolvedVar};
+use crate::core::primitives::{ResolvedPatch, ResolvedVar, VarError};
use crate::core::source::{
Provenanced, ProvenancedHook, ProvenancedPackage, ProvenancedPatch, ProvenancedVar, Source,
};
+use crate::wire::policy::{WirePatchVerdict, WireVarVerdict};
+use crate::wire::primitives::{
+ PendingId, WirePendingVar, WireResolvedVar, WireSessionPatch, WireSessionVar,
+};
/// Errors produced while a [`Composable`] materializes its
/// [`Contribution`], or while two contributions are merged.
@@ -240,6 +244,17 @@ pub enum ComposeError {
/// Free-form context.
context: String,
},
+ /// A pending patch's destination violates [`PatchDest`]'s
+ /// invariants (empty path, traversal component, absolute path).
+ /// Surfaces from `handle_response` when reconstructing a
+ /// `WirePendingPatch` into its domain form.
+ ///
+ /// [`PatchDest`]: crate::core::primitives::PatchDest
+ #[error("invalid pending patch destination: {source}")]
+ InvalidPendingPatchDest {
+ #[source]
+ source: crate::core::primitives::PatchError,
+ },
/// Expanding `~/` or `$VAR` references in a patch source or policy
/// pattern failed. Surfaces every failure mode of
/// [`expand_source`](crate::core::expansion::expand_source): malformed
@@ -247,6 +262,62 @@ pub enum ComposeError {
/// or a post-expansion string that fails to parse as a glob.
#[error("patch source expansion failed: {0}")]
Expansion(#[from] crate::core::expansion::ExpandError),
+ /// A pending var with an `Inherit`-shaped spec could not be
+ /// resolved against the client's environment (e.g. the variable
+ /// was absent and the spec had no `default`). Surfaces from
+ /// `handle_response` when processing a daemon-emitted pending
+ /// var.
+ #[error("could not resolve pending var `{name}`: {source}")]
+ VarResolution {
+ /// The pending variable's name.
+ name: String,
+ /// The underlying env-lookup failure.
+ #[source]
+ source: std::env::VarError,
+ },
+}
+
+/// Which policy domain a hook contract violation refers to. Keeps
+/// the `HookContract` message constructors exhaustively dispatched
+/// instead of stringly-typed.
+#[derive(Clone, Copy, Debug)]
+pub(crate) enum HookDomain {
+ Var,
+ Patch,
+}
+
+impl ComposeError {
+ /// Build the `HookContract` variant fired when a hook returns
+ /// `UseRule` for an item that the policy still can't decide
+ /// after the hook's `updated_policy` is installed. `item_label`
+ /// should already include any quoting the caller wants.
+ pub(crate) fn use_rule_undecided(domain: HookDomain, item_label: String) -> Self {
+ let kind = match domain {
+ HookDomain::Var => "UseRule returned for a var the policy still cannot decide",
+ HookDomain::Patch => "UseRule returned for a patch file the policy still cannot decide",
+ };
+ Self::HookContract {
+ kind,
+ context: item_label,
+ }
+ }
+
+ /// Build the `HookContract` variant fired when the hook returns
+ /// the wrong number of decisions for the batch.
+ pub(crate) fn hook_decision_count_mismatch(
+ domain: HookDomain,
+ expected: usize,
+ got: usize,
+ ) -> Self {
+ let kind = match domain {
+ HookDomain::Var => "var-domain hook returned the wrong number of decisions",
+ HookDomain::Patch => "patch-domain hook returned the wrong number of decisions",
+ };
+ Self::HookContract {
+ kind,
+ context: format!("expected {expected}, got {got}"),
+ }
+ }
}
/// Render a slice of `Display`-able errors as one indented bullet per
@@ -262,52 +333,66 @@ impl fmt::Display for DisplayJoin<'_, E> {
}
}
-/// One environment variable that survived the policy gate, paired
-/// with its origin.
+/// One environment variable that survived the policy gate.
///
-/// The source is retained so downstream layers (CLI inspection, audit
-/// logs, error reporting) can attribute each decision back to the
-/// contributor that asked for it.
+/// A thin typestate wrapper over [`ProvenancedVar`] — same data, but
+/// the type encodes that the contained var has been gated. The
+/// distinction matters at API boundaries: a function taking
+/// `&[SessionVar]` is documented to consume only post-gate items.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
-pub struct SessionVar {
- var: ResolvedVar,
- source: Source,
-}
+pub struct SessionVar(ProvenancedVar);
impl SessionVar {
+ /// Direct construction. Crate-internal because outside callers
+ /// should obtain `SessionVar`s by going through the gate (e.g.
+ /// `UserComposer::compose`) or reconstructing one from a
+ /// [`WireSessionVar`] via the `From` impl — both of which
+ /// guarantee provenance is
+ /// truthful. `pub(crate)` exposes it for in-crate handlers (e.g.
+ /// `client::handler`) that build session vars from already-gated
+ /// wire payloads.
+ #[must_use]
+ pub(crate) fn new(var: ResolvedVar, source: Source) -> Self {
+ Self(ProvenancedVar::new(var, source))
+ }
+
+ /// Lift a [`ProvenancedVar`] that has passed the gate into a
+ /// `SessionVar`. Zero-cost (no allocation, no clone).
+ #[must_use]
+ pub(crate) fn from_provenanced(pv: ProvenancedVar) -> Self {
+ Self(pv)
+ }
+
/// The variable that survived the policy gate.
#[must_use]
pub fn var(&self) -> &ResolvedVar {
- &self.var
+ self.0.var()
}
/// Consume the [`SessionVar`] and return `(var, source)`.
#[must_use]
pub fn into_parts(self) -> (ResolvedVar, Source) {
- (self.var, self.source)
+ self.0.into_parts()
}
}
impl Provenanced for SessionVar {
fn source(&self) -> &Source {
- &self.source
+ self.0.source()
}
}
impl crate::core::expansion::VarLookup for [SessionVar] {
fn lookup(&self, name: &str) -> Option<&str> {
self.iter()
- .find(|v| v.var.name() == name)
- .map(|v| v.var.value())
+ .find(|v| v.var().name() == name)
+ .map(|v| v.var().value())
}
}
-impl From for SessionVar {
- fn from(v: crate::wire::primitives::WireSessionVar) -> Self {
- Self {
- var: v.var.into(),
- source: v.source.into(),
- }
+impl From for SessionVar {
+ fn from(v: WireSessionVar) -> Self {
+ Self::new(v.var.into(), v.source.into())
}
}
@@ -340,8 +425,8 @@ impl Provenanced for SessionPatch {
}
}
-impl From for SessionPatch {
- fn from(p: crate::wire::primitives::WireSessionPatch) -> Self {
+impl From for SessionPatch {
+ fn from(p: WireSessionPatch) -> Self {
Self {
patch: p.patch.into(),
source: p.source.into(),
@@ -349,6 +434,155 @@ impl From for SessionPatch {
}
}
+/// One environment variable the daemon emitted as pending: id-tagged
+/// for wire correlation, paired with the resolved domain
+/// [`ProvenancedVar`] the client built from the wire spec + env.
+///
+/// Bridges wire and domain on the verdict-emitting side: the policy
+/// check consumes the inner `ProvenancedVar`; the consuming
+/// `into_*` methods on this type produce the matching
+/// [`WireVarVerdict`] without extra clones.
+#[derive(Clone, Debug, PartialEq, Eq, Hash)]
+pub(crate) struct PendingVar {
+ id: PendingId,
+ var: ProvenancedVar,
+}
+
+impl PendingVar {
+ /// Build from a wire pending var by resolving its spec against
+ /// `env`. Delegates to [`ResolvedVar::resolve_with`] for the
+ /// env-handling logic so the rules stay in one place.
+ ///
+ /// # Errors
+ ///
+ /// Returns [`ComposeError::VarResolution`] if the spec asks for
+ /// an env lookup that fails (and `InheritWithDefault` can't
+ /// recover via its default).
+ pub(crate) fn from_wire(
+ wire: WirePendingVar,
+ env: &dyn Fn(&str) -> Result,
+ ) -> Result {
+ let resolved = ResolvedVar::resolve_with(wire.name, wire.spec.into(), env).map_err(
+ |err| match err {
+ VarError::ResolutionFailure { name, source } => {
+ ComposeError::VarResolution { name, source }
+ }
+ // `resolve_with` only documents `ResolutionFailure` for
+ // resolution input, but `VarError` is `#[non_exhaustive]`
+ // — fall back to a recoverable error instead of panicking
+ // if a new variant ever leaks through.
+ other => ComposeError::InvalidWireItem {
+ what: "pending var resolution",
+ context: format!("{other}"),
+ },
+ },
+ )?;
+ Ok(Self {
+ id: wire.id,
+ var: ProvenancedVar::new(resolved, wire.source.into()),
+ })
+ }
+
+ /// Reassemble after the policy check hands the inner
+ /// [`ProvenancedVar`] back (`Allowed`, `Denied`, or
+ /// `NeedsApproval`). The id is supplied separately because the
+ /// policy machinery doesn't know about it.
+ #[must_use]
+ pub(crate) fn reassemble(id: PendingId, var: ProvenancedVar) -> Self {
+ Self { id, var }
+ }
+
+ /// Borrow the inner [`ProvenancedVar`]. Used to feed `policy.check`.
+ #[must_use]
+ pub(crate) fn provenanced(&self) -> &ProvenancedVar {
+ &self.var
+ }
+
+ /// The variable's name.
+ #[must_use]
+ pub(crate) fn name(&self) -> &str {
+ self.var.var().name()
+ }
+
+ /// Consume into `(id, ProvenancedVar)` for moves that the
+ /// classifier needs to hand into `policy.check`.
+ #[must_use]
+ pub(crate) fn into_parts(self) -> (PendingId, ProvenancedVar) {
+ (self.id, self.var)
+ }
+
+ /// Consume and emit an Approved verdict carrying the resolved
+ /// name and value back to the daemon.
+ #[must_use]
+ pub(crate) fn into_approved_verdict(self) -> WireVarVerdict {
+ let (resolved, _source) = self.var.into_parts();
+ let (name, value) = resolved.into_parts();
+ WireVarVerdict::Approved {
+ id: self.id,
+ value: WireResolvedVar { name, value },
+ }
+ }
+
+ /// Consume and emit a Denied verdict.
+ #[must_use]
+ pub(crate) fn into_denied_verdict(self) -> WireVarVerdict {
+ let (resolved, _source) = self.var.into_parts();
+ let (name, _value) = resolved.into_parts();
+ WireVarVerdict::Denied { id: self.id, name }
+ }
+}
+
+/// One filesystem entry the daemon emitted as pending: id-tagged for
+/// wire correlation, paired with the canonical [`PatchFile`] the
+/// client's walker produced.
+///
+/// Bridges wire and domain on the patch verdict-emitting side, same
+/// role as [`PendingVar`] does for vars.
+pub(crate) struct PendingPatchFile {
+ id: PendingId,
+ file: PatchFile,
+}
+
+impl PendingPatchFile {
+ #[must_use]
+ pub(crate) fn new(id: PendingId, file: PatchFile) -> Self {
+ Self { id, file }
+ }
+
+ /// Borrow the underlying file (e.g. to build an `Unapproved`
+ /// view for hook prompts).
+ #[must_use]
+ pub(crate) fn file(&self) -> &PatchFile {
+ &self.file
+ }
+
+ /// Consume into `(id, PatchFile)` so the classifier can hand the
+ /// file into `policy.check`.
+ #[must_use]
+ pub(crate) fn into_parts(self) -> (PendingId, PatchFile) {
+ (self.id, self.file)
+ }
+
+ /// Consume and emit an Approved verdict carrying the canonical
+ /// target path back to the daemon.
+ #[must_use]
+ pub(crate) fn into_approved_verdict(self) -> WirePatchVerdict {
+ WirePatchVerdict::Approved {
+ id: self.id,
+ host_path: self.file.target_path,
+ }
+ }
+
+ /// Consume and emit a Denied verdict.
+ #[must_use]
+ pub(crate) fn into_denied_verdict(self) -> WirePatchVerdict {
+ WirePatchVerdict::Denied {
+ id: self.id,
+ host_path: self.file.target_path,
+ }
+ }
+}
+
/// Everything that survived the policy gate.
///
/// Vars and patches are policy-gated. Packages and lifecycle hooks
@@ -464,6 +698,73 @@ pub struct ComposeOptions {
// Per-domain gating
// =====================================================================
+/// Invoke a var-domain hook on a batch of unapproved items. The
+/// hook gets `policy` cloned (it can't mutate the caller's directly);
+/// on success the caller gets back `(decisions, policy)` where
+/// `policy` is the hook's `updated_policy` if it returned one, else
+/// the original. Decision count is validated; mismatches return
+/// `HookContract`.
+///
+/// Lifts the boilerplate (call hook, handle `Abort`, fold in
+/// `updated_policy`, validate decision count) shared by [`gate_vars`]
+/// (Phase 1 of `docs/COMPOSITION.md`) and
+/// [`handle_response`](crate::client::handler::handle_response)
+/// (Phase 3).
+pub(crate) fn prompt_var_hook(
+ hooks: &dyn PolicyHooks,
+ policy: VarsPolicy,
+ view: &[Unapproved<'_, str>],
+) -> Result<(Vec, VarsPolicy), ComposeError> {
+ match hooks.on_var_unapproved(policy.clone(), view) {
+ HookResult::Abort => Err(ComposeError::Aborted),
+ HookResult::Decided {
+ decisions,
+ updated_policy,
+ } => {
+ if decisions.len() != view.len() {
+ return Err(ComposeError::hook_decision_count_mismatch(
+ HookDomain::Var,
+ view.len(),
+ decisions.len(),
+ ));
+ }
+ Ok((decisions, updated_policy.unwrap_or(policy)))
+ }
+ }
+}
+
+/// Invoke a patch-domain hook on a batch of unapproved files. Same
+/// shape as [`prompt_var_hook`], plus a `bool` indicating whether
+/// the hook installed an `updated_policy` — the caller uses that
+/// flag to decide whether to re-expand the policy's patterns against
+/// the resolved vars.
+pub(crate) fn prompt_patch_hook(
+ hooks: &dyn PolicyHooks,
+ policy: PatchPolicy,
+ view: &[Unapproved<'_, camino::Utf8Path>],
+) -> Result<(Vec, PatchPolicy, bool), ComposeError> {
+ match hooks.on_patch_unapproved(policy.clone(), view) {
+ HookResult::Abort => Err(ComposeError::Aborted),
+ HookResult::Decided {
+ decisions,
+ updated_policy,
+ } => {
+ if decisions.len() != view.len() {
+ return Err(ComposeError::hook_decision_count_mismatch(
+ HookDomain::Patch,
+ view.len(),
+ decisions.len(),
+ ));
+ }
+ let (policy, updated) = match updated_policy {
+ Some(new) => (new, true),
+ None => (policy, false),
+ };
+ Ok((decisions, policy, updated))
+ }
+ }
+}
+
/// Push, drop, or fail on a single [`Decision`].
///
/// Used by Pass 1 (categorizing every item) and by Pass 3's `UseRule`
@@ -524,8 +825,7 @@ pub(crate) fn gate_vars(
from: source_of(pv),
});
};
- // Pass 2: prompt. Hand the hook an owned copy of the policy
- // so it cannot mutate ours directly.
+ // Pass 2: prompt.
let view: Vec> = unapproved
.iter()
.map(|pv| Unapproved {
@@ -533,24 +833,8 @@ pub(crate) fn gate_vars(
source: pv.source(),
})
.collect();
- let decisions = match hooks.on_var_unapproved(policy.clone(), &view) {
- HookResult::Decided {
- decisions,
- updated_policy,
- } => {
- if let Some(new_policy) = updated_policy {
- policy = new_policy;
- }
- decisions
- }
- HookResult::Abort => return Err(ComposeError::Aborted),
- };
- if decisions.len() != unapproved.len() {
- return Err(ComposeError::HookContract {
- kind: "var-domain hook returned the wrong number of decisions",
- context: format!("expected {}, got {}", unapproved.len(), decisions.len()),
- });
- }
+ let (decisions, new_policy) = prompt_var_hook(hooks, policy, &view)?;
+ policy = new_policy;
// Pass 3: apply.
for (pv, decision) in unapproved.into_iter().zip(decisions) {
match decision {
@@ -562,10 +846,10 @@ pub(crate) fn gate_vars(
apply_decision(d, &mut allowed, name_of, source_of)?;
}
CheckOutcome::NeedsApproval(pv) => {
- return Err(ComposeError::HookContract {
- kind: "UseRule returned for a var the policy still cannot decide",
- context: format!("variable `{}`", pv.var().name()),
- });
+ return Err(ComposeError::use_rule_undecided(
+ HookDomain::Var,
+ format!("variable `{}`", pv.var().name()),
+ ));
}
}
}
@@ -576,10 +860,7 @@ pub(crate) fn gate_vars(
Ok((
allowed
.into_iter()
- .map(|pv| {
- let (var, source) = pv.into_parts();
- SessionVar { var, source }
- })
+ .map(SessionVar::from_provenanced)
.collect(),
policy,
))
@@ -674,24 +955,10 @@ pub(crate) fn gate_patches(
source: &pf.provenance,
})
.collect();
- let decisions = match hooks.on_patch_unapproved(policy.clone(), &view) {
- HookResult::Decided {
- decisions,
- updated_policy,
- } => {
- if let Some(new_policy) = updated_policy {
- policy = new_policy;
- expanded = policy.expand_with(gated_vars, home_fallback)?;
- }
- decisions
- }
- HookResult::Abort => return Err(ComposeError::Aborted),
- };
- if decisions.len() != unapproved.len() {
- return Err(ComposeError::HookContract {
- kind: "patch-domain hook returned the wrong number of decisions",
- context: format!("expected {}, got {}", unapproved.len(), decisions.len()),
- });
+ let (decisions, new_policy, policy_updated) = prompt_patch_hook(hooks, policy, &view)?;
+ policy = new_policy;
+ if policy_updated {
+ expanded = policy.expand_with(gated_vars, home_fallback)?;
}
// Pass 3: apply.
for (pf, decision) in unapproved.into_iter().zip(decisions) {
@@ -708,10 +975,10 @@ pub(crate) fn gate_patches(
apply_decision(d, &mut allowed, name_of, source_of)?;
}
CheckOutcome::NeedsApproval(pf) => {
- return Err(ComposeError::HookContract {
- kind: "UseRule returned for a patch file the policy still cannot decide",
- context: format!("source path `{}`", pf.user_facing()),
- });
+ return Err(ComposeError::use_rule_undecided(
+ HookDomain::Patch,
+ format!("source path `{}`", pf.user_facing()),
+ ));
}
}
}
@@ -1223,10 +1490,7 @@ mod tests {
Err(std::env::VarError::NotPresent)
})
.unwrap();
- SessionVar {
- var: resolved,
- source: user_source(),
- }
+ SessionVar::new(resolved, user_source())
}
#[test]
diff --git a/crates/sessions/src/core/primitives.rs b/crates/sessions/src/core/primitives.rs
index 5303c2f402..7b6e3680f0 100644
--- a/crates/sessions/src/core/primitives.rs
+++ b/crates/sessions/src/core/primitives.rs
@@ -640,6 +640,18 @@ impl From for ResolvedVar {
}
}
+impl From for VarValue {
+ fn from(spec: crate::wire::primitives::WireVarSpec) -> Self {
+ match spec {
+ crate::wire::primitives::WireVarSpec::Specified { value } => Self::Specified { value },
+ crate::wire::primitives::WireVarSpec::Inherit => Self::Inherit,
+ crate::wire::primitives::WireVarSpec::InheritWithDefault { default } => {
+ Self::InheritWithDefault { default }
+ }
+ }
+ }
+}
+
// =====================================================================
// FileSet
// =====================================================================
diff --git a/crates/sessions/src/wire/policy.rs b/crates/sessions/src/wire/policy.rs
index b36b03d972..b210c8f6a3 100644
--- a/crates/sessions/src/wire/policy.rs
+++ b/crates/sessions/src/wire/policy.rs
@@ -9,6 +9,13 @@
use super::primitives::{PendingId, WireResolvedVar};
/// The client's decision about one pending variable.
+///
+/// Every variant exposes the variable name — directly on `Denied`
+/// and `Ignored`, nested in `value` on `Approved`. This mirrors
+/// [`WirePatchVerdict`], which carries `host_path` on every
+/// variant. The daemon can correlate by `id` alone, but the
+/// redundant name lets logs and audit records be self-describing
+/// without joining against the original pending batch.
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum WireVarVerdict {
@@ -24,35 +31,51 @@ pub enum WireVarVerdict {
Denied {
/// Matches the corresponding `WirePendingVar::id`.
id: PendingId,
+ /// Name of the rejected variable.
+ name: String,
},
/// User policy's `ignore` rule matched; silently drop.
Ignored {
/// Matches the corresponding `WirePendingVar::id`.
id: PendingId,
+ /// Name of the dropped variable.
+ name: String,
},
}
-/// The client's decision about one pending patch.
+/// The client's decision about a single file matched by a pending
+/// patch's source pattern.
///
-/// Approved patches' file contents arrive separately as a tarball
-/// stream — not in this message.
+/// One [`WirePendingPatch`](super::primitives::WirePendingPatch) can
+/// fan out to multiple files (its `source_pattern` is a glob), so
+/// each is voted on independently. `id` correlates back to the
+/// pending patch; `host_path` is the canonical absolute path the
+/// daemon will copy from.
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum WirePatchVerdict {
- /// User policy or prompt approved. Content streamed out-of-band.
+ /// User policy or prompt approved this file.
Approved {
/// Matches the corresponding `WirePendingPatch::id`.
id: PendingId,
+ /// Absolute host path of the matched file.
+ host_path: paths::HostAbsPath,
},
- /// User policy or prompt rejected.
+ /// User policy or prompt rejected this file.
Denied {
/// Matches the corresponding `WirePendingPatch::id`.
id: PendingId,
+ /// Absolute host path of the rejected file.
+ host_path: paths::HostAbsPath,
},
- /// User policy's `ignore` rule matched; silently drop.
+ /// User policy's `ignore` rule matched; silently drop this file.
+ /// `host_path` is carried for audit/logging parity with the
+ /// other variants — the daemon must not copy the file.
Ignored {
/// Matches the corresponding `WirePendingPatch::id`.
id: PendingId,
+ /// Absolute host path of the dropped file. Logging only.
+ host_path: paths::HostAbsPath,
},
}
@@ -80,9 +103,11 @@ mod tests {
},
WireVarVerdict::Denied {
id: PendingId::new(2),
+ name: "AWS_KEY".into(),
},
WireVarVerdict::Ignored {
id: PendingId::new(3),
+ name: "_TMP".into(),
},
];
for v in cases {
@@ -95,12 +120,15 @@ mod tests {
let cases = [
WirePatchVerdict::Approved {
id: PendingId::new(1),
+ host_path: paths::HostAbsPath::try_new("/home/u/.gitconfig").unwrap(),
},
WirePatchVerdict::Denied {
id: PendingId::new(2),
+ host_path: paths::HostAbsPath::try_new("/home/u/secret").unwrap(),
},
WirePatchVerdict::Ignored {
id: PendingId::new(3),
+ host_path: paths::HostAbsPath::try_new("/home/u/.cache").unwrap(),
},
];
for v in cases {
@@ -112,6 +140,7 @@ mod tests {
fn var_verdict_uses_explicit_kind_tag() {
let v = WireVarVerdict::Denied {
id: PendingId::new(7),
+ name: "x".into(),
};
let json = serde_json::to_string(&v).unwrap();
assert!(
diff --git a/crates/sessions/src/wire/request.rs b/crates/sessions/src/wire/request.rs
index fda4240832..b402368eb2 100644
--- a/crates/sessions/src/wire/request.rs
+++ b/crates/sessions/src/wire/request.rs
@@ -242,6 +242,7 @@ mod tests {
}],
patches: vec![WirePatchVerdict::Denied {
id: PendingId::new(2),
+ host_path: paths::HostAbsPath::try_new("/etc/secret").unwrap(),
}],
};
assert_eq!(round_trip(&v), v);
diff --git a/crates/sessions/tests/client_flow2.rs b/crates/sessions/tests/client_flow2.rs
new file mode 100644
index 0000000000..96bc565e1d
--- /dev/null
+++ b/crates/sessions/tests/client_flow2.rs
@@ -0,0 +1,1048 @@
+//! Integration tests for flow 2 of session creation: receiving the
+//! daemon's [`ContributionResponse`] and emitting a
+//! [`ContributionVerdict`].
+//!
+//! Same constraints as `client_flow1.rs` — exercises the crate's
+//! public surface only.
+
+use std::collections::HashMap;
+
+use camino::Utf8Path;
+use sessions::SessionId;
+use sessions::client::handler::handle_response;
+use sessions::core::compose::{ComposeError, ComposeOptions, SessionVar};
+use sessions::core::decision::ItemDecision;
+use sessions::core::hooks::{HookResult, PolicyHooks, Unapproved};
+use sessions::core::policy::{PatchPolicy, UserPolicy, VarsPolicy};
+use sessions::wire::policy::{WirePatchVerdict, WireVarVerdict};
+use sessions::wire::primitives::{
+ PendingId, WirePendingPatch, WirePendingVar, WireResolvedVar, WireSessionVar, WireSource,
+ WireVarSpec,
+};
+use sessions::wire::request::{ContributionResponse, ContributionVerdict};
+
+// =====================================================================
+// Support
+// =====================================================================
+
+fn session_id() -> SessionId {
+ SessionId::parse_str("00000000-0000-0000-0000-000000000001").unwrap()
+}
+
+fn project_source() -> WireSource {
+ WireSource::Project {
+ path: paths::HostPath::new("/repo"),
+ }
+}
+
+fn package_source(name: &str) -> WireSource {
+ WireSource::Package {
+ name: name.to_owned(),
+ }
+}
+
+fn pinned_env(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Result {
+ let owned: HashMap = pairs
+ .iter()
+ .map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
+ .collect();
+ move |name: &str| {
+ owned
+ .get(name)
+ .cloned()
+ .ok_or(std::env::VarError::NotPresent)
+ }
+}
+
+fn fixture_tree<'a>(root: &Utf8Path, files: impl IntoIterator
- ) {
+ for (rel, body) in files {
+ let p = root.join(rel);
+ if let Some(parent) = p.parent() {
+ std::fs::create_dir_all(parent.as_std_path()).unwrap();
+ }
+ std::fs::write(p.as_std_path(), body).unwrap();
+ }
+}
+
+/// Pre-gated client var (as would be produced by Phase 1's
+/// `UserComposer`) for use as `gated_vars` context.
+fn gated_var(name: &str, value: &str, loadout: &str) -> SessionVar {
+ let wire = WireSessionVar {
+ var: WireResolvedVar {
+ name: name.to_owned(),
+ value: value.to_owned(),
+ },
+ source: WireSource::UserLoadout {
+ name: loadout.to_owned(),
+ },
+ };
+ wire.into()
+}
+
+struct PassThroughHooks;
+impl PolicyHooks for PassThroughHooks {
+ fn on_var_unapproved(
+ &self,
+ _: VarsPolicy,
+ items: &[Unapproved<'_, str>],
+ ) -> HookResult {
+ HookResult::decided(vec![ItemDecision::AllowOnce; items.len()])
+ }
+ fn on_patch_unapproved(
+ &self,
+ _: PatchPolicy,
+ items: &[Unapproved<'_, camino::Utf8Path>],
+ ) -> HookResult {
+ HookResult::decided(vec![ItemDecision::AllowOnce; items.len()])
+ }
+}
+
+struct AbortHooks;
+impl PolicyHooks for AbortHooks {
+ fn on_var_unapproved(
+ &self,
+ _: VarsPolicy,
+ _: &[Unapproved<'_, str>],
+ ) -> HookResult {
+ HookResult::abort()
+ }
+ fn on_patch_unapproved(
+ &self,
+ _: PatchPolicy,
+ _: &[Unapproved<'_, camino::Utf8Path>],
+ ) -> HookResult {
+ HookResult::abort()
+ }
+}
+
+/// Hook that should never be reached.
+struct PanicHooks;
+impl PolicyHooks for PanicHooks {
+ fn on_var_unapproved(
+ &self,
+ _: VarsPolicy,
+ _: &[Unapproved<'_, str>],
+ ) -> HookResult {
+ panic!("var hook should not have been invoked")
+ }
+ fn on_patch_unapproved(
+ &self,
+ _: PatchPolicy,
+ _: &[Unapproved<'_, camino::Utf8Path>],
+ ) -> HookResult {
+ panic!("patch hook should not have been invoked")
+ }
+}
+
+fn empty_response() -> ContributionResponse {
+ ContributionResponse {
+ session_id: session_id(),
+ vars: vec![],
+ patches: vec![],
+ lifecycle_hooks: vec![],
+ }
+}
+
+// =====================================================================
+// Tests
+// =====================================================================
+
+/// Empty pending → empty verdict echoing the session id.
+#[test]
+fn empty_response_produces_empty_verdict() {
+ let verdict = handle_response(
+ empty_response(),
+ &[],
+ UserPolicy::empty(),
+ &PanicHooks,
+ ComposeOptions::default(),
+ &pinned_env(&[]),
+ )
+ .unwrap();
+ assert_eq!(verdict.session_id, session_id());
+ assert!(verdict.vars.is_empty());
+ assert!(verdict.patches.is_empty());
+}
+
+/// A Specified pending var that matches the policy's `allow` rule
+/// is auto-approved; the verdict carries the value the daemon will
+/// see.
+#[test]
+fn specified_var_allow_listed_is_approved() {
+ let response = ContributionResponse {
+ session_id: session_id(),
+ vars: vec![WirePendingVar {
+ id: PendingId::new(1),
+ name: "EDITOR".into(),
+ spec: WireVarSpec::Specified { value: "hx".into() },
+ source: package_source("helix"),
+ }],
+ patches: vec![],
+ lifecycle_hooks: vec![],
+ };
+ let vars_policy = VarsPolicy::empty().try_with_allow(["EDITOR"]).unwrap();
+ let policy = UserPolicy::empty().with_vars(vars_policy);
+
+ let verdict = handle_response(
+ response,
+ &[],
+ policy,
+ &PanicHooks,
+ ComposeOptions::default(),
+ &pinned_env(&[]),
+ )
+ .unwrap();
+ assert_eq!(verdict.vars.len(), 1);
+ match &verdict.vars[0] {
+ WireVarVerdict::Approved { id, value } => {
+ assert_eq!(*id, PendingId::new(1));
+ assert_eq!(value.name, "EDITOR");
+ assert_eq!(value.value, "hx");
+ }
+ other => panic!("expected Approved, got: {other:?}"),
+ }
+}
+
+/// `Inherit`-shaped pending var resolves against the client's env.
+#[test]
+fn inherit_var_resolves_against_env() {
+ let response = ContributionResponse {
+ session_id: session_id(),
+ vars: vec![WirePendingVar {
+ id: PendingId::new(1),
+ name: "LANG".into(),
+ spec: WireVarSpec::Inherit,
+ source: package_source("locales"),
+ }],
+ patches: vec![],
+ lifecycle_hooks: vec![],
+ };
+ let policy =
+ UserPolicy::empty().with_vars(VarsPolicy::empty().try_with_allow(["LANG"]).unwrap());
+ let env = pinned_env(&[("LANG", "sjn_IV")]);
+
+ let verdict = handle_response(
+ response,
+ &[],
+ policy,
+ &PanicHooks,
+ ComposeOptions::default(),
+ &env,
+ )
+ .unwrap();
+ match &verdict.vars[0] {
+ WireVarVerdict::Approved { value, .. } => assert_eq!(value.value, "sjn_IV"),
+ other => panic!("expected Approved, got: {other:?}"),
+ }
+}
+
+/// `InheritWithDefault` falls back when the env is missing.
+#[test]
+fn inherit_with_default_falls_back() {
+ let response = ContributionResponse {
+ session_id: session_id(),
+ vars: vec![WirePendingVar {
+ id: PendingId::new(1),
+ name: "LANG".into(),
+ spec: WireVarSpec::InheritWithDefault {
+ default: "sjn_IV".into(),
+ },
+ source: package_source("locales"),
+ }],
+ patches: vec![],
+ lifecycle_hooks: vec![],
+ };
+ let policy =
+ UserPolicy::empty().with_vars(VarsPolicy::empty().try_with_allow(["LANG"]).unwrap());
+
+ let verdict = handle_response(
+ response,
+ &[],
+ policy,
+ &PanicHooks,
+ ComposeOptions::default(),
+ &pinned_env(&[]),
+ )
+ .unwrap();
+ match &verdict.vars[0] {
+ WireVarVerdict::Approved { value, .. } => assert_eq!(value.value, "sjn_IV"),
+ other => panic!("expected Approved, got: {other:?}"),
+ }
+}
+
+/// `Inherit` with a missing env value → [`ComposeError::VarResolution`].
+#[test]
+fn inherit_var_missing_env_errors() {
+ let response = ContributionResponse {
+ session_id: session_id(),
+ vars: vec![WirePendingVar {
+ id: PendingId::new(1),
+ name: "MUST_BE_SET".into(),
+ spec: WireVarSpec::Inherit,
+ source: package_source("strict"),
+ }],
+ patches: vec![],
+ lifecycle_hooks: vec![],
+ };
+ let err = handle_response(
+ response,
+ &[],
+ UserPolicy::empty(),
+ &PanicHooks,
+ ComposeOptions::default(),
+ &pinned_env(&[]),
+ )
+ .unwrap_err();
+ assert!(
+ matches!(err, ComposeError::VarResolution { ref name, .. } if name == "MUST_BE_SET"),
+ "got: {err:?}",
+ );
+}
+
+/// A `deny` rule on a pending var produces a per-item Denied verdict
+/// but doesn't abort sibling items.
+#[test]
+fn policy_deny_per_item() {
+ let response = ContributionResponse {
+ session_id: session_id(),
+ vars: vec![
+ WirePendingVar {
+ id: PendingId::new(1),
+ name: "AWS_KEY".into(),
+ spec: WireVarSpec::Specified {
+ value: "leaked".into(),
+ },
+ source: package_source("evil"),
+ },
+ WirePendingVar {
+ id: PendingId::new(2),
+ name: "EDITOR".into(),
+ spec: WireVarSpec::Specified { value: "hx".into() },
+ source: package_source("helix"),
+ },
+ ],
+ patches: vec![],
+ lifecycle_hooks: vec![],
+ };
+ let vars_policy = VarsPolicy::empty()
+ .try_with_deny(["AWS_*"])
+ .unwrap()
+ .try_with_allow(["EDITOR"])
+ .unwrap();
+ let policy = UserPolicy::empty().with_vars(vars_policy);
+
+ let verdict = handle_response(
+ response,
+ &[],
+ policy,
+ &PanicHooks,
+ ComposeOptions::default(),
+ &pinned_env(&[]),
+ )
+ .unwrap();
+
+ let by_id: HashMap = verdict
+ .vars
+ .iter()
+ .map(|v| (verdict_var_id(v), v))
+ .collect();
+ assert!(matches!(by_id.get(&1), Some(WireVarVerdict::Denied { .. })));
+ assert!(matches!(
+ by_id.get(&2),
+ Some(WireVarVerdict::Approved { .. })
+ ));
+}
+
+/// `ignore` rule produces an Ignored verdict.
+#[test]
+fn policy_ignore_per_item() {
+ let response = ContributionResponse {
+ session_id: session_id(),
+ vars: vec![WirePendingVar {
+ id: PendingId::new(1),
+ name: "_TMP".into(),
+ spec: WireVarSpec::Specified { value: "x".into() },
+ source: package_source("noisy"),
+ }],
+ patches: vec![],
+ lifecycle_hooks: vec![],
+ };
+ let vars_policy = VarsPolicy::empty().try_with_ignore(["_*"]).unwrap();
+ let policy = UserPolicy::empty().with_vars(vars_policy);
+
+ let verdict = handle_response(
+ response,
+ &[],
+ policy,
+ &PanicHooks,
+ ComposeOptions::default(),
+ &pinned_env(&[]),
+ )
+ .unwrap();
+ assert!(matches!(verdict.vars[0], WireVarVerdict::Ignored { .. }));
+}
+
+/// A pending var that policy can't auto-decide goes to the hook;
+/// `AllowOnce` produces an Approved verdict.
+#[test]
+fn hook_approves_unapproved() {
+ let response = ContributionResponse {
+ session_id: session_id(),
+ vars: vec![WirePendingVar {
+ id: PendingId::new(1),
+ name: "MY_VAR".into(),
+ spec: WireVarSpec::Specified { value: "v".into() },
+ source: package_source("p"),
+ }],
+ patches: vec![],
+ lifecycle_hooks: vec![],
+ };
+ let verdict = handle_response(
+ response,
+ &[],
+ UserPolicy::empty(),
+ &PassThroughHooks,
+ ComposeOptions::default(),
+ &pinned_env(&[]),
+ )
+ .unwrap();
+ assert!(matches!(verdict.vars[0], WireVarVerdict::Approved { .. }));
+}
+
+/// Hook returns Abort → [`ComposeError::Aborted`].
+#[test]
+fn hook_abort_propagates() {
+ let response = ContributionResponse {
+ session_id: session_id(),
+ vars: vec![WirePendingVar {
+ id: PendingId::new(1),
+ name: "MY_VAR".into(),
+ spec: WireVarSpec::Specified { value: "v".into() },
+ source: package_source("p"),
+ }],
+ patches: vec![],
+ lifecycle_hooks: vec![],
+ };
+ let err = handle_response(
+ response,
+ &[],
+ UserPolicy::empty(),
+ &AbortHooks,
+ ComposeOptions::default(),
+ &pinned_env(&[]),
+ )
+ .unwrap_err();
+ assert!(matches!(err, ComposeError::Aborted), "got: {err:?}");
+}
+
+/// A pending patch's source pattern references a `$VAR` defined in
+/// the gated client vars (from Phase 1). Expansion succeeds and the
+/// matched files emit verdicts.
+#[test]
+fn patch_source_uses_gated_vars() {
+ let tmp = tempfile::tempdir().unwrap();
+ let root = Utf8Path::from_path(tmp.path()).unwrap();
+ fixture_tree(root, [("helix/themes/nord.toml", "# nord\n")]);
+
+ let response = ContributionResponse {
+ session_id: session_id(),
+ vars: vec![],
+ patches: vec![WirePendingPatch {
+ id: PendingId::new(1),
+ source_pattern: "$HELIX_CONFIG/themes/*.toml".into(),
+ destination: paths::SandboxRelPath::try_new(".config/helix/themes").unwrap(),
+ description: None,
+ source: package_source("helix"),
+ }],
+ lifecycle_hooks: vec![],
+ };
+ let gated = vec![gated_var(
+ "HELIX_CONFIG",
+ root.join("helix").as_str(),
+ "dev",
+ )];
+ let policy = UserPolicy::empty().with_patches(PatchPolicy::empty().with_allow(["/**/*.toml"]));
+
+ let verdict = handle_response(
+ response,
+ &gated,
+ policy,
+ &PanicHooks,
+ ComposeOptions::default(),
+ &pinned_env(&[]),
+ )
+ .unwrap();
+ assert_eq!(verdict.patches.len(), 1);
+ match &verdict.patches[0] {
+ WirePatchVerdict::Approved { id, host_path } => {
+ assert_eq!(*id, PendingId::new(1));
+ assert!(host_path.as_str().ends_with("helix/themes/nord.toml"));
+ }
+ other => panic!("expected Approved, got: {other:?}"),
+ }
+}
+
+/// A pending var defined earlier in this response is visible to
+/// pending patches in the same response.
+#[test]
+fn patch_source_uses_batch_approved_vars() {
+ let tmp = tempfile::tempdir().unwrap();
+ let root = Utf8Path::from_path(tmp.path()).unwrap();
+ fixture_tree(root, [("helix/themes/nord.toml", "# nord\n")]);
+
+ let response = ContributionResponse {
+ session_id: session_id(),
+ vars: vec![WirePendingVar {
+ id: PendingId::new(1),
+ name: "HELIX_CONFIG".into(),
+ spec: WireVarSpec::Specified {
+ value: root.join("helix").to_string(),
+ },
+ source: package_source("helix"),
+ }],
+ patches: vec![WirePendingPatch {
+ id: PendingId::new(2),
+ source_pattern: "$HELIX_CONFIG/themes/*.toml".into(),
+ destination: paths::SandboxRelPath::try_new(".config/helix/themes").unwrap(),
+ description: None,
+ source: package_source("helix"),
+ }],
+ lifecycle_hooks: vec![],
+ };
+ let policy = UserPolicy::empty()
+ .with_vars(
+ VarsPolicy::empty()
+ .try_with_allow(["HELIX_CONFIG"])
+ .unwrap(),
+ )
+ .with_patches(PatchPolicy::empty().with_allow(["/**/*.toml"]));
+
+ let verdict = handle_response(
+ response,
+ &[],
+ policy,
+ &PanicHooks,
+ ComposeOptions::default(),
+ &pinned_env(&[]),
+ )
+ .unwrap();
+ assert!(matches!(verdict.vars[0], WireVarVerdict::Approved { .. }));
+ assert!(matches!(
+ verdict.patches[0],
+ WirePatchVerdict::Approved { .. }
+ ));
+}
+
+/// A multi-file glob fan-out yields one verdict per matched file;
+/// the deny pattern can reject one without aborting the others.
+#[test]
+fn multi_file_patch_yields_per_file_verdicts() {
+ let tmp = tempfile::tempdir().unwrap();
+ let root = Utf8Path::from_path(tmp.path()).unwrap();
+ fixture_tree(
+ root,
+ [
+ ("themes/nord.toml", "# nord\n"),
+ ("themes/nord-light.toml", "# light\n"),
+ ("themes/draft.toml.bak", "stale\n"),
+ ],
+ );
+
+ let response = ContributionResponse {
+ session_id: session_id(),
+ vars: vec![],
+ patches: vec![WirePendingPatch {
+ id: PendingId::new(1),
+ source_pattern: format!("{root}/themes/*"),
+ destination: paths::SandboxRelPath::try_new(".config/helix/themes").unwrap(),
+ description: None,
+ source: project_source(),
+ }],
+ lifecycle_hooks: vec![],
+ };
+ let policy = UserPolicy::empty().with_patches(
+ PatchPolicy::empty()
+ .with_allow(["/**/*.toml"])
+ .with_deny(["/**/*.bak"]),
+ );
+
+ let verdict = handle_response(
+ response,
+ &[],
+ policy,
+ &PanicHooks,
+ ComposeOptions::default(),
+ &pinned_env(&[]),
+ )
+ .unwrap();
+
+ // Three matched files → three verdicts under the same pending id.
+ assert_eq!(verdict.patches.len(), 3);
+ let id = PendingId::new(1);
+ for v in &verdict.patches {
+ assert_eq!(verdict_patch_id(v), id);
+ }
+ let approved: Vec<&str> = verdict
+ .patches
+ .iter()
+ .filter_map(|v| match v {
+ WirePatchVerdict::Approved { host_path, .. } => Some(host_path.as_str()),
+ _ => None,
+ })
+ .collect();
+ let denied: Vec<&str> = verdict
+ .patches
+ .iter()
+ .filter_map(|v| match v {
+ WirePatchVerdict::Denied { host_path, .. } => Some(host_path.as_str()),
+ _ => None,
+ })
+ .collect();
+ assert_eq!(approved.len(), 2);
+ assert_eq!(denied.len(), 1);
+ assert!(
+ denied[0].ends_with("draft.toml.bak"),
+ "expected .bak file in denied list, got: {denied:?}",
+ );
+}
+
+/// Lifecycle hooks in the response are silently dropped — the
+/// verdict has no hook field. This test asserts the handler doesn't
+/// fail or otherwise observe them, since there's no per-hook policy.
+#[test]
+fn lifecycle_hooks_are_dropped() {
+ use sessions::wire::primitives::{WireHookScript, WireLifecycleHook, WireProvenancedHook};
+
+ let response = ContributionResponse {
+ session_id: session_id(),
+ vars: vec![],
+ patches: vec![],
+ lifecycle_hooks: vec![WireProvenancedHook {
+ hook: WireLifecycleHook {
+ on_activate: Some(WireHookScript::Inline {
+ body: "echo hi".into(),
+ }),
+ ..Default::default()
+ },
+ source: package_source("helix"),
+ }],
+ };
+ let verdict: ContributionVerdict = handle_response(
+ response,
+ &[],
+ UserPolicy::empty(),
+ &PanicHooks,
+ ComposeOptions::default(),
+ &pinned_env(&[]),
+ )
+ .unwrap();
+ assert!(verdict.vars.is_empty());
+ assert!(verdict.patches.is_empty());
+}
+
+/// Patch-side parity for `policy_ignore_per_item`: a file matched
+/// by the patch policy's `ignore` rule produces an `Ignored`
+/// verdict (not Approved, not Denied).
+#[test]
+fn patch_policy_ignore_produces_ignored_verdict() {
+ let tmp = tempfile::tempdir().unwrap();
+ let root = Utf8Path::from_path(tmp.path()).unwrap();
+ fixture_tree(root, [("themes/draft.toml", "stale\n")]);
+
+ let response = ContributionResponse {
+ session_id: session_id(),
+ vars: vec![],
+ patches: vec![WirePendingPatch {
+ id: PendingId::new(1),
+ source_pattern: format!("{root}/themes/*.toml"),
+ destination: paths::SandboxRelPath::try_new(".config/helix/themes").unwrap(),
+ description: None,
+ source: project_source(),
+ }],
+ lifecycle_hooks: vec![],
+ };
+ let policy = UserPolicy::empty().with_patches(
+ PatchPolicy::empty()
+ .with_ignore(["/**/draft.toml"])
+ .with_allow(["/**/*.toml"]),
+ );
+
+ let verdict = handle_response(
+ response,
+ &[],
+ policy,
+ &PanicHooks,
+ ComposeOptions::default(),
+ &pinned_env(&[]),
+ )
+ .unwrap();
+ assert_eq!(verdict.patches.len(), 1);
+ assert!(matches!(
+ verdict.patches[0],
+ WirePatchVerdict::Ignored { .. }
+ ));
+}
+
+/// Var-side parity for `unapproved_files_batched_into_one_hook_call`:
+/// two unapproved pending vars produce a single hook invocation
+/// carrying both items, not one call per var.
+#[test]
+fn unapproved_vars_batched_into_one_hook_call() {
+ use std::cell::RefCell;
+
+ struct CountingHook {
+ calls: RefCell,
+ batch_sizes: RefCell>,
+ }
+ impl PolicyHooks for CountingHook {
+ fn on_var_unapproved(
+ &self,
+ _: VarsPolicy,
+ items: &[Unapproved<'_, str>],
+ ) -> HookResult {
+ *self.calls.borrow_mut() += 1;
+ self.batch_sizes.borrow_mut().push(items.len());
+ HookResult::decided(vec![ItemDecision::AllowOnce; items.len()])
+ }
+ fn on_patch_unapproved(
+ &self,
+ _: PatchPolicy,
+ _: &[Unapproved<'_, camino::Utf8Path>],
+ ) -> HookResult {
+ panic!("patch hook not expected")
+ }
+ }
+
+ let response = ContributionResponse {
+ session_id: session_id(),
+ vars: vec![
+ WirePendingVar {
+ id: PendingId::new(1),
+ name: "ONE".into(),
+ spec: WireVarSpec::Specified { value: "1".into() },
+ source: package_source("a"),
+ },
+ WirePendingVar {
+ id: PendingId::new(2),
+ name: "TWO".into(),
+ spec: WireVarSpec::Specified { value: "2".into() },
+ source: package_source("b"),
+ },
+ ],
+ patches: vec![],
+ lifecycle_hooks: vec![],
+ };
+
+ let hook = CountingHook {
+ calls: RefCell::new(0),
+ batch_sizes: RefCell::new(Vec::new()),
+ };
+ let verdict = handle_response(
+ response,
+ &[],
+ UserPolicy::empty(),
+ &hook,
+ ComposeOptions::default(),
+ &pinned_env(&[]),
+ )
+ .unwrap();
+
+ assert_eq!(*hook.calls.borrow(), 1, "expected exactly one hook call");
+ assert_eq!(
+ *hook.batch_sizes.borrow(),
+ vec![2],
+ "expected both vars in the same batch",
+ );
+ assert_eq!(verdict.vars.len(), 2);
+}
+
+// ---------------------------------------------------------------------
+// Error / edge-case coverage
+// ---------------------------------------------------------------------
+
+/// Hook returns `UseRule` along with an `updated_policy` that
+/// auto-approves the item via a new allow rule. Verdict is
+/// `Approved`.
+#[test]
+fn hook_use_rule_with_updated_policy_approves() {
+ struct UseRuleHook;
+ impl PolicyHooks for UseRuleHook {
+ fn on_var_unapproved(
+ &self,
+ policy: VarsPolicy,
+ items: &[Unapproved<'_, str>],
+ ) -> HookResult {
+ let updated = policy.try_with_allow(["MY_*"]).unwrap();
+ HookResult::decided_with_policy(vec![ItemDecision::UseRule; items.len()], updated)
+ }
+ fn on_patch_unapproved(
+ &self,
+ _: PatchPolicy,
+ _: &[Unapproved<'_, camino::Utf8Path>],
+ ) -> HookResult {
+ panic!("not expected")
+ }
+ }
+
+ let response = ContributionResponse {
+ session_id: session_id(),
+ vars: vec![WirePendingVar {
+ id: PendingId::new(1),
+ name: "MY_VAR".into(),
+ spec: WireVarSpec::Specified { value: "v".into() },
+ source: package_source("p"),
+ }],
+ patches: vec![],
+ lifecycle_hooks: vec![],
+ };
+ let verdict = handle_response(
+ response,
+ &[],
+ UserPolicy::empty(),
+ &UseRuleHook,
+ ComposeOptions::default(),
+ &pinned_env(&[]),
+ )
+ .unwrap();
+ assert!(matches!(verdict.vars[0], WireVarVerdict::Approved { .. }));
+}
+
+/// Hook returns `UseRule` but the policy still can't decide the item
+/// (no `updated_policy` and no matching rule) → `HookContract`.
+#[test]
+fn hook_use_rule_without_decision_errors_as_hook_contract() {
+ struct BadUseRuleHook;
+ impl PolicyHooks for BadUseRuleHook {
+ fn on_var_unapproved(
+ &self,
+ _: VarsPolicy,
+ items: &[Unapproved<'_, str>],
+ ) -> HookResult {
+ HookResult::decided(vec![ItemDecision::UseRule; items.len()])
+ }
+ fn on_patch_unapproved(
+ &self,
+ _: PatchPolicy,
+ _: &[Unapproved<'_, camino::Utf8Path>],
+ ) -> HookResult {
+ panic!("not expected")
+ }
+ }
+
+ let response = ContributionResponse {
+ session_id: session_id(),
+ vars: vec![WirePendingVar {
+ id: PendingId::new(1),
+ name: "MY_VAR".into(),
+ spec: WireVarSpec::Specified { value: "v".into() },
+ source: package_source("p"),
+ }],
+ patches: vec![],
+ lifecycle_hooks: vec![],
+ };
+ let err = handle_response(
+ response,
+ &[],
+ UserPolicy::empty(),
+ &BadUseRuleHook,
+ ComposeOptions::default(),
+ &pinned_env(&[]),
+ )
+ .unwrap_err();
+ assert!(
+ matches!(err, ComposeError::HookContract { .. }),
+ "got: {err:?}",
+ );
+}
+
+/// Hook returns the wrong number of decisions → `HookContract`.
+#[test]
+fn hook_wrong_decision_count_errors_as_hook_contract() {
+ struct WrongCountHook;
+ impl PolicyHooks for WrongCountHook {
+ fn on_var_unapproved(
+ &self,
+ _: VarsPolicy,
+ _items: &[Unapproved<'_, str>],
+ ) -> HookResult {
+ // Always emit two, regardless of input length.
+ HookResult::decided(vec![ItemDecision::AllowOnce, ItemDecision::AllowOnce])
+ }
+ fn on_patch_unapproved(
+ &self,
+ _: PatchPolicy,
+ _: &[Unapproved<'_, camino::Utf8Path>],
+ ) -> HookResult {
+ panic!("not expected")
+ }
+ }
+
+ let response = ContributionResponse {
+ session_id: session_id(),
+ vars: vec![WirePendingVar {
+ id: PendingId::new(1),
+ name: "MY_VAR".into(),
+ spec: WireVarSpec::Specified { value: "v".into() },
+ source: package_source("p"),
+ }],
+ patches: vec![],
+ lifecycle_hooks: vec![],
+ };
+ let err = handle_response(
+ response,
+ &[],
+ UserPolicy::empty(),
+ &WrongCountHook,
+ ComposeOptions::default(),
+ &pinned_env(&[]),
+ )
+ .unwrap_err();
+ assert!(
+ matches!(err, ComposeError::HookContract { .. }),
+ "got: {err:?}",
+ );
+}
+
+/// A pending patch whose destination violates `PatchDest` invariants
+/// surfaces as [`ComposeError::InvalidPendingPatchDest`].
+#[test]
+fn invalid_pending_patch_dest_errors() {
+ use sessions::core::primitives::PatchError;
+
+ let response = ContributionResponse {
+ session_id: session_id(),
+ vars: vec![],
+ patches: vec![WirePendingPatch {
+ id: PendingId::new(1),
+ source_pattern: "/tmp/nonexistent/*".into(),
+ // Empty path passes `SandboxRelPath` validation but
+ // `PatchDest::try_new` rejects it.
+ destination: paths::SandboxRelPath::try_new("").unwrap(),
+ description: None,
+ source: package_source("p"),
+ }],
+ lifecycle_hooks: vec![],
+ };
+ let err = handle_response(
+ response,
+ &[],
+ UserPolicy::empty(),
+ &PanicHooks,
+ ComposeOptions::default(),
+ &pinned_env(&[]),
+ )
+ .unwrap_err();
+ assert!(
+ matches!(
+ err,
+ ComposeError::InvalidPendingPatchDest {
+ source: PatchError::EmptyDest
+ }
+ ),
+ "got: {err:?}",
+ );
+}
+
+/// Two pending patches whose source patterns each yield one
+/// unapproved file: the handler batches them into a *single* hook
+/// call so the user sees one prompt per response, not one per
+/// pending patch.
+#[test]
+fn unapproved_files_batched_into_one_hook_call() {
+ use std::cell::RefCell;
+
+ struct CountingHook {
+ calls: RefCell,
+ batch_sizes: RefCell>,
+ }
+ impl PolicyHooks for CountingHook {
+ fn on_var_unapproved(
+ &self,
+ _: VarsPolicy,
+ _: &[Unapproved<'_, str>],
+ ) -> HookResult {
+ panic!("var hook not expected")
+ }
+ fn on_patch_unapproved(
+ &self,
+ _: PatchPolicy,
+ items: &[Unapproved<'_, camino::Utf8Path>],
+ ) -> HookResult {
+ *self.calls.borrow_mut() += 1;
+ self.batch_sizes.borrow_mut().push(items.len());
+ HookResult::decided(vec![ItemDecision::AllowOnce; items.len()])
+ }
+ }
+
+ let tmp = tempfile::tempdir().unwrap();
+ let root = Utf8Path::from_path(tmp.path()).unwrap();
+ fixture_tree(root, [("a/conf.toml", "a"), ("b/conf.toml", "b")]);
+
+ let response = ContributionResponse {
+ session_id: session_id(),
+ vars: vec![],
+ patches: vec![
+ WirePendingPatch {
+ id: PendingId::new(1),
+ source_pattern: format!("{root}/a/*.toml"),
+ destination: paths::SandboxRelPath::try_new(".config/a").unwrap(),
+ description: None,
+ source: package_source("a"),
+ },
+ WirePendingPatch {
+ id: PendingId::new(2),
+ source_pattern: format!("{root}/b/*.toml"),
+ destination: paths::SandboxRelPath::try_new(".config/b").unwrap(),
+ description: None,
+ source: package_source("b"),
+ },
+ ],
+ lifecycle_hooks: vec![],
+ };
+
+ let hook = CountingHook {
+ calls: RefCell::new(0),
+ batch_sizes: RefCell::new(Vec::new()),
+ };
+ let verdict = handle_response(
+ response,
+ &[],
+ UserPolicy::empty(),
+ &hook,
+ ComposeOptions::default(),
+ &pinned_env(&[]),
+ )
+ .unwrap();
+
+ assert_eq!(*hook.calls.borrow(), 1, "expected exactly one hook call");
+ assert_eq!(
+ *hook.batch_sizes.borrow(),
+ vec![2],
+ "expected both files in the same batch",
+ );
+ assert_eq!(verdict.patches.len(), 2);
+ let ids: Vec<_> = verdict.patches.iter().map(verdict_patch_id).collect();
+ assert!(ids.contains(&PendingId::new(1)));
+ assert!(ids.contains(&PendingId::new(2)));
+}
+
+// =====================================================================
+// Helpers for verdict introspection
+// =====================================================================
+
+fn verdict_var_id(v: &WireVarVerdict) -> u32 {
+ let id = match v {
+ WireVarVerdict::Approved { id, .. }
+ | WireVarVerdict::Denied { id, .. }
+ | WireVarVerdict::Ignored { id, .. } => *id,
+ };
+ id.get()
+}
+
+fn verdict_patch_id(v: &WirePatchVerdict) -> PendingId {
+ match v {
+ WirePatchVerdict::Approved { id, .. }
+ | WirePatchVerdict::Denied { id, .. }
+ | WirePatchVerdict::Ignored { id, .. } => *id,
+ }
+}