Skip to content

feat(box): add reload library API - #217

Merged
gautamsirdeshmukh merged 16 commits into
strands-agents:mainfrom
gautamsirdeshmukh:gsird-task/reload-library-api
Nov 2, 2026
Merged

gautamsirdeshmukh merged 16 commits into
strands-agents:mainfrom
gautamsirdeshmukh:gsird-task/reload-library-api

Conversation

@gautamsirdeshmukh

@gautamsirdeshmukh gautamsirdeshmukh commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Description

A library caller cannot change the policy of a running box. It must stop the box and start a new one, and that ends the agent's work.

This PR adds strands_box::reload(&[Policy]) -> Result<(), ReloadRefused>. It replaces the running box's policy in the same process, and the workload keeps running.

Decisions:

  • Reload is strict. It uses the existing PolicyEngine::reload, and its signature does not change. The new policy must validate in full, or Box refuses it and the old policy stays. A rule about one MCP server's tool can only be checked after the agent has used that server. Before that, the reload is refused. The README states this limit. An earlier version of this PR kept such rules pending. That design let a forbidden tool become allowed, so this PR removes it.
  • The handle is in-process. HostedBox::open publishes the box's policy engine in a private static, and Drop clears it. feat(box): reach a running box's policy from a library caller #149 left open whether reload is an in-process call or a request to another process. This PR answers it for the current in-process library. A cross-process design would need a new call.
  • Errors use the existing wrapper pattern. ReloadRefused wraps the internal BoxError, as CheckFailed and GrantRefused do. BoxError stays private. ReloadRefused::is_not_running() tells a caller that no box is open yet, so the caller can retry.
  • Reload is recorded. Each reload writes a policy_installed or policy_refused control record. policy_refused can now also mean a refused reload, not only a box that did not start.
  • It fixes a defect that is also on main. When discovery ends with a rule still waiting, Box blocks that rule's tools. But if the tool's server had already reported its tools, a call to it was allowed. Now the tool stays blocked, and a successful reload removes the block. The check now runs under one lock, so a reload cannot change the state in the middle of a decision.

API approval: this PR adds reload, ReloadRefused, ReloadRefused::is_not_running, and a re-export of Policy to the frozen strands-box surface. It also widens what policy_refused means. These need maintainer approval.

Deferred:

  • A tool name that contains a " can still get past the block, because the scan for typed actions stops at the first quote. This is also on main, and it needs its own fix.
  • A degraded tool stays blocked if its server reports its tools later without a reload. This fails closed and is also on main.

Related Issues

Covers the library reload use case in #149.

Type of Change

New feature

Testing

  • I ran the relevant suites (just check, or cargo test --workspace --all-features)
  • If I touched Rust, I ran cargo fmt --all and cargo clippy --workspace --all-targets --all-features -- -D warnings

On macOS: the policy crate tests, the live library reload test, clippy, and fmt pass. The containment suite passes (121 passed, 12 Linux cases skipped). Linux runs in CI only.

  • The live library test changes a real box's policy from deny to allow to deny, and the workload keeps running. It also checks invalid policy, empty policy, a rule for a server the agent has not used, unchanged policy files, and refusal when no box is open. It checks the control records too.
  • A policy test shows the degraded-tool fix. It fails on main's code. Removing the block, or removing the clear on reload, makes it fail.
  • A policy test shows that during discovery a reload that names a server the agent has not used is refused, and the old forbid stays through the end of discovery.

Checklist

  • I have read the CONTRIBUTING document
  • I have reviewed and understand every line of code in this PR, including any generated by AI tools, and I can explain why it works
  • My change is focused and reasonably small; I have split unrelated work into separate PRs
  • I have added any necessary tests that prove my fix is effective or my feature works
  • I have updated the documentation accordingly
  • My changes generate no new warnings

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.

## Problem

A library caller cannot reach the policy engine that its running box uses.
Boxy needs to replace that policy without restarting the workload.

## Solution

