Compare commits
2 Commits
rcc/sandbo
...
rcc/api
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
962292dd27 | ||
|
|
074bd5b7b7 |
127
rust/.omc/project-memory.json
Normal file
127
rust/.omc/project-memory.json
Normal file
@@ -0,0 +1,127 @@
|
||||
{
|
||||
"version": "1.0.0",
|
||||
"lastScanned": 1774971516826,
|
||||
"projectRoot": "/home/bellman/Workspace/clawd-code-worktrees/api/rust",
|
||||
"techStack": {
|
||||
"languages": [
|
||||
{
|
||||
"name": "Rust",
|
||||
"version": null,
|
||||
"confidence": "high",
|
||||
"markers": [
|
||||
"Cargo.toml"
|
||||
]
|
||||
}
|
||||
],
|
||||
"frameworks": [],
|
||||
"packageManager": "cargo",
|
||||
"runtime": null
|
||||
},
|
||||
"build": {
|
||||
"buildCommand": "cargo build",
|
||||
"testCommand": "cargo test",
|
||||
"lintCommand": "cargo clippy",
|
||||
"devCommand": "cargo run",
|
||||
"scripts": {}
|
||||
},
|
||||
"conventions": {
|
||||
"namingStyle": null,
|
||||
"importStyle": null,
|
||||
"testPattern": null,
|
||||
"fileOrganization": null
|
||||
},
|
||||
"structure": {
|
||||
"isMonorepo": false,
|
||||
"workspaces": [],
|
||||
"mainDirectories": [],
|
||||
"gitBranches": {
|
||||
"defaultBranch": "main",
|
||||
"branchingStrategy": null
|
||||
}
|
||||
},
|
||||
"customNotes": [],
|
||||
"directoryMap": {
|
||||
"crates": {
|
||||
"path": "crates",
|
||||
"purpose": null,
|
||||
"fileCount": 0,
|
||||
"lastAccessed": 1774971516823,
|
||||
"keyFiles": []
|
||||
},
|
||||
"target": {
|
||||
"path": "target",
|
||||
"purpose": null,
|
||||
"fileCount": 2,
|
||||
"lastAccessed": 1774971516823,
|
||||
"keyFiles": [
|
||||
"CACHEDIR.TAG"
|
||||
]
|
||||
},
|
||||
"crates/api": {
|
||||
"path": "crates/api",
|
||||
"purpose": "API routes",
|
||||
"fileCount": 1,
|
||||
"lastAccessed": 1774971516824,
|
||||
"keyFiles": [
|
||||
"Cargo.toml"
|
||||
]
|
||||
}
|
||||
},
|
||||
"hotPaths": [
|
||||
{
|
||||
"path": "crates/api/Cargo.toml",
|
||||
"accessCount": 1,
|
||||
"lastAccessed": 1774971547109,
|
||||
"type": "file"
|
||||
},
|
||||
{
|
||||
"path": "crates/api/src/lib.rs",
|
||||
"accessCount": 1,
|
||||
"lastAccessed": 1774971547624,
|
||||
"type": "file"
|
||||
},
|
||||
{
|
||||
"path": "crates/api/src/client.rs",
|
||||
"accessCount": 1,
|
||||
"lastAccessed": 1774971548001,
|
||||
"type": "file"
|
||||
},
|
||||
{
|
||||
"path": "crates/api/src/error.rs",
|
||||
"accessCount": 1,
|
||||
"lastAccessed": 1774971548503,
|
||||
"type": "file"
|
||||
},
|
||||
{
|
||||
"path": "crates/api/src/sse.rs",
|
||||
"accessCount": 1,
|
||||
"lastAccessed": 1774971549311,
|
||||
"type": "file"
|
||||
},
|
||||
{
|
||||
"path": "crates/api/src/types.rs",
|
||||
"accessCount": 1,
|
||||
"lastAccessed": 1774971549472,
|
||||
"type": "file"
|
||||
},
|
||||
{
|
||||
"path": "crates/api/tests/client_integration.rs",
|
||||
"accessCount": 1,
|
||||
"lastAccessed": 1774971550143,
|
||||
"type": "file"
|
||||
},
|
||||
{
|
||||
"path": "Cargo.toml",
|
||||
"accessCount": 1,
|
||||
"lastAccessed": 1774971550539,
|
||||
"type": "file"
|
||||
},
|
||||
{
|
||||
"path": "crates/rusty-claude-cli/src/main.rs",
|
||||
"accessCount": 1,
|
||||
"lastAccessed": 1774971551474,
|
||||
"type": "file"
|
||||
}
|
||||
],
|
||||
"userDirectives": []
|
||||
}
|
||||
3
rust/.omc/state/idle-notif-cooldown.json
Normal file
3
rust/.omc/state/idle-notif-cooldown.json
Normal file
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"lastSentAt": "2026-03-31T15:39:44.771Z"
|
||||
}
|
||||
@@ -109,6 +109,13 @@ cd rust
|
||||
cargo run -p rusty-claude-cli -- --allowedTools read,glob
|
||||
```
|
||||
|
||||
Bootstrap Claude project files for the current repo:
|
||||
|
||||
```bash
|
||||
cd rust
|
||||
cargo run -p rusty-claude-cli -- init
|
||||
```
|
||||
|
||||
### 2) REPL mode
|
||||
|
||||
Start the interactive shell:
|
||||
@@ -179,7 +186,7 @@ cargo run -p rusty-claude-cli -- --resume session.json /memory /config
|
||||
- `/resume <session-path>` — load a saved session into the REPL
|
||||
- `/config [env|hooks|model]` — inspect discovered Claude config
|
||||
- `/memory` — inspect loaded instruction memory files
|
||||
- `/init` — create a starter `CLAUDE.md`
|
||||
- `/init` — bootstrap `.claude.json`, `.claude/`, `CLAUDE.md`, and local ignore rules
|
||||
- `/diff` — show the current git diff for the workspace
|
||||
- `/version` — print version and build metadata locally
|
||||
- `/export [file]` — export the current conversation transcript
|
||||
|
||||
@@ -51,12 +51,6 @@ const SLASH_COMMAND_SPECS: &[SlashCommandSpec] = &[
|
||||
argument_hint: None,
|
||||
resume_supported: true,
|
||||
},
|
||||
SlashCommandSpec {
|
||||
name: "sandbox",
|
||||
summary: "Show sandbox isolation status",
|
||||
argument_hint: None,
|
||||
resume_supported: true,
|
||||
},
|
||||
SlashCommandSpec {
|
||||
name: "compact",
|
||||
summary: "Compact local session history",
|
||||
@@ -107,7 +101,7 @@ const SLASH_COMMAND_SPECS: &[SlashCommandSpec] = &[
|
||||
},
|
||||
SlashCommandSpec {
|
||||
name: "init",
|
||||
summary: "Create a starter CLAUDE.md for this repo",
|
||||
summary: "Bootstrap Claude project files for this repo",
|
||||
argument_hint: None,
|
||||
resume_supported: true,
|
||||
},
|
||||
@@ -141,7 +135,6 @@ const SLASH_COMMAND_SPECS: &[SlashCommandSpec] = &[
|
||||
pub enum SlashCommand {
|
||||
Help,
|
||||
Status,
|
||||
Sandbox,
|
||||
Compact,
|
||||
Model {
|
||||
model: Option<String>,
|
||||
@@ -186,7 +179,6 @@ impl SlashCommand {
|
||||
Some(match command {
|
||||
"help" => Self::Help,
|
||||
"status" => Self::Status,
|
||||
"sandbox" => Self::Sandbox,
|
||||
"compact" => Self::Compact,
|
||||
"model" => Self::Model {
|
||||
model: parts.next().map(ToOwned::to_owned),
|
||||
@@ -287,7 +279,6 @@ pub fn handle_slash_command(
|
||||
session: session.clone(),
|
||||
}),
|
||||
SlashCommand::Status
|
||||
| SlashCommand::Sandbox
|
||||
| SlashCommand::Model { .. }
|
||||
| SlashCommand::Permissions { .. }
|
||||
| SlashCommand::Clear { .. }
|
||||
@@ -316,7 +307,6 @@ mod tests {
|
||||
fn parses_supported_slash_commands() {
|
||||
assert_eq!(SlashCommand::parse("/help"), Some(SlashCommand::Help));
|
||||
assert_eq!(SlashCommand::parse(" /status "), Some(SlashCommand::Status));
|
||||
assert_eq!(SlashCommand::parse("/sandbox"), Some(SlashCommand::Sandbox));
|
||||
assert_eq!(
|
||||
SlashCommand::parse("/model claude-opus"),
|
||||
Some(SlashCommand::Model {
|
||||
@@ -383,7 +373,6 @@ mod tests {
|
||||
assert!(help.contains("works with --resume SESSION.json"));
|
||||
assert!(help.contains("/help"));
|
||||
assert!(help.contains("/status"));
|
||||
assert!(help.contains("/sandbox"));
|
||||
assert!(help.contains("/compact"));
|
||||
assert!(help.contains("/model [model]"));
|
||||
assert!(help.contains("/permissions [read-only|workspace-write|danger-full-access]"));
|
||||
@@ -397,8 +386,8 @@ mod tests {
|
||||
assert!(help.contains("/version"));
|
||||
assert!(help.contains("/export [file]"));
|
||||
assert!(help.contains("/session [list|switch <session-id>]"));
|
||||
assert_eq!(slash_command_specs().len(), 16);
|
||||
assert_eq!(resume_supported_slash_commands().len(), 12);
|
||||
assert_eq!(slash_command_specs().len(), 15);
|
||||
assert_eq!(resume_supported_slash_commands().len(), 11);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -445,7 +434,6 @@ mod tests {
|
||||
let session = Session::new();
|
||||
assert!(handle_slash_command("/unknown", &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!(
|
||||
handle_slash_command("/model claude", &session, CompactionConfig::default()).is_none()
|
||||
);
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
use std::env;
|
||||
use std::io;
|
||||
use std::process::{Command, Stdio};
|
||||
use std::time::Duration;
|
||||
@@ -8,12 +7,6 @@ use tokio::process::Command as TokioCommand;
|
||||
use tokio::runtime::Builder;
|
||||
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)]
|
||||
pub struct BashCommandInput {
|
||||
pub command: String,
|
||||
@@ -23,14 +16,6 @@ pub struct BashCommandInput {
|
||||
pub run_in_background: Option<bool>,
|
||||
#[serde(rename = "dangerouslyDisableSandbox")]
|
||||
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)]
|
||||
@@ -60,17 +45,13 @@ pub struct BashCommandOutput {
|
||||
pub persisted_output_path: Option<String>,
|
||||
#[serde(rename = "persistedOutputSize")]
|
||||
pub persisted_output_size: Option<u64>,
|
||||
#[serde(rename = "sandboxStatus")]
|
||||
pub sandbox_status: Option<SandboxStatus>,
|
||||
}
|
||||
|
||||
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) {
|
||||
let mut child = prepare_command(&input.command, &cwd, &sandbox_status, false);
|
||||
let child = child
|
||||
let child = Command::new("sh")
|
||||
.arg("-lc")
|
||||
.arg(&input.command)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
@@ -91,20 +72,16 @@ pub fn execute_bash(input: BashCommandInput) -> io::Result<BashCommandOutput> {
|
||||
structured_content: None,
|
||||
persisted_output_path: None,
|
||||
persisted_output_size: None,
|
||||
sandbox_status: Some(sandbox_status),
|
||||
});
|
||||
}
|
||||
|
||||
let runtime = Builder::new_current_thread().enable_all().build()?;
|
||||
runtime.block_on(execute_bash_async(input, sandbox_status, cwd))
|
||||
runtime.block_on(execute_bash_async(input))
|
||||
}
|
||||
|
||||
async fn execute_bash_async(
|
||||
input: BashCommandInput,
|
||||
sandbox_status: SandboxStatus,
|
||||
cwd: std::path::PathBuf,
|
||||
) -> io::Result<BashCommandOutput> {
|
||||
let mut command = prepare_tokio_command(&input.command, &cwd, &sandbox_status, true);
|
||||
async fn execute_bash_async(input: BashCommandInput) -> io::Result<BashCommandOutput> {
|
||||
let mut command = TokioCommand::new("sh");
|
||||
command.arg("-lc").arg(&input.command);
|
||||
|
||||
let output_result = if let Some(timeout_ms) = input.timeout {
|
||||
match timeout(Duration::from_millis(timeout_ms), command.output()).await {
|
||||
@@ -125,7 +102,6 @@ async fn execute_bash_async(
|
||||
structured_content: None,
|
||||
persisted_output_path: None,
|
||||
persisted_output_size: None,
|
||||
sandbox_status: Some(sandbox_status),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -160,88 +136,12 @@ async fn execute_bash_async(
|
||||
structured_content: None,
|
||||
persisted_output_path: 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)]
|
||||
mod tests {
|
||||
use super::{execute_bash, BashCommandInput};
|
||||
use crate::sandbox::FilesystemIsolationMode;
|
||||
|
||||
#[test]
|
||||
fn executes_simple_command() {
|
||||
@@ -251,33 +151,10 @@ mod tests {
|
||||
description: None,
|
||||
run_in_background: 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");
|
||||
|
||||
assert_eq!(output.stdout, "hello");
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::json::JsonValue;
|
||||
use crate::sandbox::{FilesystemIsolationMode, SandboxConfig};
|
||||
|
||||
pub const CLAUDE_CODE_SETTINGS_SCHEMA_NAME: &str = "SettingsSchema";
|
||||
|
||||
@@ -41,7 +40,6 @@ pub struct RuntimeFeatureConfig {
|
||||
oauth: Option<OAuthConfig>,
|
||||
model: Option<String>,
|
||||
permission_mode: Option<ResolvedPermissionMode>,
|
||||
sandbox: SandboxConfig,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
||||
@@ -227,7 +225,6 @@ impl ConfigLoader {
|
||||
oauth: parse_optional_oauth_config(&merged_value, "merged settings.oauth")?,
|
||||
model: parse_optional_model(&merged_value),
|
||||
permission_mode: parse_optional_permission_mode(&merged_value)?,
|
||||
sandbox: parse_optional_sandbox_config(&merged_value)?,
|
||||
};
|
||||
|
||||
Ok(RuntimeConfig {
|
||||
@@ -292,11 +289,6 @@ impl RuntimeConfig {
|
||||
pub fn permission_mode(&self) -> Option<ResolvedPermissionMode> {
|
||||
self.feature_config.permission_mode
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn sandbox(&self) -> &SandboxConfig {
|
||||
&self.feature_config.sandbox
|
||||
}
|
||||
}
|
||||
|
||||
impl RuntimeFeatureConfig {
|
||||
@@ -319,11 +311,6 @@ impl RuntimeFeatureConfig {
|
||||
pub fn permission_mode(&self) -> Option<ResolvedPermissionMode> {
|
||||
self.permission_mode
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn sandbox(&self) -> &SandboxConfig {
|
||||
&self.sandbox
|
||||
}
|
||||
}
|
||||
|
||||
impl McpConfigCollection {
|
||||
@@ -458,42 +445,6 @@ 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(
|
||||
root: &JsonValue,
|
||||
context: &str,
|
||||
@@ -737,7 +688,6 @@ mod tests {
|
||||
CLAUDE_CODE_SETTINGS_SCHEMA_NAME,
|
||||
};
|
||||
use crate::json::JsonValue;
|
||||
use crate::sandbox::FilesystemIsolationMode;
|
||||
use std::fs;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
@@ -842,44 +792,6 @@ mod tests {
|
||||
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]
|
||||
fn parses_typed_mcp_and_oauth_config() {
|
||||
let root = temp_dir();
|
||||
|
||||
@@ -12,7 +12,6 @@ mod oauth;
|
||||
mod permissions;
|
||||
mod prompt;
|
||||
mod remote;
|
||||
mod sandbox;
|
||||
mod session;
|
||||
mod usage;
|
||||
|
||||
@@ -74,12 +73,6 @@ pub use remote::{
|
||||
RemoteSessionContext, UpstreamProxyBootstrap, UpstreamProxyState, DEFAULT_REMOTE_BASE_URL,
|
||||
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 usage::{
|
||||
format_usd, pricing_for_model, ModelPricing, TokenUsage, UsageCostEstimate, UsageTracker,
|
||||
|
||||
@@ -5,8 +5,6 @@ pub enum PermissionMode {
|
||||
ReadOnly,
|
||||
WorkspaceWrite,
|
||||
DangerFullAccess,
|
||||
Prompt,
|
||||
Allow,
|
||||
}
|
||||
|
||||
impl PermissionMode {
|
||||
@@ -16,8 +14,6 @@ impl PermissionMode {
|
||||
Self::ReadOnly => "read-only",
|
||||
Self::WorkspaceWrite => "workspace-write",
|
||||
Self::DangerFullAccess => "danger-full-access",
|
||||
Self::Prompt => "prompt",
|
||||
Self::Allow => "allow",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -94,7 +90,7 @@ impl PermissionPolicy {
|
||||
) -> PermissionOutcome {
|
||||
let current_mode = self.active_mode();
|
||||
let required_mode = self.required_mode_for(tool_name);
|
||||
if current_mode == PermissionMode::Allow || current_mode >= required_mode {
|
||||
if current_mode >= required_mode {
|
||||
return PermissionOutcome::Allow;
|
||||
}
|
||||
|
||||
@@ -105,9 +101,8 @@ impl PermissionPolicy {
|
||||
required_mode,
|
||||
};
|
||||
|
||||
if current_mode == PermissionMode::Prompt
|
||||
|| (current_mode == PermissionMode::WorkspaceWrite
|
||||
&& required_mode == PermissionMode::DangerFullAccess)
|
||||
if current_mode == PermissionMode::WorkspaceWrite
|
||||
&& required_mode == PermissionMode::DangerFullAccess
|
||||
{
|
||||
return match prompter.as_mut() {
|
||||
Some(prompter) => match prompter.decide(&request) {
|
||||
|
||||
@@ -1,364 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
433
rust/crates/rusty-claude-cli/src/init.rs
Normal file
433
rust/crates/rusty-claude-cli/src/init.rs
Normal file
@@ -0,0 +1,433 @@
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
const STARTER_CLAUDE_JSON: &str = concat!(
|
||||
"{\n",
|
||||
" \"permissions\": {\n",
|
||||
" \"defaultMode\": \"acceptEdits\"\n",
|
||||
" }\n",
|
||||
"}\n",
|
||||
);
|
||||
const GITIGNORE_COMMENT: &str = "# Claude Code local artifacts";
|
||||
const GITIGNORE_ENTRIES: [&str; 2] = [".claude/settings.local.json", ".claude/sessions/"];
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum InitStatus {
|
||||
Created,
|
||||
Updated,
|
||||
Skipped,
|
||||
}
|
||||
|
||||
impl InitStatus {
|
||||
#[must_use]
|
||||
pub(crate) fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::Created => "created",
|
||||
Self::Updated => "updated",
|
||||
Self::Skipped => "skipped (already exists)",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct InitArtifact {
|
||||
pub(crate) name: &'static str,
|
||||
pub(crate) status: InitStatus,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct InitReport {
|
||||
pub(crate) project_root: PathBuf,
|
||||
pub(crate) artifacts: Vec<InitArtifact>,
|
||||
}
|
||||
|
||||
impl InitReport {
|
||||
#[must_use]
|
||||
pub(crate) fn render(&self) -> String {
|
||||
let mut lines = vec![
|
||||
"Init".to_string(),
|
||||
format!(" Project {}", self.project_root.display()),
|
||||
];
|
||||
for artifact in &self.artifacts {
|
||||
lines.push(format!(
|
||||
" {:<16} {}",
|
||||
artifact.name,
|
||||
artifact.status.label()
|
||||
));
|
||||
}
|
||||
lines.push(" Next step Review and tailor the generated guidance".to_string());
|
||||
lines.join("\n")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
#[allow(clippy::struct_excessive_bools)]
|
||||
struct RepoDetection {
|
||||
rust_workspace: bool,
|
||||
rust_root: bool,
|
||||
python: bool,
|
||||
package_json: bool,
|
||||
typescript: bool,
|
||||
nextjs: bool,
|
||||
react: bool,
|
||||
vite: bool,
|
||||
nest: bool,
|
||||
src_dir: bool,
|
||||
tests_dir: bool,
|
||||
rust_dir: bool,
|
||||
}
|
||||
|
||||
pub(crate) fn initialize_repo(cwd: &Path) -> Result<InitReport, Box<dyn std::error::Error>> {
|
||||
let mut artifacts = Vec::new();
|
||||
|
||||
let claude_dir = cwd.join(".claude");
|
||||
artifacts.push(InitArtifact {
|
||||
name: ".claude/",
|
||||
status: ensure_dir(&claude_dir)?,
|
||||
});
|
||||
|
||||
let claude_json = cwd.join(".claude.json");
|
||||
artifacts.push(InitArtifact {
|
||||
name: ".claude.json",
|
||||
status: write_file_if_missing(&claude_json, STARTER_CLAUDE_JSON)?,
|
||||
});
|
||||
|
||||
let gitignore = cwd.join(".gitignore");
|
||||
artifacts.push(InitArtifact {
|
||||
name: ".gitignore",
|
||||
status: ensure_gitignore_entries(&gitignore)?,
|
||||
});
|
||||
|
||||
let claude_md = cwd.join("CLAUDE.md");
|
||||
let content = render_init_claude_md(cwd);
|
||||
artifacts.push(InitArtifact {
|
||||
name: "CLAUDE.md",
|
||||
status: write_file_if_missing(&claude_md, &content)?,
|
||||
});
|
||||
|
||||
Ok(InitReport {
|
||||
project_root: cwd.to_path_buf(),
|
||||
artifacts,
|
||||
})
|
||||
}
|
||||
|
||||
fn ensure_dir(path: &Path) -> Result<InitStatus, std::io::Error> {
|
||||
if path.is_dir() {
|
||||
return Ok(InitStatus::Skipped);
|
||||
}
|
||||
fs::create_dir_all(path)?;
|
||||
Ok(InitStatus::Created)
|
||||
}
|
||||
|
||||
fn write_file_if_missing(path: &Path, content: &str) -> Result<InitStatus, std::io::Error> {
|
||||
if path.exists() {
|
||||
return Ok(InitStatus::Skipped);
|
||||
}
|
||||
fs::write(path, content)?;
|
||||
Ok(InitStatus::Created)
|
||||
}
|
||||
|
||||
fn ensure_gitignore_entries(path: &Path) -> Result<InitStatus, std::io::Error> {
|
||||
if !path.exists() {
|
||||
let mut lines = vec![GITIGNORE_COMMENT.to_string()];
|
||||
lines.extend(GITIGNORE_ENTRIES.iter().map(|entry| (*entry).to_string()));
|
||||
fs::write(path, format!("{}\n", lines.join("\n")))?;
|
||||
return Ok(InitStatus::Created);
|
||||
}
|
||||
|
||||
let existing = fs::read_to_string(path)?;
|
||||
let mut lines = existing.lines().map(ToOwned::to_owned).collect::<Vec<_>>();
|
||||
let mut changed = false;
|
||||
|
||||
if !lines.iter().any(|line| line == GITIGNORE_COMMENT) {
|
||||
lines.push(GITIGNORE_COMMENT.to_string());
|
||||
changed = true;
|
||||
}
|
||||
|
||||
for entry in GITIGNORE_ENTRIES {
|
||||
if !lines.iter().any(|line| line == entry) {
|
||||
lines.push(entry.to_string());
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
if !changed {
|
||||
return Ok(InitStatus::Skipped);
|
||||
}
|
||||
|
||||
fs::write(path, format!("{}\n", lines.join("\n")))?;
|
||||
Ok(InitStatus::Updated)
|
||||
}
|
||||
|
||||
pub(crate) fn render_init_claude_md(cwd: &Path) -> String {
|
||||
let detection = detect_repo(cwd);
|
||||
let mut lines = vec![
|
||||
"# CLAUDE.md".to_string(),
|
||||
String::new(),
|
||||
"This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.".to_string(),
|
||||
String::new(),
|
||||
];
|
||||
|
||||
let detected_languages = detected_languages(&detection);
|
||||
let detected_frameworks = detected_frameworks(&detection);
|
||||
lines.push("## Detected stack".to_string());
|
||||
if detected_languages.is_empty() {
|
||||
lines.push("- No specific language markers were detected yet; document the primary language and verification commands once the project structure settles.".to_string());
|
||||
} else {
|
||||
lines.push(format!("- Languages: {}.", detected_languages.join(", ")));
|
||||
}
|
||||
if detected_frameworks.is_empty() {
|
||||
lines.push("- Frameworks: none detected from the supported starter markers.".to_string());
|
||||
} else {
|
||||
lines.push(format!(
|
||||
"- Frameworks/tooling markers: {}.",
|
||||
detected_frameworks.join(", ")
|
||||
));
|
||||
}
|
||||
lines.push(String::new());
|
||||
|
||||
let verification_lines = verification_lines(cwd, &detection);
|
||||
if !verification_lines.is_empty() {
|
||||
lines.push("## Verification".to_string());
|
||||
lines.extend(verification_lines);
|
||||
lines.push(String::new());
|
||||
}
|
||||
|
||||
let structure_lines = repository_shape_lines(&detection);
|
||||
if !structure_lines.is_empty() {
|
||||
lines.push("## Repository shape".to_string());
|
||||
lines.extend(structure_lines);
|
||||
lines.push(String::new());
|
||||
}
|
||||
|
||||
let framework_lines = framework_notes(&detection);
|
||||
if !framework_lines.is_empty() {
|
||||
lines.push("## Framework notes".to_string());
|
||||
lines.extend(framework_lines);
|
||||
lines.push(String::new());
|
||||
}
|
||||
|
||||
lines.push("## Working agreement".to_string());
|
||||
lines.push("- Prefer small, reviewable changes and keep generated bootstrap files aligned with actual repo workflows.".to_string());
|
||||
lines.push("- Keep shared defaults in `.claude.json`; reserve `.claude/settings.local.json` for machine-local overrides.".to_string());
|
||||
lines.push("- Do not overwrite existing `CLAUDE.md` content automatically; update it intentionally when repo workflows change.".to_string());
|
||||
lines.push(String::new());
|
||||
|
||||
lines.join("\n")
|
||||
}
|
||||
|
||||
fn detect_repo(cwd: &Path) -> RepoDetection {
|
||||
let package_json_contents = fs::read_to_string(cwd.join("package.json"))
|
||||
.unwrap_or_default()
|
||||
.to_ascii_lowercase();
|
||||
RepoDetection {
|
||||
rust_workspace: cwd.join("rust").join("Cargo.toml").is_file(),
|
||||
rust_root: cwd.join("Cargo.toml").is_file(),
|
||||
python: cwd.join("pyproject.toml").is_file()
|
||||
|| cwd.join("requirements.txt").is_file()
|
||||
|| cwd.join("setup.py").is_file(),
|
||||
package_json: cwd.join("package.json").is_file(),
|
||||
typescript: cwd.join("tsconfig.json").is_file()
|
||||
|| package_json_contents.contains("typescript"),
|
||||
nextjs: package_json_contents.contains("\"next\""),
|
||||
react: package_json_contents.contains("\"react\""),
|
||||
vite: package_json_contents.contains("\"vite\""),
|
||||
nest: package_json_contents.contains("@nestjs"),
|
||||
src_dir: cwd.join("src").is_dir(),
|
||||
tests_dir: cwd.join("tests").is_dir(),
|
||||
rust_dir: cwd.join("rust").is_dir(),
|
||||
}
|
||||
}
|
||||
|
||||
fn detected_languages(detection: &RepoDetection) -> Vec<&'static str> {
|
||||
let mut languages = Vec::new();
|
||||
if detection.rust_workspace || detection.rust_root {
|
||||
languages.push("Rust");
|
||||
}
|
||||
if detection.python {
|
||||
languages.push("Python");
|
||||
}
|
||||
if detection.typescript {
|
||||
languages.push("TypeScript");
|
||||
} else if detection.package_json {
|
||||
languages.push("JavaScript/Node.js");
|
||||
}
|
||||
languages
|
||||
}
|
||||
|
||||
fn detected_frameworks(detection: &RepoDetection) -> Vec<&'static str> {
|
||||
let mut frameworks = Vec::new();
|
||||
if detection.nextjs {
|
||||
frameworks.push("Next.js");
|
||||
}
|
||||
if detection.react {
|
||||
frameworks.push("React");
|
||||
}
|
||||
if detection.vite {
|
||||
frameworks.push("Vite");
|
||||
}
|
||||
if detection.nest {
|
||||
frameworks.push("NestJS");
|
||||
}
|
||||
frameworks
|
||||
}
|
||||
|
||||
fn verification_lines(cwd: &Path, detection: &RepoDetection) -> Vec<String> {
|
||||
let mut lines = Vec::new();
|
||||
if detection.rust_workspace {
|
||||
lines.push("- Run Rust verification from `rust/`: `cargo fmt`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo test --workspace`".to_string());
|
||||
} else if detection.rust_root {
|
||||
lines.push("- Run Rust verification from the repo root: `cargo fmt`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo test --workspace`".to_string());
|
||||
}
|
||||
if detection.python {
|
||||
if cwd.join("pyproject.toml").is_file() {
|
||||
lines.push("- Run the Python project checks declared in `pyproject.toml` (for example: `pytest`, `ruff check`, and `mypy` when configured).".to_string());
|
||||
} else {
|
||||
lines.push(
|
||||
"- Run the repo's Python test/lint commands before shipping changes.".to_string(),
|
||||
);
|
||||
}
|
||||
}
|
||||
if detection.package_json {
|
||||
lines.push("- Run the JavaScript/TypeScript checks from `package.json` before shipping changes (`npm test`, `npm run lint`, `npm run build`, or the repo equivalent).".to_string());
|
||||
}
|
||||
if detection.tests_dir && detection.src_dir {
|
||||
lines.push("- `src/` and `tests/` are both present; update both surfaces together when behavior changes.".to_string());
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
fn repository_shape_lines(detection: &RepoDetection) -> Vec<String> {
|
||||
let mut lines = Vec::new();
|
||||
if detection.rust_dir {
|
||||
lines.push(
|
||||
"- `rust/` contains the Rust workspace and active CLI/runtime implementation."
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
if detection.src_dir {
|
||||
lines.push("- `src/` contains source files that should stay consistent with generated guidance and tests.".to_string());
|
||||
}
|
||||
if detection.tests_dir {
|
||||
lines.push("- `tests/` contains validation surfaces that should be reviewed alongside code changes.".to_string());
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
fn framework_notes(detection: &RepoDetection) -> Vec<String> {
|
||||
let mut lines = Vec::new();
|
||||
if detection.nextjs {
|
||||
lines.push("- Next.js detected: preserve routing/data-fetching conventions and verify production builds after changing app structure.".to_string());
|
||||
}
|
||||
if detection.react && !detection.nextjs {
|
||||
lines.push("- React detected: keep component behavior covered with focused tests and avoid unnecessary prop/API churn.".to_string());
|
||||
}
|
||||
if detection.vite {
|
||||
lines.push("- Vite detected: validate the production bundle after changing build-sensitive configuration or imports.".to_string());
|
||||
}
|
||||
if detection.nest {
|
||||
lines.push("- NestJS detected: keep module/provider boundaries explicit and verify controller/service wiring after refactors.".to_string());
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{initialize_repo, render_init_claude_md};
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
fn temp_dir() -> std::path::PathBuf {
|
||||
let nanos = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.expect("time should be after epoch")
|
||||
.as_nanos();
|
||||
std::env::temp_dir().join(format!("rusty-claude-init-{nanos}"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn initialize_repo_creates_expected_files_and_gitignore_entries() {
|
||||
let root = temp_dir();
|
||||
fs::create_dir_all(root.join("rust")).expect("create rust dir");
|
||||
fs::write(root.join("rust").join("Cargo.toml"), "[workspace]\n").expect("write cargo");
|
||||
|
||||
let report = initialize_repo(&root).expect("init should succeed");
|
||||
let rendered = report.render();
|
||||
assert!(rendered.contains(".claude/ created"));
|
||||
assert!(rendered.contains(".claude.json created"));
|
||||
assert!(rendered.contains(".gitignore created"));
|
||||
assert!(rendered.contains("CLAUDE.md created"));
|
||||
assert!(root.join(".claude").is_dir());
|
||||
assert!(root.join(".claude.json").is_file());
|
||||
assert!(root.join("CLAUDE.md").is_file());
|
||||
assert_eq!(
|
||||
fs::read_to_string(root.join(".claude.json")).expect("read claude json"),
|
||||
concat!(
|
||||
"{\n",
|
||||
" \"permissions\": {\n",
|
||||
" \"defaultMode\": \"acceptEdits\"\n",
|
||||
" }\n",
|
||||
"}\n",
|
||||
)
|
||||
);
|
||||
let gitignore = fs::read_to_string(root.join(".gitignore")).expect("read gitignore");
|
||||
assert!(gitignore.contains(".claude/settings.local.json"));
|
||||
assert!(gitignore.contains(".claude/sessions/"));
|
||||
let claude_md = fs::read_to_string(root.join("CLAUDE.md")).expect("read claude md");
|
||||
assert!(claude_md.contains("Languages: Rust."));
|
||||
assert!(claude_md.contains("cargo clippy --workspace --all-targets -- -D warnings"));
|
||||
|
||||
fs::remove_dir_all(root).expect("cleanup temp dir");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn initialize_repo_is_idempotent_and_preserves_existing_files() {
|
||||
let root = temp_dir();
|
||||
fs::create_dir_all(&root).expect("create root");
|
||||
fs::write(root.join("CLAUDE.md"), "custom guidance\n").expect("write existing claude md");
|
||||
fs::write(root.join(".gitignore"), ".claude/settings.local.json\n")
|
||||
.expect("write gitignore");
|
||||
|
||||
let first = initialize_repo(&root).expect("first init should succeed");
|
||||
assert!(first
|
||||
.render()
|
||||
.contains("CLAUDE.md skipped (already exists)"));
|
||||
let second = initialize_repo(&root).expect("second init should succeed");
|
||||
let second_rendered = second.render();
|
||||
assert!(second_rendered.contains(".claude/ skipped (already exists)"));
|
||||
assert!(second_rendered.contains(".claude.json skipped (already exists)"));
|
||||
assert!(second_rendered.contains(".gitignore skipped (already exists)"));
|
||||
assert!(second_rendered.contains("CLAUDE.md skipped (already exists)"));
|
||||
assert_eq!(
|
||||
fs::read_to_string(root.join("CLAUDE.md")).expect("read existing claude md"),
|
||||
"custom guidance\n"
|
||||
);
|
||||
let gitignore = fs::read_to_string(root.join(".gitignore")).expect("read gitignore");
|
||||
assert_eq!(gitignore.matches(".claude/settings.local.json").count(), 1);
|
||||
assert_eq!(gitignore.matches(".claude/sessions/").count(), 1);
|
||||
|
||||
fs::remove_dir_all(root).expect("cleanup temp dir");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_init_template_mentions_detected_python_and_nextjs_markers() {
|
||||
let root = temp_dir();
|
||||
fs::create_dir_all(&root).expect("create root");
|
||||
fs::write(root.join("pyproject.toml"), "[project]\nname = \"demo\"\n")
|
||||
.expect("write pyproject");
|
||||
fs::write(
|
||||
root.join("package.json"),
|
||||
r#"{"dependencies":{"next":"14.0.0","react":"18.0.0"},"devDependencies":{"typescript":"5.0.0"}}"#,
|
||||
)
|
||||
.expect("write package json");
|
||||
|
||||
let rendered = render_init_claude_md(Path::new(&root));
|
||||
assert!(rendered.contains("Languages: Python, TypeScript."));
|
||||
assert!(rendered.contains("Frameworks/tooling markers: Next.js, React."));
|
||||
assert!(rendered.contains("pyproject.toml"));
|
||||
assert!(rendered.contains("Next.js detected"));
|
||||
|
||||
fs::remove_dir_all(root).expect("cleanup temp dir");
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
mod init;
|
||||
mod input;
|
||||
mod render;
|
||||
|
||||
@@ -20,11 +21,12 @@ use commands::{
|
||||
render_slash_command_help, resume_supported_slash_commands, slash_command_specs, SlashCommand,
|
||||
};
|
||||
use compat_harness::{extract_manifest, UpstreamPaths};
|
||||
use init::initialize_repo;
|
||||
use render::{Spinner, TerminalRenderer};
|
||||
use runtime::{
|
||||
clear_oauth_credentials, generate_pkce_pair, generate_state, load_system_prompt,
|
||||
parse_oauth_callback_request_target, resolve_sandbox_status, save_oauth_credentials, ApiClient,
|
||||
ApiRequest, AssistantEvent, CompactionConfig, ConfigLoader, ConfigSource, ContentBlock,
|
||||
parse_oauth_callback_request_target, save_oauth_credentials, ApiClient, ApiRequest,
|
||||
AssistantEvent, CompactionConfig, ConfigLoader, ConfigSource, ContentBlock,
|
||||
ConversationMessage, ConversationRuntime, MessageRole, OAuthAuthorizationRequest,
|
||||
OAuthTokenExchangeRequest, PermissionMode, PermissionPolicy, ProjectContext, RuntimeError,
|
||||
Session, TokenUsage, ToolError, ToolExecutor, UsageTracker,
|
||||
@@ -74,6 +76,7 @@ fn run() -> Result<(), Box<dyn std::error::Error>> {
|
||||
.run_turn_with_output(&prompt, output_format)?,
|
||||
CliAction::Login => run_login()?,
|
||||
CliAction::Logout => run_logout()?,
|
||||
CliAction::Init => run_init()?,
|
||||
CliAction::Repl {
|
||||
model,
|
||||
allowed_tools,
|
||||
@@ -106,6 +109,7 @@ enum CliAction {
|
||||
},
|
||||
Login,
|
||||
Logout,
|
||||
Init,
|
||||
Repl {
|
||||
model: String,
|
||||
allowed_tools: Option<AllowedToolSet>,
|
||||
@@ -230,6 +234,7 @@ fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
||||
"system-prompt" => parse_system_prompt_args(&rest[1..]),
|
||||
"login" => Ok(CliAction::Login),
|
||||
"logout" => Ok(CliAction::Logout),
|
||||
"init" => Ok(CliAction::Init),
|
||||
"prompt" => {
|
||||
let prompt = rest[1..].join(" ");
|
||||
if prompt.trim().is_empty() {
|
||||
@@ -591,7 +596,6 @@ struct StatusContext {
|
||||
memory_file_count: usize,
|
||||
project_root: Option<PathBuf>,
|
||||
git_branch: Option<String>,
|
||||
sandbox_status: runtime::SandboxStatus,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
@@ -704,26 +708,6 @@ fn format_resume_report(session_path: &str, message_count: usize, turns: u32) ->
|
||||
)
|
||||
}
|
||||
|
||||
fn format_init_report(path: &Path, created: bool) -> String {
|
||||
if created {
|
||||
format!(
|
||||
"Init
|
||||
CLAUDE.md {}
|
||||
Result created
|
||||
Next step Review and tailor the generated guidance",
|
||||
path.display()
|
||||
)
|
||||
} else {
|
||||
format!(
|
||||
"Init
|
||||
CLAUDE.md {}
|
||||
Result skipped (already exists)
|
||||
Next step Edit the existing file intentionally if workflows changed",
|
||||
path.display()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn format_compact_report(removed: usize, resulting_messages: usize, skipped: bool) -> String {
|
||||
if skipped {
|
||||
format!(
|
||||
@@ -841,18 +825,6 @@ 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 => {
|
||||
let usage = UsageTracker::from_session(session).cumulative_usage();
|
||||
Ok(ResumeCommandOutcome {
|
||||
@@ -1104,10 +1076,6 @@ impl LiveCli {
|
||||
self.print_status();
|
||||
false
|
||||
}
|
||||
SlashCommand::Sandbox => {
|
||||
Self::print_sandbox_status();
|
||||
false
|
||||
}
|
||||
SlashCommand::Compact => {
|
||||
self.compact()?;
|
||||
false
|
||||
@@ -1129,7 +1097,7 @@ impl LiveCli {
|
||||
false
|
||||
}
|
||||
SlashCommand::Init => {
|
||||
Self::run_init()?;
|
||||
run_init()?;
|
||||
false
|
||||
}
|
||||
SlashCommand::Diff => {
|
||||
@@ -1179,18 +1147,6 @@ 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>> {
|
||||
let Some(model) = model else {
|
||||
println!(
|
||||
@@ -1349,11 +1305,6 @@ impl LiveCli {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn run_init() -> Result<(), Box<dyn std::error::Error>> {
|
||||
println!("{}", init_claude_md()?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn print_diff() -> Result<(), Box<dyn std::error::Error>> {
|
||||
println!("{}", render_diff_report()?);
|
||||
Ok(())
|
||||
@@ -1566,7 +1517,6 @@ fn status_context(
|
||||
let project_context = ProjectContext::discover_with_git(&cwd, DEFAULT_DATE)?;
|
||||
let (project_root, git_branch) =
|
||||
parse_git_status_metadata(project_context.git_status.as_deref());
|
||||
let sandbox_status = resolve_sandbox_status(runtime_config.sandbox(), &cwd);
|
||||
Ok(StatusContext {
|
||||
cwd,
|
||||
session_path: session_path.map(Path::to_path_buf),
|
||||
@@ -1575,7 +1525,6 @@ fn status_context(
|
||||
memory_file_count: project_context.instruction_files.len(),
|
||||
project_root,
|
||||
git_branch,
|
||||
sandbox_status,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1628,7 +1577,6 @@ fn format_status_report(
|
||||
context.discovered_config_files,
|
||||
context.memory_file_count,
|
||||
),
|
||||
format_sandbox_report(&context.sandbox_status),
|
||||
]
|
||||
.join(
|
||||
"
|
||||
@@ -1637,49 +1585,6 @@ 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>> {
|
||||
let cwd = env::current_dir()?;
|
||||
let loader = ConfigLoader::default_for(&cwd);
|
||||
@@ -1797,67 +1702,12 @@ fn render_memory_report() -> Result<String, Box<dyn std::error::Error>> {
|
||||
|
||||
fn init_claude_md() -> Result<String, Box<dyn std::error::Error>> {
|
||||
let cwd = env::current_dir()?;
|
||||
let claude_md = cwd.join("CLAUDE.md");
|
||||
if claude_md.exists() {
|
||||
return Ok(format_init_report(&claude_md, false));
|
||||
}
|
||||
|
||||
let content = render_init_claude_md(&cwd);
|
||||
fs::write(&claude_md, content)?;
|
||||
Ok(format_init_report(&claude_md, true))
|
||||
Ok(initialize_repo(&cwd)?.render())
|
||||
}
|
||||
|
||||
fn render_init_claude_md(cwd: &Path) -> String {
|
||||
let mut lines = vec![
|
||||
"# CLAUDE.md".to_string(),
|
||||
String::new(),
|
||||
"This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.".to_string(),
|
||||
String::new(),
|
||||
];
|
||||
|
||||
let mut command_lines = Vec::new();
|
||||
if cwd.join("rust").join("Cargo.toml").is_file() {
|
||||
command_lines.push("- Run Rust verification from `rust/`: `cargo fmt`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo test --workspace`".to_string());
|
||||
} else if cwd.join("Cargo.toml").is_file() {
|
||||
command_lines.push("- Run Rust verification from the repo root: `cargo fmt`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo test --workspace`".to_string());
|
||||
}
|
||||
if cwd.join("tests").is_dir() && cwd.join("src").is_dir() {
|
||||
command_lines.push("- `src/` and `tests/` are also present; check those surfaces before removing or renaming Python-era compatibility assets.".to_string());
|
||||
}
|
||||
if !command_lines.is_empty() {
|
||||
lines.push("## Verification".to_string());
|
||||
lines.extend(command_lines);
|
||||
lines.push(String::new());
|
||||
}
|
||||
|
||||
let mut structure_lines = Vec::new();
|
||||
if cwd.join("rust").is_dir() {
|
||||
structure_lines.push(
|
||||
"- `rust/` contains the Rust workspace and the active CLI/runtime implementation."
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
if cwd.join("src").is_dir() {
|
||||
structure_lines.push("- `src/` contains the older Python-first workspace artifacts referenced by the repo history and tests.".to_string());
|
||||
}
|
||||
if cwd.join("tests").is_dir() {
|
||||
structure_lines.push("- `tests/` exercises compatibility and porting behavior across the repository surfaces.".to_string());
|
||||
}
|
||||
if !structure_lines.is_empty() {
|
||||
lines.push("## Repository shape".to_string());
|
||||
lines.extend(structure_lines);
|
||||
lines.push(String::new());
|
||||
}
|
||||
|
||||
lines.push("## Working agreement".to_string());
|
||||
lines.push("- Prefer small, reviewable Rust changes and keep slash-command behavior aligned between the shared command registry and the CLI entrypoints.".to_string());
|
||||
lines.push("- Do not overwrite existing CLAUDE.md content automatically; update it intentionally when repo workflows change.".to_string());
|
||||
lines.push(String::new());
|
||||
|
||||
lines.join(
|
||||
"
|
||||
",
|
||||
)
|
||||
fn run_init() -> Result<(), Box<dyn std::error::Error>> {
|
||||
println!("{}", init_claude_md()?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn normalize_permission_mode(mode: &str) -> Option<&'static str> {
|
||||
@@ -2416,34 +2266,65 @@ fn convert_messages(messages: &[ConversationMessage]) -> Vec<InputMessage> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn print_help() {
|
||||
println!("rusty-claude-cli v{VERSION}");
|
||||
println!();
|
||||
println!("Usage:");
|
||||
println!(" rusty-claude-cli [--model MODEL] [--allowedTools TOOL[,TOOL...]]");
|
||||
println!(" Start the interactive REPL");
|
||||
println!(" rusty-claude-cli [--model MODEL] [--output-format text|json] prompt TEXT");
|
||||
println!(" Send one prompt and exit");
|
||||
println!(" rusty-claude-cli [--model MODEL] [--output-format text|json] TEXT");
|
||||
println!(" Shorthand non-interactive prompt mode");
|
||||
println!(" rusty-claude-cli --resume SESSION.json [/status] [/compact] [...]");
|
||||
println!(" Inspect or maintain a saved session without entering the REPL");
|
||||
println!(" rusty-claude-cli dump-manifests");
|
||||
println!(" rusty-claude-cli bootstrap-plan");
|
||||
println!(" rusty-claude-cli system-prompt [--cwd PATH] [--date YYYY-MM-DD]");
|
||||
println!(" rusty-claude-cli login");
|
||||
println!(" rusty-claude-cli logout");
|
||||
println!();
|
||||
println!("Flags:");
|
||||
println!(" --model MODEL Override the active model");
|
||||
println!(" --output-format FORMAT Non-interactive output format: text or json");
|
||||
println!(" --permission-mode MODE Set read-only, workspace-write, or danger-full-access");
|
||||
println!(" --allowedTools TOOLS Restrict enabled tools (repeatable; comma-separated aliases supported)");
|
||||
println!(" --version, -V Print version and build information locally");
|
||||
println!();
|
||||
println!("Interactive slash commands:");
|
||||
println!("{}", render_slash_command_help());
|
||||
println!();
|
||||
fn print_help_to(out: &mut impl Write) -> io::Result<()> {
|
||||
writeln!(out, "rusty-claude-cli v{VERSION}")?;
|
||||
writeln!(out)?;
|
||||
writeln!(out, "Usage:")?;
|
||||
writeln!(
|
||||
out,
|
||||
" rusty-claude-cli [--model MODEL] [--allowedTools TOOL[,TOOL...]]"
|
||||
)?;
|
||||
writeln!(out, " Start the interactive REPL")?;
|
||||
writeln!(
|
||||
out,
|
||||
" rusty-claude-cli [--model MODEL] [--output-format text|json] prompt TEXT"
|
||||
)?;
|
||||
writeln!(out, " Send one prompt and exit")?;
|
||||
writeln!(
|
||||
out,
|
||||
" rusty-claude-cli [--model MODEL] [--output-format text|json] TEXT"
|
||||
)?;
|
||||
writeln!(out, " Shorthand non-interactive prompt mode")?;
|
||||
writeln!(
|
||||
out,
|
||||
" rusty-claude-cli --resume SESSION.json [/status] [/compact] [...]"
|
||||
)?;
|
||||
writeln!(
|
||||
out,
|
||||
" Inspect or maintain a saved session without entering the REPL"
|
||||
)?;
|
||||
writeln!(out, " rusty-claude-cli dump-manifests")?;
|
||||
writeln!(out, " rusty-claude-cli bootstrap-plan")?;
|
||||
writeln!(
|
||||
out,
|
||||
" rusty-claude-cli system-prompt [--cwd PATH] [--date YYYY-MM-DD]"
|
||||
)?;
|
||||
writeln!(out, " rusty-claude-cli login")?;
|
||||
writeln!(out, " rusty-claude-cli logout")?;
|
||||
writeln!(out, " rusty-claude-cli init")?;
|
||||
writeln!(out)?;
|
||||
writeln!(out, "Flags:")?;
|
||||
writeln!(
|
||||
out,
|
||||
" --model MODEL Override the active model"
|
||||
)?;
|
||||
writeln!(
|
||||
out,
|
||||
" --output-format FORMAT Non-interactive output format: text or json"
|
||||
)?;
|
||||
writeln!(
|
||||
out,
|
||||
" --permission-mode MODE Set read-only, workspace-write, or danger-full-access"
|
||||
)?;
|
||||
writeln!(out, " --allowedTools TOOLS Restrict enabled tools (repeatable; comma-separated aliases supported)")?;
|
||||
writeln!(
|
||||
out,
|
||||
" --version, -V Print version and build information locally"
|
||||
)?;
|
||||
writeln!(out)?;
|
||||
writeln!(out, "Interactive slash commands:")?;
|
||||
writeln!(out, "{}", render_slash_command_help())?;
|
||||
writeln!(out)?;
|
||||
let resume_commands = resume_supported_slash_commands()
|
||||
.into_iter()
|
||||
.map(|spec| match spec.argument_hint {
|
||||
@@ -2452,28 +2333,46 @@ fn print_help() {
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
println!("Resume-safe commands: {resume_commands}");
|
||||
println!("Examples:");
|
||||
println!(" rusty-claude-cli --model claude-opus \"summarize this repo\"");
|
||||
println!(" rusty-claude-cli --output-format json prompt \"explain src/main.rs\"");
|
||||
println!(" rusty-claude-cli --allowedTools read,glob \"summarize Cargo.toml\"");
|
||||
println!(" rusty-claude-cli --resume session.json /status /diff /export notes.txt");
|
||||
println!(" rusty-claude-cli login");
|
||||
writeln!(out, "Resume-safe commands: {resume_commands}")?;
|
||||
writeln!(out, "Examples:")?;
|
||||
writeln!(
|
||||
out,
|
||||
" rusty-claude-cli --model claude-opus \"summarize this repo\""
|
||||
)?;
|
||||
writeln!(
|
||||
out,
|
||||
" rusty-claude-cli --output-format json prompt \"explain src/main.rs\""
|
||||
)?;
|
||||
writeln!(
|
||||
out,
|
||||
" rusty-claude-cli --allowedTools read,glob \"summarize Cargo.toml\""
|
||||
)?;
|
||||
writeln!(
|
||||
out,
|
||||
" rusty-claude-cli --resume session.json /status /diff /export notes.txt"
|
||||
)?;
|
||||
writeln!(out, " rusty-claude-cli login")?;
|
||||
writeln!(out, " rusty-claude-cli init")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn print_help() {
|
||||
let _ = print_help_to(&mut io::stdout());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{
|
||||
filter_tool_specs, format_compact_report, format_cost_report, format_init_report,
|
||||
format_model_report, format_model_switch_report, format_permissions_report,
|
||||
format_permissions_switch_report, format_resume_report, format_status_report,
|
||||
format_tool_call_start, format_tool_result, normalize_permission_mode, parse_args,
|
||||
parse_git_status_metadata, render_config_report, render_init_claude_md,
|
||||
render_memory_report, render_repl_help, resume_supported_slash_commands, status_context,
|
||||
CliAction, CliOutputFormat, SlashCommand, StatusUsage, DEFAULT_MODEL,
|
||||
filter_tool_specs, format_compact_report, format_cost_report, format_model_report,
|
||||
format_model_switch_report, format_permissions_report, format_permissions_switch_report,
|
||||
format_resume_report, format_status_report, format_tool_call_start, format_tool_result,
|
||||
normalize_permission_mode, parse_args, parse_git_status_metadata, print_help_to,
|
||||
render_config_report, render_memory_report, render_repl_help,
|
||||
resume_supported_slash_commands, status_context, CliAction, CliOutputFormat, SlashCommand,
|
||||
StatusUsage, DEFAULT_MODEL,
|
||||
};
|
||||
use runtime::{ContentBlock, ConversationMessage, MessageRole, PermissionMode};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[test]
|
||||
fn defaults_to_repl_when_no_args() {
|
||||
@@ -2609,6 +2508,10 @@ mod tests {
|
||||
parse_args(&["logout".to_string()]).expect("logout should parse"),
|
||||
CliAction::Logout
|
||||
);
|
||||
assert_eq!(
|
||||
parse_args(&["init".to_string()]).expect("init should parse"),
|
||||
CliAction::Init
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2676,7 +2579,6 @@ mod tests {
|
||||
assert!(help.contains("REPL"));
|
||||
assert!(help.contains("/help"));
|
||||
assert!(help.contains("/status"));
|
||||
assert!(help.contains("/sandbox"));
|
||||
assert!(help.contains("/model [model]"));
|
||||
assert!(help.contains("/permissions [read-only|workspace-write|danger-full-access]"));
|
||||
assert!(help.contains("/clear [--confirm]"));
|
||||
@@ -2701,8 +2603,8 @@ mod tests {
|
||||
assert_eq!(
|
||||
names,
|
||||
vec![
|
||||
"help", "status", "sandbox", "compact", "clear", "cost", "config", "memory",
|
||||
"init", "diff", "version", "export",
|
||||
"help", "status", "compact", "clear", "cost", "config", "memory", "init", "diff",
|
||||
"version", "export",
|
||||
]
|
||||
);
|
||||
}
|
||||
@@ -2764,12 +2666,11 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn init_report_uses_structured_output() {
|
||||
let created = format_init_report(Path::new("/tmp/CLAUDE.md"), true);
|
||||
assert!(created.contains("Init"));
|
||||
assert!(created.contains("Result created"));
|
||||
let skipped = format_init_report(Path::new("/tmp/CLAUDE.md"), false);
|
||||
assert!(skipped.contains("skipped (already exists)"));
|
||||
fn init_help_mentions_direct_subcommand() {
|
||||
let mut help = Vec::new();
|
||||
print_help_to(&mut help).expect("help should render");
|
||||
let help = String::from_utf8(help).expect("help should be utf8");
|
||||
assert!(help.contains("rusty-claude-cli init"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2820,7 +2721,6 @@ mod tests {
|
||||
memory_file_count: 4,
|
||||
project_root: Some(PathBuf::from("/tmp")),
|
||||
git_branch: Some("main".to_string()),
|
||||
sandbox_status: runtime::SandboxStatus::default(),
|
||||
},
|
||||
);
|
||||
assert!(status.contains("Status"));
|
||||
@@ -2932,7 +2832,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn init_template_mentions_detected_rust_workspace() {
|
||||
let rendered = render_init_claude_md(Path::new("."));
|
||||
let rendered = crate::init::render_init_claude_md(std::path::Path::new("."));
|
||||
assert!(rendered.contains("# CLAUDE.md"));
|
||||
assert!(rendered.contains("cargo clippy --workspace --all-targets -- -D warnings"));
|
||||
}
|
||||
@@ -2982,17 +2882,3 @@ mod tests {
|
||||
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,11 +62,7 @@ pub fn mvp_tool_specs() -> Vec<ToolSpec> {
|
||||
"timeout": { "type": "integer", "minimum": 1 },
|
||||
"description": { "type": "string" },
|
||||
"run_in_background": { "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" } }
|
||||
"dangerouslyDisableSandbox": { "type": "boolean" }
|
||||
},
|
||||
"required": ["command"],
|
||||
"additionalProperties": false
|
||||
@@ -2218,7 +2214,6 @@ fn execute_shell_command(
|
||||
structured_content: None,
|
||||
persisted_output_path: None,
|
||||
persisted_output_size: None,
|
||||
sandbox_status: None,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -2256,7 +2251,6 @@ fn execute_shell_command(
|
||||
structured_content: None,
|
||||
persisted_output_path: None,
|
||||
persisted_output_size: None,
|
||||
sandbox_status: None,
|
||||
});
|
||||
}
|
||||
if started.elapsed() >= Duration::from_millis(timeout_ms) {
|
||||
@@ -2287,7 +2281,6 @@ Command exceeded timeout of {timeout_ms} ms",
|
||||
structured_content: None,
|
||||
persisted_output_path: None,
|
||||
persisted_output_size: None,
|
||||
sandbox_status: None,
|
||||
});
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
@@ -2314,7 +2307,6 @@ Command exceeded timeout of {timeout_ms} ms",
|
||||
structured_content: None,
|
||||
persisted_output_path: None,
|
||||
persisted_output_size: None,
|
||||
sandbox_status: None,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user