Compare commits
1 Commits
rcc/memory
...
rcc/sandbo
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2d09bf9961 |
@@ -51,6 +51,12 @@ const SLASH_COMMAND_SPECS: &[SlashCommandSpec] = &[
|
|||||||
argument_hint: None,
|
argument_hint: None,
|
||||||
resume_supported: true,
|
resume_supported: true,
|
||||||
},
|
},
|
||||||
|
SlashCommandSpec {
|
||||||
|
name: "sandbox",
|
||||||
|
summary: "Show sandbox isolation status",
|
||||||
|
argument_hint: None,
|
||||||
|
resume_supported: true,
|
||||||
|
},
|
||||||
SlashCommandSpec {
|
SlashCommandSpec {
|
||||||
name: "compact",
|
name: "compact",
|
||||||
summary: "Compact local session history",
|
summary: "Compact local session history",
|
||||||
@@ -135,6 +141,7 @@ const SLASH_COMMAND_SPECS: &[SlashCommandSpec] = &[
|
|||||||
pub enum SlashCommand {
|
pub enum SlashCommand {
|
||||||
Help,
|
Help,
|
||||||
Status,
|
Status,
|
||||||
|
Sandbox,
|
||||||
Compact,
|
Compact,
|
||||||
Model {
|
Model {
|
||||||
model: Option<String>,
|
model: Option<String>,
|
||||||
@@ -179,6 +186,7 @@ impl SlashCommand {
|
|||||||
Some(match command {
|
Some(match command {
|
||||||
"help" => Self::Help,
|
"help" => Self::Help,
|
||||||
"status" => Self::Status,
|
"status" => Self::Status,
|
||||||
|
"sandbox" => Self::Sandbox,
|
||||||
"compact" => Self::Compact,
|
"compact" => Self::Compact,
|
||||||
"model" => Self::Model {
|
"model" => Self::Model {
|
||||||
model: parts.next().map(ToOwned::to_owned),
|
model: parts.next().map(ToOwned::to_owned),
|
||||||
@@ -279,6 +287,7 @@ pub fn handle_slash_command(
|
|||||||
session: session.clone(),
|
session: session.clone(),
|
||||||
}),
|
}),
|
||||||
SlashCommand::Status
|
SlashCommand::Status
|
||||||
|
| SlashCommand::Sandbox
|
||||||
| SlashCommand::Model { .. }
|
| SlashCommand::Model { .. }
|
||||||
| SlashCommand::Permissions { .. }
|
| SlashCommand::Permissions { .. }
|
||||||
| SlashCommand::Clear { .. }
|
| SlashCommand::Clear { .. }
|
||||||
@@ -307,6 +316,7 @@ mod tests {
|
|||||||
fn parses_supported_slash_commands() {
|
fn parses_supported_slash_commands() {
|
||||||
assert_eq!(SlashCommand::parse("/help"), Some(SlashCommand::Help));
|
assert_eq!(SlashCommand::parse("/help"), Some(SlashCommand::Help));
|
||||||
assert_eq!(SlashCommand::parse(" /status "), Some(SlashCommand::Status));
|
assert_eq!(SlashCommand::parse(" /status "), Some(SlashCommand::Status));
|
||||||
|
assert_eq!(SlashCommand::parse("/sandbox"), Some(SlashCommand::Sandbox));
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
SlashCommand::parse("/model claude-opus"),
|
SlashCommand::parse("/model claude-opus"),
|
||||||
Some(SlashCommand::Model {
|
Some(SlashCommand::Model {
|
||||||
@@ -373,6 +383,7 @@ mod tests {
|
|||||||
assert!(help.contains("works with --resume SESSION.json"));
|
assert!(help.contains("works with --resume SESSION.json"));
|
||||||
assert!(help.contains("/help"));
|
assert!(help.contains("/help"));
|
||||||
assert!(help.contains("/status"));
|
assert!(help.contains("/status"));
|
||||||
|
assert!(help.contains("/sandbox"));
|
||||||
assert!(help.contains("/compact"));
|
assert!(help.contains("/compact"));
|
||||||
assert!(help.contains("/model [model]"));
|
assert!(help.contains("/model [model]"));
|
||||||
assert!(help.contains("/permissions [read-only|workspace-write|danger-full-access]"));
|
assert!(help.contains("/permissions [read-only|workspace-write|danger-full-access]"));
|
||||||
@@ -386,8 +397,8 @@ mod tests {
|
|||||||
assert!(help.contains("/version"));
|
assert!(help.contains("/version"));
|
||||||
assert!(help.contains("/export [file]"));
|
assert!(help.contains("/export [file]"));
|
||||||
assert!(help.contains("/session [list|switch <session-id>]"));
|
assert!(help.contains("/session [list|switch <session-id>]"));
|
||||||
assert_eq!(slash_command_specs().len(), 15);
|
assert_eq!(slash_command_specs().len(), 16);
|
||||||
assert_eq!(resume_supported_slash_commands().len(), 11);
|
assert_eq!(resume_supported_slash_commands().len(), 12);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -434,6 +445,7 @@ mod tests {
|
|||||||
let session = Session::new();
|
let session = Session::new();
|
||||||
assert!(handle_slash_command("/unknown", &session, CompactionConfig::default()).is_none());
|
assert!(handle_slash_command("/unknown", &session, CompactionConfig::default()).is_none());
|
||||||
assert!(handle_slash_command("/status", &session, CompactionConfig::default()).is_none());
|
assert!(handle_slash_command("/status", &session, CompactionConfig::default()).is_none());
|
||||||
|
assert!(handle_slash_command("/sandbox", &session, CompactionConfig::default()).is_none());
|
||||||
assert!(
|
assert!(
|
||||||
handle_slash_command("/model claude", &session, CompactionConfig::default()).is_none()
|
handle_slash_command("/model claude", &session, CompactionConfig::default()).is_none()
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
use std::env;
|
||||||
use std::io;
|
use std::io;
|
||||||
use std::process::{Command, Stdio};
|
use std::process::{Command, Stdio};
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
@@ -7,6 +8,12 @@ use tokio::process::Command as TokioCommand;
|
|||||||
use tokio::runtime::Builder;
|
use tokio::runtime::Builder;
|
||||||
use tokio::time::timeout;
|
use tokio::time::timeout;
|
||||||
|
|
||||||
|
use crate::sandbox::{
|
||||||
|
build_linux_sandbox_command, resolve_sandbox_status_for_request, FilesystemIsolationMode,
|
||||||
|
SandboxConfig, SandboxStatus,
|
||||||
|
};
|
||||||
|
use crate::ConfigLoader;
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||||
pub struct BashCommandInput {
|
pub struct BashCommandInput {
|
||||||
pub command: String,
|
pub command: String,
|
||||||
@@ -16,6 +23,14 @@ pub struct BashCommandInput {
|
|||||||
pub run_in_background: Option<bool>,
|
pub run_in_background: Option<bool>,
|
||||||
#[serde(rename = "dangerouslyDisableSandbox")]
|
#[serde(rename = "dangerouslyDisableSandbox")]
|
||||||
pub dangerously_disable_sandbox: Option<bool>,
|
pub dangerously_disable_sandbox: Option<bool>,
|
||||||
|
#[serde(rename = "namespaceRestrictions")]
|
||||||
|
pub namespace_restrictions: Option<bool>,
|
||||||
|
#[serde(rename = "isolateNetwork")]
|
||||||
|
pub isolate_network: Option<bool>,
|
||||||
|
#[serde(rename = "filesystemMode")]
|
||||||
|
pub filesystem_mode: Option<FilesystemIsolationMode>,
|
||||||
|
#[serde(rename = "allowedMounts")]
|
||||||
|
pub allowed_mounts: Option<Vec<String>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||||
@@ -45,13 +60,17 @@ pub struct BashCommandOutput {
|
|||||||
pub persisted_output_path: Option<String>,
|
pub persisted_output_path: Option<String>,
|
||||||
#[serde(rename = "persistedOutputSize")]
|
#[serde(rename = "persistedOutputSize")]
|
||||||
pub persisted_output_size: Option<u64>,
|
pub persisted_output_size: Option<u64>,
|
||||||
|
#[serde(rename = "sandboxStatus")]
|
||||||
|
pub sandbox_status: Option<SandboxStatus>,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn execute_bash(input: BashCommandInput) -> io::Result<BashCommandOutput> {
|
pub fn execute_bash(input: BashCommandInput) -> io::Result<BashCommandOutput> {
|
||||||
|
let cwd = env::current_dir()?;
|
||||||
|
let sandbox_status = sandbox_status_for_input(&input, &cwd);
|
||||||
|
|
||||||
if input.run_in_background.unwrap_or(false) {
|
if input.run_in_background.unwrap_or(false) {
|
||||||
let child = Command::new("sh")
|
let mut child = prepare_command(&input.command, &cwd, &sandbox_status, false);
|
||||||
.arg("-lc")
|
let child = child
|
||||||
.arg(&input.command)
|
|
||||||
.stdin(Stdio::null())
|
.stdin(Stdio::null())
|
||||||
.stdout(Stdio::null())
|
.stdout(Stdio::null())
|
||||||
.stderr(Stdio::null())
|
.stderr(Stdio::null())
|
||||||
@@ -72,16 +91,20 @@ pub fn execute_bash(input: BashCommandInput) -> io::Result<BashCommandOutput> {
|
|||||||
structured_content: None,
|
structured_content: None,
|
||||||
persisted_output_path: None,
|
persisted_output_path: None,
|
||||||
persisted_output_size: None,
|
persisted_output_size: None,
|
||||||
|
sandbox_status: Some(sandbox_status),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
let runtime = Builder::new_current_thread().enable_all().build()?;
|
let runtime = Builder::new_current_thread().enable_all().build()?;
|
||||||
runtime.block_on(execute_bash_async(input))
|
runtime.block_on(execute_bash_async(input, sandbox_status, cwd))
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn execute_bash_async(input: BashCommandInput) -> io::Result<BashCommandOutput> {
|
async fn execute_bash_async(
|
||||||
let mut command = TokioCommand::new("sh");
|
input: BashCommandInput,
|
||||||
command.arg("-lc").arg(&input.command);
|
sandbox_status: SandboxStatus,
|
||||||
|
cwd: std::path::PathBuf,
|
||||||
|
) -> io::Result<BashCommandOutput> {
|
||||||
|
let mut command = prepare_tokio_command(&input.command, &cwd, &sandbox_status, true);
|
||||||
|
|
||||||
let output_result = if let Some(timeout_ms) = input.timeout {
|
let output_result = if let Some(timeout_ms) = input.timeout {
|
||||||
match timeout(Duration::from_millis(timeout_ms), command.output()).await {
|
match timeout(Duration::from_millis(timeout_ms), command.output()).await {
|
||||||
@@ -102,6 +125,7 @@ async fn execute_bash_async(input: BashCommandInput) -> io::Result<BashCommandOu
|
|||||||
structured_content: None,
|
structured_content: None,
|
||||||
persisted_output_path: None,
|
persisted_output_path: None,
|
||||||
persisted_output_size: None,
|
persisted_output_size: None,
|
||||||
|
sandbox_status: Some(sandbox_status),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -136,12 +160,88 @@ async fn execute_bash_async(input: BashCommandInput) -> io::Result<BashCommandOu
|
|||||||
structured_content: None,
|
structured_content: None,
|
||||||
persisted_output_path: None,
|
persisted_output_path: None,
|
||||||
persisted_output_size: None,
|
persisted_output_size: None,
|
||||||
|
sandbox_status: Some(sandbox_status),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn sandbox_status_for_input(input: &BashCommandInput, cwd: &std::path::Path) -> SandboxStatus {
|
||||||
|
let config = ConfigLoader::default_for(cwd).load().map_or_else(
|
||||||
|
|_| SandboxConfig::default(),
|
||||||
|
|runtime_config| runtime_config.sandbox().clone(),
|
||||||
|
);
|
||||||
|
let request = config.resolve_request(
|
||||||
|
input.dangerously_disable_sandbox.map(|disabled| !disabled),
|
||||||
|
input.namespace_restrictions,
|
||||||
|
input.isolate_network,
|
||||||
|
input.filesystem_mode,
|
||||||
|
input.allowed_mounts.clone(),
|
||||||
|
);
|
||||||
|
resolve_sandbox_status_for_request(&request, cwd)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn prepare_command(
|
||||||
|
command: &str,
|
||||||
|
cwd: &std::path::Path,
|
||||||
|
sandbox_status: &SandboxStatus,
|
||||||
|
create_dirs: bool,
|
||||||
|
) -> Command {
|
||||||
|
if create_dirs {
|
||||||
|
prepare_sandbox_dirs(cwd);
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(launcher) = build_linux_sandbox_command(command, cwd, sandbox_status) {
|
||||||
|
let mut prepared = Command::new(launcher.program);
|
||||||
|
prepared.args(launcher.args);
|
||||||
|
prepared.current_dir(cwd);
|
||||||
|
prepared.envs(launcher.env);
|
||||||
|
return prepared;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut prepared = Command::new("sh");
|
||||||
|
prepared.arg("-lc").arg(command).current_dir(cwd);
|
||||||
|
if sandbox_status.filesystem_active {
|
||||||
|
prepared.env("HOME", cwd.join(".sandbox-home"));
|
||||||
|
prepared.env("TMPDIR", cwd.join(".sandbox-tmp"));
|
||||||
|
}
|
||||||
|
prepared
|
||||||
|
}
|
||||||
|
|
||||||
|
fn prepare_tokio_command(
|
||||||
|
command: &str,
|
||||||
|
cwd: &std::path::Path,
|
||||||
|
sandbox_status: &SandboxStatus,
|
||||||
|
create_dirs: bool,
|
||||||
|
) -> TokioCommand {
|
||||||
|
if create_dirs {
|
||||||
|
prepare_sandbox_dirs(cwd);
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(launcher) = build_linux_sandbox_command(command, cwd, sandbox_status) {
|
||||||
|
let mut prepared = TokioCommand::new(launcher.program);
|
||||||
|
prepared.args(launcher.args);
|
||||||
|
prepared.current_dir(cwd);
|
||||||
|
prepared.envs(launcher.env);
|
||||||
|
return prepared;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut prepared = TokioCommand::new("sh");
|
||||||
|
prepared.arg("-lc").arg(command).current_dir(cwd);
|
||||||
|
if sandbox_status.filesystem_active {
|
||||||
|
prepared.env("HOME", cwd.join(".sandbox-home"));
|
||||||
|
prepared.env("TMPDIR", cwd.join(".sandbox-tmp"));
|
||||||
|
}
|
||||||
|
prepared
|
||||||
|
}
|
||||||
|
|
||||||
|
fn prepare_sandbox_dirs(cwd: &std::path::Path) {
|
||||||
|
let _ = std::fs::create_dir_all(cwd.join(".sandbox-home"));
|
||||||
|
let _ = std::fs::create_dir_all(cwd.join(".sandbox-tmp"));
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::{execute_bash, BashCommandInput};
|
use super::{execute_bash, BashCommandInput};
|
||||||
|
use crate::sandbox::FilesystemIsolationMode;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn executes_simple_command() {
|
fn executes_simple_command() {
|
||||||
@@ -151,10 +251,33 @@ mod tests {
|
|||||||
description: None,
|
description: None,
|
||||||
run_in_background: Some(false),
|
run_in_background: Some(false),
|
||||||
dangerously_disable_sandbox: Some(false),
|
dangerously_disable_sandbox: Some(false),
|
||||||
|
namespace_restrictions: Some(false),
|
||||||
|
isolate_network: Some(false),
|
||||||
|
filesystem_mode: Some(FilesystemIsolationMode::WorkspaceOnly),
|
||||||
|
allowed_mounts: None,
|
||||||
})
|
})
|
||||||
.expect("bash command should execute");
|
.expect("bash command should execute");
|
||||||
|
|
||||||
assert_eq!(output.stdout, "hello");
|
assert_eq!(output.stdout, "hello");
|
||||||
assert!(!output.interrupted);
|
assert!(!output.interrupted);
|
||||||
|
assert!(output.sandbox_status.is_some());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn disables_sandbox_when_requested() {
|
||||||
|
let output = execute_bash(BashCommandInput {
|
||||||
|
command: String::from("printf 'hello'"),
|
||||||
|
timeout: Some(1_000),
|
||||||
|
description: None,
|
||||||
|
run_in_background: Some(false),
|
||||||
|
dangerously_disable_sandbox: Some(true),
|
||||||
|
namespace_restrictions: None,
|
||||||
|
isolate_network: None,
|
||||||
|
filesystem_mode: None,
|
||||||
|
allowed_mounts: None,
|
||||||
|
})
|
||||||
|
.expect("bash command should execute");
|
||||||
|
|
||||||
|
assert!(!output.sandbox_status.expect("sandbox status").enabled);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,3 @@
|
|||||||
use std::fs;
|
|
||||||
use std::time::{SystemTime, UNIX_EPOCH};
|
|
||||||
|
|
||||||
use crate::session::{ContentBlock, ConversationMessage, MessageRole, Session};
|
use crate::session::{ContentBlock, ConversationMessage, MessageRole, Session};
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
@@ -93,7 +90,6 @@ pub fn compact_session(session: &Session, config: CompactionConfig) -> Compactio
|
|||||||
let preserved = session.messages[keep_from..].to_vec();
|
let preserved = session.messages[keep_from..].to_vec();
|
||||||
let summary = summarize_messages(removed);
|
let summary = summarize_messages(removed);
|
||||||
let formatted_summary = format_compact_summary(&summary);
|
let formatted_summary = format_compact_summary(&summary);
|
||||||
persist_compact_summary(&formatted_summary);
|
|
||||||
let continuation = get_compact_continuation_message(&summary, true, !preserved.is_empty());
|
let continuation = get_compact_continuation_message(&summary, true, !preserved.is_empty());
|
||||||
|
|
||||||
let mut compacted_messages = vec![ConversationMessage {
|
let mut compacted_messages = vec![ConversationMessage {
|
||||||
@@ -114,35 +110,6 @@ pub fn compact_session(session: &Session, config: CompactionConfig) -> Compactio
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn persist_compact_summary(formatted_summary: &str) {
|
|
||||||
if formatted_summary.trim().is_empty() {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
let Ok(cwd) = std::env::current_dir() else {
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
let memory_dir = cwd.join(".claude").join("memory");
|
|
||||||
if fs::create_dir_all(&memory_dir).is_err() {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
let path = memory_dir.join(compact_summary_filename());
|
|
||||||
let _ = fs::write(path, render_memory_file(formatted_summary));
|
|
||||||
}
|
|
||||||
|
|
||||||
fn compact_summary_filename() -> String {
|
|
||||||
let timestamp = SystemTime::now()
|
|
||||||
.duration_since(UNIX_EPOCH)
|
|
||||||
.unwrap_or_default()
|
|
||||||
.as_secs();
|
|
||||||
format!("summary-{timestamp}.md")
|
|
||||||
}
|
|
||||||
|
|
||||||
fn render_memory_file(formatted_summary: &str) -> String {
|
|
||||||
format!("# Project memory\n\n{}\n", formatted_summary.trim())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn summarize_messages(messages: &[ConversationMessage]) -> String {
|
fn summarize_messages(messages: &[ConversationMessage]) -> String {
|
||||||
let user_messages = messages
|
let user_messages = messages
|
||||||
.iter()
|
.iter()
|
||||||
@@ -411,21 +378,14 @@ fn collapse_blank_lines(content: &str) -> String {
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::{
|
use super::{
|
||||||
collect_key_files, compact_session, estimate_session_tokens, format_compact_summary,
|
collect_key_files, compact_session, estimate_session_tokens, format_compact_summary,
|
||||||
infer_pending_work, render_memory_file, should_compact, CompactionConfig,
|
infer_pending_work, should_compact, CompactionConfig,
|
||||||
};
|
};
|
||||||
use std::fs;
|
|
||||||
use std::time::{SystemTime, UNIX_EPOCH};
|
|
||||||
|
|
||||||
use crate::session::{ContentBlock, ConversationMessage, MessageRole, Session};
|
use crate::session::{ContentBlock, ConversationMessage, MessageRole, Session};
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn formats_compact_summary_like_upstream() {
|
fn formats_compact_summary_like_upstream() {
|
||||||
let summary = "<analysis>scratch</analysis>\n<summary>Kept work</summary>";
|
let summary = "<analysis>scratch</analysis>\n<summary>Kept work</summary>";
|
||||||
assert_eq!(format_compact_summary(summary), "Summary:\nKept work");
|
assert_eq!(format_compact_summary(summary), "Summary:\nKept work");
|
||||||
assert_eq!(
|
|
||||||
render_memory_file("Summary:\nKept work"),
|
|
||||||
"# Project memory\n\nSummary:\nKept work\n"
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -442,63 +402,6 @@ mod tests {
|
|||||||
assert!(result.formatted_summary.is_empty());
|
assert!(result.formatted_summary.is_empty());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn persists_compacted_summaries_under_dot_claude_memory() {
|
|
||||||
let _guard = crate::test_env_lock();
|
|
||||||
let temp = std::env::temp_dir().join(format!(
|
|
||||||
"runtime-compact-memory-{}",
|
|
||||||
SystemTime::now()
|
|
||||||
.duration_since(UNIX_EPOCH)
|
|
||||||
.expect("time after epoch")
|
|
||||||
.as_nanos()
|
|
||||||
));
|
|
||||||
fs::create_dir_all(&temp).expect("temp dir");
|
|
||||||
let previous = std::env::current_dir().expect("cwd");
|
|
||||||
std::env::set_current_dir(&temp).expect("set cwd");
|
|
||||||
|
|
||||||
let session = Session {
|
|
||||||
version: 1,
|
|
||||||
messages: vec![
|
|
||||||
ConversationMessage::user_text("one ".repeat(200)),
|
|
||||||
ConversationMessage::assistant(vec![ContentBlock::Text {
|
|
||||||
text: "two ".repeat(200),
|
|
||||||
}]),
|
|
||||||
ConversationMessage::tool_result("1", "bash", "ok ".repeat(200), false),
|
|
||||||
ConversationMessage {
|
|
||||||
role: MessageRole::Assistant,
|
|
||||||
blocks: vec![ContentBlock::Text {
|
|
||||||
text: "recent".to_string(),
|
|
||||||
}],
|
|
||||||
usage: None,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
};
|
|
||||||
|
|
||||||
let result = compact_session(
|
|
||||||
&session,
|
|
||||||
CompactionConfig {
|
|
||||||
preserve_recent_messages: 2,
|
|
||||||
max_estimated_tokens: 1,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
let memory_dir = temp.join(".claude").join("memory");
|
|
||||||
let files = fs::read_dir(&memory_dir)
|
|
||||||
.expect("memory dir exists")
|
|
||||||
.flatten()
|
|
||||||
.map(|entry| entry.path())
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
|
|
||||||
assert_eq!(result.removed_message_count, 2);
|
|
||||||
assert_eq!(files.len(), 1);
|
|
||||||
let persisted = fs::read_to_string(&files[0]).expect("memory file readable");
|
|
||||||
|
|
||||||
std::env::set_current_dir(previous).expect("restore cwd");
|
|
||||||
fs::remove_dir_all(temp).expect("cleanup temp dir");
|
|
||||||
|
|
||||||
assert!(persisted.contains("# Project memory"));
|
|
||||||
assert!(persisted.contains("Summary:"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn compacts_older_messages_into_a_system_summary() {
|
fn compacts_older_messages_into_a_system_summary() {
|
||||||
let session = Session {
|
let session = Session {
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ use std::fs;
|
|||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
use crate::json::JsonValue;
|
use crate::json::JsonValue;
|
||||||
|
use crate::sandbox::{FilesystemIsolationMode, SandboxConfig};
|
||||||
|
|
||||||
pub const CLAUDE_CODE_SETTINGS_SCHEMA_NAME: &str = "SettingsSchema";
|
pub const CLAUDE_CODE_SETTINGS_SCHEMA_NAME: &str = "SettingsSchema";
|
||||||
|
|
||||||
@@ -40,6 +41,7 @@ pub struct RuntimeFeatureConfig {
|
|||||||
oauth: Option<OAuthConfig>,
|
oauth: Option<OAuthConfig>,
|
||||||
model: Option<String>,
|
model: Option<String>,
|
||||||
permission_mode: Option<ResolvedPermissionMode>,
|
permission_mode: Option<ResolvedPermissionMode>,
|
||||||
|
sandbox: SandboxConfig,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
||||||
@@ -225,6 +227,7 @@ impl ConfigLoader {
|
|||||||
oauth: parse_optional_oauth_config(&merged_value, "merged settings.oauth")?,
|
oauth: parse_optional_oauth_config(&merged_value, "merged settings.oauth")?,
|
||||||
model: parse_optional_model(&merged_value),
|
model: parse_optional_model(&merged_value),
|
||||||
permission_mode: parse_optional_permission_mode(&merged_value)?,
|
permission_mode: parse_optional_permission_mode(&merged_value)?,
|
||||||
|
sandbox: parse_optional_sandbox_config(&merged_value)?,
|
||||||
};
|
};
|
||||||
|
|
||||||
Ok(RuntimeConfig {
|
Ok(RuntimeConfig {
|
||||||
@@ -289,6 +292,11 @@ impl RuntimeConfig {
|
|||||||
pub fn permission_mode(&self) -> Option<ResolvedPermissionMode> {
|
pub fn permission_mode(&self) -> Option<ResolvedPermissionMode> {
|
||||||
self.feature_config.permission_mode
|
self.feature_config.permission_mode
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn sandbox(&self) -> &SandboxConfig {
|
||||||
|
&self.feature_config.sandbox
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RuntimeFeatureConfig {
|
impl RuntimeFeatureConfig {
|
||||||
@@ -311,6 +319,11 @@ impl RuntimeFeatureConfig {
|
|||||||
pub fn permission_mode(&self) -> Option<ResolvedPermissionMode> {
|
pub fn permission_mode(&self) -> Option<ResolvedPermissionMode> {
|
||||||
self.permission_mode
|
self.permission_mode
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn sandbox(&self) -> &SandboxConfig {
|
||||||
|
&self.sandbox
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl McpConfigCollection {
|
impl McpConfigCollection {
|
||||||
@@ -445,6 +458,42 @@ fn parse_permission_mode_label(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn parse_optional_sandbox_config(root: &JsonValue) -> Result<SandboxConfig, ConfigError> {
|
||||||
|
let Some(object) = root.as_object() else {
|
||||||
|
return Ok(SandboxConfig::default());
|
||||||
|
};
|
||||||
|
let Some(sandbox_value) = object.get("sandbox") else {
|
||||||
|
return Ok(SandboxConfig::default());
|
||||||
|
};
|
||||||
|
let sandbox = expect_object(sandbox_value, "merged settings.sandbox")?;
|
||||||
|
let filesystem_mode = optional_string(sandbox, "filesystemMode", "merged settings.sandbox")?
|
||||||
|
.map(parse_filesystem_mode_label)
|
||||||
|
.transpose()?;
|
||||||
|
Ok(SandboxConfig {
|
||||||
|
enabled: optional_bool(sandbox, "enabled", "merged settings.sandbox")?,
|
||||||
|
namespace_restrictions: optional_bool(
|
||||||
|
sandbox,
|
||||||
|
"namespaceRestrictions",
|
||||||
|
"merged settings.sandbox",
|
||||||
|
)?,
|
||||||
|
network_isolation: optional_bool(sandbox, "networkIsolation", "merged settings.sandbox")?,
|
||||||
|
filesystem_mode,
|
||||||
|
allowed_mounts: optional_string_array(sandbox, "allowedMounts", "merged settings.sandbox")?
|
||||||
|
.unwrap_or_default(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_filesystem_mode_label(value: &str) -> Result<FilesystemIsolationMode, ConfigError> {
|
||||||
|
match value {
|
||||||
|
"off" => Ok(FilesystemIsolationMode::Off),
|
||||||
|
"workspace-only" => Ok(FilesystemIsolationMode::WorkspaceOnly),
|
||||||
|
"allow-list" => Ok(FilesystemIsolationMode::AllowList),
|
||||||
|
other => Err(ConfigError::Parse(format!(
|
||||||
|
"merged settings.sandbox.filesystemMode: unsupported filesystem mode {other}"
|
||||||
|
))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn parse_optional_oauth_config(
|
fn parse_optional_oauth_config(
|
||||||
root: &JsonValue,
|
root: &JsonValue,
|
||||||
context: &str,
|
context: &str,
|
||||||
@@ -688,6 +737,7 @@ mod tests {
|
|||||||
CLAUDE_CODE_SETTINGS_SCHEMA_NAME,
|
CLAUDE_CODE_SETTINGS_SCHEMA_NAME,
|
||||||
};
|
};
|
||||||
use crate::json::JsonValue;
|
use crate::json::JsonValue;
|
||||||
|
use crate::sandbox::FilesystemIsolationMode;
|
||||||
use std::fs;
|
use std::fs;
|
||||||
use std::time::{SystemTime, UNIX_EPOCH};
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
@@ -792,6 +842,44 @@ mod tests {
|
|||||||
fs::remove_dir_all(root).expect("cleanup temp dir");
|
fs::remove_dir_all(root).expect("cleanup temp dir");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_sandbox_config() {
|
||||||
|
let root = temp_dir();
|
||||||
|
let cwd = root.join("project");
|
||||||
|
let home = root.join("home").join(".claude");
|
||||||
|
fs::create_dir_all(cwd.join(".claude")).expect("project config dir");
|
||||||
|
fs::create_dir_all(&home).expect("home config dir");
|
||||||
|
|
||||||
|
fs::write(
|
||||||
|
cwd.join(".claude").join("settings.local.json"),
|
||||||
|
r#"{
|
||||||
|
"sandbox": {
|
||||||
|
"enabled": true,
|
||||||
|
"namespaceRestrictions": false,
|
||||||
|
"networkIsolation": true,
|
||||||
|
"filesystemMode": "allow-list",
|
||||||
|
"allowedMounts": ["logs", "tmp/cache"]
|
||||||
|
}
|
||||||
|
}"#,
|
||||||
|
)
|
||||||
|
.expect("write local settings");
|
||||||
|
|
||||||
|
let loaded = ConfigLoader::new(&cwd, &home)
|
||||||
|
.load()
|
||||||
|
.expect("config should load");
|
||||||
|
|
||||||
|
assert_eq!(loaded.sandbox().enabled, Some(true));
|
||||||
|
assert_eq!(loaded.sandbox().namespace_restrictions, Some(false));
|
||||||
|
assert_eq!(loaded.sandbox().network_isolation, Some(true));
|
||||||
|
assert_eq!(
|
||||||
|
loaded.sandbox().filesystem_mode,
|
||||||
|
Some(FilesystemIsolationMode::AllowList)
|
||||||
|
);
|
||||||
|
assert_eq!(loaded.sandbox().allowed_mounts, vec!["logs", "tmp/cache"]);
|
||||||
|
|
||||||
|
fs::remove_dir_all(root).expect("cleanup temp dir");
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn parses_typed_mcp_and_oauth_config() {
|
fn parses_typed_mcp_and_oauth_config() {
|
||||||
let root = temp_dir();
|
let root = temp_dir();
|
||||||
|
|||||||
@@ -415,7 +415,6 @@ mod tests {
|
|||||||
current_date: "2026-03-31".to_string(),
|
current_date: "2026-03-31".to_string(),
|
||||||
git_status: None,
|
git_status: None,
|
||||||
instruction_files: Vec::new(),
|
instruction_files: Vec::new(),
|
||||||
memory_files: Vec::new(),
|
|
||||||
})
|
})
|
||||||
.with_os("linux", "6.8")
|
.with_os("linux", "6.8")
|
||||||
.build();
|
.build();
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ mod oauth;
|
|||||||
mod permissions;
|
mod permissions;
|
||||||
mod prompt;
|
mod prompt;
|
||||||
mod remote;
|
mod remote;
|
||||||
|
mod sandbox;
|
||||||
mod session;
|
mod session;
|
||||||
mod usage;
|
mod usage;
|
||||||
|
|
||||||
@@ -73,6 +74,12 @@ pub use remote::{
|
|||||||
RemoteSessionContext, UpstreamProxyBootstrap, UpstreamProxyState, DEFAULT_REMOTE_BASE_URL,
|
RemoteSessionContext, UpstreamProxyBootstrap, UpstreamProxyState, DEFAULT_REMOTE_BASE_URL,
|
||||||
DEFAULT_SESSION_TOKEN_PATH, DEFAULT_SYSTEM_CA_BUNDLE, NO_PROXY_HOSTS, UPSTREAM_PROXY_ENV_KEYS,
|
DEFAULT_SESSION_TOKEN_PATH, DEFAULT_SYSTEM_CA_BUNDLE, NO_PROXY_HOSTS, UPSTREAM_PROXY_ENV_KEYS,
|
||||||
};
|
};
|
||||||
|
pub use sandbox::{
|
||||||
|
build_linux_sandbox_command, detect_container_environment, detect_container_environment_from,
|
||||||
|
resolve_sandbox_status, resolve_sandbox_status_for_request, ContainerEnvironment,
|
||||||
|
FilesystemIsolationMode, LinuxSandboxCommand, SandboxConfig, SandboxDetectionInputs,
|
||||||
|
SandboxRequest, SandboxStatus,
|
||||||
|
};
|
||||||
pub use session::{ContentBlock, ConversationMessage, MessageRole, Session, SessionError};
|
pub use session::{ContentBlock, ConversationMessage, MessageRole, Session, SessionError};
|
||||||
pub use usage::{
|
pub use usage::{
|
||||||
format_usd, pricing_for_model, ModelPricing, TokenUsage, UsageCostEstimate, UsageTracker,
|
format_usd, pricing_for_model, ModelPricing, TokenUsage, UsageCostEstimate, UsageTracker,
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ pub enum PermissionMode {
|
|||||||
ReadOnly,
|
ReadOnly,
|
||||||
WorkspaceWrite,
|
WorkspaceWrite,
|
||||||
DangerFullAccess,
|
DangerFullAccess,
|
||||||
|
Prompt,
|
||||||
|
Allow,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl PermissionMode {
|
impl PermissionMode {
|
||||||
@@ -14,6 +16,8 @@ impl PermissionMode {
|
|||||||
Self::ReadOnly => "read-only",
|
Self::ReadOnly => "read-only",
|
||||||
Self::WorkspaceWrite => "workspace-write",
|
Self::WorkspaceWrite => "workspace-write",
|
||||||
Self::DangerFullAccess => "danger-full-access",
|
Self::DangerFullAccess => "danger-full-access",
|
||||||
|
Self::Prompt => "prompt",
|
||||||
|
Self::Allow => "allow",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -90,7 +94,7 @@ impl PermissionPolicy {
|
|||||||
) -> PermissionOutcome {
|
) -> PermissionOutcome {
|
||||||
let current_mode = self.active_mode();
|
let current_mode = self.active_mode();
|
||||||
let required_mode = self.required_mode_for(tool_name);
|
let required_mode = self.required_mode_for(tool_name);
|
||||||
if current_mode >= required_mode {
|
if current_mode == PermissionMode::Allow || current_mode >= required_mode {
|
||||||
return PermissionOutcome::Allow;
|
return PermissionOutcome::Allow;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -101,8 +105,9 @@ impl PermissionPolicy {
|
|||||||
required_mode,
|
required_mode,
|
||||||
};
|
};
|
||||||
|
|
||||||
if current_mode == PermissionMode::WorkspaceWrite
|
if current_mode == PermissionMode::Prompt
|
||||||
&& required_mode == PermissionMode::DangerFullAccess
|
|| (current_mode == PermissionMode::WorkspaceWrite
|
||||||
|
&& required_mode == PermissionMode::DangerFullAccess)
|
||||||
{
|
{
|
||||||
return match prompter.as_mut() {
|
return match prompter.as_mut() {
|
||||||
Some(prompter) => match prompter.decide(&request) {
|
Some(prompter) => match prompter.decide(&request) {
|
||||||
|
|||||||
@@ -51,7 +51,6 @@ pub struct ProjectContext {
|
|||||||
pub current_date: String,
|
pub current_date: String,
|
||||||
pub git_status: Option<String>,
|
pub git_status: Option<String>,
|
||||||
pub instruction_files: Vec<ContextFile>,
|
pub instruction_files: Vec<ContextFile>,
|
||||||
pub memory_files: Vec<ContextFile>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ProjectContext {
|
impl ProjectContext {
|
||||||
@@ -61,13 +60,11 @@ impl ProjectContext {
|
|||||||
) -> std::io::Result<Self> {
|
) -> std::io::Result<Self> {
|
||||||
let cwd = cwd.into();
|
let cwd = cwd.into();
|
||||||
let instruction_files = discover_instruction_files(&cwd)?;
|
let instruction_files = discover_instruction_files(&cwd)?;
|
||||||
let memory_files = discover_memory_files(&cwd)?;
|
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
cwd,
|
cwd,
|
||||||
current_date: current_date.into(),
|
current_date: current_date.into(),
|
||||||
git_status: None,
|
git_status: None,
|
||||||
instruction_files,
|
instruction_files,
|
||||||
memory_files,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -147,9 +144,6 @@ impl SystemPromptBuilder {
|
|||||||
if !project_context.instruction_files.is_empty() {
|
if !project_context.instruction_files.is_empty() {
|
||||||
sections.push(render_instruction_files(&project_context.instruction_files));
|
sections.push(render_instruction_files(&project_context.instruction_files));
|
||||||
}
|
}
|
||||||
if !project_context.memory_files.is_empty() {
|
|
||||||
sections.push(render_memory_files(&project_context.memory_files));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if let Some(config) = &self.config {
|
if let Some(config) = &self.config {
|
||||||
sections.push(render_config_section(config));
|
sections.push(render_config_section(config));
|
||||||
@@ -192,7 +186,7 @@ pub fn prepend_bullets(items: Vec<String>) -> Vec<String> {
|
|||||||
items.into_iter().map(|item| format!(" - {item}")).collect()
|
items.into_iter().map(|item| format!(" - {item}")).collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn discover_context_directories(cwd: &Path) -> Vec<PathBuf> {
|
fn discover_instruction_files(cwd: &Path) -> std::io::Result<Vec<ContextFile>> {
|
||||||
let mut directories = Vec::new();
|
let mut directories = Vec::new();
|
||||||
let mut cursor = Some(cwd);
|
let mut cursor = Some(cwd);
|
||||||
while let Some(dir) = cursor {
|
while let Some(dir) = cursor {
|
||||||
@@ -200,11 +194,6 @@ fn discover_context_directories(cwd: &Path) -> Vec<PathBuf> {
|
|||||||
cursor = dir.parent();
|
cursor = dir.parent();
|
||||||
}
|
}
|
||||||
directories.reverse();
|
directories.reverse();
|
||||||
directories
|
|
||||||
}
|
|
||||||
|
|
||||||
fn discover_instruction_files(cwd: &Path) -> std::io::Result<Vec<ContextFile>> {
|
|
||||||
let directories = discover_context_directories(cwd);
|
|
||||||
|
|
||||||
let mut files = Vec::new();
|
let mut files = Vec::new();
|
||||||
for dir in directories {
|
for dir in directories {
|
||||||
@@ -220,26 +209,6 @@ fn discover_instruction_files(cwd: &Path) -> std::io::Result<Vec<ContextFile>> {
|
|||||||
Ok(dedupe_instruction_files(files))
|
Ok(dedupe_instruction_files(files))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn discover_memory_files(cwd: &Path) -> std::io::Result<Vec<ContextFile>> {
|
|
||||||
let mut files = Vec::new();
|
|
||||||
for dir in discover_context_directories(cwd) {
|
|
||||||
let memory_dir = dir.join(".claude").join("memory");
|
|
||||||
let Ok(entries) = fs::read_dir(&memory_dir) else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
let mut paths = entries
|
|
||||||
.flatten()
|
|
||||||
.map(|entry| entry.path())
|
|
||||||
.filter(|path| path.is_file())
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
paths.sort();
|
|
||||||
for path in paths {
|
|
||||||
push_context_file(&mut files, path)?;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(dedupe_instruction_files(files))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn push_context_file(files: &mut Vec<ContextFile>, path: PathBuf) -> std::io::Result<()> {
|
fn push_context_file(files: &mut Vec<ContextFile>, path: PathBuf) -> std::io::Result<()> {
|
||||||
match fs::read_to_string(&path) {
|
match fs::read_to_string(&path) {
|
||||||
Ok(content) if !content.trim().is_empty() => {
|
Ok(content) if !content.trim().is_empty() => {
|
||||||
@@ -282,12 +251,6 @@ fn render_project_context(project_context: &ProjectContext) -> String {
|
|||||||
project_context.instruction_files.len()
|
project_context.instruction_files.len()
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
if !project_context.memory_files.is_empty() {
|
|
||||||
bullets.push(format!(
|
|
||||||
"Project memory files discovered: {}.",
|
|
||||||
project_context.memory_files.len()
|
|
||||||
));
|
|
||||||
}
|
|
||||||
lines.extend(prepend_bullets(bullets));
|
lines.extend(prepend_bullets(bullets));
|
||||||
if let Some(status) = &project_context.git_status {
|
if let Some(status) = &project_context.git_status {
|
||||||
lines.push(String::new());
|
lines.push(String::new());
|
||||||
@@ -298,15 +261,7 @@ fn render_project_context(project_context: &ProjectContext) -> String {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn render_instruction_files(files: &[ContextFile]) -> String {
|
fn render_instruction_files(files: &[ContextFile]) -> String {
|
||||||
render_context_file_section("# Claude instructions", files)
|
let mut sections = vec!["# Claude instructions".to_string()];
|
||||||
}
|
|
||||||
|
|
||||||
fn render_memory_files(files: &[ContextFile]) -> String {
|
|
||||||
render_context_file_section("# Project memory", files)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn render_context_file_section(title: &str, files: &[ContextFile]) -> String {
|
|
||||||
let mut sections = vec![title.to_string()];
|
|
||||||
let mut remaining_chars = MAX_TOTAL_INSTRUCTION_CHARS;
|
let mut remaining_chars = MAX_TOTAL_INSTRUCTION_CHARS;
|
||||||
for file in files {
|
for file in files {
|
||||||
if remaining_chars == 0 {
|
if remaining_chars == 0 {
|
||||||
@@ -498,9 +453,8 @@ fn get_actions_section() -> String {
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::{
|
use super::{
|
||||||
collapse_blank_lines, display_context_path, normalize_instruction_content,
|
collapse_blank_lines, display_context_path, normalize_instruction_content,
|
||||||
render_instruction_content, render_instruction_files, render_memory_files,
|
render_instruction_content, render_instruction_files, truncate_instruction_content,
|
||||||
truncate_instruction_content, ContextFile, ProjectContext, SystemPromptBuilder,
|
ContextFile, ProjectContext, SystemPromptBuilder, SYSTEM_PROMPT_DYNAMIC_BOUNDARY,
|
||||||
SYSTEM_PROMPT_DYNAMIC_BOUNDARY,
|
|
||||||
};
|
};
|
||||||
use crate::config::ConfigLoader;
|
use crate::config::ConfigLoader;
|
||||||
use std::fs;
|
use std::fs;
|
||||||
@@ -565,35 +519,6 @@ mod tests {
|
|||||||
fs::remove_dir_all(root).expect("cleanup temp dir");
|
fs::remove_dir_all(root).expect("cleanup temp dir");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn discovers_project_memory_files_from_ancestor_chain() {
|
|
||||||
let root = temp_dir();
|
|
||||||
let nested = root.join("apps").join("api");
|
|
||||||
fs::create_dir_all(root.join(".claude").join("memory")).expect("root memory dir");
|
|
||||||
fs::create_dir_all(nested.join(".claude").join("memory")).expect("nested memory dir");
|
|
||||||
fs::write(
|
|
||||||
root.join(".claude").join("memory").join("2026-03-30.md"),
|
|
||||||
"root memory",
|
|
||||||
)
|
|
||||||
.expect("write root memory");
|
|
||||||
fs::write(
|
|
||||||
nested.join(".claude").join("memory").join("2026-03-31.md"),
|
|
||||||
"nested memory",
|
|
||||||
)
|
|
||||||
.expect("write nested memory");
|
|
||||||
|
|
||||||
let context = ProjectContext::discover(&nested, "2026-03-31").expect("context should load");
|
|
||||||
let contents = context
|
|
||||||
.memory_files
|
|
||||||
.iter()
|
|
||||||
.map(|file| file.content.as_str())
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
|
|
||||||
assert_eq!(contents, vec!["root memory", "nested memory"]);
|
|
||||||
assert!(render_memory_files(&context.memory_files).contains("# Project memory"));
|
|
||||||
fs::remove_dir_all(root).expect("cleanup temp dir");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn dedupes_identical_instruction_content_across_scopes() {
|
fn dedupes_identical_instruction_content_across_scopes() {
|
||||||
let root = temp_dir();
|
let root = temp_dir();
|
||||||
|
|||||||
364
rust/crates/runtime/src/sandbox.rs
Normal file
364
rust/crates/runtime/src/sandbox.rs
Normal file
@@ -0,0 +1,364 @@
|
|||||||
|
use std::env;
|
||||||
|
use std::fs;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
|
||||||
|
#[serde(rename_all = "kebab-case")]
|
||||||
|
pub enum FilesystemIsolationMode {
|
||||||
|
Off,
|
||||||
|
#[default]
|
||||||
|
WorkspaceOnly,
|
||||||
|
AllowList,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FilesystemIsolationMode {
|
||||||
|
#[must_use]
|
||||||
|
pub fn as_str(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Self::Off => "off",
|
||||||
|
Self::WorkspaceOnly => "workspace-only",
|
||||||
|
Self::AllowList => "allow-list",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
|
||||||
|
pub struct SandboxConfig {
|
||||||
|
pub enabled: Option<bool>,
|
||||||
|
pub namespace_restrictions: Option<bool>,
|
||||||
|
pub network_isolation: Option<bool>,
|
||||||
|
pub filesystem_mode: Option<FilesystemIsolationMode>,
|
||||||
|
pub allowed_mounts: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
|
||||||
|
pub struct SandboxRequest {
|
||||||
|
pub enabled: bool,
|
||||||
|
pub namespace_restrictions: bool,
|
||||||
|
pub network_isolation: bool,
|
||||||
|
pub filesystem_mode: FilesystemIsolationMode,
|
||||||
|
pub allowed_mounts: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
|
||||||
|
pub struct ContainerEnvironment {
|
||||||
|
pub in_container: bool,
|
||||||
|
pub markers: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(clippy::struct_excessive_bools)]
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
|
||||||
|
pub struct SandboxStatus {
|
||||||
|
pub enabled: bool,
|
||||||
|
pub requested: SandboxRequest,
|
||||||
|
pub supported: bool,
|
||||||
|
pub active: bool,
|
||||||
|
pub namespace_supported: bool,
|
||||||
|
pub namespace_active: bool,
|
||||||
|
pub network_supported: bool,
|
||||||
|
pub network_active: bool,
|
||||||
|
pub filesystem_mode: FilesystemIsolationMode,
|
||||||
|
pub filesystem_active: bool,
|
||||||
|
pub allowed_mounts: Vec<String>,
|
||||||
|
pub in_container: bool,
|
||||||
|
pub container_markers: Vec<String>,
|
||||||
|
pub fallback_reason: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct SandboxDetectionInputs<'a> {
|
||||||
|
pub env_pairs: Vec<(String, String)>,
|
||||||
|
pub dockerenv_exists: bool,
|
||||||
|
pub containerenv_exists: bool,
|
||||||
|
pub proc_1_cgroup: Option<&'a str>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct LinuxSandboxCommand {
|
||||||
|
pub program: String,
|
||||||
|
pub args: Vec<String>,
|
||||||
|
pub env: Vec<(String, String)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SandboxConfig {
|
||||||
|
#[must_use]
|
||||||
|
pub fn resolve_request(
|
||||||
|
&self,
|
||||||
|
enabled_override: Option<bool>,
|
||||||
|
namespace_override: Option<bool>,
|
||||||
|
network_override: Option<bool>,
|
||||||
|
filesystem_mode_override: Option<FilesystemIsolationMode>,
|
||||||
|
allowed_mounts_override: Option<Vec<String>>,
|
||||||
|
) -> SandboxRequest {
|
||||||
|
SandboxRequest {
|
||||||
|
enabled: enabled_override.unwrap_or(self.enabled.unwrap_or(true)),
|
||||||
|
namespace_restrictions: namespace_override
|
||||||
|
.unwrap_or(self.namespace_restrictions.unwrap_or(true)),
|
||||||
|
network_isolation: network_override.unwrap_or(self.network_isolation.unwrap_or(false)),
|
||||||
|
filesystem_mode: filesystem_mode_override
|
||||||
|
.or(self.filesystem_mode)
|
||||||
|
.unwrap_or_default(),
|
||||||
|
allowed_mounts: allowed_mounts_override.unwrap_or_else(|| self.allowed_mounts.clone()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn detect_container_environment() -> ContainerEnvironment {
|
||||||
|
let proc_1_cgroup = fs::read_to_string("/proc/1/cgroup").ok();
|
||||||
|
detect_container_environment_from(SandboxDetectionInputs {
|
||||||
|
env_pairs: env::vars().collect(),
|
||||||
|
dockerenv_exists: Path::new("/.dockerenv").exists(),
|
||||||
|
containerenv_exists: Path::new("/run/.containerenv").exists(),
|
||||||
|
proc_1_cgroup: proc_1_cgroup.as_deref(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn detect_container_environment_from(
|
||||||
|
inputs: SandboxDetectionInputs<'_>,
|
||||||
|
) -> ContainerEnvironment {
|
||||||
|
let mut markers = Vec::new();
|
||||||
|
if inputs.dockerenv_exists {
|
||||||
|
markers.push("/.dockerenv".to_string());
|
||||||
|
}
|
||||||
|
if inputs.containerenv_exists {
|
||||||
|
markers.push("/run/.containerenv".to_string());
|
||||||
|
}
|
||||||
|
for (key, value) in inputs.env_pairs {
|
||||||
|
let normalized = key.to_ascii_lowercase();
|
||||||
|
if matches!(
|
||||||
|
normalized.as_str(),
|
||||||
|
"container" | "docker" | "podman" | "kubernetes_service_host"
|
||||||
|
) && !value.is_empty()
|
||||||
|
{
|
||||||
|
markers.push(format!("env:{key}={value}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(cgroup) = inputs.proc_1_cgroup {
|
||||||
|
for needle in ["docker", "containerd", "kubepods", "podman", "libpod"] {
|
||||||
|
if cgroup.contains(needle) {
|
||||||
|
markers.push(format!("/proc/1/cgroup:{needle}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
markers.sort();
|
||||||
|
markers.dedup();
|
||||||
|
ContainerEnvironment {
|
||||||
|
in_container: !markers.is_empty(),
|
||||||
|
markers,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn resolve_sandbox_status(config: &SandboxConfig, cwd: &Path) -> SandboxStatus {
|
||||||
|
let request = config.resolve_request(None, None, None, None, None);
|
||||||
|
resolve_sandbox_status_for_request(&request, cwd)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn resolve_sandbox_status_for_request(request: &SandboxRequest, cwd: &Path) -> SandboxStatus {
|
||||||
|
let container = detect_container_environment();
|
||||||
|
let namespace_supported = cfg!(target_os = "linux") && command_exists("unshare");
|
||||||
|
let network_supported = namespace_supported;
|
||||||
|
let filesystem_active =
|
||||||
|
request.enabled && request.filesystem_mode != FilesystemIsolationMode::Off;
|
||||||
|
let mut fallback_reasons = Vec::new();
|
||||||
|
|
||||||
|
if request.enabled && request.namespace_restrictions && !namespace_supported {
|
||||||
|
fallback_reasons
|
||||||
|
.push("namespace isolation unavailable (requires Linux with `unshare`)".to_string());
|
||||||
|
}
|
||||||
|
if request.enabled && request.network_isolation && !network_supported {
|
||||||
|
fallback_reasons
|
||||||
|
.push("network isolation unavailable (requires Linux with `unshare`)".to_string());
|
||||||
|
}
|
||||||
|
if request.enabled
|
||||||
|
&& request.filesystem_mode == FilesystemIsolationMode::AllowList
|
||||||
|
&& request.allowed_mounts.is_empty()
|
||||||
|
{
|
||||||
|
fallback_reasons
|
||||||
|
.push("filesystem allow-list requested without configured mounts".to_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
let active = request.enabled
|
||||||
|
&& (!request.namespace_restrictions || namespace_supported)
|
||||||
|
&& (!request.network_isolation || network_supported);
|
||||||
|
|
||||||
|
let allowed_mounts = normalize_mounts(&request.allowed_mounts, cwd);
|
||||||
|
|
||||||
|
SandboxStatus {
|
||||||
|
enabled: request.enabled,
|
||||||
|
requested: request.clone(),
|
||||||
|
supported: namespace_supported,
|
||||||
|
active,
|
||||||
|
namespace_supported,
|
||||||
|
namespace_active: request.enabled && request.namespace_restrictions && namespace_supported,
|
||||||
|
network_supported,
|
||||||
|
network_active: request.enabled && request.network_isolation && network_supported,
|
||||||
|
filesystem_mode: request.filesystem_mode,
|
||||||
|
filesystem_active,
|
||||||
|
allowed_mounts,
|
||||||
|
in_container: container.in_container,
|
||||||
|
container_markers: container.markers,
|
||||||
|
fallback_reason: (!fallback_reasons.is_empty()).then(|| fallback_reasons.join("; ")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn build_linux_sandbox_command(
|
||||||
|
command: &str,
|
||||||
|
cwd: &Path,
|
||||||
|
status: &SandboxStatus,
|
||||||
|
) -> Option<LinuxSandboxCommand> {
|
||||||
|
if !cfg!(target_os = "linux")
|
||||||
|
|| !status.enabled
|
||||||
|
|| (!status.namespace_active && !status.network_active)
|
||||||
|
{
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut args = vec![
|
||||||
|
"--user".to_string(),
|
||||||
|
"--map-root-user".to_string(),
|
||||||
|
"--mount".to_string(),
|
||||||
|
"--ipc".to_string(),
|
||||||
|
"--pid".to_string(),
|
||||||
|
"--uts".to_string(),
|
||||||
|
"--fork".to_string(),
|
||||||
|
];
|
||||||
|
if status.network_active {
|
||||||
|
args.push("--net".to_string());
|
||||||
|
}
|
||||||
|
args.push("sh".to_string());
|
||||||
|
args.push("-lc".to_string());
|
||||||
|
args.push(command.to_string());
|
||||||
|
|
||||||
|
let sandbox_home = cwd.join(".sandbox-home");
|
||||||
|
let sandbox_tmp = cwd.join(".sandbox-tmp");
|
||||||
|
let mut env = vec![
|
||||||
|
("HOME".to_string(), sandbox_home.display().to_string()),
|
||||||
|
("TMPDIR".to_string(), sandbox_tmp.display().to_string()),
|
||||||
|
(
|
||||||
|
"CLAWD_SANDBOX_FILESYSTEM_MODE".to_string(),
|
||||||
|
status.filesystem_mode.as_str().to_string(),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"CLAWD_SANDBOX_ALLOWED_MOUNTS".to_string(),
|
||||||
|
status.allowed_mounts.join(":"),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
if let Ok(path) = env::var("PATH") {
|
||||||
|
env.push(("PATH".to_string(), path));
|
||||||
|
}
|
||||||
|
|
||||||
|
Some(LinuxSandboxCommand {
|
||||||
|
program: "unshare".to_string(),
|
||||||
|
args,
|
||||||
|
env,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn normalize_mounts(mounts: &[String], cwd: &Path) -> Vec<String> {
|
||||||
|
let cwd = cwd.to_path_buf();
|
||||||
|
mounts
|
||||||
|
.iter()
|
||||||
|
.map(|mount| {
|
||||||
|
let path = PathBuf::from(mount);
|
||||||
|
if path.is_absolute() {
|
||||||
|
path
|
||||||
|
} else {
|
||||||
|
cwd.join(path)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.map(|path| path.display().to_string())
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn command_exists(command: &str) -> bool {
|
||||||
|
env::var_os("PATH")
|
||||||
|
.is_some_and(|paths| env::split_paths(&paths).any(|path| path.join(command).exists()))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::{
|
||||||
|
build_linux_sandbox_command, detect_container_environment_from, FilesystemIsolationMode,
|
||||||
|
SandboxConfig, SandboxDetectionInputs,
|
||||||
|
};
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn detects_container_markers_from_multiple_sources() {
|
||||||
|
let detected = detect_container_environment_from(SandboxDetectionInputs {
|
||||||
|
env_pairs: vec![("container".to_string(), "docker".to_string())],
|
||||||
|
dockerenv_exists: true,
|
||||||
|
containerenv_exists: false,
|
||||||
|
proc_1_cgroup: Some("12:memory:/docker/abc"),
|
||||||
|
});
|
||||||
|
|
||||||
|
assert!(detected.in_container);
|
||||||
|
assert!(detected
|
||||||
|
.markers
|
||||||
|
.iter()
|
||||||
|
.any(|marker| marker == "/.dockerenv"));
|
||||||
|
assert!(detected
|
||||||
|
.markers
|
||||||
|
.iter()
|
||||||
|
.any(|marker| marker == "env:container=docker"));
|
||||||
|
assert!(detected
|
||||||
|
.markers
|
||||||
|
.iter()
|
||||||
|
.any(|marker| marker == "/proc/1/cgroup:docker"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn resolves_request_with_overrides() {
|
||||||
|
let config = SandboxConfig {
|
||||||
|
enabled: Some(true),
|
||||||
|
namespace_restrictions: Some(true),
|
||||||
|
network_isolation: Some(false),
|
||||||
|
filesystem_mode: Some(FilesystemIsolationMode::WorkspaceOnly),
|
||||||
|
allowed_mounts: vec!["logs".to_string()],
|
||||||
|
};
|
||||||
|
|
||||||
|
let request = config.resolve_request(
|
||||||
|
Some(true),
|
||||||
|
Some(false),
|
||||||
|
Some(true),
|
||||||
|
Some(FilesystemIsolationMode::AllowList),
|
||||||
|
Some(vec!["tmp".to_string()]),
|
||||||
|
);
|
||||||
|
|
||||||
|
assert!(request.enabled);
|
||||||
|
assert!(!request.namespace_restrictions);
|
||||||
|
assert!(request.network_isolation);
|
||||||
|
assert_eq!(request.filesystem_mode, FilesystemIsolationMode::AllowList);
|
||||||
|
assert_eq!(request.allowed_mounts, vec!["tmp"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn builds_linux_launcher_with_network_flag_when_requested() {
|
||||||
|
let config = SandboxConfig::default();
|
||||||
|
let status = super::resolve_sandbox_status_for_request(
|
||||||
|
&config.resolve_request(
|
||||||
|
Some(true),
|
||||||
|
Some(true),
|
||||||
|
Some(true),
|
||||||
|
Some(FilesystemIsolationMode::WorkspaceOnly),
|
||||||
|
None,
|
||||||
|
),
|
||||||
|
Path::new("/workspace"),
|
||||||
|
);
|
||||||
|
|
||||||
|
if let Some(launcher) =
|
||||||
|
build_linux_sandbox_command("printf hi", Path::new("/workspace"), &status)
|
||||||
|
{
|
||||||
|
assert_eq!(launcher.program, "unshare");
|
||||||
|
assert!(launcher.args.iter().any(|arg| arg == "--mount"));
|
||||||
|
assert!(launcher.args.iter().any(|arg| arg == "--net") == status.network_active);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -23,8 +23,8 @@ use compat_harness::{extract_manifest, UpstreamPaths};
|
|||||||
use render::{Spinner, TerminalRenderer};
|
use render::{Spinner, TerminalRenderer};
|
||||||
use runtime::{
|
use runtime::{
|
||||||
clear_oauth_credentials, generate_pkce_pair, generate_state, load_system_prompt,
|
clear_oauth_credentials, generate_pkce_pair, generate_state, load_system_prompt,
|
||||||
parse_oauth_callback_request_target, save_oauth_credentials, ApiClient, ApiRequest,
|
parse_oauth_callback_request_target, resolve_sandbox_status, save_oauth_credentials, ApiClient,
|
||||||
AssistantEvent, CompactionConfig, ConfigLoader, ConfigSource, ContentBlock,
|
ApiRequest, AssistantEvent, CompactionConfig, ConfigLoader, ConfigSource, ContentBlock,
|
||||||
ConversationMessage, ConversationRuntime, MessageRole, OAuthAuthorizationRequest,
|
ConversationMessage, ConversationRuntime, MessageRole, OAuthAuthorizationRequest,
|
||||||
OAuthTokenExchangeRequest, PermissionMode, PermissionPolicy, ProjectContext, RuntimeError,
|
OAuthTokenExchangeRequest, PermissionMode, PermissionPolicy, ProjectContext, RuntimeError,
|
||||||
Session, TokenUsage, ToolError, ToolExecutor, UsageTracker,
|
Session, TokenUsage, ToolError, ToolExecutor, UsageTracker,
|
||||||
@@ -591,6 +591,7 @@ struct StatusContext {
|
|||||||
memory_file_count: usize,
|
memory_file_count: usize,
|
||||||
project_root: Option<PathBuf>,
|
project_root: Option<PathBuf>,
|
||||||
git_branch: Option<String>,
|
git_branch: Option<String>,
|
||||||
|
sandbox_status: runtime::SandboxStatus,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy)]
|
#[derive(Debug, Clone, Copy)]
|
||||||
@@ -840,6 +841,18 @@ fn run_resume_command(
|
|||||||
)),
|
)),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
SlashCommand::Sandbox => {
|
||||||
|
let cwd = env::current_dir()?;
|
||||||
|
let loader = ConfigLoader::default_for(&cwd);
|
||||||
|
let runtime_config = loader.load()?;
|
||||||
|
Ok(ResumeCommandOutcome {
|
||||||
|
session: session.clone(),
|
||||||
|
message: Some(format_sandbox_report(&resolve_sandbox_status(
|
||||||
|
runtime_config.sandbox(),
|
||||||
|
&cwd,
|
||||||
|
))),
|
||||||
|
})
|
||||||
|
}
|
||||||
SlashCommand::Cost => {
|
SlashCommand::Cost => {
|
||||||
let usage = UsageTracker::from_session(session).cumulative_usage();
|
let usage = UsageTracker::from_session(session).cumulative_usage();
|
||||||
Ok(ResumeCommandOutcome {
|
Ok(ResumeCommandOutcome {
|
||||||
@@ -1091,6 +1104,10 @@ impl LiveCli {
|
|||||||
self.print_status();
|
self.print_status();
|
||||||
false
|
false
|
||||||
}
|
}
|
||||||
|
SlashCommand::Sandbox => {
|
||||||
|
Self::print_sandbox_status();
|
||||||
|
false
|
||||||
|
}
|
||||||
SlashCommand::Compact => {
|
SlashCommand::Compact => {
|
||||||
self.compact()?;
|
self.compact()?;
|
||||||
false
|
false
|
||||||
@@ -1162,6 +1179,18 @@ impl LiveCli {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn print_sandbox_status() {
|
||||||
|
let cwd = env::current_dir().expect("current dir");
|
||||||
|
let loader = ConfigLoader::default_for(&cwd);
|
||||||
|
let runtime_config = loader
|
||||||
|
.load()
|
||||||
|
.unwrap_or_else(|_| runtime::RuntimeConfig::empty());
|
||||||
|
println!(
|
||||||
|
"{}",
|
||||||
|
format_sandbox_report(&resolve_sandbox_status(runtime_config.sandbox(), &cwd))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
fn set_model(&mut self, model: Option<String>) -> Result<bool, Box<dyn std::error::Error>> {
|
fn set_model(&mut self, model: Option<String>) -> Result<bool, Box<dyn std::error::Error>> {
|
||||||
let Some(model) = model else {
|
let Some(model) = model else {
|
||||||
println!(
|
println!(
|
||||||
@@ -1537,15 +1566,16 @@ fn status_context(
|
|||||||
let project_context = ProjectContext::discover_with_git(&cwd, DEFAULT_DATE)?;
|
let project_context = ProjectContext::discover_with_git(&cwd, DEFAULT_DATE)?;
|
||||||
let (project_root, git_branch) =
|
let (project_root, git_branch) =
|
||||||
parse_git_status_metadata(project_context.git_status.as_deref());
|
parse_git_status_metadata(project_context.git_status.as_deref());
|
||||||
|
let sandbox_status = resolve_sandbox_status(runtime_config.sandbox(), &cwd);
|
||||||
Ok(StatusContext {
|
Ok(StatusContext {
|
||||||
cwd,
|
cwd,
|
||||||
session_path: session_path.map(Path::to_path_buf),
|
session_path: session_path.map(Path::to_path_buf),
|
||||||
loaded_config_files: runtime_config.loaded_entries().len(),
|
loaded_config_files: runtime_config.loaded_entries().len(),
|
||||||
discovered_config_files,
|
discovered_config_files,
|
||||||
memory_file_count: project_context.instruction_files.len()
|
memory_file_count: project_context.instruction_files.len(),
|
||||||
+ project_context.memory_files.len(),
|
|
||||||
project_root,
|
project_root,
|
||||||
git_branch,
|
git_branch,
|
||||||
|
sandbox_status,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1598,6 +1628,7 @@ fn format_status_report(
|
|||||||
context.discovered_config_files,
|
context.discovered_config_files,
|
||||||
context.memory_file_count,
|
context.memory_file_count,
|
||||||
),
|
),
|
||||||
|
format_sandbox_report(&context.sandbox_status),
|
||||||
]
|
]
|
||||||
.join(
|
.join(
|
||||||
"
|
"
|
||||||
@@ -1606,6 +1637,49 @@ fn format_status_report(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn format_sandbox_report(status: &runtime::SandboxStatus) -> String {
|
||||||
|
format!(
|
||||||
|
"Sandbox
|
||||||
|
Enabled {}
|
||||||
|
Active {}
|
||||||
|
Supported {}
|
||||||
|
In container {}
|
||||||
|
Requested ns {}
|
||||||
|
Active ns {}
|
||||||
|
Requested net {}
|
||||||
|
Active net {}
|
||||||
|
Filesystem mode {}
|
||||||
|
Filesystem active {}
|
||||||
|
Allowed mounts {}
|
||||||
|
Markers {}
|
||||||
|
Fallback reason {}",
|
||||||
|
status.enabled,
|
||||||
|
status.active,
|
||||||
|
status.supported,
|
||||||
|
status.in_container,
|
||||||
|
status.requested.namespace_restrictions,
|
||||||
|
status.namespace_active,
|
||||||
|
status.requested.network_isolation,
|
||||||
|
status.network_active,
|
||||||
|
status.filesystem_mode.as_str(),
|
||||||
|
status.filesystem_active,
|
||||||
|
if status.allowed_mounts.is_empty() {
|
||||||
|
"<none>".to_string()
|
||||||
|
} else {
|
||||||
|
status.allowed_mounts.join(", ")
|
||||||
|
},
|
||||||
|
if status.container_markers.is_empty() {
|
||||||
|
"<none>".to_string()
|
||||||
|
} else {
|
||||||
|
status.container_markers.join(", ")
|
||||||
|
},
|
||||||
|
status
|
||||||
|
.fallback_reason
|
||||||
|
.clone()
|
||||||
|
.unwrap_or_else(|| "<none>".to_string()),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
fn render_config_report(section: Option<&str>) -> Result<String, Box<dyn std::error::Error>> {
|
fn render_config_report(section: Option<&str>) -> Result<String, Box<dyn std::error::Error>> {
|
||||||
let cwd = env::current_dir()?;
|
let cwd = env::current_dir()?;
|
||||||
let loader = ConfigLoader::default_for(&cwd);
|
let loader = ConfigLoader::default_for(&cwd);
|
||||||
@@ -1688,58 +1762,39 @@ fn render_memory_report() -> Result<String, Box<dyn std::error::Error>> {
|
|||||||
let mut lines = vec![format!(
|
let mut lines = vec![format!(
|
||||||
"Memory
|
"Memory
|
||||||
Working directory {}
|
Working directory {}
|
||||||
Instruction files {}
|
Instruction files {}",
|
||||||
Project memory files {}",
|
|
||||||
cwd.display(),
|
cwd.display(),
|
||||||
project_context.instruction_files.len(),
|
project_context.instruction_files.len()
|
||||||
project_context.memory_files.len()
|
|
||||||
)];
|
)];
|
||||||
append_memory_section(
|
if project_context.instruction_files.is_empty() {
|
||||||
&mut lines,
|
lines.push("Discovered files".to_string());
|
||||||
"Instruction files",
|
lines.push(
|
||||||
&project_context.instruction_files,
|
" No CLAUDE instruction files discovered in the current directory ancestry."
|
||||||
"No CLAUDE instruction files discovered in the current directory ancestry.",
|
.to_string(),
|
||||||
);
|
);
|
||||||
append_memory_section(
|
} else {
|
||||||
&mut lines,
|
lines.push("Discovered files".to_string());
|
||||||
"Project memory files",
|
for (index, file) in project_context.instruction_files.iter().enumerate() {
|
||||||
&project_context.memory_files,
|
let preview = file.content.lines().next().unwrap_or("").trim();
|
||||||
"No persisted project memory files discovered in .claude/memory.",
|
let preview = if preview.is_empty() {
|
||||||
);
|
"<empty>"
|
||||||
|
} else {
|
||||||
|
preview
|
||||||
|
};
|
||||||
|
lines.push(format!(" {}. {}", index + 1, file.path.display(),));
|
||||||
|
lines.push(format!(
|
||||||
|
" lines={} preview={}",
|
||||||
|
file.content.lines().count(),
|
||||||
|
preview
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
Ok(lines.join(
|
Ok(lines.join(
|
||||||
"
|
"
|
||||||
",
|
",
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn append_memory_section(
|
|
||||||
lines: &mut Vec<String>,
|
|
||||||
title: &str,
|
|
||||||
files: &[runtime::ContextFile],
|
|
||||||
empty_message: &str,
|
|
||||||
) {
|
|
||||||
lines.push(title.to_string());
|
|
||||||
if files.is_empty() {
|
|
||||||
lines.push(format!(" {empty_message}"));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (index, file) in files.iter().enumerate() {
|
|
||||||
let preview = file.content.lines().next().unwrap_or("").trim();
|
|
||||||
let preview = if preview.is_empty() {
|
|
||||||
"<empty>"
|
|
||||||
} else {
|
|
||||||
preview
|
|
||||||
};
|
|
||||||
lines.push(format!(" {}. {}", index + 1, file.path.display()));
|
|
||||||
lines.push(format!(
|
|
||||||
" lines={} preview={}",
|
|
||||||
file.content.lines().count(),
|
|
||||||
preview
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn init_claude_md() -> Result<String, Box<dyn std::error::Error>> {
|
fn init_claude_md() -> Result<String, Box<dyn std::error::Error>> {
|
||||||
let cwd = env::current_dir()?;
|
let cwd = env::current_dir()?;
|
||||||
let claude_md = cwd.join("CLAUDE.md");
|
let claude_md = cwd.join("CLAUDE.md");
|
||||||
@@ -2621,6 +2676,7 @@ mod tests {
|
|||||||
assert!(help.contains("REPL"));
|
assert!(help.contains("REPL"));
|
||||||
assert!(help.contains("/help"));
|
assert!(help.contains("/help"));
|
||||||
assert!(help.contains("/status"));
|
assert!(help.contains("/status"));
|
||||||
|
assert!(help.contains("/sandbox"));
|
||||||
assert!(help.contains("/model [model]"));
|
assert!(help.contains("/model [model]"));
|
||||||
assert!(help.contains("/permissions [read-only|workspace-write|danger-full-access]"));
|
assert!(help.contains("/permissions [read-only|workspace-write|danger-full-access]"));
|
||||||
assert!(help.contains("/clear [--confirm]"));
|
assert!(help.contains("/clear [--confirm]"));
|
||||||
@@ -2645,8 +2701,8 @@ mod tests {
|
|||||||
assert_eq!(
|
assert_eq!(
|
||||||
names,
|
names,
|
||||||
vec![
|
vec![
|
||||||
"help", "status", "compact", "clear", "cost", "config", "memory", "init", "diff",
|
"help", "status", "sandbox", "compact", "clear", "cost", "config", "memory",
|
||||||
"version", "export",
|
"init", "diff", "version", "export",
|
||||||
]
|
]
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -2764,6 +2820,7 @@ mod tests {
|
|||||||
memory_file_count: 4,
|
memory_file_count: 4,
|
||||||
project_root: Some(PathBuf::from("/tmp")),
|
project_root: Some(PathBuf::from("/tmp")),
|
||||||
git_branch: Some("main".to_string()),
|
git_branch: Some("main".to_string()),
|
||||||
|
sandbox_status: runtime::SandboxStatus::default(),
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
assert!(status.contains("Status"));
|
assert!(status.contains("Status"));
|
||||||
@@ -2792,7 +2849,7 @@ mod tests {
|
|||||||
assert!(report.contains("Memory"));
|
assert!(report.contains("Memory"));
|
||||||
assert!(report.contains("Working directory"));
|
assert!(report.contains("Working directory"));
|
||||||
assert!(report.contains("Instruction files"));
|
assert!(report.contains("Instruction files"));
|
||||||
assert!(report.contains("Project memory files"));
|
assert!(report.contains("Discovered files"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -2817,7 +2874,7 @@ mod tests {
|
|||||||
fn status_context_reads_real_workspace_metadata() {
|
fn status_context_reads_real_workspace_metadata() {
|
||||||
let context = status_context(None).expect("status context should load");
|
let context = status_context(None).expect("status context should load");
|
||||||
assert!(context.cwd.is_absolute());
|
assert!(context.cwd.is_absolute());
|
||||||
assert!(context.discovered_config_files >= 3);
|
assert_eq!(context.discovered_config_files, 5);
|
||||||
assert!(context.loaded_config_files <= context.discovered_config_files);
|
assert!(context.loaded_config_files <= context.discovered_config_files);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2925,3 +2982,17 @@ mod tests {
|
|||||||
assert!(done.contains("contents"));
|
assert!(done.contains("contents"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod sandbox_report_tests {
|
||||||
|
use super::format_sandbox_report;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn sandbox_report_renders_expected_fields() {
|
||||||
|
let report = format_sandbox_report(&runtime::SandboxStatus::default());
|
||||||
|
assert!(report.contains("Sandbox"));
|
||||||
|
assert!(report.contains("Enabled"));
|
||||||
|
assert!(report.contains("Filesystem mode"));
|
||||||
|
assert!(report.contains("Fallback reason"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -62,7 +62,11 @@ pub fn mvp_tool_specs() -> Vec<ToolSpec> {
|
|||||||
"timeout": { "type": "integer", "minimum": 1 },
|
"timeout": { "type": "integer", "minimum": 1 },
|
||||||
"description": { "type": "string" },
|
"description": { "type": "string" },
|
||||||
"run_in_background": { "type": "boolean" },
|
"run_in_background": { "type": "boolean" },
|
||||||
"dangerouslyDisableSandbox": { "type": "boolean" }
|
"dangerouslyDisableSandbox": { "type": "boolean" },
|
||||||
|
"namespaceRestrictions": { "type": "boolean" },
|
||||||
|
"isolateNetwork": { "type": "boolean" },
|
||||||
|
"filesystemMode": { "type": "string", "enum": ["off", "workspace-only", "allow-list"] },
|
||||||
|
"allowedMounts": { "type": "array", "items": { "type": "string" } }
|
||||||
},
|
},
|
||||||
"required": ["command"],
|
"required": ["command"],
|
||||||
"additionalProperties": false
|
"additionalProperties": false
|
||||||
@@ -1199,9 +1203,10 @@ fn execute_todo_write(input: TodoWriteInput) -> Result<TodoWriteOutput, String>
|
|||||||
validate_todos(&input.todos)?;
|
validate_todos(&input.todos)?;
|
||||||
let store_path = todo_store_path()?;
|
let store_path = todo_store_path()?;
|
||||||
let old_todos = if store_path.exists() {
|
let old_todos = if store_path.exists() {
|
||||||
parse_todo_markdown(
|
serde_json::from_str::<Vec<TodoItem>>(
|
||||||
&std::fs::read_to_string(&store_path).map_err(|error| error.to_string())?,
|
&std::fs::read_to_string(&store_path).map_err(|error| error.to_string())?,
|
||||||
)?
|
)
|
||||||
|
.map_err(|error| error.to_string())?
|
||||||
} else {
|
} else {
|
||||||
Vec::new()
|
Vec::new()
|
||||||
};
|
};
|
||||||
@@ -1219,8 +1224,11 @@ fn execute_todo_write(input: TodoWriteInput) -> Result<TodoWriteOutput, String>
|
|||||||
if let Some(parent) = store_path.parent() {
|
if let Some(parent) = store_path.parent() {
|
||||||
std::fs::create_dir_all(parent).map_err(|error| error.to_string())?;
|
std::fs::create_dir_all(parent).map_err(|error| error.to_string())?;
|
||||||
}
|
}
|
||||||
std::fs::write(&store_path, render_todo_markdown(&persisted))
|
std::fs::write(
|
||||||
.map_err(|error| error.to_string())?;
|
&store_path,
|
||||||
|
serde_json::to_string_pretty(&persisted).map_err(|error| error.to_string())?,
|
||||||
|
)
|
||||||
|
.map_err(|error| error.to_string())?;
|
||||||
|
|
||||||
let verification_nudge_needed = (all_done
|
let verification_nudge_needed = (all_done
|
||||||
&& input.todos.len() >= 3
|
&& input.todos.len() >= 3
|
||||||
@@ -1278,58 +1286,7 @@ fn todo_store_path() -> Result<std::path::PathBuf, String> {
|
|||||||
return Ok(std::path::PathBuf::from(path));
|
return Ok(std::path::PathBuf::from(path));
|
||||||
}
|
}
|
||||||
let cwd = std::env::current_dir().map_err(|error| error.to_string())?;
|
let cwd = std::env::current_dir().map_err(|error| error.to_string())?;
|
||||||
Ok(cwd.join(".claude").join("todos.md"))
|
Ok(cwd.join(".clawd-todos.json"))
|
||||||
}
|
|
||||||
|
|
||||||
fn render_todo_markdown(todos: &[TodoItem]) -> String {
|
|
||||||
let mut lines = vec!["# Todo list".to_string(), String::new()];
|
|
||||||
for todo in todos {
|
|
||||||
let marker = match todo.status {
|
|
||||||
TodoStatus::Pending => "[ ]",
|
|
||||||
TodoStatus::InProgress => "[~]",
|
|
||||||
TodoStatus::Completed => "[x]",
|
|
||||||
};
|
|
||||||
lines.push(format!(
|
|
||||||
"- {marker} {} :: {}",
|
|
||||||
todo.content, todo.active_form
|
|
||||||
));
|
|
||||||
}
|
|
||||||
lines.push(String::new());
|
|
||||||
lines.join("\n")
|
|
||||||
}
|
|
||||||
|
|
||||||
fn parse_todo_markdown(content: &str) -> Result<Vec<TodoItem>, String> {
|
|
||||||
let mut todos = Vec::new();
|
|
||||||
for line in content.lines() {
|
|
||||||
let trimmed = line.trim();
|
|
||||||
if trimmed.is_empty() || trimmed.starts_with('#') {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let Some(rest) = trimmed.strip_prefix("- [") else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
let mut chars = rest.chars();
|
|
||||||
let status = match chars.next() {
|
|
||||||
Some(' ') => TodoStatus::Pending,
|
|
||||||
Some('~') => TodoStatus::InProgress,
|
|
||||||
Some('x' | 'X') => TodoStatus::Completed,
|
|
||||||
Some(other) => return Err(format!("unsupported todo status marker: {other}")),
|
|
||||||
None => return Err(String::from("malformed todo line")),
|
|
||||||
};
|
|
||||||
let remainder = chars.as_str();
|
|
||||||
let Some(body) = remainder.strip_prefix("] ") else {
|
|
||||||
return Err(String::from("malformed todo line"));
|
|
||||||
};
|
|
||||||
let Some((content, active_form)) = body.split_once(" :: ") else {
|
|
||||||
return Err(String::from("todo line missing active form separator"));
|
|
||||||
};
|
|
||||||
todos.push(TodoItem {
|
|
||||||
content: content.trim().to_string(),
|
|
||||||
active_form: active_form.trim().to_string(),
|
|
||||||
status,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
Ok(todos)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn resolve_skill_path(skill: &str) -> Result<std::path::PathBuf, String> {
|
fn resolve_skill_path(skill: &str) -> Result<std::path::PathBuf, String> {
|
||||||
@@ -2261,6 +2218,7 @@ fn execute_shell_command(
|
|||||||
structured_content: None,
|
structured_content: None,
|
||||||
persisted_output_path: None,
|
persisted_output_path: None,
|
||||||
persisted_output_size: None,
|
persisted_output_size: None,
|
||||||
|
sandbox_status: None,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2298,6 +2256,7 @@ fn execute_shell_command(
|
|||||||
structured_content: None,
|
structured_content: None,
|
||||||
persisted_output_path: None,
|
persisted_output_path: None,
|
||||||
persisted_output_size: None,
|
persisted_output_size: None,
|
||||||
|
sandbox_status: None,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if started.elapsed() >= Duration::from_millis(timeout_ms) {
|
if started.elapsed() >= Duration::from_millis(timeout_ms) {
|
||||||
@@ -2328,6 +2287,7 @@ Command exceeded timeout of {timeout_ms} ms",
|
|||||||
structured_content: None,
|
structured_content: None,
|
||||||
persisted_output_path: None,
|
persisted_output_path: None,
|
||||||
persisted_output_size: None,
|
persisted_output_size: None,
|
||||||
|
sandbox_status: None,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
std::thread::sleep(Duration::from_millis(10));
|
std::thread::sleep(Duration::from_millis(10));
|
||||||
@@ -2354,6 +2314,7 @@ Command exceeded timeout of {timeout_ms} ms",
|
|||||||
structured_content: None,
|
structured_content: None,
|
||||||
persisted_output_path: None,
|
persisted_output_path: None,
|
||||||
persisted_output_size: None,
|
persisted_output_size: None,
|
||||||
|
sandbox_status: None,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2685,37 +2646,6 @@ mod tests {
|
|||||||
assert!(second_output["verificationNudgeNeeded"].is_null());
|
assert!(second_output["verificationNudgeNeeded"].is_null());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn todo_write_persists_markdown_in_claude_directory() {
|
|
||||||
let _guard = env_lock()
|
|
||||||
.lock()
|
|
||||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
|
||||||
let temp = temp_path("todos-md-dir");
|
|
||||||
std::fs::create_dir_all(&temp).expect("temp dir");
|
|
||||||
let previous = std::env::current_dir().expect("cwd");
|
|
||||||
std::env::set_current_dir(&temp).expect("set cwd");
|
|
||||||
|
|
||||||
execute_tool(
|
|
||||||
"TodoWrite",
|
|
||||||
&json!({
|
|
||||||
"todos": [
|
|
||||||
{"content": "Add tool", "activeForm": "Adding tool", "status": "in_progress"},
|
|
||||||
{"content": "Run tests", "activeForm": "Running tests", "status": "pending"}
|
|
||||||
]
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
.expect("TodoWrite should succeed");
|
|
||||||
|
|
||||||
let persisted = std::fs::read_to_string(temp.join(".claude").join("todos.md"))
|
|
||||||
.expect("todo markdown exists");
|
|
||||||
std::env::set_current_dir(previous).expect("restore cwd");
|
|
||||||
let _ = std::fs::remove_dir_all(temp);
|
|
||||||
|
|
||||||
assert!(persisted.contains("# Todo list"));
|
|
||||||
assert!(persisted.contains("- [~] Add tool :: Adding tool"));
|
|
||||||
assert!(persisted.contains("- [ ] Run tests :: Running tests"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn todo_write_rejects_invalid_payloads_and_sets_verification_nudge() {
|
fn todo_write_rejects_invalid_payloads_and_sets_verification_nudge() {
|
||||||
let _guard = env_lock()
|
let _guard = env_lock()
|
||||||
|
|||||||
Reference in New Issue
Block a user