Add reload(&[Policy]) beside run, with ReloadFailed over the existing BoxError.
The private run path holds a reference to its existing engine during workload
supervision. Reload withdrawal waits for an active call before the box lock
is released. The run signature, RunOptions, and policy engine stay unchanged.
The library guide and architecture describe the added surface and its lifetime.

## Tests

Ran just check across the workspace. Final changes passed just build,
just fmt-check, just clippy, and cargo test -p strands-box --all-features.
All commands used RUSTFLAGS='-C debuginfo=0', as CI does.

box_library::reload_tests::running_box covers live deny/allow/deny changes,
invalid replacements, default-deny, unchanged policy files, and reload refusal
outside the run. The workload keeps its process ID throughout the probe.
The existing fatal_durable_staging_stops_the_supervised_workload_and_withdraws_live_state
test now pins ownership until explicit teardown.

Both negative controls failed as expected: a no-op reload leaves the read
denied, and an early ownership release fails the live-state assertion.
Both restored tests passed. Feature-critic reported no remaining findings.
Existing ignored tests remain ignored. Linux and separate example and
containment harnesses were not run locally.
@github-actions github-actions Bot added Area - policy-engine enhancement New feature or request labels Oct 29, 2026
@gautamsirdeshmukh gautamsirdeshmukh changed the title feat(box): expose live policy reload to library callers feat(box): add reload library API Oct 29, 2026
Comment thread crates/box/src/run/hosted.rs Resolved
Comment thread crates/box/src/run/hosted.rs Resolved
Comment thread crates/box/src/run/hosted.rs Resolved
@github-actions

Copy link
Copy Markdown

Assessment: Request Changes

This review covers head 8802b8b. The reload path is easy to follow and tears down correctly. However, it is reachable from the end of HostedBox::open, and the policy engine's reload assumes it only runs after MCP discovery has finished. The authority change it makes is also not visible in the box's audit records.

Review Categories
  • Correctness: Live reload was only tested with built-in Box::Action rules. Reload during MCP discovery is not tested, and that is where it gives wrong results (see the inline comment).
  • Written rules: The control-plane telemetry contract (docs/design/telemetry.md) and the typed-error rule (crates/box/AGENTS.md) are not met.
  • API scope: Root AGENTS.md says an addition to the strands-box surface needs explicit approval ("a rename counts, and so does an addition"). This PR adds reload and makes BoxError public, but has no api/needs-review label. feat(box): reach a running box's policy from a library caller #149 left open questions that this design answers implicitly: in-process pointer or cross-process request, who owns the policy source, and whether a reload needs a receipt. The description should state those decisions.

Checked and held:

  • No public signature names a PolicyEngine, and BoxError stays an opaque struct.
  • Each box still has one engine. STARTED allows one run per process, and the static points at that run's existing Arc.
  • reload(&[]) falls back to default-deny, which matches the premise that absent policy is default-deny.
  • RUNNING_POLICY is set after the last fallible step of open, and Drop clears it before the lock is released. Drop waits for an active reload because reload holds the mutex.
  • ApprovedReach does not depend on policy, so the README is correct that the OS sandbox is unchanged.
  • The workload runs in a separate process and cannot reach the in-process static.

@gautamsirdeshmukh
gautamsirdeshmukh marked this pull request as ready for review October 30, 2026 17:50
hanaduy
hanaduy previously approved these changes Oct 30, 2026

@kevin-orellana kevin-orellana left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I reproduced a case where reload reports success, but a previously forbidden tool becomes allowed after discovery finishes.

The replacement rule forbids two tools. One tool’s definition is available; the other is still missing. Reload accepts the replacement and temporarily blocks the known tool. If discovery ends without the missing definition, the known tool becomes allowed.

The replacement is invalid when checked against both definitions. Before this change, reload rejects it and preserves the original prohibition.

Could we reject invalid replacements without changing the active policy, and ensure unresolved rules keep their tools blocked after discovery? A regression covering this sequence would help. I am requesting changes because this can remove a working authorization restriction.

