Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion docs/studio/behaviour/background-runs.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ A run that cannot start is refused at the click with why and its prompt: the har

## On the map

The Map view's side area lists the project's runs under **Background runs** (`ui/map-runs.ts`): a running run with when it started, the queued ones, and each ended run with how it ended and the calls it was denied. They sit on the sheet's glass, since the map pans under the side column and they can cross a plate as the sheet can (#472). A queued or running run has **Cancel**; an ended one has **Dismiss**, and **Copy prompt** unless it finished cleanly. Cancel on a running run asks first (#459): a dialog names what goes, the run's worktree and the changes it made, with Cancel focused and **Cancel run** to go ahead; Esc or Cancel sends nothing. Cancel on a queued run and Dismiss act at once. An ended run stays until it is dismissed or plotkeeper starts again. While plotkeeper still reads an ended run's folder (back a law's proof, a micro-world's host checks and its rewrite) the runner holds the run (`Runner::hold`), and Dismiss is refused, with the notice line saying so, until that is done. A copied prompt's note stays under its row when the map is drawn again. The server tells the page when a run starts or ends, so the rows change with no timer. A past commit's map shows no runs.
The Map view's side area lists the project's runs under **Background runs** (`ui/map-runs.ts`): a running run with when it started, the queued ones, and each ended run with how it ended and the calls it was denied. A run on a Claude Code the sandbox gate has not passed on has the warning under its note in every state ([The gated version](#the-gated-version)). They sit on the sheet's glass, since the map pans under the side column and they can cross a plate as the sheet can (#472). A queued or running run has **Cancel**; an ended one has **Dismiss**, and **Copy prompt** unless it finished cleanly. Cancel on a running run asks first (#459): a dialog names what goes, the run's worktree and the changes it made, with Cancel focused and **Cancel run** to go ahead; Esc or Cancel sends nothing. Cancel on a queued run and Dismiss act at once. An ended run stays until it is dismissed or plotkeeper starts again. While plotkeeper still reads an ended run's folder (back a law's proof, a micro-world's host checks and its rewrite) the runner holds the run (`Runner::hold`), and Dismiss is refused, with the notice line saying so, until that is done. A copied prompt's note stays under its row when the map is drawn again. The server tells the page when a run starts or ends, so the rows change with no timer. A past commit's map shows no runs.

## Micro-worlds

Expand Down Expand Up @@ -153,6 +153,12 @@ What the gate found on the way, and changed here:

The raw output of each round is in `local-evidence/2026-11-24-issue-395-sandbox-gate/` on Daniel's machine, and of #773's run in `local-evidence/2026-11-28-issue-773-sandbox-gate/`. Rerun the gate after a Claude Code update: its behaviour here changed between the versions tried.

### The gated version

The version the gate last passed on is a constant in the code, `GATED_CLAUDE_CODE` in `server/src/runner.rs`, beside the sandbox block: now 2.1.326, #773's run. A gate rerun that passes sets it to the version its `summary.md` names (the gate writes `claude --version` there), in the same PR that records the result in the table above.

When a run is submitted, plotkeeper reads `claude --version`. On any other version the run still starts, and carries a warning (#774): "The sandbox gate has not run on Claude Code <version> (last passed on 2.1.326)." A version that does not read, such as a `claude` that fails or prints no version, gives "The sandbox gate has not run on an unknown version of Claude Code (last passed on 2.1.326)." Claude Code updates every few days, so an ungated version is the usual case, and a refusal would block every run after each update ([decision](https://github.com/danielrispler/plotkeeper/issues/411#issuecomment-7226068820)). The warning is kept in the run's `run.json`, so it outlives a restart, and reaches the map as the run's `warning`, beside its `line`. The run's row shows it under its note while the run is queued, running and ended.

### On Linux

Claude Code's sandbox on Linux is bubblewrap, with socat for its network bridge, and when either is missing or the sandbox cannot start, Claude Code runs commands unsandboxed. So the launcher's check on Linux (`BWRAP_CHECK`, #704) looks both up on `PATH`, as Claude Code does, then runs `/bin/sh -c true` under bubblewrap in the shape Claude Code's sandbox runtime gives it, less its mounts and bridges:
Expand Down
5 changes: 4 additions & 1 deletion scripts/snap/fixtures-runs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@ export const mapRuns = (): Fixture =>
if (rows[0].dataset.state !== "running" || !rows[0].textContent.includes("Running since")) log("snap:fail the running row: " + rows[0].textContent);
if (!rows[1].textContent.includes("Queued, next") || !rows[2].textContent.includes("Micro-world")) log("snap:fail the queue: " + rows[1].textContent + " / " + rows[2].textContent);
if (!rows[3].textContent.includes("1 tool call was denied") || !rows[3].textContent.includes("git push")) log("snap:fail the denied run: " + rows[3].textContent);
const warned = rows.map((row) => row.querySelector(".run-warning")?.textContent ?? "");
if (!warned[0].startsWith("The sandbox gate has not run on Claude Code 2.1.399") || warned.slice(1).some(Boolean)) log("snap:fail the ungated warning: " + warned.join(" / "));
if (rows[0].querySelector(".run-note")?.nextElementSibling?.className !== "run-warning") log("snap:fail the warning is not under the note");
const words = (row) => [...row.querySelectorAll("button")].map((button) => button.textContent).join(",");
if (words(rows[0]) !== "Cancel" || words(rows[1]) !== "Cancel" || words(rows[3]) !== "Copy prompt,Dismiss") log("snap:fail the buttons: " + rows.map(words).join(" / "));
if (document.querySelector("#map-runs .runs-paused")) log("snap:fail a pause shows with no pause");
Expand All @@ -65,7 +68,7 @@ export const mapRuns = (): Fixture =>
runs: {
paused: null,
runs: [
{ id: "19a2f-1", kind: "back-law", state: "running", at: runAt, outcome: null, line: null, denials: [], prompt: null },
{ id: "19a2f-1", kind: "back-law", state: "running", at: runAt, outcome: null, line: null, warning: "The sandbox gate has not run on Claude Code 2.1.399 (last passed on 2.1.326).", denials: [], prompt: null },
{ id: "19a2f-2", kind: "back-law", state: "queued", at: runAt, outcome: null, line: null, denials: [], prompt: null },
{ id: "19a2f-3", kind: "micro-world", state: "queued", at: runAt, outcome: null, line: null, denials: [], prompt: null },
{ id: "19a2f-0", kind: "back-law", state: "ended", at: runAt, outcome: "denied", line: "Finished, but 1 tool call was denied", denials: ["Bash: git push origin HEAD"], prompt: "Write a test tagged @law: core-order." },
Expand Down
53 changes: 52 additions & 1 deletion server/src/runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,11 @@ pub struct Plan<'a> {
pub trait Harness: Send + Sync {
/// The command for `plan`, or why there is none, such as a program that is not installed.
fn command(&self, plan: &Plan) -> Result<HarnessCommand, String>;

/// What a run of `command` warns of while it runs anyway, such as a version the sandbox gate has not passed on.
fn warning(&self, _command: &HarnessCommand) -> Option<String> {
None
}
}

/// Claude Code, headless: `claude -p`, found as the login shell's `command -v` finds it.
Expand All @@ -209,6 +214,10 @@ impl Harness for Claude {
.ok_or("`claude` was not found, so the run cannot start")?;
Ok(claude_command(&program, plan))
}

fn warning(&self, command: &HarnessCommand) -> Option<String> {
gate_warning(&command.program)
}
}

/// The sandbox block a run's `--settings` carries, as spec #378 gives it and the sandbox gate (#395) settled: the user's
Expand Down Expand Up @@ -251,6 +260,39 @@ pub fn shared_tmp() -> Vec<PathBuf> {
shared
}

/// The Claude Code version the sandbox gate (#395) last passed on. A gate rerun that passes updates it, in the PR that
/// records the result (`docs/studio/behaviour/background-runs.md`, "The sandbox gate").
pub const GATED_CLAUDE_CODE: &str = "2.1.326";

/// The warning a run on the Claude Code at `program` carries when the sandbox gate has not passed on its version, read
/// from `<program> --version` (`2.1.326 (Claude Code)`); none on [`GATED_CLAUDE_CODE`]. A version that does not read is
/// an unknown one. The run starts either way: Claude Code updates every few days, so an ungated version is the usual
/// case (#774).
pub fn gate_warning(program: &Path) -> Option<String> {
let output = studio_workbench::run::run_until(
Command::new(program).arg("--version"),
Duration::from_secs(10),
);
let said = output.map(|output| String::from_utf8_lossy(&output.stdout).into_owned());
let version = said.ok().and_then(|said| {
let first = said.split_whitespace().next()?.to_string();
let numbers = first.split('.').collect::<Vec<_>>();
let reads = numbers.len() > 1
&& numbers
.iter()
.all(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()));
reads.then_some(first)
});
let on = match version.as_deref() {
Some(GATED_CLAUDE_CODE) => return None,
Some(version) => format!("Claude Code {version}"),
None => "an unknown version of Claude Code".into(),
};
Some(format!(
"The sandbox gate has not run on {on} (last passed on {GATED_CLAUDE_CODE})."
))
}

/// The git commands a run's shell may use: reading, and staging inside its own clone. Never a commit, a push or `gh`.
const GIT: [&str; 4] = ["git status", "git diff", "git log", "git add"];

Expand Down Expand Up @@ -461,6 +503,8 @@ pub struct RunView {
/// How an ended run ended, and one line on it.
pub outcome: Option<End>,
pub line: Option<String>,
/// What the run warns of in every state, such as a Claude Code the sandbox gate has not passed on ([`gate_warning`]).
pub warning: Option<String>,
pub denials: Vec<String>,
/// The fallback: the run's prompt, for Daniel to paste into his own agent, on every end but a clean one.
pub prompt: Option<String>,
Expand Down Expand Up @@ -529,6 +573,9 @@ struct Stored {
#[serde(default)]
setup: Option<String>,
command: HarnessCommand,
/// What the run warns of, read when it was submitted ([`Harness::warning`]); a run from before #774 has none.
#[serde(default, skip_serializing_if = "Option::is_none")]
warning: Option<String>,
}

/// What the launcher reads of `run.json`: only what it runs, so a run of a kind this build does not know still keeps its
Expand Down Expand Up @@ -1124,7 +1171,8 @@ impl Runner {
}

/// Queues `request` and starts it when its project has no run going: the run's id. Reads `settings.json` now, so a
/// saved change counts from the next run. A run that cannot start is refused with the prompt to copy instead, and its
/// saved change counts from the next run, and asks the harness what the run warns of ([`Harness::warning`]: for
/// `claude`, a `claude --version` of up to 10 s), before it takes the runner's lock. A run that cannot start is refused with the prompt to copy instead, and its
/// folder is removed: a harness other than `claude`, a kind with a shell in a project with no `checks`, or a harness
/// that builds no command.
pub fn submit(&self, request: Request) -> Result<String, Refusal> {
Expand Down Expand Up @@ -1172,6 +1220,7 @@ impl Runner {
data: &self.config.data,
};
let mut command = self.config.harness.command(&plan).map_err(refuse)?;
let warning = self.config.harness.warning(&command);
let cores = cores().to_string();
for name in ["CARGO_BUILD_JOBS", "NEXTEST_TEST_THREADS"] {
command.env.insert(name.into(), cores.clone());
Expand All @@ -1186,6 +1235,7 @@ impl Runner {
timeout_secs: request.limits.timeout.as_secs().max(1),
setup: settings.setup.filter(|_| request.kind.takes_setup()),
command,
warning,
};
write_json(&dir.join(RUN), &stored)
.map_err(|e| refuse(format!("the run could not be saved: {e}")))?;
Expand Down Expand Up @@ -1673,6 +1723,7 @@ impl Runner {
at,
outcome: outcome.map(|outcome| outcome.end),
line: outcome.map(|outcome| line(stored, outcome)),
warning: stored.warning.clone(),
denials: outcome
.map(|outcome| outcome.denials.clone())
.unwrap_or_default(),
Expand Down
135 changes: 133 additions & 2 deletions server/tests/runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@ use std::{
time::{Duration, Instant},
};
use studio_server::runner::{
BWRAP_CHECK, Config, End, Harness, HarnessCommand, Kind, Limits, Plan, Request, RunState,
Runner, SANDBOX_DOWN, allowed_tools, claude_command, private_tmp, sandbox_settings,
BWRAP_CHECK, Config, End, GATED_CLAUDE_CODE, Harness, HarnessCommand, Kind, Limits, Plan,
Request, RunState, Runner, SANDBOX_DOWN, allowed_tools, claude_command, gate_warning,
private_tmp, sandbox_settings,
};
use studio_test_support::LauncherGuard;

Expand Down Expand Up @@ -454,6 +455,43 @@ fn stand_ins(bin: &Path, bwrap: Option<(&str, i32)>, socat: bool) {
}
}

#[test]
fn a_claude_code_version_the_sandbox_gate_has_not_passed_on_warns() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let other = format!(
"The sandbox gate has not run on Claude Code 2.1.399 (last passed on {GATED_CLAUDE_CODE})."
);
let unknown = format!(
"The sandbox gate has not run on an unknown version of Claude Code (last passed on {GATED_CLAUDE_CODE})."
);
// What the fake `claude` prints for `--version`, and its exit; none: no such program.
let gated = format!("echo '{GATED_CLAUDE_CODE} (Claude Code)'");
let cases: [(&str, Option<&str>, Option<&str>); 5] = [
("gated", Some(&gated), None),
("other", Some("echo '2.1.399 (Claude Code)'"), Some(&other)),
(
"fails",
Some("echo '2.1.399 (Claude Code)'; exit 1"),
Some(&unknown),
),
("garbled", Some("echo 'usage: claude'"), Some(&unknown)),
("missing", None, Some(&unknown)),
];
for (name, script, warning) in cases {
let program = dir.path().join(name);
if let Some(script) = script {
fs::write(
&program,
format!("#!/bin/sh\n[ \"$1\" = --version ] || exit 9\n{script}\n"),
)
.unwrap();
fs::set_permissions(&program, fs::Permissions::from_mode(0o755)).unwrap();
}
assert_eq!(gate_warning(&program).as_deref(), warning, "{name}");
}
}

#[test]
fn a_runs_private_temp_folder_is_made_new_and_private_and_removed_after() {
let dir = tempfile::tempdir().unwrap();
Expand Down Expand Up @@ -964,6 +1002,99 @@ fn a_run_survives_a_restart_and_is_picked_up() {
assert_eq!(fs::read_dir(dir.path().join("runs")).unwrap().count(), 0);
}

/// [`Script`], on a Claude Code the sandbox gate has not passed on.
struct Ungated;

/// The warning [`Ungated`] gives: any text, since the runner only carries it.
const UNGATED: &str = "The sandbox gate has not run on this Claude Code.";

impl Harness for Ungated {
fn command(&self, plan: &Plan) -> Result<HarnessCommand, String> {
Script.command(plan)
}

fn warning(&self, _: &HarnessCommand) -> Option<String> {
Some(UNGATED.into())
}
}

#[test]
fn a_run_on_an_ungated_claude_code_starts_and_warns_while_queued_running_ended_and_after_a_restart()
{
let Bench {
dir,
// Before `runner`, so it drops after it and before `dir`.
guard: _guard,
runner,
changes,
} = bench_with(Arc::new(Ungated));
let folder = runner.new_folder().unwrap();
let request = |folder, prompt: &str| Request {
kind: Kind::BackLaw,
project: PROJECT.into(),
folder,
prompt: prompt.into(),
limits: Limits::of(Kind::BackLaw),
};
let running = runner
.submit(request(folder.clone(), &waits("ran")))
.unwrap();
let queued = runner
.submit(request(runner.new_folder().unwrap(), "echo queued ran"))
.unwrap();
until(&runner, &changes, |r| {
state(r, &running) == Some(RunState::Running)
});
let warnings = |runner: &Runner| {
let runs = runner.runs(PROJECT).runs;
let views = runs
.iter()
.map(|run| (run.id.clone(), run.state, run.warning.clone()));
views.collect::<Vec<_>>()
};
// Both runs, in these states, each with the warning.
let warned = |first, second| {
let warning = Some(UNGATED.to_string());
vec![
(running.clone(), first, warning.clone()),
(queued.clone(), second, warning),
]
};
assert_eq!(
warnings(&runner),
warned(RunState::Running, RunState::Queued)
);
// plotkeeper starts again with a harness that warns of nothing: the runs keep the warning they were submitted with.
drop((runner, changes));
let (runner, changes) = open(dir.path(), Arc::new(Script));
assert_eq!(
warnings(&runner),
warned(RunState::Running, RunState::Queued)
);
fs::write(folder.join("go"), "").unwrap();
until(&runner, &changes, ended(&queued));
until(&runner, &changes, ended(&running));
assert_eq!(warnings(&runner), warned(RunState::Ended, RunState::Ended));
assert_eq!(
runner.outcome(&running).unwrap().result,
"ran",
"the warned run ran"
);
let gated = runner
.submit(request(runner.new_folder().unwrap(), "echo gated"))
.unwrap();
let view = runner
.runs(PROJECT)
.runs
.into_iter()
.find(|run| run.id == gated);
assert_eq!(
view.unwrap().warning,
None,
"a harness that warns of nothing gives no warning"
);
}

#[test]
fn a_dead_run_is_failed_and_frees_the_queue() {
let bench = bench_with(Arc::new(WithTmp));
Expand Down
12 changes: 11 additions & 1 deletion server/tests/wire.rs
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,7 @@ fn law_patches() -> Vec<LawPatch> {
]
}

/// The background runs paused, with a run in each state, of each kind and with each end.
/// The background runs paused, with a run in each state, of each kind and with each end, and runs that warn.
fn runs() -> Runs {
let run = |state, kind, outcome: Option<End>| RunView {
id: "19a2f-4d2-0".into(),
Expand All @@ -307,6 +307,7 @@ fn runs() -> Runs {
at: 1_761_743_990_000,
outcome,
line: outcome.map(|_| "Finished, but 1 tool call was denied".into()),
warning: None,
denials: outcome.map_or_else(Vec::new, |_| vec!["Bash: git push".into()]),
prompt: outcome.map(|_| "Write a test that backs the law.".into()),
};
Expand All @@ -326,6 +327,15 @@ fn runs() -> Runs {
run(RunState::Queued, Kind::MapReview, None),
];
list.extend(ends.map(|end| run(RunState::Ended, Kind::BackLaw, Some(end))));
let warning = "The sandbox gate has not run on Claude Code 2.1.399 (last passed on 2.1.326).";
list.extend(
[(RunState::Queued, None), (RunState::Ended, Some(End::Done))].map(|(state, outcome)| {
RunView {
warning: Some(warning.into()),
..run(state, Kind::BackLaw, outcome)
}
}),
);
Runs {
paused: Some("Claude hit its usage or rate limit".into()),
runs: list,
Expand Down
Loading
Loading