refactor: massive codebase restructuring — naming, splitting, DRY
Crate renames: - zesdex-entities::seaorm → domain (misleading name, no SeaORM used) - zesdex-dto → merged into zesdex-entities (100% re-exports) - zesdex-libs → zesdex-infra (vague name) Module renames: - app/harness → guard (misleading: safety gatekeeper, not test harness) - runtime/commands → action_dispatch (name clashed with controller/command) - resources → prompts (embedded prompt text, not general resources) - tool/seqthink → sequential_think (unreadable abbreviation) - msglog/query → insert (module only inserts, never queries) Dead code removal: - app/mode/help.rs (orphaned — not declared in mod.rs) - app/mode/loading.rs (orphaned — not declared in mod.rs) File splitting (71 new files, avg ~115 lines/file): - app/runtime/actions/: 1→8 files (was 2030 lines) - view/overlays/: 1→16 files (was 1167 lines) - tool/lsp/: 1→8 per-tool files (was 909 lines) - main.rs: 1→5 files (session, daemon, attach, event_loop) - workflow/engine + hive_mind: 2→10 files - subagent/engine + auto: 2→9 files - lsp/provisioner: 1→5 files - review/: 1→6 files - guard/: 1→2 files (extracted patterns) - state/misc: 1→3 files (input, scroll) - mcp/: 1→3 files (transport, adapter) - stream/json_repair extracted from turn.rs DRY: - Pattern constants (STUB_PATTERNS etc) in guard/patterns shared with subagent - 3 near-identical background spawners → 1 generic + thin wrappers - Shared spawn_subagent_with_drain() extracted - Shared create_session() in main - write_osc52 deduplicated Bug fixes: - archive_message(): sess.db → db (wrong variable name) - execute_one_tool(): wrong parameter name - check_credential_read() function was missing (restored from test expectations)
This commit is contained in:
+152
-284
@@ -15,32 +15,21 @@
|
||||
//! wrote this file, let me check if it's correct before continuing").
|
||||
//! - Background reviews catch broader concerns (missing tests, architectural
|
||||
//! drift, security issues) without blocking the main agent's flow.
|
||||
pub(crate) mod paths;
|
||||
|
||||
pub use paths::is_reviewable_path;
|
||||
pub(crate) use paths::is_production_code;
|
||||
|
||||
use crate::app::state::runtime::TurnEvent;
|
||||
use crate::app::subagent::context::build_subagent_context;
|
||||
use crate::app::subagent::engine::run_subagent;
|
||||
use crate::app::subagent::event::SubagentEvent;
|
||||
use crate::app::subagent::spawn::AgentDefinition;
|
||||
use crate::app::subagent::spawn::{spawn_subagent_with_drain, AgentDefinition};
|
||||
use std::collections::VecDeque;
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
/// File extensions that should not trigger auto-review (config, lock, data).
|
||||
const SKIP_REVIEW_EXTENSIONS: &[&str] = &[
|
||||
".lock", ".md", ".txt", ".json", ".toml", ".yaml", ".yml", ".svg", ".png", ".jpg", ".ico",
|
||||
".woff", ".woff2",
|
||||
];
|
||||
|
||||
/// File names that should not trigger auto-review.
|
||||
const SKIP_REVIEW_FILES: &[&str] = &[
|
||||
"Cargo.lock",
|
||||
"yarn.lock",
|
||||
"package-lock.json",
|
||||
".gitignore",
|
||||
".env",
|
||||
".env.example",
|
||||
];
|
||||
|
||||
/// Prevents a second background subagent of the same kind from spawning
|
||||
/// while one is already in flight. Without this, a chatty multi-turn edit
|
||||
/// session could stack overlapping test-gen/arch/security reviews of
|
||||
@@ -64,97 +53,24 @@ impl Drop for RunningGuard {
|
||||
}
|
||||
|
||||
/// ─── Helpers ───
|
||||
|
||||
/// Derive a human-readable message prefix from the internal kind label.
|
||||
/// Derive a human-readable message prefix from the internal kind label.
|
||||
///
|
||||
/// Check whether a file path is worth auto-reviewing (not config/lock/data).
|
||||
///
|
||||
/// Vendored/generated directories are matched by path *segment* rather than
|
||||
/// a `/target/`-style substring check — the substring form misses paths
|
||||
/// where the directory is the first component (e.g. `target/debug/build.rs`,
|
||||
/// which has no leading slash), the same class of bug fixed in
|
||||
/// `is_production_code` below.
|
||||
pub fn is_reviewable_path(path: &str) -> bool {
|
||||
let lower = path.to_lowercase();
|
||||
if SKIP_REVIEW_FILES.iter().any(|f| lower.ends_with(f)) {
|
||||
return false;
|
||||
/// Production callers always pass one of the three known labels
|
||||
/// (`"bg-test-gen"`, `"bg-arch-review"`, `"bg-security-review"`).
|
||||
fn message_prefix(kind: &str) -> &'static str {
|
||||
match kind {
|
||||
"bg-test-gen" => "Auto test-gen",
|
||||
"bg-arch-review" => "Architecture review",
|
||||
"bg-security-review" => "Security review",
|
||||
other => {
|
||||
// Production callers always use one of the three known labels.
|
||||
// This path is a safety net only.
|
||||
debug_assert!(false, "unknown background review kind: {other}");
|
||||
""
|
||||
}
|
||||
}
|
||||
if SKIP_REVIEW_EXTENSIONS.iter().any(|e| lower.ends_with(e)) {
|
||||
return false;
|
||||
}
|
||||
// Skip paths that are clearly generated or vendored
|
||||
let in_vendored_dir = std::path::Path::new(&lower).components().any(|c| {
|
||||
matches!(
|
||||
c,
|
||||
std::path::Component::Normal(seg)
|
||||
if matches!(seg.to_str(), Some("target" | "node_modules" | ".git" | "vendor"))
|
||||
)
|
||||
});
|
||||
if in_vendored_dir {
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Determine whether a file change looks like it modifies production logic
|
||||
/// (vs. tests, config, or documentation) — used to decide if a test-gen
|
||||
/// or security-review background subagent should fire.
|
||||
///
|
||||
/// Matches test-ness by path *segment* (a directory literally named
|
||||
/// "test"/"tests"/"__tests__") or by filename convention
|
||||
/// (`foo_test.rs`, `foo.test.ts`, `test_foo.py`, `foo_spec.rb`), not by a
|
||||
/// raw substring check — a plain `.contains("test")` would wrongly exclude
|
||||
/// legitimate production files like `src/attestation.rs` or
|
||||
/// `src/latest/foo.rs`.
|
||||
fn is_production_code(path: &str) -> bool {
|
||||
let lower = path.to_lowercase();
|
||||
let path_obj = std::path::Path::new(&lower);
|
||||
|
||||
let in_test_dir = path_obj.components().any(|c| {
|
||||
matches!(
|
||||
c,
|
||||
std::path::Component::Normal(seg)
|
||||
if matches!(seg.to_str(), Some("test" | "tests" | "__tests__"))
|
||||
)
|
||||
});
|
||||
|
||||
let file_stem = path_obj.file_stem().and_then(|s| s.to_str()).unwrap_or("");
|
||||
let is_test_filename = file_stem.starts_with("test_")
|
||||
|| file_stem.ends_with("_test")
|
||||
|| std::path::Path::new(file_stem)
|
||||
.extension()
|
||||
.is_some_and(|ext| ext.eq_ignore_ascii_case("test"))
|
||||
|| file_stem == "spec"
|
||||
|| file_stem.ends_with("_spec")
|
||||
|| std::path::Path::new(file_stem)
|
||||
.extension()
|
||||
.is_some_and(|ext| ext.eq_ignore_ascii_case("spec"));
|
||||
|
||||
if in_test_dir || is_test_filename {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Only source files — use Path::extension() to avoid clippy
|
||||
// case_sensitive_file_extension_comparisons lint
|
||||
path_obj
|
||||
.extension()
|
||||
.and_then(|ext| ext.to_str())
|
||||
.is_some_and(|ext| {
|
||||
matches!(
|
||||
ext,
|
||||
"rs" | "ts"
|
||||
| "tsx"
|
||||
| "js"
|
||||
| "jsx"
|
||||
| "go"
|
||||
| "py"
|
||||
| "java"
|
||||
| "kt"
|
||||
| "swift"
|
||||
| "c"
|
||||
| "cpp"
|
||||
| "h"
|
||||
| "hpp"
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// ─── Inline Quick Review (synchronous, feeds back to LLM) ───
|
||||
@@ -177,7 +93,7 @@ pub fn spawn_quick_review(
|
||||
) -> anyhow::Result<String> {
|
||||
let prompt = format!(
|
||||
"{}\n\nFile to review: {}",
|
||||
crate::resources::AUTO_REVIEWER_PROMPT,
|
||||
crate::prompts::AUTO_REVIEWER_PROMPT,
|
||||
file_path,
|
||||
);
|
||||
|
||||
@@ -188,21 +104,18 @@ pub fn spawn_quick_review(
|
||||
ctx.session_dir = session_dir.to_path_buf();
|
||||
ctx.workspaces = workspaces.to_vec();
|
||||
|
||||
let (tx, mut rx) = tokio::sync::mpsc::channel(32);
|
||||
let _drain = std::thread::spawn(move || {
|
||||
while let Some(event) = rx.blocking_recv() {
|
||||
match &event {
|
||||
SubagentEvent::ToolCall { tool, .. } => {
|
||||
tracing::debug!("[auto-review] tool call: {}", tool);
|
||||
}
|
||||
SubagentEvent::ToolResult { tool, .. } => {
|
||||
tracing::debug!("[auto-review] tool result: {}", tool);
|
||||
}
|
||||
SubagentEvent::Completed => {
|
||||
tracing::debug!("[auto-review] completed");
|
||||
}
|
||||
_ => {}
|
||||
let (tx, _drain) = spawn_subagent_with_drain(|event| {
|
||||
match &event {
|
||||
SubagentEvent::ToolCall { tool, .. } => {
|
||||
tracing::debug!("[auto-review] tool call: {}", tool);
|
||||
}
|
||||
SubagentEvent::ToolResult { tool, .. } => {
|
||||
tracing::debug!("[auto-review] tool result: {}", tool);
|
||||
}
|
||||
SubagentEvent::Completed => {
|
||||
tracing::debug!("[auto-review] completed");
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -247,13 +160,10 @@ fn run_subagent_with_retry(
|
||||
ctx.workspaces = workspaces.to_vec();
|
||||
ctx.abort_flag = abort_flag.cloned();
|
||||
|
||||
let (tx, mut rx) = tokio::sync::mpsc::channel(32);
|
||||
let drain_label = label.to_string();
|
||||
let _drain = std::thread::spawn(move || {
|
||||
while let Some(event) = rx.blocking_recv() {
|
||||
if let SubagentEvent::StepFailed { step, error } = &event {
|
||||
tracing::warn!("[{drain_label}] step {step} failed: {error}");
|
||||
}
|
||||
let (tx, _drain) = spawn_subagent_with_drain(move |event| {
|
||||
if let SubagentEvent::StepFailed { step, error } = &event {
|
||||
tracing::warn!("[{drain_label}] step {step} failed: {error}");
|
||||
}
|
||||
});
|
||||
|
||||
@@ -268,6 +178,76 @@ fn run_subagent_with_retry(
|
||||
Err(format!("failed after 2 attempts: {last_err}"))
|
||||
}
|
||||
|
||||
/// ─── Generic background review spawner ───
|
||||
///
|
||||
/// Runs a subagent in a background OS thread, gated by `running_flag` so
|
||||
/// only one instance of a given kind can be in flight at a time. Reports
|
||||
/// completion via a `TurnEvent::SystemNote` pushed to `turn_events`.
|
||||
///
|
||||
/// `kind` is the internal label used for logging and the `SystemNote` kind
|
||||
/// (e.g. `"bg-test-gen"`, `"bg-arch-review"`). The human-readable message
|
||||
/// prefix is derived from this label via [`message_prefix`].
|
||||
fn spawn_background_review(
|
||||
kind: &str,
|
||||
running_flag: &'static AtomicBool,
|
||||
prompt_constant: &str,
|
||||
agent_name: &str,
|
||||
agent_role: &str,
|
||||
file_paths: Vec<String>,
|
||||
session_dir: std::path::PathBuf,
|
||||
workspaces: Vec<std::path::PathBuf>,
|
||||
turn_events: Arc<Mutex<VecDeque<TurnEvent>>>,
|
||||
abort_flag: Arc<AtomicBool>,
|
||||
) {
|
||||
if file_paths.is_empty() {
|
||||
return;
|
||||
}
|
||||
if running_flag
|
||||
.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
|
||||
.is_err()
|
||||
{
|
||||
tracing::debug!("[{kind}] skipped — a {kind} run is already in flight");
|
||||
return;
|
||||
}
|
||||
|
||||
let sd = session_dir;
|
||||
let ws = workspaces;
|
||||
let events = turn_events;
|
||||
let prompt_text = format!(
|
||||
"{}\n\nModified files:\n{}",
|
||||
prompt_constant,
|
||||
file_paths.join("\n"),
|
||||
);
|
||||
let label = kind.to_string();
|
||||
let agent_name = agent_name.to_string();
|
||||
let agent_role = agent_role.to_string();
|
||||
let prefix = message_prefix(kind);
|
||||
|
||||
std::thread::spawn(move || {
|
||||
let _running_guard = RunningGuard(running_flag);
|
||||
tracing::info!("[{label}] spawning for {} file(s)", file_paths.len());
|
||||
|
||||
let def = AgentDefinition::new(agent_name, agent_role).with_system_prompt(prompt_text);
|
||||
|
||||
let result = run_subagent_with_retry(&def, &sd, &ws, &label, Some(&abort_flag));
|
||||
let message = match &result {
|
||||
Ok(output) => {
|
||||
let first = output.lines().next().unwrap_or(output);
|
||||
format!("{prefix}: {first}")
|
||||
}
|
||||
Err(e) if e.contains("aborted") => format!("{prefix} cancelled: {e}"),
|
||||
Err(e) => format!("ESCALATED: {prefix} {e}"),
|
||||
};
|
||||
|
||||
if let Ok(mut q) = events.lock() {
|
||||
q.push_back(TurnEvent::SystemNote {
|
||||
kind: label,
|
||||
message,
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Spawn a background subagent that generates tests for modified files.
|
||||
///
|
||||
/// Uses the test-generator prompt and has read-write access so it can
|
||||
@@ -276,8 +256,8 @@ fn run_subagent_with_retry(
|
||||
///
|
||||
/// Skipped (no-op) if a test-gen run is already in flight (guarded by
|
||||
/// `TEST_GEN_RUNNING`) — prevents a chatty multi-turn edit session from
|
||||
/// stacking overlapping runs. `abort_flag` is forwarded to
|
||||
/// `run_subagent_with_retry` so the run can be cancelled if the turn aborts.
|
||||
/// stacking overlapping runs. `abort_flag` is forwarded to the generic
|
||||
/// spawner so the run can be cancelled if the turn aborts.
|
||||
pub fn spawn_background_test_gen(
|
||||
file_paths: &[String],
|
||||
session_dir: &Path,
|
||||
@@ -285,60 +265,18 @@ pub fn spawn_background_test_gen(
|
||||
turn_events: &Arc<Mutex<VecDeque<TurnEvent>>>,
|
||||
abort_flag: Arc<AtomicBool>,
|
||||
) {
|
||||
if file_paths.is_empty() {
|
||||
return;
|
||||
}
|
||||
if TEST_GEN_RUNNING
|
||||
.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
|
||||
.is_err()
|
||||
{
|
||||
tracing::debug!("[bg-test-gen] skipped — a test-gen run is already in flight");
|
||||
return;
|
||||
}
|
||||
|
||||
let paths = file_paths.to_vec();
|
||||
let sd = session_dir.to_path_buf();
|
||||
let ws = workspaces.to_vec();
|
||||
let events = turn_events.clone();
|
||||
|
||||
std::thread::spawn(move || {
|
||||
let _running_guard = RunningGuard(&TEST_GEN_RUNNING);
|
||||
tracing::info!(
|
||||
"[bg-test-gen] spawning for {} file(s): {:?}",
|
||||
paths.len(),
|
||||
paths,
|
||||
);
|
||||
|
||||
let file_list = paths.join("\n");
|
||||
let prompt = format!(
|
||||
"{}\n\nModified files that need tests:\n{}",
|
||||
crate::resources::TEST_GENERATOR_PROMPT,
|
||||
file_list,
|
||||
);
|
||||
|
||||
let def = AgentDefinition::new(
|
||||
"test-generator".to_string(),
|
||||
"coder".to_string(), // needs write access
|
||||
)
|
||||
.with_system_prompt(prompt);
|
||||
|
||||
let result = run_subagent_with_retry(&def, &sd, &ws, "bg-test-gen", Some(&abort_flag));
|
||||
let message = match &result {
|
||||
Ok(output) => {
|
||||
let first = output.lines().next().unwrap_or(output);
|
||||
format!("Auto test-gen: {first}")
|
||||
}
|
||||
Err(e) if e.contains("aborted") => format!("Auto test-gen cancelled: {e}"),
|
||||
Err(e) => format!("ESCALATED: Auto test-gen {e}"),
|
||||
};
|
||||
|
||||
if let Ok(mut q) = events.lock() {
|
||||
q.push_back(TurnEvent::SystemNote {
|
||||
kind: "bg-test-gen".to_string(),
|
||||
message,
|
||||
});
|
||||
}
|
||||
});
|
||||
spawn_background_review(
|
||||
"bg-test-gen",
|
||||
&TEST_GEN_RUNNING,
|
||||
crate::prompts::TEST_GENERATOR_PROMPT,
|
||||
"test-generator",
|
||||
"coder",
|
||||
file_paths.to_vec(),
|
||||
session_dir.to_path_buf(),
|
||||
workspaces.to_vec(),
|
||||
turn_events.clone(),
|
||||
abort_flag,
|
||||
);
|
||||
}
|
||||
|
||||
/// Spawn a background architecture-review subagent.
|
||||
@@ -348,8 +286,8 @@ pub fn spawn_background_test_gen(
|
||||
/// `TurnEvent::SystemNote { kind: "bg-arch-review" }`.
|
||||
///
|
||||
/// Skipped (no-op) if an arch-review run is already in flight (guarded by
|
||||
/// `ARCH_REVIEW_RUNNING`). `abort_flag` is forwarded to
|
||||
/// `run_subagent_with_retry` so the run can be cancelled if the turn aborts.
|
||||
/// `ARCH_REVIEW_RUNNING`). `abort_flag` is forwarded to the generic
|
||||
/// spawner so the run can be cancelled if the turn aborts.
|
||||
pub fn spawn_background_arch_review(
|
||||
file_paths: &[String],
|
||||
session_dir: &Path,
|
||||
@@ -357,51 +295,18 @@ pub fn spawn_background_arch_review(
|
||||
turn_events: &Arc<Mutex<VecDeque<TurnEvent>>>,
|
||||
abort_flag: Arc<AtomicBool>,
|
||||
) {
|
||||
if file_paths.is_empty() {
|
||||
return;
|
||||
}
|
||||
if ARCH_REVIEW_RUNNING
|
||||
.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
|
||||
.is_err()
|
||||
{
|
||||
tracing::debug!("[bg-arch-review] skipped — an arch-review run is already in flight");
|
||||
return;
|
||||
}
|
||||
|
||||
let paths = file_paths.to_vec();
|
||||
let sd = session_dir.to_path_buf();
|
||||
let ws = workspaces.to_vec();
|
||||
let events = turn_events.clone();
|
||||
|
||||
std::thread::spawn(move || {
|
||||
let _running_guard = RunningGuard(&ARCH_REVIEW_RUNNING);
|
||||
let file_list = paths.join("\n");
|
||||
let prompt = format!(
|
||||
"{}\n\nModified files for architecture review:\n{}",
|
||||
crate::resources::ARCH_REVIEWER_PROMPT,
|
||||
file_list,
|
||||
);
|
||||
|
||||
let def = AgentDefinition::new("arch-reviewer".to_string(), "reviewer".to_string())
|
||||
.with_system_prompt(prompt);
|
||||
|
||||
let result = run_subagent_with_retry(&def, &sd, &ws, "bg-arch-review", Some(&abort_flag));
|
||||
let message = match &result {
|
||||
Ok(output) => {
|
||||
let first = output.lines().next().unwrap_or(output);
|
||||
format!("Architecture review: {first}")
|
||||
}
|
||||
Err(e) if e.contains("aborted") => format!("Architecture review cancelled: {e}"),
|
||||
Err(e) => format!("ESCALATED: Architecture review {e}"),
|
||||
};
|
||||
|
||||
if let Ok(mut q) = events.lock() {
|
||||
q.push_back(TurnEvent::SystemNote {
|
||||
kind: "bg-arch-review".to_string(),
|
||||
message,
|
||||
});
|
||||
}
|
||||
});
|
||||
spawn_background_review(
|
||||
"bg-arch-review",
|
||||
&ARCH_REVIEW_RUNNING,
|
||||
crate::prompts::ARCH_REVIEWER_PROMPT,
|
||||
"arch-reviewer",
|
||||
"reviewer",
|
||||
file_paths.to_vec(),
|
||||
session_dir.to_path_buf(),
|
||||
workspaces.to_vec(),
|
||||
turn_events.clone(),
|
||||
abort_flag,
|
||||
);
|
||||
}
|
||||
|
||||
/// Spawn a background security-review subagent.
|
||||
@@ -409,9 +314,12 @@ pub fn spawn_background_arch_review(
|
||||
/// Checks modified files for security vulnerabilities. Reports via
|
||||
/// `TurnEvent::SystemNote { kind: "bg-security-review" }`.
|
||||
///
|
||||
/// Only reviews production code files for security — test files and
|
||||
/// config files are out of scope for security review.
|
||||
///
|
||||
/// Skipped (no-op) if a security-review run is already in flight (guarded by
|
||||
/// `SECURITY_REVIEW_RUNNING`). `abort_flag` is forwarded to
|
||||
/// `run_subagent_with_retry` so the run can be cancelled if the turn aborts.
|
||||
/// `SECURITY_REVIEW_RUNNING`). `abort_flag` is forwarded to the generic
|
||||
/// spawner so the run can be cancelled if the turn aborts.
|
||||
pub fn spawn_background_security_review(
|
||||
file_paths: &[String],
|
||||
session_dir: &Path,
|
||||
@@ -419,10 +327,6 @@ pub fn spawn_background_security_review(
|
||||
turn_events: &Arc<Mutex<VecDeque<TurnEvent>>>,
|
||||
abort_flag: Arc<AtomicBool>,
|
||||
) {
|
||||
if file_paths.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Only review production code files for security — test files and
|
||||
// config files are out of scope for security review.
|
||||
let prod_paths: Vec<String> = file_paths
|
||||
@@ -431,54 +335,18 @@ pub fn spawn_background_security_review(
|
||||
.cloned()
|
||||
.collect();
|
||||
|
||||
if prod_paths.is_empty() {
|
||||
return;
|
||||
}
|
||||
if SECURITY_REVIEW_RUNNING
|
||||
.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
|
||||
.is_err()
|
||||
{
|
||||
tracing::debug!(
|
||||
"[bg-security-review] skipped — a security-review run is already in flight"
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
let paths = prod_paths;
|
||||
let sd = session_dir.to_path_buf();
|
||||
let ws = workspaces.to_vec();
|
||||
let events = turn_events.clone();
|
||||
|
||||
std::thread::spawn(move || {
|
||||
let _running_guard = RunningGuard(&SECURITY_REVIEW_RUNNING);
|
||||
let file_list = paths.join("\n");
|
||||
let prompt = format!(
|
||||
"{}\n\nModified files for security review:\n{}",
|
||||
crate::resources::SECURITY_REVIEWER_PROMPT,
|
||||
file_list,
|
||||
);
|
||||
|
||||
let def = AgentDefinition::new("security-reviewer".to_string(), "reviewer".to_string())
|
||||
.with_system_prompt(prompt);
|
||||
|
||||
let result =
|
||||
run_subagent_with_retry(&def, &sd, &ws, "bg-security-review", Some(&abort_flag));
|
||||
let message = match &result {
|
||||
Ok(output) => {
|
||||
let first = output.lines().next().unwrap_or(output);
|
||||
format!("Security review: {first}")
|
||||
}
|
||||
Err(e) if e.contains("aborted") => format!("Security review cancelled: {e}"),
|
||||
Err(e) => format!("ESCALATED: Security review {e}"),
|
||||
};
|
||||
|
||||
if let Ok(mut q) = events.lock() {
|
||||
q.push_back(TurnEvent::SystemNote {
|
||||
kind: "bg-security-review".to_string(),
|
||||
message,
|
||||
});
|
||||
}
|
||||
});
|
||||
spawn_background_review(
|
||||
"bg-security-review",
|
||||
&SECURITY_REVIEW_RUNNING,
|
||||
crate::prompts::SECURITY_REVIEWER_PROMPT,
|
||||
"security-reviewer",
|
||||
"reviewer",
|
||||
prod_paths,
|
||||
session_dir.to_path_buf(),
|
||||
workspaces.to_vec(),
|
||||
turn_events.clone(),
|
||||
abort_flag,
|
||||
);
|
||||
}
|
||||
|
||||
/// Convenience: spawn all applicable background subagents for a set of edited
|
||||
@@ -0,0 +1,124 @@
|
||||
//! Path classification helpers for auto-subagent orchestration.
|
||||
//!
|
||||
//! Determines whether a file path is reviewable and whether it represents
|
||||
//! production code (vs. tests, config, or documentation) — used to decide
|
||||
//! which background subagents should fire for a given set of modified files.
|
||||
|
||||
/// File extensions that should not trigger auto-review (config, lock, data).
|
||||
pub(crate) const SKIP_REVIEW_EXTENSIONS: &[&str] = &[
|
||||
".lock",
|
||||
".md",
|
||||
".txt",
|
||||
".json",
|
||||
".toml",
|
||||
".yaml",
|
||||
".yml",
|
||||
".svg",
|
||||
".png",
|
||||
".jpg",
|
||||
".ico",
|
||||
".woff",
|
||||
".woff2",
|
||||
];
|
||||
|
||||
/// File names that should not trigger auto-review.
|
||||
pub(crate) const SKIP_REVIEW_FILES: &[&str] = &[
|
||||
"Cargo.lock",
|
||||
"yarn.lock",
|
||||
"package-lock.json",
|
||||
".gitignore",
|
||||
".env",
|
||||
".env.example",
|
||||
];
|
||||
|
||||
/// Check whether a file path is worth auto-reviewing (not config/lock/data).
|
||||
///
|
||||
/// Vendored/generated directories are matched by path *segment* rather than
|
||||
/// a `/target/`-style substring check — the substring form misses paths
|
||||
/// where the directory is the first component (e.g. `target/debug/build.rs`,
|
||||
/// which has no leading slash), the same class of bug fixed in
|
||||
/// `is_production_code` below.
|
||||
pub fn is_reviewable_path(path: &str) -> bool {
|
||||
let lower = path.to_lowercase();
|
||||
if SKIP_REVIEW_FILES.iter().any(|f| lower.ends_with(f)) {
|
||||
return false;
|
||||
}
|
||||
if SKIP_REVIEW_EXTENSIONS.iter().any(|e| lower.ends_with(e)) {
|
||||
return false;
|
||||
}
|
||||
// Skip paths that are clearly generated or vendored
|
||||
let in_vendored_dir = std::path::Path::new(&lower).components().any(|c| {
|
||||
matches!(
|
||||
c,
|
||||
std::path::Component::Normal(seg)
|
||||
if matches!(seg.to_str(), Some("target" | "node_modules" | ".git" | "vendor"))
|
||||
)
|
||||
});
|
||||
if in_vendored_dir {
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Determine whether a file change looks like it modifies production logic
|
||||
/// (vs. tests, config, or documentation) — used to decide if a test-gen
|
||||
/// or security-review background subagent should fire.
|
||||
///
|
||||
/// Matches test-ness by path *segment* (a directory literally named
|
||||
/// "test"/"tests"/"__tests__") or by filename convention
|
||||
/// (`foo_test.rs`, `foo.test.ts`, `test_foo.py`, `foo_spec.rb`), not by a
|
||||
/// raw substring check — a plain `.contains("test")` would wrongly exclude
|
||||
/// legitimate production files like `src/attestation.rs` or
|
||||
/// `src/latest/foo.rs`.
|
||||
pub(crate) fn is_production_code(path: &str) -> bool {
|
||||
let lower = path.to_lowercase();
|
||||
let path_obj = std::path::Path::new(&lower);
|
||||
|
||||
let in_test_dir = path_obj.components().any(|c| {
|
||||
matches!(
|
||||
c,
|
||||
std::path::Component::Normal(seg)
|
||||
if matches!(seg.to_str(), Some("test" | "tests" | "__tests__"))
|
||||
)
|
||||
});
|
||||
|
||||
let file_stem = path_obj.file_stem().and_then(|s| s.to_str()).unwrap_or("");
|
||||
let is_test_filename = file_stem.starts_with("test_")
|
||||
|| file_stem.ends_with("_test")
|
||||
|| std::path::Path::new(file_stem)
|
||||
.extension()
|
||||
.is_some_and(|ext| ext.eq_ignore_ascii_case("test"))
|
||||
|| file_stem == "spec"
|
||||
|| file_stem.ends_with("_spec")
|
||||
|| std::path::Path::new(file_stem)
|
||||
.extension()
|
||||
.is_some_and(|ext| ext.eq_ignore_ascii_case("spec"));
|
||||
|
||||
if in_test_dir || is_test_filename {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Only source files — use Path::extension() to avoid clippy
|
||||
// case_sensitive_file_extension_comparisons lint
|
||||
path_obj
|
||||
.extension()
|
||||
.and_then(|ext| ext.to_str())
|
||||
.is_some_and(|ext| {
|
||||
matches!(
|
||||
ext,
|
||||
"rs" | "ts"
|
||||
| "tsx"
|
||||
| "js"
|
||||
| "jsx"
|
||||
| "go"
|
||||
| "py"
|
||||
| "java"
|
||||
| "kt"
|
||||
| "swift"
|
||||
| "c"
|
||||
| "cpp"
|
||||
| "h"
|
||||
| "hpp"
|
||||
)
|
||||
})
|
||||
}
|
||||
@@ -1,384 +1,22 @@
|
||||
//! Subagent execution loop: drive an LLM conversation, gate tool calls
|
||||
//! against the context's allowlist, run tools, and stream progress events
|
||||
//! to the parent via an mpsc channel.
|
||||
//! Subagent execution loop: drive an LLM conversation, run tools, and stream
|
||||
//! progress events to the parent via an mpsc channel.
|
||||
//!
|
||||
//! Security: subagent tool gating mirrors the main agent's `Harness` checks
|
||||
//! (path traversal, reason validation, stub/denial/assumption scanning,
|
||||
//! bash exfiltration and destructive-pattern detection) so that subagents
|
||||
//! are not a weaker link than the main agent.
|
||||
//! Tool gating and pattern-constant definitions live in sibling modules
|
||||
//! (`gating`, `provider`, `tools`, `workspace`) rather than here, so each
|
||||
//! concern is independently testable and maintainable.
|
||||
|
||||
use super::context::SubagentContext;
|
||||
use super::event::SubagentEvent;
|
||||
use super::gating::gate_subagent_tool_call;
|
||||
use super::provider::{require_api_key, resolve_provider_config};
|
||||
use super::tools::build_subagent_tools;
|
||||
use super::workspace::generate_workspace_tree;
|
||||
use crate::dto::chat::message::ChatMessage;
|
||||
use crate::dto::provider::request::ToolDef;
|
||||
use crate::tool::{all_tools, tool_defs, tool_is_risky};
|
||||
use crate::tool::tool_is_risky;
|
||||
use sha2::Digest;
|
||||
use std::fmt::Write;
|
||||
use tokio::sync::mpsc;
|
||||
use zesdex_cms::domain::repository::AppConfigRepository;
|
||||
use zesdex_cms::domain::repository::EditLogRepository;
|
||||
use zesdex_cms::domain::repository::SettingsRepository;
|
||||
|
||||
/// Maps a subagent's allowed tool names to concrete Tool trait objects and
|
||||
/// OpenAI-style tool definitions.
|
||||
///
|
||||
/// Flow: load `all_tools()` → if `allowed_tools` is empty, use all; else
|
||||
/// filter by membership → derive `ToolDef`s for the LLM.
|
||||
///
|
||||
/// Why: an empty allowlist means "no restriction" (matches
|
||||
/// `build_subagent_context`'s default for non-reviewer roles).
|
||||
///
|
||||
/// Return: `(tool impls, schema defs)` for the subagent to use.
|
||||
fn build_subagent_tools(
|
||||
allowed_tools: &[String],
|
||||
) -> (Vec<Box<dyn crate::tool::Tool>>, Vec<ToolDef>) {
|
||||
let all = all_tools();
|
||||
let filtered: Vec<Box<dyn crate::tool::Tool>> = if allowed_tools.is_empty() {
|
||||
all.into_iter()
|
||||
.filter(|t| t.name() != "hive_mind" && t.name() != "workflow_run")
|
||||
.collect()
|
||||
} else {
|
||||
all.into_iter()
|
||||
.filter(|t| {
|
||||
allowed_tools.contains(&t.name().to_string())
|
||||
&& t.name() != "hive_mind"
|
||||
&& t.name() != "workflow_run"
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let defs = tool_defs(&filtered);
|
||||
(filtered, defs)
|
||||
}
|
||||
|
||||
/// Resolve the API key, model, and base URL from persisted app config.
|
||||
///
|
||||
/// Flow: try the settings key for the active provider → fall back to the
|
||||
/// provider's `api_key_env` env-var → fall back to the provider's
|
||||
/// `default_api_key` → fall back to an empty string.
|
||||
///
|
||||
/// Why: matches the main agent's credential resolution exactly, so
|
||||
/// subagents automatically inherit the same provider settings.
|
||||
///
|
||||
/// Return: `(api_key, model, optional_base_url, provider_name)`. `api_key`
|
||||
/// is empty when every resolution path was exhausted — callers must check
|
||||
/// for this before issuing requests (see `run_subagent`).
|
||||
fn resolve_provider_config() -> (String, String, Option<String>, String) {
|
||||
let store_base_dir = zesdex_entities::seaorm::common::store::Store::new().base_dir;
|
||||
let settings =
|
||||
zesdex_cms::infrastructure::persistence::settings_repo::JsonSettingsRepository::new()
|
||||
.load(&store_base_dir)
|
||||
.unwrap_or_default();
|
||||
let app_config =
|
||||
zesdex_cms::infrastructure::persistence::app_config_repo::JsonAppConfigRepository::new()
|
||||
.load(&store_base_dir)
|
||||
.unwrap_or_default();
|
||||
|
||||
let mut api_key = settings
|
||||
.api_keys
|
||||
.get(&settings.provider)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| {
|
||||
tracing::warn!(
|
||||
"[subagent] no API key for provider '{}' in settings, trying env/default",
|
||||
settings.provider
|
||||
);
|
||||
String::new()
|
||||
});
|
||||
let model = settings.model.clone();
|
||||
let base_url = app_config
|
||||
.providers
|
||||
.get(&settings.provider)
|
||||
.map(|p| p.api_base.clone());
|
||||
|
||||
if api_key.is_empty() {
|
||||
if let Some(provider_cfg) = app_config.providers.get(&settings.provider) {
|
||||
api_key = provider_cfg
|
||||
.api_key_env
|
||||
.as_ref()
|
||||
.and_then(|env| std::env::var(env).ok())
|
||||
.or_else(|| provider_cfg.default_api_key.clone())
|
||||
.unwrap_or_else(|| {
|
||||
tracing::warn!(
|
||||
"[subagent] all API key resolution paths exhausted for '{}'",
|
||||
settings.provider
|
||||
);
|
||||
String::new()
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
(api_key, model, base_url, settings.provider)
|
||||
}
|
||||
|
||||
/// Reject an empty API key with an actionable error instead of letting the
|
||||
/// caller send a request that is guaranteed to fail once it reaches the network.
|
||||
///
|
||||
/// Return: `Ok(())` if `api_key` is non-empty, `Err` with a message naming
|
||||
/// `provider` and where to fix it otherwise.
|
||||
fn require_api_key(api_key: &str, provider: &str) -> anyhow::Result<()> {
|
||||
if api_key.is_empty() {
|
||||
anyhow::bail!(
|
||||
"no API key configured for provider '{provider}' — set one in Settings or ~/.claude/settings.json"
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ─── Subagent-level tool gating (mirrors Harness checks) ───
|
||||
|
||||
const STUB_PATTERNS: &[&str] = &[
|
||||
"todo!()",
|
||||
"todo!(",
|
||||
"unimplemented!()",
|
||||
"unimplemented!(",
|
||||
"FIXME",
|
||||
"fixme:",
|
||||
"XXX:",
|
||||
"PLACEHOLDER",
|
||||
"REPLACE_ME",
|
||||
"stub_value",
|
||||
"stub_function",
|
||||
"fake_response",
|
||||
"fake_data",
|
||||
"not implemented",
|
||||
"not yet implemented",
|
||||
"to be implemented",
|
||||
"to be done",
|
||||
];
|
||||
|
||||
const DENIAL_PATTERNS: &[&str] = &[
|
||||
"// skip",
|
||||
"// skipping",
|
||||
"// skipping for now",
|
||||
"// for now just",
|
||||
"// punt",
|
||||
"// hack:",
|
||||
"// workaround:",
|
||||
"// cba",
|
||||
"// later",
|
||||
"// do later",
|
||||
"// ignore for now",
|
||||
"// disable",
|
||||
"// bypass",
|
||||
"// quick fix",
|
||||
"// temp fix",
|
||||
"// temporary fix",
|
||||
"// temp:",
|
||||
"// temporary:",
|
||||
"// noop",
|
||||
];
|
||||
|
||||
const ASSUMPTION_PATTERNS: &[&str] = &[
|
||||
"// assume",
|
||||
"// probably",
|
||||
"// guess",
|
||||
"// should work",
|
||||
"// hopefully",
|
||||
"// i think",
|
||||
"// should be fine",
|
||||
"// likely",
|
||||
];
|
||||
|
||||
const EXFIL_PATTERNS: &[&str] = &[
|
||||
"curl ",
|
||||
"wget ",
|
||||
"nc -e ",
|
||||
"ncat ",
|
||||
"/dev/tcp/",
|
||||
"base64 -d |",
|
||||
"base64 --decode |",
|
||||
"openssl s_client",
|
||||
"ssh -R ",
|
||||
"scp /",
|
||||
"rsync /",
|
||||
];
|
||||
|
||||
const SENSITIVE_PATH_PATTERNS: &[&str] = &[
|
||||
".ssh/id_rsa",
|
||||
".ssh/id_ed25519",
|
||||
".aws/credentials",
|
||||
".aws/config",
|
||||
".kube/config",
|
||||
".docker/config.json",
|
||||
"/etc/shadow",
|
||||
"/etc/passwd",
|
||||
"/proc/self/environ",
|
||||
];
|
||||
|
||||
const MIN_REASON_LEN: usize = 8;
|
||||
|
||||
/// Gate a tool call in the subagent context. Returns `Some(block_reason)` if
|
||||
/// the call should be blocked, `None` to allow.
|
||||
///
|
||||
/// Flow: always blocks dangerous patterns — path traversal, stub/denial/
|
||||
/// assumption language, bash exfiltration, destructive commands, sensitive
|
||||
/// path reads — regardless of the allowed-tools list. Tools that are not
|
||||
/// risky only get the basic allowlist check.
|
||||
fn gate_subagent_tool_call(tool_name: &str, args: &serde_json::Value) -> Option<String> {
|
||||
// File-mutating tools: write / edit / delete
|
||||
if matches!(tool_name, "write" | "edit" | "delete") {
|
||||
if let Some(path) = args.get("path").and_then(|v| v.as_str()) {
|
||||
if path.contains("..") {
|
||||
return Some("path traversal detected in 'path' argument".to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// write / edit require a non-trivial `reason`
|
||||
if matches!(tool_name, "write" | "edit" | "delete") {
|
||||
let reason = args.get("reason").and_then(|v| v.as_str()).unwrap_or("");
|
||||
if reason.trim().len() < MIN_REASON_LEN {
|
||||
return Some(format!(
|
||||
"{tool_name} requires a non-trivial 'reason' (>= {MIN_REASON_LEN} chars) explaining why",
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// write / edit content must not contain stubs, denial, or assumption language
|
||||
if matches!(tool_name, "write" | "edit") {
|
||||
let content = match tool_name {
|
||||
"write" => args.get("content").and_then(|v| v.as_str()).unwrap_or(""),
|
||||
"edit" => {
|
||||
let old = args.get("old").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let new = args.get("new").and_then(|v| v.as_str()).unwrap_or("");
|
||||
// For edits, scanning old+new together catches stubs in both
|
||||
return if contains_any(old, STUB_PATTERNS) || contains_any(new, STUB_PATTERNS) {
|
||||
Some("content contains stub/placeholder pattern; production code must be fully implemented".to_string())
|
||||
} else if contains_any(new, DENIAL_PATTERNS) {
|
||||
Some("content contains denial/punt pattern; implement properly instead of skipping".to_string())
|
||||
} else if contains_any(new, ASSUMPTION_PATTERNS) {
|
||||
Some("content contains assumption pattern; verify against data instead of guessing".to_string())
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
}
|
||||
_ => "",
|
||||
};
|
||||
if contains_any(content, STUB_PATTERNS) {
|
||||
return Some("content contains stub/placeholder pattern; production code must be fully implemented".to_string());
|
||||
}
|
||||
if contains_any(content, DENIAL_PATTERNS) {
|
||||
return Some(
|
||||
"content contains denial/punt pattern; implement properly instead of skipping"
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
if contains_any(content, ASSUMPTION_PATTERNS) {
|
||||
return Some(
|
||||
"content contains assumption pattern; verify against data instead of guessing"
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Bash: exfiltration, sensitive paths, destructive commands
|
||||
if tool_name == "bash" {
|
||||
let cmd = args.get("command").and_then(|v| v.as_str()).unwrap_or("");
|
||||
if cmd.contains("..") {
|
||||
return Some("path traversal detected in bash command".to_string());
|
||||
}
|
||||
// Only check exfiltration for non-standard commands
|
||||
let is_standard = cmd.trim_start().starts_with("cargo")
|
||||
|| cmd.trim_start().starts_with("rustc")
|
||||
|| cmd.trim_start().starts_with("git ")
|
||||
|| cmd.trim_start().starts_with("ls")
|
||||
|| cmd.trim_start().starts_with("pwd")
|
||||
|| cmd.trim_start().starts_with("echo")
|
||||
|| cmd.trim_start().starts_with("cat")
|
||||
|| cmd.trim_start().starts_with("find")
|
||||
|| cmd.trim_start().starts_with("grep")
|
||||
|| cmd.trim_start().starts_with("test");
|
||||
if !is_standard {
|
||||
for pat in EXFIL_PATTERNS {
|
||||
if cmd.contains(pat) {
|
||||
return Some(format!(
|
||||
"potential data-exfiltration command blocked (matched '{pat}')"
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
for pat in SENSITIVE_PATH_PATTERNS {
|
||||
if cmd.contains(pat) {
|
||||
return Some(format!("refused to read/write sensitive path '{pat}'"));
|
||||
}
|
||||
}
|
||||
let dangerous = [
|
||||
"rm -rf /",
|
||||
"rm -rf --no-preserve-root",
|
||||
"rm -rf ~",
|
||||
"rm -fr /",
|
||||
"mkfs.",
|
||||
"dd if=",
|
||||
":(){",
|
||||
"> /dev/sda",
|
||||
"chmod -R 000 /",
|
||||
"shutdown ",
|
||||
"poweroff ",
|
||||
"reboot ",
|
||||
"halt ",
|
||||
];
|
||||
for pat in &dangerous {
|
||||
if cmd.contains(pat) {
|
||||
return Some(format!("destructive command pattern blocked: {pat}"));
|
||||
}
|
||||
}
|
||||
if contains_any(cmd, STUB_PATTERNS) {
|
||||
return Some("bash command contains stub pattern".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
// git_operator: require reason
|
||||
if tool_name == "git_operator" {
|
||||
let reason = args.get("reason").and_then(|v| v.as_str()).unwrap_or("");
|
||||
if reason.trim().len() < MIN_REASON_LEN {
|
||||
return Some("git_operator requires a non-trivial 'reason' (>= 8 chars)".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
/// Check if `text` matches any pattern (case-insensitive substring).
|
||||
fn contains_any(text: &str, patterns: &[&str]) -> bool {
|
||||
let lower = text.to_lowercase();
|
||||
patterns.iter().any(|p| lower.contains(&p.to_lowercase()))
|
||||
}
|
||||
|
||||
/// Build an ASCII tree of the workspace directory structure for the
|
||||
/// system prompt, so the LLM can see the file layout.
|
||||
///
|
||||
/// Flow: for each root, walk using `ignore::WalkBuilder` (respecting
|
||||
/// `.gitignore` and hidden files) → prefix `[DIR]` for directories →
|
||||
/// truncate after 1000 entries.
|
||||
fn generate_workspace_tree(roots: &[std::path::PathBuf]) -> String {
|
||||
let mut out = String::new();
|
||||
out.push_str("Current Workspace Directory Structure:\n");
|
||||
for root in roots {
|
||||
writeln!(out, "Root: {}", root.display()).unwrap();
|
||||
let walker = ignore::WalkBuilder::new(root)
|
||||
.hidden(true)
|
||||
.git_ignore(true)
|
||||
.build();
|
||||
let mut count = 0;
|
||||
for entry in walker.flatten() {
|
||||
let path = entry.path();
|
||||
if let Ok(rel) = path.strip_prefix(root) {
|
||||
if rel.as_os_str().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let is_dir = entry.file_type().is_some_and(|ft| ft.is_dir());
|
||||
let prefix = if is_dir { "[DIR] " } else { " " };
|
||||
writeln!(out, " {}{}", prefix, rel.display()).unwrap();
|
||||
count += 1;
|
||||
if count > 1000 {
|
||||
out.push_str(" ... (truncated)\n");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn format_subagent_progress(prefix: &str, text: &str) -> String {
|
||||
let lines: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty()).collect();
|
||||
@@ -786,19 +424,3 @@ pub fn run_subagent(
|
||||
let _ = tx.blocking_send(SubagentEvent::Completed);
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn require_api_key_rejects_empty_key_with_provider_named_in_message() {
|
||||
let err = require_api_key("", "claude").unwrap_err();
|
||||
assert!(err.to_string().contains("claude"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn require_api_key_accepts_non_empty_key() {
|
||||
assert!(require_api_key("sk-live-abc123", "claude").is_ok());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
//! Subagent-level tool gating (mirrors Harness checks).
|
||||
//!
|
||||
//! Flow: always blocks dangerous patterns — path traversal, stub/denial/
|
||||
//! assumption language, bash exfiltration, destructive commands, sensitive
|
||||
//! path reads — regardless of the allowed-tools list. Tools that are not
|
||||
//! risky only get the basic allowlist check.
|
||||
//!
|
||||
//! Security: subagent tool gating mirrors the main agent's `Guard` checks
|
||||
//! (path traversal, reason validation, stub/denial/assumption scanning,
|
||||
//! bash exfiltration and destructive-pattern detection) so that subagents
|
||||
//! are not a weaker link than the main agent.
|
||||
|
||||
use crate::app::guard::patterns::{
|
||||
ASSUMPTION_PATTERNS, DENIAL_PATTERNS, EXFIL_PATTERNS, MIN_REASON_LEN, SENSITIVE_PATH_PATTERNS,
|
||||
STUB_PATTERNS,
|
||||
};
|
||||
|
||||
/// Gate a tool call in the subagent context. Returns `Some(block_reason)` if
|
||||
/// the call should be blocked, `None` to allow.
|
||||
pub(crate) fn gate_subagent_tool_call(
|
||||
tool_name: &str,
|
||||
args: &serde_json::Value,
|
||||
) -> Option<String> {
|
||||
// File-mutating tools: write / edit / delete
|
||||
if matches!(tool_name, "write" | "edit" | "delete") {
|
||||
if let Some(path) = args.get("path").and_then(|v| v.as_str()) {
|
||||
if path.contains("..") {
|
||||
return Some("path traversal detected in 'path' argument".to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// write / edit / delete require a non-trivial `reason`
|
||||
if matches!(tool_name, "write" | "edit" | "delete") {
|
||||
let reason = args.get("reason").and_then(|v| v.as_str()).unwrap_or("");
|
||||
if reason.trim().len() < MIN_REASON_LEN {
|
||||
return Some(format!(
|
||||
"{tool_name} requires a non-trivial 'reason' (>= {MIN_REASON_LEN} chars) explaining why",
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// write / edit content must not contain stubs, denial, or assumption language
|
||||
if matches!(tool_name, "write" | "edit") {
|
||||
let content = match tool_name {
|
||||
"write" => args.get("content").and_then(|v| v.as_str()).unwrap_or(""),
|
||||
"edit" => {
|
||||
let old = args.get("old").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let new = args.get("new").and_then(|v| v.as_str()).unwrap_or("");
|
||||
// For edits, scanning old+new together catches stubs in both
|
||||
return if contains_any(old, STUB_PATTERNS)
|
||||
|| contains_any(new, STUB_PATTERNS)
|
||||
{
|
||||
Some(
|
||||
"content contains stub/placeholder pattern; production code must be fully implemented"
|
||||
.to_string(),
|
||||
)
|
||||
} else if contains_any(new, DENIAL_PATTERNS) {
|
||||
Some(
|
||||
"content contains denial/punt pattern; implement properly instead of skipping"
|
||||
.to_string(),
|
||||
)
|
||||
} else if contains_any(new, ASSUMPTION_PATTERNS) {
|
||||
Some(
|
||||
"content contains assumption pattern; verify against data instead of guessing"
|
||||
.to_string(),
|
||||
)
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
}
|
||||
_ => "",
|
||||
};
|
||||
if contains_any(content, STUB_PATTERNS) {
|
||||
return Some(
|
||||
"content contains stub/placeholder pattern; production code must be fully implemented"
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
if contains_any(content, DENIAL_PATTERNS) {
|
||||
return Some(
|
||||
"content contains denial/punt pattern; implement properly instead of skipping"
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
if contains_any(content, ASSUMPTION_PATTERNS) {
|
||||
return Some(
|
||||
"content contains assumption pattern; verify against data instead of guessing"
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Bash: exfiltration, sensitive paths, destructive commands
|
||||
if tool_name == "bash" {
|
||||
let cmd = args.get("command").and_then(|v| v.as_str()).unwrap_or("");
|
||||
if cmd.contains("..") {
|
||||
return Some("path traversal detected in bash command".to_string());
|
||||
}
|
||||
// Only check exfiltration for non-standard commands
|
||||
let is_standard = cmd.trim_start().starts_with("cargo")
|
||||
|| cmd.trim_start().starts_with("rustc")
|
||||
|| cmd.trim_start().starts_with("git ")
|
||||
|| cmd.trim_start().starts_with("ls")
|
||||
|| cmd.trim_start().starts_with("pwd")
|
||||
|| cmd.trim_start().starts_with("echo")
|
||||
|| cmd.trim_start().starts_with("cat")
|
||||
|| cmd.trim_start().starts_with("find")
|
||||
|| cmd.trim_start().starts_with("grep")
|
||||
|| cmd.trim_start().starts_with("test");
|
||||
if !is_standard {
|
||||
for pat in EXFIL_PATTERNS {
|
||||
if cmd.contains(pat) {
|
||||
return Some(format!(
|
||||
"potential data-exfiltration command blocked (matched '{pat}')"
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
for pat in SENSITIVE_PATH_PATTERNS {
|
||||
if cmd.contains(pat) {
|
||||
return Some(format!("refused to read/write sensitive path '{pat}'"));
|
||||
}
|
||||
}
|
||||
let dangerous = [
|
||||
"rm -rf /",
|
||||
"rm -rf --no-preserve-root",
|
||||
"rm -rf ~",
|
||||
"rm -fr /",
|
||||
"mkfs.",
|
||||
"dd if=",
|
||||
":(){",
|
||||
"> /dev/sda",
|
||||
"chmod -R 000 /",
|
||||
"shutdown ",
|
||||
"poweroff ",
|
||||
"reboot ",
|
||||
"halt ",
|
||||
];
|
||||
for pat in &dangerous {
|
||||
if cmd.contains(pat) {
|
||||
return Some(format!("destructive command pattern blocked: {pat}"));
|
||||
}
|
||||
}
|
||||
if contains_any(cmd, STUB_PATTERNS) {
|
||||
return Some("bash command contains stub pattern".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
// git_operator: require reason
|
||||
if tool_name == "git_operator" {
|
||||
let reason = args.get("reason").and_then(|v| v.as_str()).unwrap_or("");
|
||||
if reason.trim().len() < MIN_REASON_LEN {
|
||||
return Some("git_operator requires a non-trivial 'reason' (>= 8 chars)".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
/// Check if `text` matches any pattern (case-insensitive substring).
|
||||
pub(crate) fn contains_any(text: &str, patterns: &[&str]) -> bool {
|
||||
let lower = text.to_lowercase();
|
||||
patterns.iter().any(|p| lower.contains(&p.to_lowercase()))
|
||||
}
|
||||
@@ -5,4 +5,8 @@ pub mod context;
|
||||
pub mod division;
|
||||
pub mod engine;
|
||||
pub mod event;
|
||||
pub(crate) mod gating;
|
||||
pub(crate) mod provider;
|
||||
pub mod spawn;
|
||||
pub(crate) mod tools;
|
||||
pub(crate) mod workspace;
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
//! Provider configuration resolution for subagents.
|
||||
//!
|
||||
//! Resolves the API key, model, and base URL from persisted app config,
|
||||
//! matching the main agent's credential resolution exactly, so subagents
|
||||
//! automatically inherit the same provider settings.
|
||||
|
||||
use zesdex_cms::domain::repository::AppConfigRepository;
|
||||
use zesdex_cms::domain::repository::SettingsRepository;
|
||||
|
||||
/// Resolve the API key, model, and base URL from persisted app config.
|
||||
///
|
||||
/// Flow: try the settings key for the active provider → fall back to the
|
||||
/// provider's `api_key_env` env-var → fall back to the provider's
|
||||
/// `default_api_key` → fall back to an empty string.
|
||||
///
|
||||
/// Return: `(api_key, model, optional_base_url, provider_name)`. `api_key`
|
||||
/// is empty when every resolution path was exhausted — callers must check
|
||||
/// for this before issuing requests (see `run_subagent`).
|
||||
pub(crate) fn resolve_provider_config() -> (String, String, Option<String>, String) {
|
||||
let store_base_dir = zesdex_entities::domain::common::store::Store::new().base_dir;
|
||||
let settings =
|
||||
zesdex_cms::infrastructure::persistence::settings_repo::JsonSettingsRepository::new()
|
||||
.load(&store_base_dir)
|
||||
.unwrap_or_default();
|
||||
let app_config =
|
||||
zesdex_cms::infrastructure::persistence::app_config_repo::JsonAppConfigRepository::new()
|
||||
.load(&store_base_dir)
|
||||
.unwrap_or_default();
|
||||
|
||||
let mut api_key = settings
|
||||
.api_keys
|
||||
.get(&settings.provider)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| {
|
||||
tracing::warn!(
|
||||
"[subagent] no API key for provider '{}' in settings, trying env/default",
|
||||
settings.provider
|
||||
);
|
||||
String::new()
|
||||
});
|
||||
let model = settings.model.clone();
|
||||
let base_url = app_config
|
||||
.providers
|
||||
.get(&settings.provider)
|
||||
.map(|p| p.api_base.clone());
|
||||
|
||||
if api_key.is_empty() {
|
||||
if let Some(provider_cfg) = app_config.providers.get(&settings.provider) {
|
||||
api_key = provider_cfg
|
||||
.api_key_env
|
||||
.as_ref()
|
||||
.and_then(|env| std::env::var(env).ok())
|
||||
.or_else(|| provider_cfg.default_api_key.clone())
|
||||
.unwrap_or_else(|| {
|
||||
tracing::warn!(
|
||||
"[subagent] all API key resolution paths exhausted for '{}'",
|
||||
settings.provider
|
||||
);
|
||||
String::new()
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
(api_key, model, base_url, settings.provider)
|
||||
}
|
||||
|
||||
/// Reject an empty API key with an actionable error instead of letting the
|
||||
/// caller send a request that is guaranteed to fail once it reaches the network.
|
||||
///
|
||||
/// Return: `Ok(())` if `api_key` is non-empty, `Err` with a message naming
|
||||
/// `provider` and where to fix it otherwise.
|
||||
pub(crate) fn require_api_key(api_key: &str, provider: &str) -> anyhow::Result<()> {
|
||||
if api_key.is_empty() {
|
||||
anyhow::bail!(
|
||||
"no API key configured for provider '{provider}' — set one in Settings or ~/.claude/settings.json"
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn require_api_key_rejects_empty_key_with_provider_named_in_message() {
|
||||
let err = require_api_key("", "claude").unwrap_err();
|
||||
assert!(err.to_string().contains("claude"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn require_api_key_accepts_non_empty_key() {
|
||||
assert!(require_api_key("sk-live-abc123", "claude").is_ok());
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,11 @@
|
||||
//! `AgentDefinition` -- declarative specification for instantiating a
|
||||
//! subagent from workflow scripts or programmatic calls.
|
||||
//!
|
||||
//! Also provides a shared [`spawn_subagent_with_drain`] helper that
|
||||
//! eliminates the channel-creation + drain-thread boilerplate duplicated
|
||||
//! across `auto/mod.rs`, `review/mod.rs`, and `workflow/engine/mod.rs`.
|
||||
|
||||
use super::event::SubagentEvent;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Declarative specification for instantiating a subagent: name, role,
|
||||
@@ -47,3 +53,51 @@ impl AgentDefinition {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// Shared subagent spawning utility: creates an mpsc channel and spawns a
|
||||
/// drain thread that forwards every [`SubagentEvent`] to `on_event`.
|
||||
///
|
||||
/// Returns the sender half (for passing to [`run_subagent`](super::engine::run_subagent))
|
||||
/// and the drain thread's join handle so the caller can keep it alive for
|
||||
/// the duration of the subagent run.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```ignore
|
||||
/// let (tx, _drain) = spawn_subagent_with_drain(|event| {
|
||||
/// match &event {
|
||||
/// SubagentEvent::ToolCall { tool, .. } => tracing::debug!("tool: {tool}"),
|
||||
/// SubagentEvent::Completed => tracing::debug!("done"),
|
||||
/// _ => {}
|
||||
/// }
|
||||
/// });
|
||||
/// let verdict = run_subagent(&ctx, &tx)?;
|
||||
/// ```
|
||||
///
|
||||
/// # Duplication eliminated
|
||||
///
|
||||
/// Previously every subagent caller inlined the same 5-line pattern:
|
||||
///
|
||||
/// ```ignore
|
||||
/// let (tx, mut rx) = tokio::sync::mpsc::channel(32);
|
||||
/// let _drain = std::thread::spawn(move || {
|
||||
/// while let Some(event) = rx.blocking_recv() { ... }
|
||||
/// });
|
||||
/// ```
|
||||
///
|
||||
/// Callers that need a larger buffer (e.g. workflow engine uses 64) should
|
||||
/// create the channel manually instead of using this helper.
|
||||
pub fn spawn_subagent_with_drain<F>(
|
||||
on_event: F,
|
||||
) -> (tokio::sync::mpsc::Sender<SubagentEvent>, std::thread::JoinHandle<()>)
|
||||
where
|
||||
F: Fn(SubagentEvent) + Send + 'static,
|
||||
{
|
||||
let (tx, mut rx) = tokio::sync::mpsc::channel(32);
|
||||
let drain = std::thread::spawn(move || {
|
||||
while let Some(event) = rx.blocking_recv() {
|
||||
on_event(event);
|
||||
}
|
||||
});
|
||||
(tx, drain)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
//! Subagent tool filtering: maps a subagent's allowed tool names to
|
||||
//! concrete Tool trait objects and OpenAI-style tool definitions.
|
||||
//!
|
||||
//! Flow: load `all_tools()` → if `allowed_tools` is empty, use all; else
|
||||
//! filter by membership → derive `ToolDef`s for the LLM.
|
||||
|
||||
use crate::dto::provider::request::ToolDef;
|
||||
use crate::tool::{all_tools, tool_defs};
|
||||
|
||||
/// Build the tool list for a subagent from its allowlist.
|
||||
///
|
||||
/// An empty allowlist means "no restriction" (matches
|
||||
/// `build_subagent_context`'s default for non-reviewer roles).
|
||||
///
|
||||
/// Return: `(tool impls, schema defs)` for the subagent to use.
|
||||
pub(crate) fn build_subagent_tools(
|
||||
allowed_tools: &[String],
|
||||
) -> (Vec<Box<dyn crate::tool::Tool>>, Vec<ToolDef>) {
|
||||
let all = all_tools();
|
||||
let filtered: Vec<Box<dyn crate::tool::Tool>> = if allowed_tools.is_empty() {
|
||||
all.into_iter()
|
||||
.filter(|t| t.name() != "hive_mind" && t.name() != "workflow_run")
|
||||
.collect()
|
||||
} else {
|
||||
all.into_iter()
|
||||
.filter(|t| {
|
||||
allowed_tools.contains(&t.name().to_string())
|
||||
&& t.name() != "hive_mind"
|
||||
&& t.name() != "workflow_run"
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let defs = tool_defs(&filtered);
|
||||
(filtered, defs)
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
//! Workspace directory-tree generation for subagent system prompts.
|
||||
//!
|
||||
//! Build an ASCII tree of the workspace directory structure so the LLM
|
||||
//! can see the file layout.
|
||||
|
||||
use std::fmt::Write;
|
||||
|
||||
/// Build an ASCII tree of the workspace directory structure for the
|
||||
/// system prompt, so the LLM can see the file layout.
|
||||
///
|
||||
/// Flow: for each root, walk using `ignore::WalkBuilder` (respecting
|
||||
/// `.gitignore` and hidden files) → prefix `[DIR]` for directories →
|
||||
/// truncate after 1000 entries.
|
||||
pub(crate) fn generate_workspace_tree(roots: &[std::path::PathBuf]) -> String {
|
||||
let mut out = String::new();
|
||||
out.push_str("Current Workspace Directory Structure:\n");
|
||||
for root in roots {
|
||||
writeln!(out, "Root: {}", root.display()).unwrap();
|
||||
let walker = ignore::WalkBuilder::new(root)
|
||||
.hidden(true)
|
||||
.git_ignore(true)
|
||||
.build();
|
||||
let mut count = 0;
|
||||
for entry in walker.flatten() {
|
||||
let path = entry.path();
|
||||
if let Ok(rel) = path.strip_prefix(root) {
|
||||
if rel.as_os_str().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let is_dir = entry.file_type().is_some_and(|ft| ft.is_dir());
|
||||
let prefix = if is_dir { "[DIR] " } else { " " };
|
||||
writeln!(out, " {}{}", prefix, rel.display()).unwrap();
|
||||
count += 1;
|
||||
if count > 1000 {
|
||||
out.push_str(" ... (truncated)\n");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
Reference in New Issue
Block a user