Steps to reproduce

  1. Use a clean checkout at 68389401911fb967e42488f12debd14e90449650.
  2. Save the test below as crates/policy/tests/review_reload.rs.
  3. From the repository root, run:
env -u REVIEW_EXPECT_REJECT CARGO_PROFILE_DEV_DEBUG=0 CARGO_PROFILE_TEST_DEBUG=0 cargo test --locked -p strands-box-policy --all-features --test review_reload -- --nocapture

The test opens a policy engine and loads only Alpha’s tool definition. It installs a working prohibition on alpha/read. It then reloads a replacement that forbids both alpha/read and beta/read, without loading Beta’s definition. Finally, it ends discovery and checks Alpha again.

Expected: Reject the invalid replacement and preserve the original prohibition. If a replacement remains pending, discovery completion must not make its affected tool callable.

Actual: Reload succeeds. Alpha is initially denied with PolicyPending, but becomes Allow after discovery ends. The final assertion fails:

pending=Deny { reason: PolicyPending, rule: RuleId("<policy-pending>"), resource: "alpha/read" }; degraded=["alpha", "beta"]; after=Allow { rule: RuleId("<default-deny>"), resource: "alpha/read" }
Reproduction test
//! Review probes for reload and tool discovery.

use policy::{GovernedBox, Operator, Policy, PolicyEngine, Principal, generate_mcp_schema};

fn source(text: &str) -> Vec<Policy> {
    vec![Policy {
        origin: "review.dw".into(),
        text: text.into(),
    }]
}

#[test]
fn pending_forbid_keeps_known_tool_denied_when_discovery_ends() {
    let history = tempfile::tempdir().unwrap();
    let engine = PolicyEngine::open_staged(
        &Operator::unanchored(),
        source("permit(principal, action, resource);"),
        &history.path().join("history"),
    )
    .unwrap();
    let schema = generate_mcp_schema(
        "alpha",
        r#"{"result":{"tools":[{"name":"read","inputSchema":{"type":"object","properties":{}}}]}}"#,
    )
    .unwrap();
    engine.stage_mcp_schema("alpha", schema.clone()).unwrap();
    let forbidden = source(
        r#"permit(principal, action, resource);
        forbid(principal, action == alpha::Action::"read", resource);"#,
    );
    engine.reload(&forbidden).unwrap();
    let call = || {
        engine.refine_tool_call(
            &GovernedBox::assigned("review"),
            &Principal::agent(),
            "alpha",
            "read",
            &serde_json::json!({}),
        )
    };
    assert!(!call().is_allow(), "the original forbid must deny alpha");
    let replacement = source(
        r#"permit(principal, action, resource);
        forbid(principal, action in [alpha::Action::"read", beta::Action::"read"], resource);"#,
    );
    let beta_schema = generate_mcp_schema(
        "beta",
        r#"{"result":{"tools":[{"name":"read","inputSchema":{"type":"object","properties":{}}}]}}"#,
    )
    .unwrap();
    let fully_checked = PolicyEngine::validate_with_mcp_schemas(
        &Operator::unanchored(),
        &replacement,
        &[schema, beta_schema],
    );
    assert!(fully_checked.is_err(), "the replacement mixes incompatible action types");
    eprintln!("complete validation refuses replacement: {fully_checked:?}");
    let reload = engine.reload(&replacement);
    if std::env::var_os("REVIEW_EXPECT_REJECT").is_some() {
        assert!(reload.is_err(), "the baseline must refuse this replacement");
        assert!(!call().is_allow(), "the old forbid must remain installed");
        eprintln!("baseline refused replacement and preserved deny: {reload:?}");
        return;
    }
    reload.unwrap();
    let pending = call();
    assert!(!pending.is_allow(), "the pending forbid must deny alpha");
    let degraded = engine.finish_mcp_discovery().unwrap();
    let after = call();
    eprintln!("pending={pending:?}; degraded={degraded:?}; after={after:?}");
    assert!(
        !after.is_allow(),
        "finishing discovery must not turn the unresolved forbid into an allow"
    );
}

I ran this through the real policy library on macOS. The 25 existing authority tests pass. Restoring the base authority implementation rejects the replacement and preserves the denial. A temporary early check for degraded tools also prevents the demonstrated permission. That check alone does not fix acceptance of invalid replacement text. Restoring this PR’s production code reproduces the failure again.

Comment thread crates/policy/src/policy/authority.rs Resolved
Comment thread crates/box/src/lib.rs Resolved
@github-actions

Copy link
Copy Markdown

Assessment: Request Changes

This review covers head 6838940. All three earlier threads are fixed. Reload now writes policy_installed/policy_refused records, NotRunning is a typed variant, and reload during discovery keeps per-tool rules pending instead of refusing them. The new discovery-time staging path brings back the problem the old strict reload was there to prevent: a reload can succeed even though one of its rules can never become live.

Review Categories
  • Correctness: The pending path cannot tell "schema not discovered yet" from "no declared server has this name". Because discovery is lazy, that window can last the whole run (see the inline comment).
  • API usability: The caller has no way to know when the box is open. The only signal is a Display string.
  • API scope (still open): The PR still has no api/needs-review label. Root AGENTS.md requires approval for an addition to the public surface, and this PR adds reload and a public BoxError.

Checked and held this round:

  • Reload still takes the proposal lock before the live lock, so it cannot deadlock against stage_mcp_schema. finish_mcp_discovery sets discovery_finished under the proposal lock, so a reload either runs strict or is degraded later by the finish step.
  • During discovery, the reload refuses an invalid rule for a server that has already been discovered, a mixed Box/per-tool scope, and an inert error. All five reload tests in the policy crate pass locally.
  • A successful reload with nothing left pending sets the authority to Ready. A reload that leaves rules pending sets Discovering again and recomputes pending_tools.
  • Reload control records go through the run's collector and are drained at command::execute. The PolicyRefused doc and docs/design/telemetry.md now describe the refused-reload case.
  • A poisoned RUNNING_POLICY lock is recovered the same way open and Drop recover it.

Comment thread crates/policy/src/policy/authority.rs Resolved
@github-actions

Copy link
Copy Markdown

Assessment: Comment

This review covers head a7bf105, one commit over 8819daa. The commit merges reload and reload_with_mcp_servers into a single PolicyEngine::reload(&[Policy], &[String]) and restores comments that had been dropped. Behaviour does not change, and I found no new issues. The API-approval gate from the last round still applies, and it now covers crates/policy as well. crates/policy/AGENTS.md says "This crate is interface-frozen: the pub use façade", and PolicyEngine::reload is new there (it is not on main). The PR still has no api/needs-review label.

Checked and held this round:

  • The merge is mechanical. hosted::reload passes the declared servers. Every former reload(x) test call now passes &[], and every former reload_with_mcp_servers call passes ["alpha", "beta"], so each test runs the same path as before.
  • No caller of reload_with_mcp_servers remains in the workspace. cargo check --workspace --all-targets --all-features is clean; the only warnings are pre-existing ones in vendored strands-shell.
  • The restored comments match the code:
    • "Validation runs before the live lock is taken": reload validates before it calls live.lock().
    • The NoMatch → coarse-allow note describes the tool_refinement arm correctly.
  • The policy crate's lib tests pass locally: 214 passed, 7 ignored.

@github-actions

github-actions Bot commented Nov 2, 2026

Copy link
Copy Markdown

Assessment: Comment

This review covers head 8b44be7, two commits over a7bf105 (a18bcf1, 8b44be7). Reload is now strict: every rule has to validate against the schemas staged so far, or the whole reload is refused. The mcp_servers parameter, policy_is_tool_scoped, and discovery_finished are gone, and BoxError is replaced on the public surface by ReloadRefused. This design avoids the namespace-typo and pending-forever problems from earlier rounds. One new case is wrong: a degraded server (see inline).

Review Categories
  • Correctness: Strict reload treats "schema not staged yet" the same as "schema will never stage". The second case makes the startup file impossible to reload after a degrade.
  • API scope (still open): There is still no api/needs-review label. Root AGENTS.md and crates/policy/AGENTS.md ("interface-frozen: the pub use façade") require approval for the new strands_box::reload/ReloadRefused and PolicyEngine::reload.
  • Scope note: collect_typed_actions and the mcp_fragment test helper go back to main's naive quote scan, and the escaped-tool-name test is removed. That restores pre-existing behaviour, so it is not a regression from this PR.

Checked and held this round:

  • Reload during discovery with no remaining typed rules for undiscovered servers ends Ready with pending_tools empty. A later stage_mcp_schema validates against the complete set and commits.
  • finish_mcp_discovery returns early when reload has already made the authority Ready.
  • A refused reload during discovery keeps the startup pending block, and the identical file is refused before the server is discovered, as documented.
  • Lock order is still proposal, then live.
  • refine_tool_call gives the same results as the earlier decide(…, true) in every branch: degraded, pending, undeclared, no match, and cedar_uid error.
  • ReloadRefused follows the existing CheckFailed/GrantRefused newtype pattern, and BoxError is now pub(crate).
  • Tests: the policy crate passes 211 tests with 7 ignored, box_library passes, and cargo check --workspace is clean.

Comment thread crates/policy/src/policy/authority.rs Resolved
@github-actions

github-actions Bot commented Nov 2, 2026

Copy link
Copy Markdown

Assessment: Comment

This review covers head e2ed3e8, one commit over 8b44be7 (README text and one test). The degraded-server thread is fixed: you kept reload strict, documented that choice, and added a test for it. I left an optional suggestion in that thread and found no new issues. The API-approval gate is still open: there is still no api/needs-review label, and strands_box::reload/ReloadRefused and PolicyEngine::reload are new on surfaces that AGENTS.md marks interface-frozen.

Checked and held this round:

  • The new README text matches the code:
    • "even reloading the unchanged policy is refused" — the identical file → Err.
    • "The current policy stays in place" — the degraded deny survives the refused reload.
  • The new test asserts the degraded server list as a whole value (vec!["alpha"]), not field by field.
  • Tests: the policy crate's lib tests pass locally (212 passed, 7 ignored).

@gautamsirdeshmukh
gautamsirdeshmukh enabled auto-merge (squash) November 2, 2026 19:02
@gautamsirdeshmukh
gautamsirdeshmukh merged commit db48193 into strands-agents:main Nov 2, 2026
16 checks passed
@github-actions

github-actions Bot commented Nov 2, 2026

Copy link
Copy Markdown

Assessment: Comment (no new findings)

This review covers head 9f6e0a3, a merge of main (0247b23) into e2ed3e8. The merge changed nothing that this PR adds. The only conflict hunks are in policy.rs and authority.rs, and I checked both.

Checked and held this round:

  • refine_tool_call: it now calls main's decide(governed, principal, ActionRequest::Request(request)) instead of decide_with_identity. ActionIdentity::for_request returns mcp_tool(server, tool) for a tools/call, which is the same identity the old code passed in. It still takes the degraded, pending, undeclared, no-match, and fault branches under one live lock, as before.
  • conclude(&identity, request.resource(), …): this matches the new signature on main.
  • Pack schemas (feat(policy): bind a tool pack on the program file and the command name #246/feat(policy): decide and record tool pack actions in the policy engine #247): only open_complete_with_packs/open_with_packs add them, and those paths are not staged and are used only in tests. So reload cannot drop pack schemas from a staged box today. If packs reach a staged box later, reload will have to carry them into its validation.
  • Net diff against main: 11 files, +484/−109, which is the same scope as before the merge.
  • Tests:
    • The policy crate's lib tests pass locally (226 passed, 7 ignored), including all five reload and degraded-tool tests.
    • box_library builds, but its live reload test skips on this runner because no containment backend is available.
    • cargo clippy --workspace --all-targets --all-features compiles. The only warnings are in strands-shell, which this PR does not touch.

Still open: the PR has no api/needs-review label. The frozen strands-box surface needs maintainer approval for its new additions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants