diff --git a/.gitignore b/.gitignore index 123b8b2cf..7db473a18 100644 --- a/.gitignore +++ b/.gitignore @@ -16,3 +16,6 @@ config/.pi/ config/schema/sce-config.schema.json _apalache-out/ + +# Session logs written by the sce-next-task skill when run from the skill directory. +.claude/skills/sce-next-task/context/tmp/ diff --git a/cli/src/services/hooks/claude_mutation_scope/lifecycle.rs b/cli/src/services/hooks/claude_mutation_scope/lifecycle.rs index 920269ecd..c5306befe 100644 --- a/cli/src/services/hooks/claude_mutation_scope/lifecycle.rs +++ b/cli/src/services/hooks/claude_mutation_scope/lifecycle.rs @@ -1,6 +1,6 @@ use std::path::{Path, PathBuf}; -use anyhow::Result; +use anyhow::{anyhow, Result}; use crate::services::agent_trace_db::repository::RepositoryAgentTraceDb; use crate::services::hooks; @@ -8,21 +8,24 @@ use crate::services::hooks::claude_model_resolver::{ resolve_claude_model, resolve_claude_model_from_exact_evidence, ClaudeModelEvidence, }; use crate::services::managed_telemetry::trace_export::{in_child_span, ManagedChildSpan}; -use crate::services::mutation_trace::runtime::resolve_git_dir; +use crate::services::mutation_trace::runtime::{resolve_git_dir, resolve_worktree_root}; use crate::services::mutation_trace::store::{MutationTraceStore, ScopeProvenanceModelFill}; use crate::services::mutation_trace::types::ScopeId; use super::events::BASH_TOOL_NAME; +use super::routes::{self, PersistRouteOutcome, RouteRecord, RouteTarget}; use super::state; use super::{ abandon_payload, classify_tool, claude_scope_close_event_id, claude_scope_start_event_id, flush_payload, is_explicit_background_shell, parse_claude_hook_event, pre_tool_use_deny_json, scope_boundary_payload, scope_start_payload, AttemptKey, ClaudeHookEvent, ClaudeToolExecution, - ClaudeToolIdentity, ToolClassification, + ClaudeToolIdentity, ClaudeWorktreeRemove, ToolClassification, }; pub(super) const ACTOR_KIND_CLAUDE_CODE: &str = "claude_code"; +const CLAUDE_PROJECT_DIR_ENV: &str = "CLAUDE_PROJECT_DIR"; + pub(super) const FAIL_CLOSED_DENY_REASON: &str = "SCE could not establish mutation attribution for this tool execution."; pub(super) const EXPLICIT_BACKGROUND_SHELL_DENY_REASON: &str = @@ -34,6 +37,23 @@ pub(super) const MODEL_STATE_UNAVAILABLE_EVENT: &str = "sce.hooks.claude_mutation_scope.model_state_unavailable"; pub(super) const PROVENANCE_MODEL_FILL_FAILED_EVENT: &str = "sce.hooks.claude_mutation_scope.provenance_model_fill_failed"; +pub(super) const ROUTE_UNRESOLVED_EVENT: &str = "sce.hooks.claude_mutation_scope.route_unresolved"; + +fn log_route_unresolved( + logger: Option<&L>, + context: &str, + error: &dyn std::fmt::Display, + session_id: &str, +) { + if let Some(log) = logger { + log.warn( + ROUTE_UNRESOLVED_EVENT, + &error.to_string(), + &[("context", context)], + Some(session_id), + ); + } +} pub(super) fn log_pre_tool_use_fail_closed( logger: Option<&L>, @@ -83,9 +103,12 @@ pub(crate) async fn run_claude_mutation_scope_from_payload< .await }; + let project_dir = std::env::var(CLAUDE_PROJECT_DIR_ENV).ok(); + run_claude_mutation_scope_from_payload_with_resolver( stdin_payload, logger, + project_dir.as_deref(), &resolve_git_dir_fn, &model_state_resolver, &seam_fn, @@ -98,6 +121,7 @@ pub(super) async fn run_claude_mutation_scope_from_payload_with_resolver< >( stdin_payload: &str, logger: Option<&L>, + project_dir: Option<&str>, resolve_git_dir: &impl std::ops::AsyncFn(&str) -> Result, model_state_resolver: &impl std::ops::AsyncFn(&Path, &ClaudeModelEvidence) -> Result>, seam: &impl std::ops::AsyncFn(&Path, &str, Option<&L>) -> Result, @@ -113,6 +137,7 @@ pub(super) async fn run_claude_mutation_scope_from_payload_with_resolver< dispatch_claude_hook_event( event, logger, + project_dir, resolve_git_dir, model_state_resolver, &traced_seam, @@ -125,6 +150,7 @@ pub(super) async fn dispatch_claude_hook_event< >( event: ClaudeHookEvent, logger: Option<&L>, + project_dir: Option<&str>, resolve_git_dir: &impl std::ops::AsyncFn(&str) -> Result, model_state_resolver: &impl std::ops::AsyncFn(&Path, &ClaudeModelEvidence) -> Result>, seam: &impl std::ops::AsyncFn(&Path, &str, Option<&L>) -> Result, @@ -133,78 +159,401 @@ pub(super) async fn dispatch_claude_hook_event< ClaudeHookEvent::PreToolUse(execution) => Ok(handle_pre_tool_use( &execution, logger, + project_dir, resolve_git_dir, model_state_resolver, seam, ) .await), ClaudeHookEvent::PostToolUse(identity) | ClaudeHookEvent::PostToolUseFailure(identity) => { - let git_dir = resolve_git_dir(&identity.cwd).await?; - let repository_root = Path::new(&identity.cwd); - handle_close(&git_dir, repository_root, &identity, logger, seam).await - } - ClaudeHookEvent::PermissionDenied(identity) => { - let git_dir = resolve_git_dir(&identity.cwd).await?; - let repository_root = Path::new(&identity.cwd); - handle_permission_denied( - &git_dir, - repository_root, - &identity.attempt_key(), + handle_tool_terminal( + &identity, + ToolTerminal::Completed, logger, + project_dir, + resolve_git_dir, seam, ) .await } - ClaudeHookEvent::Stop(session) | ClaudeHookEvent::StopFailure(session) => { - let git_dir = resolve_git_dir(&session.cwd).await?; - let repository_root = Path::new(&session.cwd); - let session_id = session.session_id.clone(); - cleanup_attempts_matching(&git_dir, repository_root, logger, seam, |attempt| { - attempt.session_id == session_id && attempt.agent_id.is_none() - }) + ClaudeHookEvent::PermissionDenied(identity) => { + handle_tool_terminal( + &identity, + ToolTerminal::PermissionDenied, + logger, + project_dir, + resolve_git_dir, + seam, + ) .await } - ClaudeHookEvent::UserPromptSubmit(session) => { - let git_dir = resolve_git_dir(&session.cwd).await?; - let repository_root = Path::new(&session.cwd); - let session_id = session.session_id.clone(); - cleanup_attempts_matching(&git_dir, repository_root, logger, seam, |attempt| { - attempt.session_id == session_id && attempt.agent_id.is_none() - }) + ClaudeHookEvent::Stop(session) + | ClaudeHookEvent::StopFailure(session) + | ClaudeHookEvent::UserPromptSubmit(session) => { + cleanup_session_attempts( + &session.session_id, + &session.cwd, + logger, + project_dir, + resolve_git_dir, + seam, + |agent_id| agent_id.is_none(), + ) .await } ClaudeHookEvent::SubagentStop(agent) => { - let git_dir = resolve_git_dir(&agent.cwd).await?; - let repository_root = Path::new(&agent.cwd); - let session_id = agent.session_id.clone(); let agent_id = agent.agent_id.clone(); - cleanup_attempts_matching(&git_dir, repository_root, logger, seam, |attempt| { - attempt.session_id == session_id && attempt.agent_id.as_deref() == Some(&agent_id) - }) + cleanup_session_attempts( + &agent.session_id, + &agent.cwd, + logger, + project_dir, + resolve_git_dir, + seam, + |attempt_agent_id| attempt_agent_id == Some(agent_id.as_str()), + ) .await } ClaudeHookEvent::SessionEnd(session) => { - let git_dir = resolve_git_dir(&session.cwd).await?; - let repository_root = Path::new(&session.cwd); - let session_id = session.session_id.clone(); - cleanup_attempts_matching(&git_dir, repository_root, logger, seam, |attempt| { - attempt.session_id == session_id - }) + cleanup_session_attempts( + &session.session_id, + &session.cwd, + logger, + project_dir, + resolve_git_dir, + seam, + |_agent_id| true, + ) .await } ClaudeHookEvent::WorktreeRemove(worktree_remove) => { - let git_dir = resolve_git_dir(&worktree_remove.worktree_path).await?; - let repository_root = Path::new(&worktree_remove.worktree_path); - cleanup_attempts_matching(&git_dir, repository_root, logger, seam, |_attempt| true) + handle_worktree_remove(&worktree_remove, logger, project_dir, resolve_git_dir, seam) .await } ClaudeHookEvent::SessionStart | ClaudeHookEvent::SubagentStart => Ok(String::new()), } } +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum ToolTerminal { + Completed, + PermissionDenied, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum AttemptLookup { + ByRoute, + LegacyCwd, +} + +impl AttemptLookup { + fn admits(self, attempt: &state::AdapterAttempt) -> bool { + match self { + AttemptLookup::ByRoute => true, + AttemptLookup::LegacyCwd => !attempt.routed, + } + } +} + +enum ToolRoute { + Routed { + anchor_git_dir: PathBuf, + target: RouteTarget, + }, + Unrouted, +} + +async fn resolve_route_anchor_or_log( + project_dir: Option<&str>, + session_id: &str, + logger: Option<&L>, + resolve_git_dir: &impl std::ops::AsyncFn(&str) -> Result, +) -> Option { + match routes::resolve_route_anchor(project_dir, resolve_git_dir).await { + Ok(anchor_git_dir) => Some(anchor_git_dir), + Err(error) => { + log_route_unresolved(logger, "resolve_route_anchor", &error, session_id); + None + } + } +} + +async fn load_tool_route( + key: &AttemptKey, + logger: Option<&L>, + project_dir: Option<&str>, + resolve_git_dir: &impl std::ops::AsyncFn(&str) -> Result, +) -> ToolRoute { + let Some(anchor_git_dir) = + resolve_route_anchor_or_log(project_dir, &key.session_id, logger, resolve_git_dir).await + else { + return ToolRoute::Unrouted; + }; + + match routes::load_route(&anchor_git_dir, key).await { + Ok(Some(target)) => ToolRoute::Routed { + anchor_git_dir, + target, + }, + Ok(None) => ToolRoute::Unrouted, + Err(error) => { + log_route_unresolved(logger, "load_route", &error, &key.session_id); + ToolRoute::Unrouted + } + } +} + +async fn find_attempt( + git_dir: &Path, + key: &AttemptKey, + lookup: AttemptLookup, +) -> Result> { + let current = state::read_state(git_dir).await?; + Ok(current + .attempts + .into_iter() + .find(|attempt| attempt_matches_key(attempt, key) && lookup.admits(attempt))) +} + +async fn handle_tool_terminal( + identity: &ClaudeToolIdentity, + terminal: ToolTerminal, + logger: Option<&L>, + project_dir: Option<&str>, + resolve_git_dir: &impl std::ops::AsyncFn(&str) -> Result, + seam: &impl std::ops::AsyncFn(&Path, &str, Option<&L>) -> Result, +) -> Result { + let key = identity.attempt_key(); + match load_tool_route(&key, logger, project_dir, resolve_git_dir).await { + ToolRoute::Routed { + anchor_git_dir, + target, + } => { + if let Some(attempt) = + find_attempt(&target.git_dir, &key, AttemptLookup::ByRoute).await? + { + finish_attempt( + identity, + terminal, + &target.git_dir, + &target.checkout_path, + &attempt, + logger, + seam, + ) + .await?; + } + retire_route_if_terminal(&anchor_git_dir, &key, &target).await?; + } + ToolRoute::Unrouted => { + let Ok(git_dir) = resolve_git_dir(&identity.cwd).await else { + return Ok(String::new()); + }; + if let Some(attempt) = find_attempt(&git_dir, &key, AttemptLookup::LegacyCwd).await? { + finish_attempt( + identity, + terminal, + &git_dir, + Path::new(&identity.cwd), + &attempt, + logger, + seam, + ) + .await?; + } + } + } + Ok(String::new()) +} + +async fn finish_attempt( + identity: &ClaudeToolIdentity, + terminal: ToolTerminal, + git_dir: &Path, + repository_root: &Path, + attempt: &state::AdapterAttempt, + logger: Option<&L>, + seam: &impl std::ops::AsyncFn(&Path, &str, Option<&L>) -> Result, +) -> Result<()> { + match terminal { + ToolTerminal::Completed => { + close_attempt(git_dir, repository_root, attempt, identity, logger, seam).await + } + ToolTerminal::PermissionDenied => { + abandon_attempt(git_dir, repository_root, attempt, logger, seam).await + } + } +} + +async fn retire_route_if_terminal( + anchor_git_dir: &Path, + key: &AttemptKey, + target: &RouteTarget, +) -> Result<()> { + if find_attempt(&target.git_dir, key, AttemptLookup::ByRoute) + .await? + .is_none() + { + routes::remove_route(anchor_git_dir, key, target).await?; + } + Ok(()) +} + +fn group_routes_by_target( + session_routes: impl IntoIterator, +) -> Vec<(RouteTarget, Vec)> { + let mut groups: Vec<(RouteTarget, Vec)> = Vec::new(); + for route in session_routes { + let key = AttemptKey { + session_id: route.session_id, + agent_id: route.agent_id, + tool_use_id: route.tool_use_id, + }; + match groups + .iter_mut() + .find(|(target, _)| *target == route.target) + { + Some((_, keys)) => keys.push(key), + None => groups.push((route.target, vec![key])), + } + } + groups +} + +async fn cleanup_routed_target( + anchor_git_dir: &Path, + target: &RouteTarget, + keys: &[AttemptKey], + logger: Option<&L>, + seam: &impl std::ops::AsyncFn(&Path, &str, Option<&L>) -> Result, +) -> Result<()> { + cleanup_attempts_matching( + &target.git_dir, + &target.checkout_path, + logger, + seam, + |attempt| keys.iter().any(|key| attempt_matches_key(attempt, key)), + ) + .await?; + for key in keys { + retire_route_if_terminal(anchor_git_dir, key, target).await?; + } + Ok(()) +} + +async fn cleanup_session_attempts( + session_id: &str, + cwd: &str, + logger: Option<&L>, + project_dir: Option<&str>, + resolve_git_dir: &impl std::ops::AsyncFn(&str) -> Result, + seam: &impl std::ops::AsyncFn(&Path, &str, Option<&L>) -> Result, + agent_matches: impl Fn(Option<&str>) -> bool, +) -> Result { + let mut first_error: Option = None; + + if let Some(anchor_git_dir) = + resolve_route_anchor_or_log(project_dir, session_id, logger, resolve_git_dir).await + { + match routes::routes_for_session(&anchor_git_dir, session_id).await { + Ok(session_routes) => { + let groups = group_routes_by_target( + session_routes + .into_iter() + .filter(|route| agent_matches(route.agent_id.as_deref())), + ); + for (target, keys) in &groups { + if let Err(error) = + cleanup_routed_target(&anchor_git_dir, target, keys, logger, seam).await + { + first_error.get_or_insert(error); + } + } + } + Err(error) => { + log_route_unresolved(logger, "routes_for_session", &error, session_id); + } + } + } + + if let Ok(git_dir) = resolve_git_dir(cwd).await { + if let Err(error) = + cleanup_attempts_matching(&git_dir, Path::new(cwd), logger, seam, |attempt| { + AttemptLookup::LegacyCwd.admits(attempt) + && attempt.session_id == session_id + && agent_matches(attempt.agent_id.as_deref()) + }) + .await + { + first_error.get_or_insert(error); + } + } + + match first_error { + Some(error) => Err(error), + None => Ok(String::new()), + } +} + +async fn handle_worktree_remove( + worktree_remove: &ClaudeWorktreeRemove, + logger: Option<&L>, + project_dir: Option<&str>, + resolve_git_dir: &impl std::ops::AsyncFn(&str) -> Result, + seam: &impl std::ops::AsyncFn(&Path, &str, Option<&L>) -> Result, +) -> Result { + let git_dir = resolve_git_dir(&worktree_remove.worktree_path).await?; + let repository_root = Path::new(&worktree_remove.worktree_path); + cleanup_attempts_matching(&git_dir, repository_root, logger, seam, |_attempt| true).await?; + + let session_id = &worktree_remove.session_id; + let Some(anchor_git_dir) = + resolve_route_anchor_or_log(project_dir, session_id, logger, resolve_git_dir).await + else { + return Ok(String::new()); + }; + let session_routes = match routes::routes_for_session(&anchor_git_dir, session_id).await { + Ok(session_routes) => session_routes, + Err(error) => { + log_route_unresolved(logger, "routes_for_session", &error, session_id); + return Ok(String::new()); + } + }; + for route in session_routes { + if route.target.git_dir != git_dir + && !route.target.checkout_path.starts_with(repository_root) + { + continue; + } + let key = AttemptKey { + session_id: route.session_id, + agent_id: route.agent_id, + tool_use_id: route.tool_use_id, + }; + retire_route_if_terminal(&anchor_git_dir, &key, &route.target).await?; + } + Ok(String::new()) +} + +async fn persist_tool_route( + anchor_git_dir: &Path, + key: &AttemptKey, + target: &RouteTarget, +) -> Result<()> { + match routes::persist_route(anchor_git_dir, key, target).await? { + PersistRouteOutcome::Inserted | PersistRouteOutcome::AlreadyRouted => Ok(()), + PersistRouteOutcome::Conflict { existing } => Err(anyhow!( + "Claude tool invocation '{}' is already routed to checkout '{}'", + key.tool_use_id, + existing.checkout_path.display() + )), + } +} + pub(super) async fn handle_pre_tool_use( execution: &ClaudeToolExecution, logger: Option<&L>, + project_dir: Option<&str>, resolve_git_dir: &impl std::ops::AsyncFn(&str) -> Result, model_state_resolver: &impl std::ops::AsyncFn(&Path, &ClaudeModelEvidence) -> Result>, seam: &impl std::ops::AsyncFn(&Path, &str, Option<&L>) -> Result, @@ -226,8 +575,22 @@ pub(super) async fn handle_pre_tool_use anchor_git_dir, + Err(error) => { + log_pre_tool_use_fail_closed(logger, "resolve_route_anchor", &anyhow!(error)); + return pre_tool_use_deny_json(FAIL_CLOSED_DENY_REASON); + } + }; + + let repository_root = match resolve_worktree_root(Path::new(&identity.cwd)).await { + Ok(repository_root) => repository_root, + Err(error) => { + log_pre_tool_use_fail_closed(logger, "resolve_worktree_root", &error); + return pre_tool_use_deny_json(FAIL_CLOSED_DENY_REASON); + } + }; + let git_dir = match resolve_checkout_git_dir(&repository_root, resolve_git_dir).await { Ok(git_dir) => git_dir, Err(error) => { log_pre_tool_use_fail_closed(logger, "resolve_git_dir", &error); @@ -236,15 +599,25 @@ pub(super) async fn handle_pre_tool_use Result, +) -> Result { + let repository_root_str = repository_root.to_str().ok_or_else(|| { + anyhow!( + "worktree root '{}' is not valid UTF-8", + repository_root.display() + ) + })?; + resolve_git_dir(repository_root_str).await +} + fn is_untracked_background_bash(execution: &ClaudeToolExecution) -> bool { execution.run_in_background && execution.identity.tool_name == BASH_TOOL_NAME } @@ -349,27 +737,16 @@ pub(super) async fn establish_start( +async fn close_attempt( git_dir: &Path, repository_root: &Path, + attempt: &state::AdapterAttempt, identity: &ClaudeToolIdentity, logger: Option<&L>, seam: &impl std::ops::AsyncFn(&Path, &str, Option<&L>) -> Result, -) -> Result { - let key = identity.attempt_key(); - let current = state::read_state(git_dir).await?; - let Some(attempt) = current - .attempts - .iter() - .find(|attempt| attempt_matches_key(attempt, &key)) - .cloned() - else { - return Ok(String::new()); - }; - +) -> Result<()> { if attempt.phase == state::AttemptPhase::PendingStart { - abandon_attempt(git_dir, repository_root, &attempt, logger, seam).await?; - return Ok(String::new()); + return abandon_attempt(git_dir, repository_root, attempt, logger, seam).await; } let close_payload = scope_boundary_payload( @@ -381,11 +758,10 @@ pub(super) async fn handle_close( @@ -439,10 +815,11 @@ pub(super) async fn fill_claude_scope_provenance_model( .map(Some) } -pub(super) async fn handle_permission_denied( +#[cfg(test)] +pub(super) async fn handle_close( git_dir: &Path, repository_root: &Path, - key: &AttemptKey, + identity: &ClaudeToolIdentity, logger: Option<&L>, seam: &impl std::ops::AsyncFn(&Path, &str, Option<&L>) -> Result, ) -> Result { @@ -450,13 +827,13 @@ pub(super) async fn handle_permission_denied, +} + +struct Harness { + _root: tempfile::TempDir, + _outside: tempfile::TempDir, + repo_a: PathBuf, + nested_b: PathBuf, + outside: PathBuf, + calls: Mutex>, + failing_operations: Mutex>, +} + +fn git(dir: &Path, args: &[&str]) { + let status = std::process::Command::new("git") + .args(args) + .current_dir(dir) + .status() + .expect("git runs"); + assert!(status.success(), "git {args:?} failed in {}", dir.display()); +} + +impl Harness { + fn new() -> Self { + let root = tempfile::tempdir().expect("temp dir"); + let outside = tempfile::tempdir().expect("outside temp dir"); + let repo_a = root + .path() + .canonicalize() + .expect("canonical root") + .join("repoA"); + let nested_b = repo_a.join("nestedB"); + for repo in [&repo_a, &nested_b] { + std::fs::create_dir_all(repo).expect("mkdir"); + git(repo, &["init", "--quiet"]); + } + Harness { + repo_a, + nested_b, + outside: outside.path().canonicalize().expect("canonical outside"), + _root: root, + _outside: outside, + calls: Mutex::new(Vec::new()), + failing_operations: Mutex::new(Vec::new()), + } + } + + async fn send_with_project_dir( + &self, + project_dir: Option<&Path>, + payload: Value, + ) -> Result { + let resolver = async |dir: &str| resolve_git_dir(Path::new(dir)).await; + let model_state = async |_: &Path, _: &ClaudeModelEvidence| Ok(None); + let seam = async |root: &Path, payload: &str, _: Option<&NoopLogger>| { + let parsed: Value = serde_json::from_str(payload).expect("seam payload is JSON"); + let operation = parsed["operation"].as_str().expect("operation").to_string(); + if self + .failing_operations + .lock() + .unwrap() + .contains(&operation.as_str()) + { + return Err(anyhow!("injected seam failure for {operation}")); + } + self.calls.lock().unwrap().push(SeamCall { + root: root.to_path_buf(), + operation, + scope_id: parsed["scope_id"].as_str().map(str::to_string), + }); + Ok(String::new()) + }; + run_claude_mutation_scope_from_payload_with_resolver( + &payload.to_string(), + None::<&NoopLogger>, + project_dir.and_then(Path::to_str), + &resolver, + &model_state, + &seam, + ) + .await + } + + async fn send(&self, payload: Value) -> Result { + self.send_with_project_dir(Some(&self.repo_a.clone()), payload) + .await + } + + fn take_calls(&self) -> Vec { + std::mem::take(&mut *self.calls.lock().unwrap()) + } + + fn fail(&self, operation: &'static str) { + self.failing_operations.lock().unwrap().push(operation); + } + + fn heal(&self) { + self.failing_operations.lock().unwrap().clear(); + } + + fn anchor(&self) -> PathBuf { + self.repo_a.join(".git") + } + + async fn state_of(&self, repo: &Path) -> AdapterState { + state::read_state(&repo.join(".git")) + .await + .expect("state reads") + } + + async fn route_count(&self) -> usize { + routes::read_routes(&self.anchor()) + .await + .expect("routes read") + .routes + .len() + } +} + +fn tool_event(event: &str, agent: Option<&str>, tool_use_id: &str, cwd: &Path) -> Value { + json!({ + "hook_event_name": event, + "session_id": SESSION, + "agent_id": agent, + "cwd": cwd.to_str().unwrap(), + "tool_name": "Write", + "tool_use_id": tool_use_id, + "tool_input": {}, + }) +} + +fn pre(agent: Option<&str>, tool_use_id: &str, cwd: &Path) -> Value { + tool_event("PreToolUse", agent, tool_use_id, cwd) +} + +fn post(agent: Option<&str>, tool_use_id: &str, cwd: &Path) -> Value { + tool_event("PostToolUse", agent, tool_use_id, cwd) +} + +fn session_event(event: &str, cwd: &Path) -> Value { + json!({ "hook_event_name": event, "session_id": SESSION, "cwd": cwd.to_str().unwrap() }) +} + +fn started_scope(calls: &[SeamCall]) -> String { + let [call] = calls else { + panic!("expected exactly one start call, got {calls:?}"); + }; + assert_eq!(call.operation, "start"); + call.scope_id.clone().expect("start carries a scope id") +} + +fn call(root: &Path, operation: &str, scope_id: &str) -> SeamCall { + SeamCall { + root: root.to_path_buf(), + operation: operation.to_string(), + scope_id: Some(scope_id.to_string()), + } +} + +#[tokio::test] +async fn post_tool_use_from_a_nested_repository_closes_the_attempt_in_the_original_repository() { + let h = Harness::new(); + assert_eq!(h.send(pre(None, "t1", &h.repo_a)).await.unwrap(), ""); + let scope = started_scope(&h.take_calls()); + + h.send(post(None, "t1", &h.nested_b)).await.unwrap(); + + assert_eq!(h.take_calls(), vec![call(&h.repo_a, "close", &scope)]); + assert!(h.state_of(&h.repo_a).await.attempts.is_empty()); + assert!(!state::state_path(&h.nested_b.join(".git")).exists()); + assert_eq!(h.route_count().await, 0); +} + +#[tokio::test] +async fn pre_tool_use_in_a_removed_subdirectory_closes_through_the_canonical_worktree_root() { + let h = Harness::new(); + let subdirectory = h.repo_a.join("src").join("deep"); + std::fs::create_dir_all(&subdirectory).expect("mkdir"); + + h.send(pre(None, "t1", &subdirectory)).await.unwrap(); + let calls = h.take_calls(); + let scope = started_scope(&calls); + assert_eq!(calls[0].root, h.repo_a); + let route = routes::load_route( + &h.anchor(), + &AttemptKey { + session_id: SESSION.to_string(), + agent_id: None, + tool_use_id: "t1".to_string(), + }, + ) + .await + .unwrap() + .expect("route persisted before start"); + assert_eq!(route.checkout_path, h.repo_a); + + std::fs::remove_dir_all(h.repo_a.join("src")).expect("remove subdirectory"); + h.send(post(None, "t1", &subdirectory)).await.unwrap(); + + assert_eq!(h.take_calls(), vec![call(&h.repo_a, "close", &scope)]); + assert!(h.state_of(&h.repo_a).await.attempts.is_empty()); + assert_eq!(h.route_count().await, 0); +} + +#[cfg(unix)] +#[tokio::test] +async fn an_unsyncable_route_directory_denies_pre_tool_use_and_the_visible_route_is_retired() { + use std::os::unix::fs::PermissionsExt; + + let h = Harness::new(); + let route_dir = h.anchor().join("sce"); + std::fs::create_dir_all(&route_dir).expect("mkdir"); + let set_mode = |mode: u32| { + std::fs::set_permissions(&route_dir, std::fs::Permissions::from_mode(mode)).expect("chmod"); + }; + set_mode(0o300); + if std::fs::File::open(&route_dir).is_ok() { + set_mode(0o700); + return; + } + + let response = h.send(pre(None, "t1", &h.repo_a)).await.unwrap(); + set_mode(0o700); + + let decision: Value = serde_json::from_str(&response).expect("deny JSON"); + assert_eq!(decision["hookSpecificOutput"]["permissionDecision"], "deny"); + assert!(h.take_calls().is_empty()); + assert!(h.state_of(&h.repo_a).await.attempts.is_empty()); + assert_eq!(h.route_count().await, 1); + + h.send(session_event("Stop", &h.repo_a)).await.unwrap(); + assert!(h.take_calls().is_empty()); + assert_eq!(h.route_count().await, 0); +} + +#[tokio::test] +async fn concurrent_tools_in_two_repositories_close_only_their_own_attempts_in_reverse_order() { + let h = Harness::new(); + h.send(pre(None, "t1", &h.repo_a)).await.unwrap(); + let main_a = started_scope(&h.take_calls()); + h.send(pre(None, "t2", &h.nested_b)).await.unwrap(); + let main_b = started_scope(&h.take_calls()); + h.send(pre(Some("sub"), "t1", &h.nested_b)).await.unwrap(); + let sub_b = started_scope(&h.take_calls()); + + h.send(post(Some("sub"), "t1", &h.repo_a)).await.unwrap(); + h.send(post(None, "t2", &h.repo_a)).await.unwrap(); + assert_eq!( + h.take_calls(), + vec![ + call(&h.nested_b, "close", &sub_b), + call(&h.nested_b, "close", &main_b), + ] + ); + let remaining = h.state_of(&h.repo_a).await.attempts; + assert_eq!(remaining.len(), 1); + assert_eq!(remaining[0].scope_id, main_a); + + h.send(post(None, "t1", &h.nested_b)).await.unwrap(); + assert_eq!(h.take_calls(), vec![call(&h.repo_a, "close", &main_a)]); + assert_eq!(h.route_count().await, 0); +} + +#[tokio::test] +async fn failure_and_permission_denial_terminate_through_the_original_route() { + let h = Harness::new(); + h.send(pre(None, "t1", &h.repo_a)).await.unwrap(); + let failed = started_scope(&h.take_calls()); + h.send(pre(None, "t2", &h.repo_a)).await.unwrap(); + let denied = started_scope(&h.take_calls()); + + h.send(tool_event("PostToolUseFailure", None, "t1", &h.nested_b)) + .await + .unwrap(); + h.send(tool_event("PermissionDenied", None, "t2", &h.nested_b)) + .await + .unwrap(); + + assert_eq!( + h.take_calls(), + vec![ + call(&h.repo_a, "close", &failed), + call(&h.repo_a, "abandon", &denied), + ] + ); + let state_a = h.state_of(&h.repo_a).await; + assert!(state_a.attempts.is_empty()); + assert!(state_a.recovery_pending); + assert!(!state::state_path(&h.nested_b.join(".git")).exists()); + assert_eq!(h.route_count().await, 0); +} + +#[tokio::test] +async fn stop_and_subagent_stop_retire_only_their_own_routed_attempts() { + let h = Harness::new(); + h.send(pre(None, "t1", &h.repo_a)).await.unwrap(); + let main = started_scope(&h.take_calls()); + h.send(pre(Some("sub"), "t1", &h.repo_a)).await.unwrap(); + let sub = started_scope(&h.take_calls()); + + h.send(session_event("Stop", &h.nested_b)).await.unwrap(); + assert_eq!(h.take_calls(), vec![call(&h.repo_a, "abandon", &main)]); + assert_eq!(h.route_count().await, 1); + + let subagent_stop = json!({ + "hook_event_name": "SubagentStop", + "session_id": SESSION, + "agent_id": "sub", + "cwd": h.outside.to_str().unwrap(), + }); + h.send(subagent_stop).await.unwrap(); + assert_eq!(h.take_calls(), vec![call(&h.repo_a, "abandon", &sub)]); + assert!(h.state_of(&h.repo_a).await.attempts.is_empty()); + assert_eq!(h.route_count().await, 0); +} + +#[tokio::test] +async fn failed_abandon_keeps_the_route_so_session_end_can_retry() { + let h = Harness::new(); + h.send(pre(None, "t1", &h.repo_a)).await.unwrap(); + let scope = started_scope(&h.take_calls()); + + h.fail("abandon"); + assert!(h.send(session_event("Stop", &h.nested_b)).await.is_err()); + assert_eq!(h.route_count().await, 1); + assert_eq!(h.state_of(&h.repo_a).await.attempts.len(), 1); + + h.heal(); + h.send(session_event("SessionEnd", &h.outside)) + .await + .unwrap(); + assert_eq!(h.take_calls(), vec![call(&h.repo_a, "abandon", &scope)]); + assert!(h.state_of(&h.repo_a).await.attempts.is_empty()); + assert_eq!(h.route_count().await, 0); +} + +#[tokio::test] +async fn worktree_remove_retires_routes_into_the_removed_worktree_only() { + let h = Harness::new(); + git(&h.repo_a, &["config", "user.name", "SCE Test"]); + git(&h.repo_a, &["config", "user.email", "t@example.invalid"]); + git(&h.repo_a, &["commit", "--allow-empty", "-q", "-m", "init"]); + let worktree = h.outside.join("wt"); + git( + &h.repo_a, + &["worktree", "add", "-q", worktree.to_str().unwrap()], + ); + h.send(pre(None, "t1", &worktree)).await.unwrap(); + let in_worktree = started_scope(&h.take_calls()); + h.send(pre(None, "t2", &h.repo_a)).await.unwrap(); + started_scope(&h.take_calls()); + + let worktree_remove = json!({ + "hook_event_name": "WorktreeRemove", + "session_id": SESSION, + "worktree_path": worktree.to_str().unwrap(), + }); + h.send(worktree_remove).await.unwrap(); + + assert_eq!( + h.take_calls(), + vec![call(&worktree, "abandon", &in_worktree)] + ); + let remaining = routes::routes_for_session(&h.anchor(), SESSION) + .await + .unwrap(); + assert_eq!(remaining.len(), 1); + assert_eq!(remaining[0].tool_use_id, "t2"); + assert_eq!(h.state_of(&h.repo_a).await.attempts.len(), 1); +} + +#[tokio::test] +async fn post_tool_use_outside_every_repository_still_closes_through_the_route() { + let h = Harness::new(); + h.send(pre(None, "t1", &h.repo_a)).await.unwrap(); + let scope = started_scope(&h.take_calls()); + + h.send(post(None, "t1", &h.outside)).await.unwrap(); + + assert_eq!(h.take_calls(), vec![call(&h.repo_a, "close", &scope)]); + assert_eq!(h.route_count().await, 0); +} + +#[tokio::test] +async fn a_missing_route_never_closes_a_routed_attempt_but_legacy_attempts_close_by_cwd() { + let h = Harness::new(); + h.send(pre(None, "routed", &h.repo_a)).await.unwrap(); + let routed_scope = started_scope(&h.take_calls()); + let route = routes::load_route( + &h.anchor(), + &AttemptKey { + session_id: SESSION.to_string(), + agent_id: None, + tool_use_id: "routed".to_string(), + }, + ) + .await + .unwrap() + .expect("route persisted before start"); + lose_route(&h, "routed", &route).await; + + let legacy_scope = "cc-tool-v1|legacy"; + let mut seeded = h.state_of(&h.repo_a).await; + let mut legacy = seeded.attempts[0].clone(); + legacy.scope_id = legacy_scope.to_string(); + legacy.tool_use_id = "legacy".to_string(); + seeded.attempts.push(legacy); + let mut on_disk = serde_json::to_value(&seeded).unwrap(); + on_disk["attempts"][1] + .as_object_mut() + .unwrap() + .remove("routed"); + std::fs::write( + state::state_path(&h.anchor()), + serde_json::to_vec(&on_disk).unwrap(), + ) + .unwrap(); + + h.send(post(None, "routed", &h.repo_a)).await.unwrap(); + h.send(post(None, "legacy", &h.repo_a)).await.unwrap(); + + assert_eq!(h.take_calls(), vec![call(&h.repo_a, "close", legacy_scope)]); + let remaining = h.state_of(&h.repo_a).await.attempts; + assert_eq!(remaining.len(), 1); + assert_eq!(remaining[0].scope_id, routed_scope); +} + +async fn lose_route(h: &Harness, tool_use_id: &str, route: &RouteTarget) { + let key = AttemptKey { + session_id: SESSION.to_string(), + agent_id: None, + tool_use_id: tool_use_id.to_string(), + }; + routes::remove_route(&h.anchor(), &key, route) + .await + .expect("route removal"); +} + +#[tokio::test] +async fn an_unresolvable_route_anchor_denies_pre_tool_use_before_any_start() { + let h = Harness::new(); + + let unset = h + .send_with_project_dir(None, pre(None, "t1", &h.repo_a)) + .await + .unwrap(); + let outside = h + .send_with_project_dir(Some(&h.outside.clone()), pre(None, "t2", &h.repo_a)) + .await + .unwrap(); + + for response in [unset, outside] { + let decision: Value = serde_json::from_str(&response).expect("deny JSON"); + assert_eq!(decision["hookSpecificOutput"]["permissionDecision"], "deny"); + } + assert!(h.take_calls().is_empty()); + assert!(h.state_of(&h.repo_a).await.attempts.is_empty()); + assert_eq!(h.route_count().await, 0); +} diff --git a/cli/src/services/hooks/claude_mutation_scope/mod.rs b/cli/src/services/hooks/claude_mutation_scope/mod.rs index 924f23f79..43569cd97 100644 --- a/cli/src/services/hooks/claude_mutation_scope/mod.rs +++ b/cli/src/services/hooks/claude_mutation_scope/mod.rs @@ -2,6 +2,7 @@ mod events; pub(crate) mod health; mod lifecycle; mod payload; +mod routes; pub(crate) mod state; #[allow(unused_imports)] diff --git a/cli/src/services/hooks/claude_mutation_scope/routes.rs b/cli/src/services/hooks/claude_mutation_scope/routes.rs new file mode 100644 index 000000000..372e14956 --- /dev/null +++ b/cli/src/services/hooks/claude_mutation_scope/routes.rs @@ -0,0 +1,895 @@ +use std::fs::OpenOptions; +use std::io::Write as _; +use std::path::{Path, PathBuf}; + +use anyhow::{anyhow, Context, Result}; +use serde::{Deserialize, Serialize}; + +use super::AttemptKey; +use crate::services::hooks::mutation_scope_lock::AdapterLockSpec; + +const SCE_STATE_DIR: &str = "sce"; +const ROUTE_TABLE_FILE: &str = "claude-mutation-scope-routes.json"; + +const ROUTE_LOCK: AdapterLockSpec = AdapterLockSpec::state("claude-mutation-scope-routes.lock"); + +const ROUTE_TABLE_VERSION: u32 = 1; + +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +pub(crate) struct RouteTarget { + pub checkout_path: PathBuf, + pub git_dir: PathBuf, +} + +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +pub(crate) struct RouteRecord { + pub session_id: String, + pub agent_id: Option, + pub tool_use_id: String, + pub target: RouteTarget, +} + +impl RouteRecord { + fn matches_key(&self, key: &AttemptKey) -> bool { + self.session_id == key.session_id + && self.agent_id == key.agent_id + && self.tool_use_id == key.tool_use_id + } +} + +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +pub(crate) struct RouteTable { + pub version: u32, + pub routes: Vec, +} + +impl Default for RouteTable { + fn default() -> Self { + RouteTable { + version: ROUTE_TABLE_VERSION, + routes: Vec::new(), + } + } +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub(crate) enum PersistRouteOutcome { + Inserted, + AlreadyRouted, + Conflict { existing: RouteTarget }, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum RemoveRouteOutcome { + Removed, + Absent, + TargetMismatch, +} + +#[derive(Debug)] +pub(crate) enum RouteAnchorError { + ProjectDirUnset, + Unresolvable { + project_dir: String, + source: anyhow::Error, + }, +} + +impl std::fmt::Display for RouteAnchorError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + RouteAnchorError::ProjectDirUnset => { + write!(f, "CLAUDE_PROJECT_DIR is unset or blank") + } + RouteAnchorError::Unresolvable { + project_dir, + source, + } => write!( + f, + "CLAUDE_PROJECT_DIR '{project_dir}' does not resolve to a Git directory: {source}" + ), + } + } +} + +impl std::error::Error for RouteAnchorError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + RouteAnchorError::ProjectDirUnset => None, + RouteAnchorError::Unresolvable { source, .. } => Some(source.as_ref()), + } + } +} + +/// Resolves the stable route lookup anchor: the Git directory of `CLAUDE_PROJECT_DIR`. +/// The anchor only locates the route table; it never identifies a mutation target. +pub(crate) async fn resolve_route_anchor( + project_dir: Option<&str>, + resolve_git_dir: &impl std::ops::AsyncFn(&str) -> Result, +) -> Result { + let project_dir = project_dir + .map(str::trim) + .filter(|dir| !dir.is_empty()) + .ok_or(RouteAnchorError::ProjectDirUnset)?; + resolve_git_dir(project_dir) + .await + .map_err(|source| RouteAnchorError::Unresolvable { + project_dir: project_dir.to_string(), + source, + }) +} + +fn route_dir(anchor_git_dir: &Path) -> PathBuf { + anchor_git_dir.join(SCE_STATE_DIR) +} + +pub(crate) fn route_table_path(anchor_git_dir: &Path) -> PathBuf { + route_dir(anchor_git_dir).join(ROUTE_TABLE_FILE) +} + +pub(crate) async fn read_routes(anchor_git_dir: &Path) -> Result { + let anchor_git_dir = anchor_git_dir.to_owned(); + tokio::task::spawn_blocking(move || read_routes_sync(&anchor_git_dir)) + .await + .context("Route table read worker failed")? +} + +fn read_routes_sync(anchor_git_dir: &Path) -> Result { + let path = route_table_path(anchor_git_dir); + if !path.exists() { + return Ok(RouteTable::default()); + } + + let content = std::fs::read_to_string(&path) + .with_context(|| format!("Failed to read route table '{}'", path.display()))?; + let table: RouteTable = serde_json::from_str(&content) + .with_context(|| format!("Route table '{}' is malformed", path.display()))?; + if table.version != ROUTE_TABLE_VERSION { + return Err(anyhow!( + "Route table '{}' has unsupported version {} (expected {})", + path.display(), + table.version, + ROUTE_TABLE_VERSION + )); + } + Ok(table) +} + +fn write_routes_durably_sync( + anchor_git_dir: &Path, + table: &RouteTable, + before_rename: F, +) -> Result<()> +where + F: FnOnce(&Path, &Path) -> Result<()>, +{ + let dir = route_dir(anchor_git_dir); + std::fs::create_dir_all(&dir) + .with_context(|| format!("Failed to create route table directory '{}'", dir.display()))?; + + let path = dir.join(ROUTE_TABLE_FILE); + let tmp_path = dir.join(format!("{ROUTE_TABLE_FILE}.tmp")); + + let serialized = serde_json::to_vec_pretty(table).context("Failed to serialize route table")?; + + let mut tmp_file = OpenOptions::new() + .write(true) + .create(true) + .truncate(true) + .open(&tmp_path) + .with_context(|| { + format!( + "Failed to open temporary route table file '{}'", + tmp_path.display() + ) + })?; + tmp_file.write_all(&serialized).with_context(|| { + format!( + "Failed to write temporary route table file '{}'", + tmp_path.display() + ) + })?; + tmp_file.sync_data().with_context(|| { + format!( + "Failed to sync temporary route table file '{}'", + tmp_path.display() + ) + })?; + drop(tmp_file); + + before_rename(&tmp_path, &path)?; + + std::fs::rename(&tmp_path, &path).with_context(|| { + format!( + "Failed to rename '{}' to '{}'", + tmp_path.display(), + path.display() + ) + })?; + + sync_route_dir_sync(&dir) +} + +#[cfg(unix)] +fn sync_route_dir_sync(dir: &Path) -> Result<()> { + let dir_handle = std::fs::File::open(dir).with_context(|| { + format!( + "Failed to open route table directory '{}' for sync", + dir.display() + ) + })?; + dir_handle + .sync_all() + .with_context(|| format!("Failed to sync route table directory '{}'", dir.display())) +} + +#[cfg(not(unix))] +fn sync_route_dir_sync(_dir: &Path) -> Result<()> { + Ok(()) +} + +enum RouteTransaction { + Unchanged(T), + /// The table already holds the requested state, but a previous writer may have failed after + /// its rename, so the directory entry is synced again before reporting success. + ConfirmDurable(T), + Persist(T), +} + +async fn with_locked_routes( + anchor_git_dir: &Path, + before_rename: B, + operation: F, +) -> Result +where + T: Send + 'static, + B: FnOnce(&Path, &Path) -> Result<()> + Send + 'static, + F: FnOnce(&mut RouteTable) -> Result> + Send + 'static, +{ + let anchor_git_dir = anchor_git_dir.to_owned(); + ROUTE_LOCK + .run_locked_blocking(&route_dir(&anchor_git_dir), move || { + let mut table = read_routes_sync(&anchor_git_dir)?; + match operation(&mut table)? { + RouteTransaction::Unchanged(result) => Ok(result), + RouteTransaction::ConfirmDurable(result) => { + sync_route_dir_sync(&route_dir(&anchor_git_dir))?; + Ok(result) + } + RouteTransaction::Persist(result) => { + write_routes_durably_sync(&anchor_git_dir, &table, before_rename)?; + Ok(result) + } + } + }) + .await +} + +/// Durably records the target of one tool invocation. An existing route for the same key is never +/// retargeted: a different target is reported as `Conflict` so the caller can fail closed. +pub(crate) async fn persist_route( + anchor_git_dir: &Path, + key: &AttemptKey, + target: &RouteTarget, +) -> Result { + persist_route_inner(anchor_git_dir, key, target, |_, _| Ok(())).await +} + +async fn persist_route_inner( + anchor_git_dir: &Path, + key: &AttemptKey, + target: &RouteTarget, + before_rename: B, +) -> Result +where + B: FnOnce(&Path, &Path) -> Result<()> + Send + 'static, +{ + let key = key.clone(); + let target = target.clone(); + with_locked_routes(anchor_git_dir, before_rename, move |table| { + if let Some(existing) = table.routes.iter().find(|route| route.matches_key(&key)) { + return Ok(if existing.target == target { + RouteTransaction::ConfirmDurable(PersistRouteOutcome::AlreadyRouted) + } else { + RouteTransaction::Unchanged(PersistRouteOutcome::Conflict { + existing: existing.target.clone(), + }) + }); + } + + table.routes.push(RouteRecord { + session_id: key.session_id, + agent_id: key.agent_id, + tool_use_id: key.tool_use_id, + target, + }); + Ok(RouteTransaction::Persist(PersistRouteOutcome::Inserted)) + }) + .await +} + +pub(crate) async fn load_route( + anchor_git_dir: &Path, + key: &AttemptKey, +) -> Result> { + let table = read_routes(anchor_git_dir).await?; + Ok(table + .routes + .into_iter() + .find(|route| route.matches_key(key)) + .map(|route| route.target)) +} + +pub(crate) async fn routes_for_session( + anchor_git_dir: &Path, + session_id: &str, +) -> Result> { + let table = read_routes(anchor_git_dir).await?; + Ok(table + .routes + .into_iter() + .filter(|route| route.session_id == session_id) + .collect()) +} + +/// Removes a route only while it still points at `expected_target`, so a stale caller cannot +/// delete a route that was re-established for a reused tool-use ID. +pub(crate) async fn remove_route( + anchor_git_dir: &Path, + key: &AttemptKey, + expected_target: &RouteTarget, +) -> Result { + remove_route_inner(anchor_git_dir, key, expected_target, |_, _| Ok(())).await +} + +async fn remove_route_inner( + anchor_git_dir: &Path, + key: &AttemptKey, + expected_target: &RouteTarget, + before_rename: B, +) -> Result +where + B: FnOnce(&Path, &Path) -> Result<()> + Send + 'static, +{ + let key = key.clone(); + let expected_target = expected_target.clone(); + with_locked_routes(anchor_git_dir, before_rename, move |table| { + let Some(index) = table + .routes + .iter() + .position(|route| route.matches_key(&key)) + else { + return Ok(RouteTransaction::Unchanged(RemoveRouteOutcome::Absent)); + }; + if table.routes[index].target != expected_target { + return Ok(RouteTransaction::Unchanged( + RemoveRouteOutcome::TargetMismatch, + )); + } + table.routes.remove(index); + Ok(RouteTransaction::Persist(RemoveRouteOutcome::Removed)) + }) + .await +} + +#[cfg(test)] +mod tests { + use std::path::{Path, PathBuf}; + + use anyhow::anyhow; + + use super::{ + load_route, persist_route, persist_route_inner, read_routes, remove_route, + remove_route_inner, resolve_route_anchor, route_table_path, routes_for_session, + PersistRouteOutcome, RemoveRouteOutcome, RouteAnchorError, RouteTarget, + }; + use crate::services::hooks::claude_mutation_scope::AttemptKey; + + const CONCURRENT_WRITERS: usize = 16; + + fn key(session_id: &str, agent_id: Option<&str>, tool_use_id: &str) -> AttemptKey { + AttemptKey { + session_id: session_id.to_string(), + agent_id: agent_id.map(str::to_string), + tool_use_id: tool_use_id.to_string(), + } + } + + fn target(root: &Path, repo: &str) -> RouteTarget { + RouteTarget { + checkout_path: root.join(repo), + git_dir: root.join(repo).join(".git"), + } + } + + fn injected_failure(_: &Path, _: &Path) -> anyhow::Result<()> { + Err(anyhow!("injected crash before rename")) + } + + #[tokio::test] + async fn persisted_route_is_recovered_by_a_fresh_read_from_disk() { + let anchor = tempfile::tempdir().expect("temp dir"); + let repo_a = target(anchor.path(), "repoA"); + let tool = key("s1", None, "toolu_1"); + + let outcome = persist_route(anchor.path(), &tool, &repo_a) + .await + .expect("persist route"); + assert_eq!(outcome, PersistRouteOutcome::Inserted); + + assert_eq!( + load_route(anchor.path(), &tool).await.expect("load route"), + Some(repo_a) + ); + assert!(route_table_path(anchor.path()).exists()); + } + + #[tokio::test] + async fn missing_route_table_yields_no_route() { + let anchor = tempfile::tempdir().expect("temp dir"); + let route = load_route(anchor.path(), &key("s1", None, "toolu_1")) + .await + .expect("absent table reads as empty"); + assert_eq!(route, None); + } + + #[tokio::test] + async fn failed_route_write_leaves_no_route_and_preserves_existing_routes() { + let anchor = tempfile::tempdir().expect("temp dir"); + let existing = key("s1", None, "toolu_existing"); + let repo_a = target(anchor.path(), "repoA"); + persist_route(anchor.path(), &existing, &repo_a) + .await + .expect("seed route"); + + let crashed = key("s1", None, "toolu_crashed"); + let repo_b = target(anchor.path(), "repoB"); + persist_route_inner(anchor.path(), &crashed, &repo_b, injected_failure) + .await + .expect_err("injected failure must surface so PreToolUse can deny"); + + assert_eq!( + load_route(anchor.path(), &crashed).await.expect("load"), + None + ); + assert_eq!( + load_route(anchor.path(), &existing).await.expect("load"), + Some(repo_a.clone()) + ); + + let retried = persist_route(anchor.path(), &crashed, &repo_b) + .await + .expect("a leftover temporary file must not block a retry"); + assert_eq!(retried, PersistRouteOutcome::Inserted); + assert_eq!( + load_route(anchor.path(), &crashed).await.expect("load"), + Some(repo_b) + ); + assert_eq!( + load_route(anchor.path(), &existing).await.expect("load"), + Some(repo_a) + ); + } + + #[cfg(unix)] + #[tokio::test] + async fn directory_sync_failure_after_rename_surfaces_and_a_retry_confirms_the_route() { + use std::os::unix::fs::PermissionsExt; + + let anchor = tempfile::tempdir().expect("temp dir"); + let dir = route_table_path(anchor.path()) + .parent() + .expect("route dir") + .to_owned(); + std::fs::create_dir_all(&dir).expect("mkdir"); + let set_mode = |mode: u32| { + std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(mode)).expect("chmod"); + }; + set_mode(0o300); + let privileged = std::fs::File::open(&dir).is_ok(); + set_mode(0o700); + if privileged { + return; + } + + let tool = key("s1", None, "toolu_1"); + let repo_a = target(anchor.path(), "repoA"); + let error = persist_route_inner(anchor.path(), &tool, &repo_a, |_, path| { + let dir = path.parent().expect("route dir"); + std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o300))?; + Ok(()) + }) + .await + .expect_err("an unsyncable route directory must fail persistence"); + assert!( + format!("{error:#}").contains("Failed to open route table directory"), + "{error:#}" + ); + + assert_eq!( + load_route(anchor.path(), &tool).await.expect("load"), + Some(repo_a.clone()), + "the renamed table stays visible after a post-rename sync failure" + ); + persist_route(anchor.path(), &tool, &repo_a) + .await + .expect_err("a retry must not report success while the directory cannot be synced"); + + set_mode(0o700); + assert_eq!( + persist_route(anchor.path(), &tool, &repo_a) + .await + .expect("retry after the directory recovers"), + PersistRouteOutcome::AlreadyRouted + ); + } + + #[tokio::test] + async fn failed_route_removal_keeps_the_route_recoverable() { + let anchor = tempfile::tempdir().expect("temp dir"); + let tool = key("s1", None, "toolu_1"); + let repo_a = target(anchor.path(), "repoA"); + persist_route(anchor.path(), &tool, &repo_a) + .await + .expect("seed route"); + + remove_route_inner(anchor.path(), &tool, &repo_a, injected_failure) + .await + .expect_err("injected failure must surface"); + + assert_eq!( + load_route(anchor.path(), &tool).await.expect("load"), + Some(repo_a.clone()) + ); + assert_eq!( + remove_route(anchor.path(), &tool, &repo_a) + .await + .expect("retry removal"), + RemoveRouteOutcome::Removed + ); + } + + #[tokio::test] + async fn duplicate_persist_for_the_same_target_is_idempotent() { + let anchor = tempfile::tempdir().expect("temp dir"); + let tool = key("s1", None, "toolu_1"); + let repo_a = target(anchor.path(), "repoA"); + + persist_route(anchor.path(), &tool, &repo_a) + .await + .expect("first persist"); + let replay = persist_route(anchor.path(), &tool, &repo_a) + .await + .expect("replayed persist"); + + assert_eq!(replay, PersistRouteOutcome::AlreadyRouted); + assert_eq!( + read_routes(anchor.path()).await.expect("read").routes.len(), + 1 + ); + } + + #[tokio::test] + async fn live_route_is_never_silently_retargeted() { + let anchor = tempfile::tempdir().expect("temp dir"); + let tool = key("s1", None, "toolu_1"); + let repo_a = target(anchor.path(), "repoA"); + let nested_b = target(anchor.path(), "repoA/nestedB"); + persist_route(anchor.path(), &tool, &repo_a) + .await + .expect("first persist"); + + let outcome = persist_route(anchor.path(), &tool, &nested_b) + .await + .expect("conflicting persist reads successfully"); + + assert_eq!( + outcome, + PersistRouteOutcome::Conflict { + existing: repo_a.clone() + } + ); + assert_eq!( + load_route(anchor.path(), &tool).await.expect("load"), + Some(repo_a) + ); + } + + #[tokio::test] + async fn reused_tool_use_id_after_removal_routes_to_its_new_target() { + let anchor = tempfile::tempdir().expect("temp dir"); + let tool = key("s1", None, "toolu_1"); + let repo_a = target(anchor.path(), "repoA"); + let repo_b = target(anchor.path(), "repoB"); + persist_route(anchor.path(), &tool, &repo_a) + .await + .expect("first persist"); + remove_route(anchor.path(), &tool, &repo_a) + .await + .expect("terminal removal"); + + let reused = persist_route(anchor.path(), &tool, &repo_b) + .await + .expect("reuse persist"); + + assert_eq!(reused, PersistRouteOutcome::Inserted); + assert_eq!( + load_route(anchor.path(), &tool).await.expect("load"), + Some(repo_b.clone()) + ); + + let stale_removal = remove_route(anchor.path(), &tool, &repo_a) + .await + .expect("stale removal"); + assert_eq!(stale_removal, RemoveRouteOutcome::TargetMismatch); + assert_eq!( + load_route(anchor.path(), &tool).await.expect("load"), + Some(repo_b) + ); + } + + #[tokio::test] + async fn duplicate_removal_is_safe() { + let anchor = tempfile::tempdir().expect("temp dir"); + let tool = key("s1", None, "toolu_1"); + let repo_a = target(anchor.path(), "repoA"); + persist_route(anchor.path(), &tool, &repo_a) + .await + .expect("persist"); + + assert_eq!( + remove_route(anchor.path(), &tool, &repo_a) + .await + .expect("first removal"), + RemoveRouteOutcome::Removed + ); + assert_eq!( + remove_route(anchor.path(), &tool, &repo_a) + .await + .expect("duplicate removal"), + RemoveRouteOutcome::Absent + ); + } + + #[tokio::test] + async fn main_agent_and_subagent_with_the_same_tool_use_id_do_not_share_a_route() { + let anchor = tempfile::tempdir().expect("temp dir"); + let main_tool = key("s1", None, "toolu_1"); + let subagent_tool = key("s1", Some("agent_1"), "toolu_1"); + let other_session_tool = key("s2", None, "toolu_1"); + let repo_a = target(anchor.path(), "repoA"); + let repo_b = target(anchor.path(), "repoB"); + + persist_route(anchor.path(), &main_tool, &repo_a) + .await + .expect("main persist"); + assert_eq!( + persist_route(anchor.path(), &subagent_tool, &repo_b) + .await + .expect("subagent persist"), + PersistRouteOutcome::Inserted + ); + + assert_eq!( + load_route(anchor.path(), &main_tool).await.expect("load"), + Some(repo_a.clone()) + ); + assert_eq!( + load_route(anchor.path(), &subagent_tool) + .await + .expect("load"), + Some(repo_b) + ); + assert_eq!( + load_route(anchor.path(), &other_session_tool) + .await + .expect("load"), + None + ); + + assert_eq!( + remove_route(anchor.path(), &subagent_tool, &repo_a) + .await + .expect("cross-key removal"), + RemoveRouteOutcome::TargetMismatch + ); + assert_eq!( + load_route(anchor.path(), &main_tool).await.expect("load"), + Some(repo_a) + ); + } + + #[tokio::test] + async fn session_routes_include_only_that_session() { + let anchor = tempfile::tempdir().expect("temp dir"); + let repo_a = target(anchor.path(), "repoA"); + let repo_b = target(anchor.path(), "repoB"); + persist_route(anchor.path(), &key("s1", None, "t1"), &repo_a) + .await + .expect("persist"); + persist_route(anchor.path(), &key("s1", Some("agent_1"), "t2"), &repo_b) + .await + .expect("persist"); + persist_route(anchor.path(), &key("s2", None, "t3"), &repo_a) + .await + .expect("persist"); + + let mut tool_use_ids: Vec = routes_for_session(anchor.path(), "s1") + .await + .expect("session routes") + .into_iter() + .map(|route| route.tool_use_id) + .collect(); + tool_use_ids.sort(); + + assert_eq!(tool_use_ids, vec!["t1".to_string(), "t2".to_string()]); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn concurrent_writers_for_distinct_keys_lose_no_routes() { + let anchor = tempfile::tempdir().expect("temp dir"); + let anchor_path: PathBuf = anchor.path().to_owned(); + + let writers: Vec<_> = (0..CONCURRENT_WRITERS) + .map(|index| { + let anchor_path = anchor_path.clone(); + tokio::spawn(async move { + let repo = if index % 2 == 0 { "repoA" } else { "repoB" }; + persist_route( + &anchor_path, + &key("s1", None, &format!("toolu_{index}")), + &target(&anchor_path, repo), + ) + .await + }) + }) + .collect(); + for writer in writers { + assert_eq!( + writer.await.expect("join").expect("persist"), + PersistRouteOutcome::Inserted + ); + } + + assert_eq!( + read_routes(&anchor_path).await.expect("read").routes.len(), + CONCURRENT_WRITERS + ); + assert_eq!( + load_route(&anchor_path, &key("s1", None, "toolu_7")) + .await + .expect("load"), + Some(target(&anchor_path, "repoB")) + ); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn concurrent_duplicate_writers_insert_exactly_once() { + let anchor = tempfile::tempdir().expect("temp dir"); + let anchor_path: PathBuf = anchor.path().to_owned(); + let tool = key("s1", None, "toolu_dup"); + + let writers: Vec<_> = (0..CONCURRENT_WRITERS) + .map(|_| { + let anchor_path = anchor_path.clone(); + let tool = tool.clone(); + tokio::spawn(async move { + persist_route(&anchor_path, &tool, &target(&anchor_path, "repoA")).await + }) + }) + .collect(); + let mut inserted = 0; + for writer in writers { + match writer.await.expect("join").expect("persist") { + PersistRouteOutcome::Inserted => inserted += 1, + PersistRouteOutcome::AlreadyRouted => {} + PersistRouteOutcome::Conflict { existing } => { + panic!("same-target replay reported a conflict with {existing:?}") + } + } + } + + assert_eq!(inserted, 1); + assert_eq!( + read_routes(&anchor_path).await.expect("read").routes.len(), + 1 + ); + } + + #[tokio::test] + async fn malformed_route_table_fails_closed() { + let anchor = tempfile::tempdir().expect("temp dir"); + let path = route_table_path(anchor.path()); + std::fs::create_dir_all(path.parent().expect("parent")).expect("mkdir"); + std::fs::write(&path, b"{ not json").expect("write"); + + load_route(anchor.path(), &key("s1", None, "toolu_1")) + .await + .expect_err("malformed table must not read as empty"); + persist_route( + anchor.path(), + &key("s1", None, "toolu_1"), + &target(anchor.path(), "repoA"), + ) + .await + .expect_err("malformed table must not be overwritten"); + assert_eq!( + std::fs::read(&path).expect("read"), + b"{ not json", + "malformed table must be preserved for diagnosis" + ); + } + + #[tokio::test] + async fn unsupported_route_table_version_fails_closed() { + let anchor = tempfile::tempdir().expect("temp dir"); + let path = route_table_path(anchor.path()); + std::fs::create_dir_all(path.parent().expect("parent")).expect("mkdir"); + std::fs::write(&path, br#"{"version":2,"routes":[]}"#).expect("write"); + + let error = read_routes(anchor.path()) + .await + .expect_err("future version must not be read"); + assert!(error.to_string().contains("unsupported version 2")); + } + + #[tokio::test] + async fn route_anchor_requires_a_project_dir() { + let resolver = async |_: &str| -> anyhow::Result { + panic!("resolver must not run without a project dir") + }; + + for project_dir in [None, Some(""), Some(" ")] { + assert!(matches!( + resolve_route_anchor(project_dir, &resolver).await, + Err(RouteAnchorError::ProjectDirUnset) + )); + } + } + + #[tokio::test] + async fn route_anchor_reports_an_unresolvable_project_dir() { + let resolver = + async |_: &str| -> anyhow::Result { Err(anyhow!("not a git repo")) }; + + let error = resolve_route_anchor(Some("/not/a/repo"), &resolver) + .await + .expect_err("unresolvable project dir"); + + assert!(matches!( + &error, + RouteAnchorError::Unresolvable { project_dir, .. } if project_dir == "/not/a/repo" + )); + } + + #[tokio::test] + async fn route_anchor_resolves_the_project_dir_git_dir_not_a_nested_repository() { + let root = tempfile::tempdir().expect("temp dir"); + let repo_a = root.path().join("repoA"); + let nested_b = repo_a.join("nestedB"); + for repo in [&repo_a, &nested_b] { + std::fs::create_dir_all(repo).expect("mkdir"); + let status = std::process::Command::new("git") + .args(["init", "--quiet"]) + .current_dir(repo) + .status() + .expect("git init runs"); + assert!(status.success()); + } + let resolver = async |dir: &str| { + crate::services::mutation_trace::runtime::resolve_git_dir(Path::new(dir)).await + }; + + let anchor = resolve_route_anchor(repo_a.to_str(), &resolver) + .await + .expect("anchor resolves"); + + assert_eq!( + anchor.canonicalize().expect("canonical anchor"), + repo_a + .join(".git") + .canonicalize() + .expect("canonical git dir") + ); + } +} diff --git a/cli/src/services/hooks/claude_mutation_scope/state.rs b/cli/src/services/hooks/claude_mutation_scope/state.rs index 9cf2cfd8b..2eb0bfecc 100644 --- a/cli/src/services/hooks/claude_mutation_scope/state.rs +++ b/cli/src/services/hooks/claude_mutation_scope/state.rs @@ -32,6 +32,8 @@ pub(crate) struct AdapterAttempt { pub tool_use_id: String, pub tool_name: String, pub phase: AttemptPhase, + #[serde(default)] + pub routed: bool, } impl AdapterAttempt { @@ -246,6 +248,7 @@ pub(crate) async fn allocate_attempt( tool_use_id: key.tool_use_id.clone(), tool_name, phase: AttemptPhase::PendingStart, + routed: true, }; state.attempts.push(attempt.clone()); diff --git a/cli/src/services/mutation_trace/runtime/mod.rs b/cli/src/services/mutation_trace/runtime/mod.rs index 988be30e0..02d2fac3b 100644 --- a/cli/src/services/mutation_trace/runtime/mod.rs +++ b/cli/src/services/mutation_trace/runtime/mod.rs @@ -23,7 +23,9 @@ pub(crate) use external_mutation_guard::{ GuardRequest, }; #[allow(unused_imports)] -pub(crate) use git_snapshot::{resolve_git_dir, resolve_worktree_id, GitSnapshotService}; +pub(crate) use git_snapshot::{ + resolve_git_dir, resolve_worktree_id, resolve_worktree_root, GitSnapshotService, +}; #[allow(unused_imports)] pub(crate) use mutation_attribution::{ resolve_bounded_mutation_attribution, resolve_post_commit_mutation_attribution, diff --git a/context/cli/claude-mutation-scope-integration.md b/context/cli/claude-mutation-scope-integration.md index 22a0de422..b7c5142d0 100644 --- a/context/cli/claude-mutation-scope-integration.md +++ b/context/cli/claude-mutation-scope-integration.md @@ -22,7 +22,7 @@ ClaudeMutationScope` -> `convert_hooks_subcommand_request` -> from help (`#[command(hide = true)]` on the nested clap variant), the dispatch arm **unwrapped** like `mutation-scope` (no `Ok(...)` fail-open shim). It takes no `repository_root` parameter — every repository root is read from the parsed -event payload (see [Raw cwd is authoritative](#raw-cwd-is-authoritative)). STDIN +event payload (see [Repository routing](#repository-routing)). STDIN is one raw Claude hook JSON object via `super::read_hook_stdin()`; success emits **empty stdout**, except the deliberate `PreToolUse` permission-decision object below. @@ -91,7 +91,7 @@ new `ScopeId`; otherwise-identical tool IDs under main / `agent_id=A` / `/sce/claude-mutation-scope-state.json` (`` via `checkout::resolve_git_dir(cwd)` — worktree-specific for linked worktrees): a versioned `{version, next_attempt_seq, recovery_pending, attempts[]}`, each -attempt carrying `attempt_seq`, `scope_id`, the identity fields, `tool_name`, and +attempt carrying `attempt_seq`, `scope_id`, the identity fields, `tool_name`, `routed` (see [legacy attempts](claude-mutation-scope-routes.md#legacy-attempts-and-unresolved-routes)), and `phase` (`pending_start | active | pending_abandon`, the last set durably before any abandon seam call — see [Abandonment cleanup signals](#abandonment-cleanup-signals) below). This is **adapter bookkeeping, never @@ -110,15 +110,15 @@ can form. The adapter may call `checkout::resolve_git_dir` but not ## PreToolUse: write-ahead Start, fail-closed -For a mutation-capable tool, `handle_pre_tool_use` runs: background-`Bash` untracked allow (empty success, nothing below runs) -> explicit-background-shell deny (`PowerShell`) -> resolve `git_dir` -> recovery barrier -> +For a mutation-capable tool, `handle_pre_tool_use` runs: background-`Bash` untracked allow (empty success, nothing below runs) -> explicit-background-shell deny (`PowerShell`) -> resolve route anchor -> resolve canonical worktree root of `cwd` -> resolve `git_dir` of that root -> recovery barrier -> persist route -> write-ahead `Start` — persist `phase=pending_start`, resolve the model from the event's `ClaudeModelEvidence` through the injectable resolver closure (production: the [Claude model resolver](../sce/claude-model-resolver.md) full chain), call the seam with the optional provenance snapshot, persist `pending_start -> active`, return empty success. -`transcript_path` and the direct model are parsed leniently, so a malformed value is absent, not a rejected event. A missing model or resolver error becomes a null model and never denies the tool. -The seam receives the raw `cwd` as its `repository_root` and SCE derives the `WorktreeId`, so durable generic-ingress `Start` is reached before the hook returns success to Claude. +`transcript_path` and the direct model are parsed leniently, so a malformed value is absent, not a rejected event. A missing model or resolver error becomes a null model and never denies the tool. The route records the canonical worktree root and its Git directory and binds terminal events to them; the route anchor is the Git directory of `CLAUDE_PROJECT_DIR`. +The seam receives that worktree root as its `repository_root` and SCE derives the `WorktreeId`, so durable generic-ingress `Start` is reached before the hook returns success to Claude. **Fail-closed via Claude's deny decision.** Claude treats ordinary non-2 hook failures as non-blocking, so a generic non-zero exit would let the tool run without its `Start`. Therefore **any** failure in the mutation-capable `PreToolUse` path — state-allocation failure, seam `Start` failure, unresolvable -`cwd`, or a barrier denial — returns (`Ok`, never `Err`): +`cwd`, worktree root, or route anchor, route persist or directory-sync failure or conflict, or a barrier denial — returns (`Ok`, never `Err`): ```json {"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"SCE could not establish mutation attribution for this tool execution."}} @@ -199,16 +199,17 @@ onto the shared `healthy | recovering | blocked | invalid` vocabulary that for the full mapping, the `Blocked` incident this classifier exists to surface, and its read-only/observation-semantics boundaries. -## Raw cwd is authoritative +## Repository routing -The runtime's repository root is the raw payload's `cwd`, never -`$CLAUDE_PROJECT_DIR` (`WorktreeRemove` cleanup uses the event's -`worktree_path`). An `isolation: worktree` subagent's tool executions run inside -the isolated worktree and drive the runtime from that worktree's `cwd`, so a -hook process launched from checkout A with a payload `cwd = checkout B` drives -checkout B's state and only that worktree's cursor. The adapter never accepts, -derives, stores, or constructs a `WorktreeId`, and passes no `worktree_id` key -to the seam. +`PreToolUse` takes the repository root from the canonical worktree root of the +payload's `cwd`, never `$CLAUDE_PROJECT_DIR`, and records it in a route before +`Start`. Terminal events +and the cleanup sweeps above reach that original checkout through the route, +not through their own `cwd`. `$CLAUDE_PROJECT_DIR` only locates the route table; +see [Claude mutation-scope route store](claude-mutation-scope-routes.md). +`WorktreeRemove` cleanup uses the event's `worktree_path`. An `isolation: +worktree` subagent's tool runs from that worktree's `cwd`, so its route targets +that worktree's state and cursor. The adapter never constructs a `WorktreeId`. ## Background shell execution @@ -240,6 +241,7 @@ durable-completion classification, and empty-stdout semantics. The adapter also ## Related context +- [Claude mutation-scope route store](claude-mutation-scope-routes.md) - [Claude mutation-scope health classification](claude-mutation-scope-health.md) - [Claude mutation-scope background and detached execution boundaries](claude-mutation-scope-background-execution.md) - [Mutation-scope hook ingress: the harness-neutral transport seam](mutation-scope-hook-ingress.md) diff --git a/context/cli/claude-mutation-scope-routes.md b/context/cli/claude-mutation-scope-routes.md new file mode 100644 index 000000000..10f4c1d2d --- /dev/null +++ b/context/cli/claude-mutation-scope-routes.md @@ -0,0 +1,139 @@ +# Claude mutation-scope route store + +The Claude mutation-scope adapter has a durable route store in +`cli/src/services/hooks/claude_mutation_scope/routes.rs`. A route records the +checkout where one tracked Claude tool invocation started. Terminal hook events +can use the route to reach that checkout after the hook `cwd` has changed, for +example after `cd` into a nested Git repository. + +`lifecycle.rs` uses the store for every tracked tool execution. See +[Lifecycle routing](#lifecycle-routing). The decision record is +[`2026-11-24-claude-mutation-scope-routes-bind-tools-to-pretooluse-checkout.md`](../decisions/2026-11-24-claude-mutation-scope-routes-bind-tools-to-pretooluse-checkout.md). + +## Route anchor + +The route anchor is the Git directory of `CLAUDE_PROJECT_DIR`, resolved with +`git rev-parse --absolute-git-dir`. A live Claude Code probe showed that this +value stays the same across `cwd` changes, subagent events, and terminal events. +The event `cwd` and its Git directory do not stay the same. + +The anchor only locates the route table. It never identifies a mutation target. +`resolve_route_anchor` returns a typed `RouteAnchorError`: + +- `ProjectDirUnset`: `CLAUDE_PROJECT_DIR` is missing or blank. +- `Unresolvable`: `CLAUDE_PROJECT_DIR` does not resolve to a Git directory. + +The store never falls back to the event `cwd` when the anchor is unavailable. + +## Route table + +The route table is `/sce/claude-mutation-scope-routes.json`. It +is separate from the checkout-local `claude-mutation-scope-state.json`. Its shape +is a versioned `{version, routes[]}`. Each route has the full attempt key +(`session_id`, optional `agent_id`, `tool_use_id`) and a target +(`checkout_path`, `git_dir`). The route table is adapter bookkeeping. It is not +attribution evidence, and a route never proves that a scope started. + +Writes hold `/sce/claude-mutation-scope-routes.lock` and use the +durability sequence: temp file, `sync_data`, atomic rename, and a directory +sync on Unix. A failure to open or `sync_all` the directory fails the write with +the directory path in the error, so `PreToolUse` denies the tool. Such a failure +happens after the rename, so the new table can stay visible on disk. A retried +`persist_route` for the same key and target returns `AlreadyRouted` only after +it syncs the directory again. A route left visible without an attempt is +retired by the next terminal or cleanup event of that session. A malformed or +wrong-version table is rejected and never overwritten. + +## Operations + +| Operation | Behavior | +| --- | --- | +| `persist_route` | `Inserted` for a new key. `AlreadyRouted` for a replay with the same target. `Conflict { existing }` for a different target; the live route is not changed. | +| `load_route` | Returns the target for the exact attempt key, or none. | +| `routes_for_session` | Returns every route of one `session_id`. | +| `remove_route` | `Removed` only while the route still has the expected target. `TargetMismatch` leaves a route for a reused `tool_use_id` intact. `Absent` makes a duplicate removal safe. | + +Main-agent and subagent keys with the same `tool_use_id` are distinct routes. +The route lock and the checkout-state lock are separate files. + +## Lifecycle routing + +```mermaid +sequenceDiagram + participant Pre as PreToolUse (cwd = A) + participant Routes as Route table (anchor) + participant A as Checkout A state + participant Post as Terminal event (cwd = B or outside) + Pre->>Routes: persist route key -> A + Pre->>A: allocate attempt (routed), Start + Post->>Routes: load route by key + Post->>A: close or abandon attempt + Post->>Routes: remove route once attempt is gone +``` + +- `PreToolUse` resolves the anchor, then the canonical worktree root of the + `cwd` (`resolve_worktree_root`), then the Git directory of that root, then + runs the recovery barrier. Resolving the Git directory from the root keeps + both target fields in one checkout, including linked worktrees and nested + repositories. The route stores the root, not the `cwd`, so a tool may delete + or rename its starting subdirectory. A root that cannot be resolved denies + the tool. It persists the route before attempt allocation + and `Start`. An unresolvable anchor, a persist failure, or a `Conflict` denies + the tool with the standard fail-closed decision. +- `PostToolUse`, `PostToolUseFailure`, and `PermissionDenied` load the route and + finish the attempt in the route's `git_dir`, passing the route's + `checkout_path` to the seam. A route without an attempt is removed with no + seam call. +- `Stop`, `StopFailure`, `UserPromptSubmit`, `SubagentStop`, and `SessionEnd` + read the session's routes, filter them by the event's agent rule, and run the + shared cleanup once per recorded target. A failure on one target does not + stop the other targets. +- `WorktreeRemove` cleans the event's `worktree_path` as before, then retires + the session's routes into that worktree. +- A route is removed only when its attempt no longer exists in the target + state. A failed close or abandon keeps the route, so a later event can retry. + +## Legacy attempts and unresolved routes + +New adapter attempts carry `routed: true`. A state file written before routing +has no `routed` field, and its attempts load as `routed: false`. Only these +legacy attempts may be found through the event `cwd` when no route exists. A +legacy lookup whose `cwd` is outside every repository is a no-op. + +When a terminal or cleanup event cannot resolve the anchor or read the route +table, it logs `sce.hooks.claude_mutation_scope.route_unresolved` and acts only +on legacy attempts. A routed attempt whose route is missing is never closed or +abandoned through the event `cwd`. A legacy attempt whose `cwd` changed before +completion keeps the original orphaned-scope limitation. + +## Remaining limits + +- A scope binds to its `PreToolUse` checkout. A tool that starts in nested + repository B and then mutates parent repository A (for example + `cd .. && echo x > file`) closes its scope in B. A's change has no scope in + A. A's next boundary records it as unscoped. +- A route left by a start that failed after route persistence is removed only + by a later terminal or cleanup event of that session. When Claude exits + without such an event, the route stays as inert bookkeeping. It never closes + or abandons a scope by itself. +- A `PreToolUse` for the same key can arrive between a terminal event's attempt + check and its route removal. That attempt can then stay unrouted. Claude does + not reuse a live `tool_use_id` concurrently. + +## Live validation and overhead + +A live Claude Code 2.1.309 session used disposable repository A with nested +repository B. It ran Bash tools whose `cwd` changed from A to B, and from B to +A, inside one tool. Every scope ended `closed` in the Agent Trace DB of its +`PreToolUse` repository, with its `close` event in that worktree. No scope +stayed `active`, the route table ended empty, and neither adapter state had +`recovery_pending` set. + +Routing adds one anchor `git rev-parse` and one locked, fsynced route-table +write to each tracked `PreToolUse` and terminal event. On a debug build, the +measured median cost was about 15 ms per `PreToolUse` and 25 ms per +`PostToolUse`. + +## Related context + +- [Claude mutation-scope integration](claude-mutation-scope-integration.md) diff --git a/context/context-map.md b/context/context-map.md index ded40fe2b..64ea497ca 100644 --- a/context/context-map.md +++ b/context/context-map.md @@ -40,8 +40,9 @@ Feature/domain context: - `context/cli/mutation-trace-scope-abandonment.md` (the mutation-cursor runtime's second protected entrypoint in `cli/src/services/mutation_trace/runtime/scope_runtime.rs`, built by the `mutation-scope-runtime-integration` plan and the first production call site for `protocol::abandon`: `abandon_scope(repository_root, scope, open_db) -> Result` retires a scope whose final worktree boundary was never observed, sharing `coordinate()`'s `ProtectedWorktree` prefix but deliberately capturing **no** Git snapshot, pin, diff, reconciliation, scope registration, or worktree initialization — so abandonment is not a `RuntimeBoundary` and needs no Quint change; the classify-before-transition order that recovers what `protocol::abandon`'s uniform guarded no-op cannot report (`load_scope` first for the missing-row and cross-worktree cases the projection seam treats as errors, then `load_worktree` for the `NeverSeen` / terminal / `Active` split); the `Abandoned` / `AlreadyTerminal` / `RecoveryRequired` outcomes and the `InheritedExternalTaint` | `MissingScope` | `NeverSeenScope` | `MissingWorktreeState` recovery reasons; the inherited-marker short-circuit that returns before the DB provider is ever invoked; the fence-completion rule that clears the marker only for a settled abandonment or proven-terminal no-op and leaves it armed for every recovery-required outcome and every error, with `MarkerClearAfterCompletion` carrying the already-settled outcome; the CAS retry bounded by the coordinator's shared `MAX_CAS_RETRY_ATTEMPTS`, settling on a competitor's terminal status rather than overwriting it; and the deliberate false-negative tradeoff whereby a missing or `NeverSeen` target forces conservative strong recovery that may abandon unrelated live scopes, because attribution safety outranks preserving potentially valid evidence) - `context/cli/mutation-scope-runtime.md` (the crate-visible mutation-trace runtime seam and the lifecycle contract every current or future harness adapter must uphold, recorded by the `mutation-scope-runtime-integration` plan: the ten `pub(crate)` re-exports in `runtime/mod.rs` (`coordinate`, `RuntimeBoundary`, `StartProvenance`, `CoordinateOutcome`, `CoordinateError`, `ExternalTaintOperation`, `abandon_scope`, `AbandonScopeOutcome`, `AbandonRecoveryReason`, `AbandonScopeError`), with `ExternalTaintOperation` riding through `coordinator.rs`'s own `pub use` because `CoordinateError::ExternalTaintMarker` carries it — so the type becomes crate-visible without `protected_worktree` becoming a public module — while every `mod` declaration stays private and `ProtectedWorktree`/`ProtectedWorktreeError`/`WORKTREE_LOCK_TIMEOUT`/`reconcile_explicit` stay internal, kept clippy-clean by `#[allow(unused_imports)]` on the re-exports per the `services/style.rs` precedent rather than a placeholder consumer; and the adapter obligations themselves — a scope is one independently mutation-capable execution so a concurrent main agent and subagent need distinct `ScopeId`s, `Start`/`Advance`/`Close` semantics including that only `Start` may carry the optional `StartProvenance`, registered after scope registration and before the protocol commits and never inside `ProtocolState` or the CAS transition, with that registration conditional on the `ScopeState` `register_scope` returns so a provenance row may only be created while the scope is `NeverSeen` (an admission-time snapshot that a post-admission replay cannot backfill) while an existing row is still validated on every provenance-carrying `Start`, that a failed tool still requires `Advance` (the boundary is an observation, not a successful edit) and that a `ScopeId` is never reused after a terminal status (the `NeverSeen` guard silently refuses to reactivate it), `abandon_scope()` requiring positive staleness evidence and never inferring it from `ActorKind`, the `abandon` → `coordinate(Start(successor))` sequence with what each outcome implies for it including that a failed abandonment must never be treated as a safely started successor, that abandonment is not a `RuntimeBoundary` and needs no Quint change, the D1 tradeoff whereby a missing or `NeverSeen` target deliberately forces conservative strong recovery that may invalidate unrelated live scopes because attribution safety outranks preserving potentially valid evidence, and the attribution boundary that `AiExclusive(scope)` means scope exclusivity only and is not standalone proof that no human edited the worktree; a generic `sce hooks mutation-scope` ingress now drives the seam, joined by current Claude Code and Codex adapter drivers (both registered by `sce setup` and reachable) and an OpenCode adapter driver (full lifecycle + recovery, now generated as the final `sce-mutation-scope.ts` plugin and registered by `sce setup`, so reachable by a real session) — a Pi adapter driver now also exists (`cli/src/services/hooks/pi_mutation_scope/`, hidden `sce hooks pi-mutation-scope`) and is driven by the canonical generated Pi extension in ordinary Pi sessions; its human `user_bash` path uses the separate guarded external-mutation supervisor) - `context/cli/mutation-scope-hook-ingress.md` (the one harness-neutral CLI ingress that drives the mutation-scope runtime, in `cli/src/services/hooks/mutation_scope.rs`, built by the `mutation-scope-hook-ingress` plan: the hidden `sce hooks mutation-scope` command routing through the normal `cli_schema::HooksSubcommand::MutationScope` → `convert_hooks_subcommand_request` → `services::hooks::HookSubcommand::MutationScope` → `run_hooks_subcommand_in_repo` stack, reading one normalized JSON lifecycle object from STDIN; the strict `parse_mutation_scope_payload` contract supporting exactly `start`/`advance`/`close`/`flush`/`abandon` with a local `MutationScopePayload` transport enum, `claude_code`/`codex`/`opencode`/`pi` actor mapping, non-blank `scope_id`/`event_id`, exact per-operation key sets, an optional `provenance` object accepted on `start` only (a required non-blank `session_id`, an optional `model_id` where an absent key and an explicit `null` both mean no model, and no other key), and a dedicated hard rejection for any `worktree_id` key; the operation mapping to `RuntimeBoundary::Start`/`Advance`/`Close`/`Flush` through `coordinate()` or a direct `abandon_scope()` call, forwarding `ScopeId`/`EventId`/`ActorKind` and `start`'s optional `StartProvenance` verbatim because `EventId` equality is the runtime replay/idempotency key and provenance values arrive already canonical; identity ownership — the adapter owns `scope_id`/`event_id`/`actor_kind`, SCE owns `worktree_id`/Git tree identities/revisions/attempt IDs, and worktree identity is derived only by the runtime from the invoking checkout; the lazy `FnOnce` DB provider reusing `open_agent_trace_db_for_hook_runtime` so DB acquisition stays inside the runtime's protected-worktree ordering; the non-fail-open error classification by durable completion — malformed payload or any pre-completion `CoordinateError`/`AbandonScopeError` → `CliError`/non-zero, while `CoordinateError::MarkerClearAfterCommit` and `AbandonScopeError::MarkerClearAfterCompletion` are treated as durable success with empty stdout, the marker-cleanup failure logged via `sce.hooks.mutation_scope.marker_clear_after_durable_completion`, and the transition not retried; the empty-stdout success contract; abandonment ownership keeping no-snapshot semantics; and the generic-ingress vs harness-adapter boundary — a Claude Code adapter driver (`cli/src/services/hooks/claude_mutation_scope/`) and a Codex adapter driver (`cli/src/services/hooks/codex_mutation_scope/`, hidden `sce hooks codex-mutation-scope`) now exist and are registered by `sce setup`, both consuming this seam's own `pub(crate)` in-process entrypoint; an OpenCode adapter driver (`cli/src/services/hooks/opencode_mutation_scope/`, hidden `sce hooks opencode-mutation-scope`) also consumes it with a full `Start`/`Close`/`Abandon` lifecycle and checkout-local recovery state, and is now driven in production by the generated `sce-mutation-scope.ts` plugin installed last by `sce setup`; a Pi adapter driver (`cli/src/services/hooks/pi_mutation_scope/`, hidden `sce hooks pi-mutation-scope`) also consumes it now, with `(session-id, tool-call-id)`→`ScopeId` derivation and getppid()/`/proc`-start-time-based stale-process recovery; the canonical generated Pi extension drives it in ordinary sessions — see `context/cli/pi-mutation-scope-integration.md`) -- `context/cli/claude-mutation-scope-integration.md` (the first concrete harness lifecycle adapter, `cli/src/services/hooks/claude_mutation_scope/`, hidden command `sce hooks claude-mutation-scope`, built by the `claude-mutation-scope-integration` plan: one independently mutation-capable Claude tool execution = one SCE mutation `ScopeId` (a session/prompt/main agent/subagent is never a scope); the `classify_tool` table (mutation-capable including unknown names, read-only `Read`/`Glob`/`Grep`/`WebFetch`/`WebSearch`/`AskUserQuestion`, `Agent` = delegation) plus the model-only `is_explicit_background_shell` predicate; the length-prefixed hash-free `cc-tool-v1|n=|s=..|a=..|t=..` `ScopeId` keyed on a monotonic checkout-local `attempt_seq` (never reused after terminal) with deterministic `|start` / `|close` `EventId`s; the `/sce/claude-mutation-scope-state.json` bookkeeping store (never attribution evidence, never synced) with its own separate lock never held across a seam call; `PreToolUse` write-ahead `pending_start` → seam `start` → `active` and its fail-closed Claude `permissionDecision: "deny"` on any failure (never `allow`, detail logged via `sce.hooks.claude_mutation_scope.pre_tool_use_fail_closed`); `PostToolUse`/`PostToolUseFailure` → `close`, with `pending_start`+terminal → abandon-not-late-start (D11) and failed-`close` → abandon-not-replay (D12); the abandonment cleanup signals (`PermissionDenied`, `Stop`/`StopFailure`, `UserPromptSubmit`, `SubagentStop`, `SessionEnd`, best-effort `WorktreeRemove` — the last two not observed to fire on Claude Code `2.1.258`); the `recovery_pending` barrier that denies new mutation-capable `PreToolUse` until quiescent then runs one seam `flush`; raw hook `cwd` (or `worktree_path` for `WorktreeRemove`) as authoritative repository root with no adapter-constructed `WorktreeId`; `run_in_background = true` handling — native Claude background Bash is operationally supported but unsupported for mutation attribution (allowed in `PreToolUse` before repository resolution with no mutation scope, adapter attempt, or lifecycle tracking, per the effective decision `context/decisions/2026-10-02-claude-background-bash-untracked.md`), while background `PowerShell` stays denied — and the separate self-detaching-descendant unsupported boundary (D20, with T04's Git-observable evidence — full detail split out to [`claude-mutation-scope-background-execution.md`](cli/claude-mutation-scope-background-execution.md) for the repository's per-file line budget); the ten unmatched `sce setup` registrations; the strict `claude_mutation_scope → hooks::mutation_scope → mutation_trace::runtime` dependency direction through the single `run_mutation_scope_from_payload` seam import (T05); admission-time exact model-state snapshot into `ScopeProvenance`; real Git/Agent Trace persistence coverage shared with the Codex path; and, added by the `doctor-mutation-scope-fix` plan's T04, a third `pending_abandon` attempt phase durably persisted before any abandon seam call — established evidence that abandonment has already been decided, distinct from "may still be running" — with every attempt a broad cleanup signal (`Stop`/`UserPromptSubmit`/`SubagentStop`/`SessionEnd`/`WorktreeRemove`) matches now marked `pending_abandon` in one write before any of their seam calls run, so one attempt's seam failure can never leave a batch sibling without its own retryable evidence; health classification detail split out to [`claude-mutation-scope-health.md`](cli/claude-mutation-scope-health.md)) +- `context/cli/claude-mutation-scope-integration.md` (the first concrete harness lifecycle adapter, `cli/src/services/hooks/claude_mutation_scope/`, hidden command `sce hooks claude-mutation-scope`, built by the `claude-mutation-scope-integration` plan: one independently mutation-capable Claude tool execution = one SCE mutation `ScopeId` (a session/prompt/main agent/subagent is never a scope); the `classify_tool` table (mutation-capable including unknown names, read-only `Read`/`Glob`/`Grep`/`WebFetch`/`WebSearch`/`AskUserQuestion`, `Agent` = delegation) plus the model-only `is_explicit_background_shell` predicate; the length-prefixed hash-free `cc-tool-v1|n=|s=..|a=..|t=..` `ScopeId` keyed on a monotonic checkout-local `attempt_seq` (never reused after terminal) with deterministic `|start` / `|close` `EventId`s; the `/sce/claude-mutation-scope-state.json` bookkeeping store (never attribution evidence, never synced) with its own separate lock never held across a seam call; `PreToolUse` write-ahead `pending_start` → seam `start` → `active` and its fail-closed Claude `permissionDecision: "deny"` on any failure (never `allow`, detail logged via `sce.hooks.claude_mutation_scope.pre_tool_use_fail_closed`); `PostToolUse`/`PostToolUseFailure` → `close`, with `pending_start`+terminal → abandon-not-late-start (D11) and failed-`close` → abandon-not-replay (D12); the abandonment cleanup signals (`PermissionDenied`, `Stop`/`StopFailure`, `UserPromptSubmit`, `SubagentStop`, `SessionEnd`, best-effort `WorktreeRemove` — the last two not observed to fire on Claude Code `2.1.258`); the `recovery_pending` barrier that denies new mutation-capable `PreToolUse` until quiescent then runs one seam `flush`; raw `PreToolUse` `cwd` (or `worktree_path` for `WorktreeRemove`) as authoritative repository root, reached by terminal events through the route store, with no adapter-constructed `WorktreeId`; `run_in_background = true` handling — native Claude background Bash is operationally supported but unsupported for mutation attribution (allowed in `PreToolUse` before repository resolution with no mutation scope, adapter attempt, or lifecycle tracking, per the effective decision `context/decisions/2026-10-02-claude-background-bash-untracked.md`), while background `PowerShell` stays denied — and the separate self-detaching-descendant unsupported boundary (D20, with T04's Git-observable evidence — full detail split out to [`claude-mutation-scope-background-execution.md`](cli/claude-mutation-scope-background-execution.md) for the repository's per-file line budget); the ten unmatched `sce setup` registrations; the strict `claude_mutation_scope → hooks::mutation_scope → mutation_trace::runtime` dependency direction through the single `run_mutation_scope_from_payload` seam import (T05); admission-time exact model-state snapshot into `ScopeProvenance`; real Git/Agent Trace persistence coverage shared with the Codex path; and, added by the `doctor-mutation-scope-fix` plan's T04, a third `pending_abandon` attempt phase durably persisted before any abandon seam call — established evidence that abandonment has already been decided, distinct from "may still be running" — with every attempt a broad cleanup signal (`Stop`/`UserPromptSubmit`/`SubagentStop`/`SessionEnd`/`WorktreeRemove`) matches now marked `pending_abandon` in one write before any of their seam calls run, so one attempt's seam failure can never leave a batch sibling without its own retryable evidence; health classification detail split out to [`claude-mutation-scope-health.md`](cli/claude-mutation-scope-health.md)) - `context/cli/claude-mutation-scope-background-execution.md` (native Claude background Bash is operationally supported but unsupported for mutation attribution: `Bash(run_in_background=true)` is allowed in `PreToolUse` with no mutation scope, adapter attempt, lifecycle tracking, or attribution guarantee — effective record `context/decisions/2026-10-02-claude-background-bash-untracked.md` — its later terminal hooks are no-ops, and the accepted A/B contamination consequence is pinned by a regression; background `PowerShell` stays denied with the existing deny text; the T01 `2.1.284` probe result with lifecycle completion still unproven; and the separate self-detaching-descendant unsupported boundary D20 — Git-observable evidence that a foreground `setsid` command's detached descendant can still mutate the repository after `PostToolUse` returns — detail split out of `claude-mutation-scope-integration.md` for the repository's per-file line budget) +- `context/cli/claude-mutation-scope-routes.md` (the Claude adapter route store in `cli/src/services/hooks/claude_mutation_scope/routes.rs`: per-tool-invocation routes keyed by the full attempt key and stored at `/sce/claude-mutation-scope-routes.json` under their own lock; idempotent persist, refused retargeting, and target-checked removal; the lifecycle persists a route before `Start` and routes terminal events and session/agent/worktree cleanup to the original checkout; legacy `routed: false` attempts alone may use the event `cwd`; remaining limits, live nested-repository validation, and measured hook overhead) - `context/cli/claude-mutation-scope-health.md` (the `doctor-mutation-scope-health` plan's Claude task, extended by the `doctor-mutation-scope-fix` plan's T04: `classify_health` in `cli/src/services/hooks/claude_mutation_scope/health.rs` maps `recovery_pending`/`attempts` onto `healthy | recovering | blocked | invalid` — `recovery_pending == false` is `healthy` regardless of live attempts; `recovery_pending == true` with `attempts` empty is `recovering` (the barrier's own next-`PreToolUse` flush clears it); `recovery_pending == true` with `attempts` non-empty is `blocked`, the exact incident shape this classifier exists to surface, since nothing in the ordinary hook lifecycle retries, removes, flushes, or clears from that shape; a read/parse failure is `invalid`. T04 adds a separate, `doctor`-invoked repair path (`assess_repairability`/`repair_blocked` in `health.rs`/`lifecycle.rs`, wired into `sce doctor --fix` by the same plan's T05) for the `blocked` shape: `AutoFixable` only when every currently persisted attempt is already `pending_abandon` (no established-abandon-intent `pending_start`/`active` attempt present); `repair_blocked` re-reads and re-proves that same condition inside one lock-protected read-only state transaction before releasing the lock and retrying each attempt's already-established seam `abandon` call independently, clearing the `recovery_pending` barrier only once no attempts remain — this classifier's own read-only behavior is unaffected by that repair path's existence) - `context/cli/mutation-trace-ref-reconciliation.md` (the conservative per-worktree snapshot-ref reconciliation pass, built by the `mutation-cursor-ref-reconciliation` plan and wired by `mutation-cursor-ref-reconciliation-wiring`: the single lock-held algorithm `reconcile_with_held_lock` in `ref_reconciliation.rs`, the explicit production entrypoint `reconcile_explicit` in `ref_maintenance.rs` (one `WorktreeLock` acquisition, verified-existing Agent Trace DB, typed `ExplicitOutcome`), the documented 10 s concurrency contract, the `ref-maintenance.json` state file (past-only timestamps, skew normalization, atomic writes), the D4 verified-existing DB opener, the two-invariant durability model (per-worktree fail-closed local consistency vs repository-wide deletion safety, never a claim that every repository-wide root is pinned), a pointer to the missing-pin repair, and the deferred follow-ups (automatic out-of-band reclamation with its binding prerequisites, retired-worktree cleanup, evidence-based advice, historical retention); reconciliation runs only through `sce doctor --fix` and is never automatic) - `context/cli/mutation-trace-missing-history-recovery.md` (the `sce doctor --fix` missing-pin repair `repair_missing_pins`, built by the `missing-history-recovery` plan: the missing-durable-history heuristic that detects missing history, not clone identity; three cases for the target worktree (prune events with absent trees and re-pin survivors, fail closed with `unrecoverable_cursor` on an absent cursor until one agent hook boundary records a present cursor, no action and no clone-identity claim when trees exist); repair runs only from `doctor --fix`, never from hooks or plain `sce doctor`; invariants I1–I5) @@ -149,6 +150,7 @@ Supporting repo docs: Recent decision records: +- `context/decisions/2026-11-24-claude-mutation-scope-routes-bind-tools-to-pretooluse-checkout.md` (every tracked Claude tool is routed to its `PreToolUse` checkout through a route stored under the `CLAUDE_PROJECT_DIR` Git directory; an unresolvable anchor or route denies `PreToolUse`; terminal events never fall back to `cwd` for routed attempts) - `context/decisions/2026-11-23-claude-subagent-attribution.md` (Claude subagent events resolve their model from exact local evidence only: direct event model, then the exact `tool_use_id` record in the bounded subagent transcript, then `NULL`; one Claude resolver owns the chain; no inheritance or `claude_model_state` seeding; Claude provenance gains a write-once `NULL`-to-model completion fill; patch parts carry an optional `attribution` object. Partially supersedes the `agent_id` export guardrail of `2026-09-01-claude-model-attribution-state.md` and the Claude no-backfill provenance rule. Implemented by `context/plans/claude-subagent-attribution.md`) - `context/decisions/2026-11-10-setup-upgrades-config-schema-declarations.md` (`sce setup` is the only writer that upgrades an older-series config `$schema` declaration. It covers only the canonical repository and global files, changes only `$schema`, validates the candidate first, never downgrades, does no field migrations, and reports skips without failing setup. It amends the read-only global-config statement of `2026-10-22-setup-writes-access-answers-to-repository-config.md`) - `context/decisions/2026-11-10-config-schema-accepts-release-series-declarations.md` (the config schema accepts canonical `$schema` declarations within the CLI's `major.minor` series, derived from `.version`; the `$id` stays the concrete versioned URL) diff --git a/context/decisions/2026-11-24-claude-mutation-scope-routes-bind-tools-to-pretooluse-checkout.md b/context/decisions/2026-11-24-claude-mutation-scope-routes-bind-tools-to-pretooluse-checkout.md new file mode 100644 index 000000000..5fec17840 --- /dev/null +++ b/context/decisions/2026-11-24-claude-mutation-scope-routes-bind-tools-to-pretooluse-checkout.md @@ -0,0 +1,112 @@ +# Decision: Claude mutation scopes are routed to their PreToolUse checkout + +Date: 2026-11-24 +Status: Accepted +Plan: `context/plans/claude-mutation-scope-stable-repository-routing.md` +Task: `T01, T02, T03` + +## Context + +The Claude mutation-scope adapter resolved its repository from the hook `cwd` +on every hook event, independently. A live Claude Code `2.1.309` probe (plan +T01) showed that `cwd`, and the Git directory resolved from it, can change +within one `tool_use_id`. For example, `PreToolUse` reported repository A while +`PostToolUse` reported nested repository B after `cd nestedB`. The terminal +event then looked for the attempt in B, found nothing, and left the scope +`Active` in A. + +The same probe showed that `CLAUDE_PROJECT_DIR` and its Git directory stayed the +same in every hook event, including subagent and terminal events. Every +generated SCE Claude hook command already depends on `CLAUDE_PROJECT_DIR`. + +## Decision + +Every tracked Claude mutation-capable tool execution is bound to the checkout +selected at its `PreToolUse`, through a durable per-invocation route: + +- A route is keyed by the full attempt key (`session_id`, `agent_id`, + `tool_use_id`) and stores the original checkout path and Git directory. +- Routes live at `/sce/claude-mutation-scope-routes.json` + under their own lock. The anchor only locates the table and never identifies + a mutation target. +- `PreToolUse` persists the route after the recovery barrier and before attempt + allocation and `Start`. +- `PostToolUse`, `PostToolUseFailure`, and `PermissionDenied` reach the original + checkout through the route. +- `Stop`, `StopFailure`, `UserPromptSubmit`, `SubagentStop`, and `SessionEnd` + act only on that session's known routes, grouped by recorded target. +- `WorktreeRemove` keeps its event-provided worktree identity and retires + matching routes. +- A tracked `PreToolUse` is denied (fail closed) when `CLAUDE_PROJECT_DIR` is + unset or does not resolve to a Git directory, or when the route cannot be + persisted or conflicts with a live route. +- Terminal events never fall back to the event `cwd` for routed attempts. Only + legacy attempts, whose adapter-state `routed` marker is absent or `false`, may + still be found through the event `cwd`. +- A route is removed only after its attempt is gone from the original + checkout's adapter state. + +## Rationale + +The route captures the only repository identity that is known to be correct: +the checkout at `PreToolUse`. Storing it outside the target checkout lets a +terminal event with a different `cwd` find it. `CLAUDE_PROJECT_DIR` was the only +Git-derived value that stayed stable across `cwd` changes, subagents, and +terminal events, and SCE hooks already depend on it. Persisting before `Start` +keeps admission fail closed: no tracked tool runs without a recoverable route. + +## Alternatives considered + +- **Store the start path only in checkout-local adapter state** — a terminal + event with a different `cwd` cannot find that file. +- **Use `transcript_path` as the anchor** — it is a per-user Claude-internal + location, not an SCE-owned path. +- **Scan repositories for a matching attempt** — unbounded, and it can match an + unrelated checkout. +- **Fall back to the event `cwd` when no route is found** — operates on the wrong + repository for routed attempts. + +## Compatibility and risks + +- Claude sessions without a `CLAUDE_PROJECT_DIR` that resolves to a Git + directory can no longer run tracked mutation-capable tools. `sce setup` + installs hooks at a repository root, so supported installs resolve it. +- Attempts created before routing are found only through the event `cwd`. If + such an attempt's `cwd` changed before completion, the original defect + remains for that attempt. +- Each tracked hook does one more locked file transaction on the anchor's Git + directory. +- A `PreToolUse` reusing a `tool_use_id` between a terminal event's attempt check + and its route removal could leave that attempt unrouted. Claude does not + reuse a live `tool_use_id` concurrently. + +## Guardrails + +- The anchor is a lookup key only. The target is always the recorded checkout. +- A route is never evidence that a scope started. +- A live route is never retargeted. +- The routing and checkout-state locks are never held together or across a + seam call. +- The mutation-trace protocol, generic ingress, worktree ID semantics, + migrations, and `spec/mutation_cursor.qnt` are unchanged by this decision. + +## Consequences + +- A scope started in repository A closes in A when Claude later reports a + nested repository or a directory outside every repository as `cwd`. +- Concurrent tools in different repositories, and main-agent and subagent + tools sharing a `tool_use_id`, close only their own attempts. +- A failed abandon keeps the route, so a later cleanup event can retry it. + +## Follow-up + +- Live rerun and measured hook overhead in plan task T04. + +## References + +- Plan: [`claude-mutation-scope-stable-repository-routing`](../plans/claude-mutation-scope-stable-repository-routing.md) +- Task: `T01`, `T02`, `T03` +- Current-state context: [`claude-mutation-scope-integration.md`](../cli/claude-mutation-scope-integration.md) +- Current-state context: [`claude-mutation-scope-routes.md`](../cli/claude-mutation-scope-routes.md) +- Evidence: [`lifecycle_tests.rs`](../../cli/src/services/hooks/claude_mutation_scope/lifecycle_tests.rs) +- Related decision: [`Claude background Bash runs natively and untracked`](2026-10-02-claude-background-bash-untracked.md) diff --git a/context/plans/claude-mutation-scope-stable-repository-routing.md b/context/plans/claude-mutation-scope-stable-repository-routing.md new file mode 100644 index 000000000..3339094cc --- /dev/null +++ b/context/plans/claude-mutation-scope-stable-repository-routing.md @@ -0,0 +1,250 @@ +# Plan: Claude mutation-scope stable repository routing + +## Change summary + +A live concurrent-subagent experiment for PR #358 observed an orphaned Claude mutation scope after the Claude session changed its working directory into a nested Git repository. The Claude adapter currently resolves `checkout::resolve_git_dir(cwd)` independently on every hook event. `PreToolUse` can create an attempt in repository A while `PostToolUse` looks for it in repository B, finds no matching attempt, and returns success. This leaves a scope `Active` in A. It can later distort attribution or trigger recovery. + +**Goal:** Bind every tracked Claude tool execution to the repository/worktree selected at its `PreToolUse` boundary. Route its `PostToolUse`, `PostToolUseFailure`, permission denial, and terminal cleanup to that same repository even if subsequent hook `cwd` values change. Never discover the original scope by scanning other repositories. + +This is a **Claude adapter routing** change, not a change to the mutation-cursor protocol, protocol event model, or formal semantics. `spec/mutation_cursor.qnt` already maps all Start/Advance/Close boundaries for a scope to its one worktree (`scopeWorktree` / `boundaryWorktree`). The adapter must supply the correct checkout to that model. + +## Existing constraints and evidence + +- `cli/src/services/hooks/claude_mutation_scope/lifecycle.rs` resolves `git_dir` from the event `cwd` separately in `PreToolUse` and terminal handlers. +- `state.rs` stores adapter attempts under `/sce/claude-mutation-scope-state.json`. Merely adding the start path to an attempt in that file is **insufficient**: a terminal event with a different `cwd` cannot find the file. +- `AttemptKey` consists of `session_id`, optional `agent_id`, and `tool_use_id`. The durable `ScopeId` includes a checkout-local attempt sequence; tool IDs may be reused after terminal completion. +- Generated Claude commands use `$CLAUDE_PROJECT_DIR/.claude/hooks/run-sce-or-show-install-guidance.sh`. `CLAUDE_PROJECT_DIR` is a candidate for a stable **lookup anchor**, not proof that its Git repository is the mutation target. +- A session can run mutation-capable tools against more than one nested repository or linked worktree. The starting `cwd` (or its validated checkout identity) must be stored per tool invocation. +- `Start` is fail-closed; `Close` and cleanup are recovery-aware. Adapter bookkeeping is not attribution evidence. +- PR #358 (Claude subagent attribution) is still a separate open PR. Base this work on `main` and avoid coupling to its model-resolution changes. + +## Decisions to validate before implementation + +1. **Stable anchor.** Probe real Claude hook processes at `PreToolUse` and `PostToolUse` (including a nested Git repository, subagent, and changed `cwd`). Record whether `CLAUDE_PROJECT_DIR`, the hook's project directory, and `transcript_path` remain stable. Record no prompt, token, or secret contents. Use the established project Git directory only if it can be resolved consistently. If it cannot, choose and document one minimal private per-user session routing location before writing production code. +2. **Routing entry.** Store a durable mapping `(session_id, agent_id, tool_use_id) -> (original checkout path, original git_dir)` in a stable lookup location **outside** the mutable target checkout's adapter-state lookup path. Keep existing per-checkout attempt state and its monotonic scope ID allocation. Do not use `agent_id` or session alone as a route. +3. **Safety and atomicity.** Persist a route **before** allowing an observed `Start`. A failure to persist a route must deny a tracked `PreToolUse`, rather than create unrouteable active work. Lock and atomically replace route storage using existing adapter file/lock conventions. Do not hold routing and checkout-state locks simultaneously or while driving the mutation-scope ingress. Route replays idempotently, and do not silently retarget a live tool invocation. +4. **Use original checkout for lifecycle.** Terminal events load the stable route, then load the original checkout's attempt and verify the full `AttemptKey` before calling the existing `handle_close`/abandonment logic. The corresponding runtime boundary must use the original repository path, not the current event `cwd`. A route alone is never evidence that a scope actually started. +5. **Recovery.** Cover crashes between route persistence, attempt allocation, `Start`, durable `Close`, and route cleanup. On uncertainty, preserve existing fail-closed admission/recovery behavior; do not fabricate `Close` or abandon a potentially live tool. Remove a route only after the owning attempt is safely terminal or a proven unused route has been handled. A duplicate completion must be safe. +6. **Broader terminal events.** `PermissionDenied` must use the route. `Stop`, `StopFailure`, `UserPromptSubmit`, `SubagentStop`, and `SessionEnd` must be able to retire applicable attempts across the **known routes of that session only**, grouped by their recorded originating checkout. Do not scan arbitrary repositories. `WorktreeRemove` retains its event-provided worktree identity and must safely retire matching known routes. +7. **Unavailable anchor.** If the stable route cannot be read or verified, do not silently fall back to the event's possibly changed `cwd` and operate on the wrong repository. Distinguish first-time legacy attempts from attempts created with routing, log the unresolved condition, and document any backward-compatibility limitation. +8. **No scope change.** Leave the generic ingress, `mutation_trace::protocol`, worktree ID semantics, CAS batch, migrations, and `spec/mutation_cursor.qnt` unchanged. If implementation reveals a required protocol change, stop and revise this plan rather than broadening the PR. + +## T01 anchor probe findings + +**Probe setup.** Disposable repository `$S/repoA` contained nested Git repository `$S/repoA/nestedB`. `$S` is a session scratchpad directory. A project-only `.claude/settings.json` ran an allow-listed logging hook on `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `SubagentStart`, `SubagentStop`, `Stop`, and `SessionEnd`. The hook recorded only identity fields, `CLAUDE_PROJECT_DIR`, the hook `$PWD`, and `git rev-parse --absolute-git-dir` for the event `cwd` and for `CLAUDE_PROJECT_DIR`. It did not record tool input, prompts, or transcript contents. The session ran as `claude -p --setting-sources project` (Claude Code 2.1.309) from `$S/repoA` and performed these steps: `pwd`, `cd nestedB`, `pwd`, an `Agent` subagent running `pwd` and `Write`, and a final `pwd`. + +**Observations (19 events, one session).** + +| Field | Observed behavior | +|---|---| +| `cwd` | Changes within one tool: `PreToolUse` and `PostToolUse` for the `cd nestedB` Bash call have `cwd` = `$S/repoA` and `$S/repoA/nestedB`, respectively. All later events have `cwd` = `$S/repoA/nestedB`. The live defect is reproduced. | +| `git -C rev-parse --absolute-git-dir` | Follows `cwd`: `$S/repoA/.git` changes to `$S/repoA/nestedB/.git` within the same `tool_use_id`. **Not stable.** | +| Hook process `$PWD` | Equals `cwd`. **Not stable.** | +| `CLAUDE_PROJECT_DIR` | `$S/repoA` in every event, including subagent tool events, `SubagentStop`, `Stop`, and `SessionEnd`. **Stable.** | +| Project Git dir (`--absolute-git-dir` of `CLAUDE_PROJECT_DIR`) | `$S/repoA/.git` in every event. **Stable.** | +| `session_id` | Same on all events, including subagent events. | +| `agent_id` | Absent on main-agent tool events and on the delegating `Agent` tool's own Pre/Post. Present (`ae2e…`) on the subagent's `Bash`/`Write` events and on `SubagentStart`/`SubagentStop`. | +| `tool_use_id` | Matches exactly between each `PreToolUse` and `PostToolUse` pair. | +| `transcript_path` | Location is stable: the parent session transcript `~/.claude/projects//.jsonl`, including on subagent tool events. `SubagentStop` adds `agent_transcript_path` under `/subagents/`. | + +**Decision 1 outcome (selected anchor).** The route lookup anchor is the project Git directory, resolved as `git rev-parse --absolute-git-dir` of `CLAUDE_PROJECT_DIR`. Routes live in their own file, `/sce/claude-mutation-scope-routes.json`, separate from `claude-mutation-scope-state.json`. The anchor is only a lookup key. Each route record stores the original checkout path and `git_dir` of its tool invocation, and the target checkout is never inferred from the anchor. The anchor is justified for these reasons: +- It was the only Git-derived value that stayed the same across `cwd` changes, subagents, and terminal events. +- Every generated SCE Claude hook command already depends on `CLAUDE_PROJECT_DIR` (`bash "$CLAUDE_PROJECT_DIR/.claude/hooks/run-sce-or-show-install-guidance.sh" …`, generated by `cli/src/services/setup/config_merge.rs`), and `cli/src/app.rs` already uses it as a Claude caller marker. +- `sce setup` installs these hooks at a repository root, so the project directory resolves to a Git directory in supported installs. +- `transcript_path` was rejected as an anchor: it is a per-user Claude-internal location, not an SCE-owned path. +- No separate per-user routing location is needed, because the project Git dir resolved consistently. + +**Fallback policy (decisions 3 and 7).** If `CLAUDE_PROJECT_DIR` is unset or blank, or does not resolve to a Git directory: +- A tracked `PreToolUse` fails closed with a deny decision and a logged diagnostic. This matches the existing behavior when `resolve_git_dir` fails. +- Terminal events log the unresolved condition and never fall back to the event `cwd` for routed attempts. +- Only legacy attempts created before routing, which have no route-era marker, may use today's `cwd`-local lookup. This is a documented backward-compatibility limitation for scopes started before the upgrade. + +**Not probed live.** +- A `CLAUDE_PROJECT_DIR` inside a linked worktree. `--absolute-git-dir` returns the per-worktree directory, which is still stable for one session. +- A `cwd` outside every repository. The anchor does not depend on `cwd`. + +T03/AC7 cover both cases with real Git fixtures. + +## Acceptance criteria + +- [x] **AC1 — Proven anchor:** A real two-repository Claude hook probe confirms a consistent route lookup anchor across `PreToolUse` and `PostToolUse`, and records the selected anchor and fallback policy. +- [x] **AC2 — Original target:** A `Start` in repository A followed by `PostToolUse` with `cwd` in nested repository B closes the exact attempt in A; no attempt or mutation boundary is created in B. +- [x] **AC3 — Multiple target repositories:** One parent session concurrently starts tools in A and B, with distinct keys and routes. Reversed-order completions close only their own attempts. Main-agent/subagent identity collisions do not cross-route. +- [x] **AC4 — Terminal parity:** `PostToolUseFailure`, `PermissionDenied`, session/agent cleanup, and worktree removal use the original route and preserve existing abandonment and recovery semantics. +- [x] **AC5 — Crash safety:** Inject failures before/after route write, attempt allocation, Start, Close, and route removal. No tracked tool is allowed without a recoverable route; no uncertain scope is incorrectly closed or abandoned. +- [x] **AC6 — Idempotency:** Duplicate terminal events, duplicate `PreToolUse`, a reused `tool_use_id` after terminal completion, and concurrent hook processes do not cross-route or reactivate a terminal `ScopeId`. +- [x] **AC7 — Non-repository `cwd`:** If the post-hook `cwd` is outside every Git repository, an existing route still closes the original attempt; a missing route never closes an unrelated scope. +- [x] **AC8 — Protocol unchanged:** No modifications to `spec/mutation_cursor.qnt`, `cli/src/services/mutation_trace/protocol.rs`, generic ingress, or migrations; existing Quint and mutation-scope tests remain green. +- [x] **AC9 — Live rerun:** Run an isolated Claude session with A containing nested B, establish a tool's scope in A, change `cwd` to B before completion, and show the original scope becomes `Closed`. Confirm route cleanup, no unexpected `Active` scopes, and correct worktree-specific mutation events. + +## Task stack + +- [x] **T01: Verify and document the stable Claude hook lookup anchor** (status:done) + - Scope: read-only probe of hook `cwd`, `CLAUDE_PROJECT_DIR`, session ID, agent ID, tool-use ID, and transcript-path *location* (not contents); inspect generated hook commands. Record paths and stable identity in this plan. + - Done when: AC1 holds and the durable routing location is justified. + - Completed: 2026-11-24 + - Files changed: `context/plans/claude-mutation-scope-stable-repository-routing.md` + - Result: A real Claude Code 2.1.309 probe (see **T01 anchor probe findings**) reproduced the defect on a single `tool_use_id` (`PreToolUse` `cwd` = A, `PostToolUse` `cwd` = nested B). It showed that `CLAUDE_PROJECT_DIR` and its resolved Git directory stayed the same in all 19 hook events, including the subagent events. Selected anchor: `git rev-parse --absolute-git-dir` of `CLAUDE_PROJECT_DIR`. Route file: `/sce/claude-mutation-scope-routes.json`. Fallback: fail closed, with no `cwd` fallback. + - Verify: Probe log passed: 8 `PreToolUse`/`PostToolUse` pairs matched by `tool_use_id`; `CLAUDE_PROJECT_DIR` = `$S/repoA` and the project Git dir = `$S/repoA/.git` in every event; `cwd` moved A → B on the `cd nestedB` tool. Plan diff reviewed: passed. + - Context impact: none. The decision is recorded only in this plan. Durable context changes are deferred to T04 (`context/cli/claude-mutation-scope-integration.md`). + - Context synchronization: synced + +- [x] **T02: Add minimal durable route storage with atomic/idempotent semantics** (status:done) + - Scope: one Claude-only routing module; a bounded route record keyed by the exact attempt identity; existing lock/rename conventions; no generic routing framework. + - Dependencies: T01 + - Done when: route recovery and failure-injection tests cover AC5/AC6. + - Completed: 2026-11-24 + - Files changed: `cli/src/services/hooks/claude_mutation_scope/routes.rs` (new), `cli/src/services/hooks/claude_mutation_scope/mod.rs`, `context/plans/claude-mutation-scope-stable-repository-routing.md` + - Result: Added the Claude-only `routes` module. It stores a versioned route table at `/sce/claude-mutation-scope-routes.json`, protected by its own `claude-mutation-scope-routes.lock` (`AdapterLockSpec::state`). Writes use the `state.rs` temp-file, `sync_data`, rename, and directory-sync convention. Each `RouteRecord` is keyed by the full `AttemptKey` and stores a `RouteTarget` (`checkout_path`, `git_dir`). The module provides these operations: + - `persist_route` returns `Inserted`, `AlreadyRouted`, or `Conflict { existing }`. It never retargets a live route. + - `load_route` looks up one route by exact key. + - `routes_for_session` lists the routes of one session. + - `remove_route` returns `Removed`, `Absent`, or `TargetMismatch`. It removes a route only while the route still points at the expected target. + - `resolve_route_anchor` resolves `CLAUDE_PROJECT_DIR` to its Git directory. It returns a typed `RouteAnchorError` (`ProjectDirUnset`, `Unresolvable`) and never falls back to `cwd`. + + A malformed table or an unsupported version fails closed and is never overwritten. The module is not wired into `lifecycle.rs` yet (T03), so `mod routes` carries `#[allow(dead_code)]`. Assumption: I/O errors use `anyhow`, matching the sibling `state.rs`. + - Verify: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_mutation_scope` passed (21 tests, including 17 new route tests). The new tests cover: + - recovery by a fresh read from disk + - an injected failure before rename on persist, which leaves no route, keeps prior routes, and still allows a retry over the leftover `.tmp` file + - an injected failure on removal, which keeps the route recoverable + - idempotent duplicate persist and duplicate removal + - refused retargeting + - a reused `tool_use_id` after removal, plus a stale removal reporting `TargetMismatch` + - main-agent, subagent, and other-session key isolation + - 16 concurrent distinct writers with no lost updates, and 16 concurrent duplicate writers inserting exactly once + - a malformed or future-version table failing closed + - anchor errors, and a real nested-Git anchor resolving to the project repository, not the nested one + + `nix develop -c ./scripts/run-cli-cargo.sh clippy --manifest-path cli/Cargo.toml --all-targets -- -D warnings` passed. `cargo fmt --check` passed. + - Context impact: local. The new module is internal to the Claude adapter and has no runtime behavior yet. The durable context update is deferred to T04 (`context/cli/claude-mutation-scope-integration.md`) after T03 wires the module in. + - Context synchronization: synced + +- [x] **T03: Route Claude mutation lifecycle through the original checkout** (status:done) + - Scope: integrate PreToolUse, PostToolUse/Failure, PermissionDenied and session/agent/worktree cleanup into the existing lifecycle. Keep the local adapter's `AttemptKey` and existing runtime seam. + - Dependencies: T02 + - Done when: AC2/AC3/AC4/AC7 hold with real nested Git repositories. + - Completed: 2026-11-24 + - Files changed: `cli/src/services/hooks/claude_mutation_scope/lifecycle.rs`, `cli/src/services/hooks/claude_mutation_scope/lifecycle_tests.rs` (new), `cli/src/services/hooks/claude_mutation_scope/state.rs`, `cli/src/services/hooks/claude_mutation_scope/mod.rs`, `context/plans/claude-mutation-scope-stable-repository-routing.md` + - Result: `lifecycle.rs` now routes every tracked tool execution through the T02 route store: + - `PreToolUse` resolves the anchor from `CLAUDE_PROJECT_DIR` and denies (fail closed) if the anchor cannot be resolved. It then resolves the target from `cwd` and runs the recovery barrier. It persists the route after the barrier and before attempt allocation. A route `Conflict` or a persist failure denies the tool. + - `PostToolUse`, `PostToolUseFailure`, and `PermissionDenied` load the route by the full `AttemptKey` and finish the attempt in the route's `git_dir` and checkout path. The route is retired only after the attempt is gone from the original state. A route without an attempt is retired without any seam call. + - `Stop`, `StopFailure`, `UserPromptSubmit`, `SubagentStop`, and `SessionEnd` group the session's known routes, filtered by agent, by target. They then run the existing `cleanup_attempts_matching` once per target and retire routes whose attempts are gone. Errors on one target do not stop the other targets. + - `WorktreeRemove` keeps its event-provided worktree cleanup. It also retires the session's routes into that worktree, either by `git_dir` or by a checkout path under the worktree, and only when no attempt remains. + - `AdapterAttempt` gains `routed` (`#[serde(default)]`). New attempts are `routed: true`. Older state files load as `routed: false`, and only those attempts may still be found through the event `cwd`. An unresolvable anchor or route table on a terminal event is logged as `sce.hooks.claude_mutation_scope.route_unresolved` and never falls back to `cwd` for routed attempts. + - In the legacy path, a `cwd` outside every repository is now a no-op instead of an error. + - `handle_close` and `handle_permission_denied` are folded into `close_attempt`/`finish_attempt`, and the `routes` module no longer needs `#[allow(dead_code)]`. Protocol, ingress, migrations, and Quint are unchanged. + - Verify: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_mutation_scope` passed: 30 tests, including 9 new lifecycle tests on real `git init` repositories A, nested B, and a linked worktree, plus an outside-of-repository directory. The new tests cover: + - AC2: close in A from B, with no B state and the route retired + - AC3: A/B plus a subagent that reuses the same `tool_use_id`, completed in reverse order with `cwd`s swapped + - AC4: `PostToolUseFailure`/`PermissionDenied` through the route with `recovery_pending` preserved; `Stop` retiring only the main agent and `SubagentStop` from outside the repository retiring the subagent; a failed abandon keeping the route until `SessionEnd` retries; `WorktreeRemove` retiring only worktree routes + - AC7: close from an outside `cwd`; a lost route never closing a routed attempt while a seeded legacy attempt (no `routed` field) still closes through `cwd` + - anchor unset or outside a repository denying before any start + + `nix develop -c ./scripts/run-cli-cargo.sh clippy --manifest-path cli/Cargo.toml --all-targets -- -D warnings` passed. `cargo fmt --check` passed. + - Assumptions and limits: + - The route stored the raw `PreToolUse` `cwd` as the checkout path. T05 replaced this with the canonical worktree root. + - A same-key race is accepted: a `PreToolUse` for the same `tool_use_id` arriving between a terminal event's attempt check and its route removal could leave that attempt unrouted. Claude does not reuse a live `tool_use_id` concurrently. + - A route left by a start that failed after persistence is retired by the next terminal or cleanup event for that key. + - Context impact: important. Claude adapter routing behavior changed: the anchor requirement for `PreToolUse`, route-based terminal and cleanup handling, the legacy `routed` marker, and the new `route_unresolved` log event. The durable update to `context/cli/claude-mutation-scope-integration.md` and `context/cli/claude-mutation-scope-routes.md` is needed. + - Context synchronization: synced + +- [x] **T04: Validate, synchronize context, and rerun the live experiment** (status:done) + - Scope: focused Rust tests through `nix develop -c ./scripts/run-cli-cargo.sh`, existing mutation-scope and Quint checks, and read-only validation of the isolated Agent Trace database. Update `context/cli/claude-mutation-scope-integration.md` and any directly affected current-state docs. + - Dependencies: T03 + - Done when: AC8/AC9 hold; report unresolved recovery limits and measured hook overhead. + - Completed: 2026-11-24 + - Files changed: `cli/src/services/hooks/claude_mutation_scope/lifecycle_tests.rs`, `context/plans/claude-mutation-scope-stable-repository-routing.md` + - Result: Validation and the live rerun passed. One test-only fix was needed: `worktree_remove_retires_routes_into_the_removed_worktree_only` committed in a fixture repository without a commit identity, so it failed in the `nix flake check` sandbox (no global Git config). The test now sets a local `user.name`/`user.email`, following the convention in `mutation_trace/runtime` tests. No production code changed. + - **AC8.** `git diff 6cc73fe3..HEAD` (merge base with `main`) touches no file in `spec/`, `cli/src/services/mutation_trace/`, `cli/src/services/hooks/mutation_scope*.rs`, or `cli/migrations/`. All changed code is under `cli/src/services/hooks/claude_mutation_scope/`. + - **AC9 live rerun.** Disposable repository A contained nested Git repository B (ignored by A). Both were set up with `sce setup --claude --hooks` from a `sce` binary built from this branch, with an isolated `XDG_STATE_HOME`, `.invalid` remotes, and no sync. One `claude -p --setting-sources project` session (Claude Code 2.1.309) ran from A and made four Bash calls: (1) `echo one > a2.txt`; (2) `cd nestedB && echo two > b2.txt && cp ../.git/sce/claude-mutation-scope-routes.json ../route-snapshot.json`; (3) `echo three > b3.txt`; (4) `cd .. && echo four > a3.txt`. Tool 2 had `PreToolUse` `cwd` = A and `PostToolUse` `cwd` = B. Tool 4 had the reverse. The copy made while tool 2 was running showed its route (key `toolu_…WVtwKNA9` → `checkout_path` A, `git_dir` A/.git). After the session, A's Agent Trace DB had scopes `…rv8bBvvd` and `…WVtwKNA9`, both `closed`, with `close` events at revisions 2 and 4 attributed `ai_exclusive` to their own scope. B's DB had scopes `…6m1u2oib` and `…68wwUZNi`, both `closed`, with one `close` event attributed to `…6m1u2oib`. No scope was `active` in either DB. Both worktrees were untainted, with `needs_rebaseline = 0`. The route table in A was `{"routes": []}`. Both adapter state files had `attempts: []` and `recovery_pending: false`. Every hook exited 0 and returned empty stdout. + - **Pre-routing contrast.** An earlier attempt in the same setup by mistake used a stale `sce` binary built before T03 (2026-11-20). It reproduced the defect: tool 4's attempt stayed `active` in B's adapter state after `Stop` and `SessionEnd`, A was left with `recovery_pending: true`, and no route file existed. + - **Hook overhead.** A synthetic benchmark measured a debug build: 15 `PreToolUse`/`PostToolUse` pairs per round, each with a one-file mutation, in two rounds, comparing the pre-T03 binary with this branch. Median `PreToolUse` rose from 174–182 ms to 189–197 ms, about +15 ms. Median `PostToolUse` rose from 125–136 ms to 148–165 ms, about +23 to +29 ms. The extra cost is the anchor `git rev-parse` plus one locked, fsynced route-table write on each side. In the benchmark, all 15 scopes ended `closed` and no routes remained. Live-session timings (Pre median 891 ms) were inflated by cold page-in of the 560 MB debug binary and are not used as the overhead figure. + - Verify: + - `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml` passed: 880 tests, including the `mutation_trace::mbt` Quint connect tests and 51 `mutation_scope` tests. + - `nix develop -c ./scripts/run-cli-cargo.sh clippy --manifest-path cli/Cargo.toml --all-targets -- -D warnings` passed. + - `cargo fmt --check` passed. + - `nix flake check` failed on the first run (the sandboxed `cli-tests` fixture identity failure described above). It passed after the fix ("all checks passed!"). + - `nix run .#pkl-check-generated` passed (157 files). + - Live rerun and benchmark evidence as above. + - Unresolved recovery limits: + - A legacy attempt (no `routed` marker) whose `cwd` changed before completion is still orphaned. + - The T03 same-key race between a terminal event's attempt check and its route removal is accepted. + - A route left by a start that failed after the route was persisted is retired only by a later terminal or cleanup event for that session. If Claude exits without any such event, the route stays as inert bookkeeping. + - A tool started in B that mutates A, like live tool 4, is attributed to B's scope boundary only. A's change is unscoped in A until A's next boundary. This is by design: a scope binds to its `PreToolUse` checkout (non-goal: no retargeting). + - Observed outside the task scope: commit `a0918726` tracks a stray log file, `.claude/skills/sce-next-task/context/tmp/sce-24_11_2026.log`. + - Context impact: important. Facts to record in current-state context: live validation of the routing behavior, the measured hook overhead, and the remaining recovery limits. + - Context synchronization: synced + +- [x] **T05: Address PR #359 review findings** (status:done) + - Scope: persist the canonical worktree root in routes, propagate route-table directory-sync errors, and remove the tracked temporary log. No change to the Quint spec, mutation protocol, database schema, route-table format, or locking. + - Dependencies: T04 + - Completed: 2026-11-24 + - Files changed: `cli/src/services/hooks/claude_mutation_scope/lifecycle.rs`, `cli/src/services/hooks/claude_mutation_scope/lifecycle_tests.rs`, `cli/src/services/hooks/claude_mutation_scope/routes.rs`, `cli/src/services/mutation_trace/runtime/mod.rs` (re-export only), `.gitignore`, `.claude/skills/sce-next-task/context/tmp/sce-24_11_2026.log` (deleted), `context/cli/claude-mutation-scope-routes.md`, `context/cli/claude-mutation-scope-integration.md`, this plan + - Result: + - **Canonical worktree root.** `PreToolUse` now resolves the canonical worktree root of `cwd` with the existing `resolve_worktree_root` (`git rev-parse --show-toplevel`, canonicalized). It then resolves the Git directory from that root, so both route fields describe one checkout, including linked worktrees and nested repositories. The root is used for the recovery barrier, the route, and `Start`. Terminal events already use the route's `checkout_path`. A root that cannot be resolved denies the tool. Legacy (`routed: false`) lookups still use the event `cwd`. + - **Route sync errors.** On Unix, a failure to open the route directory or to `sync_all` it after the rename now fails the write, with the directory path in the error. `PreToolUse` then denies the tool. The rename has already happened, so the route can stay visible. A same-key, same-target replay (`AlreadyRouted`) syncs the directory again before it reports success. The visible route has no attempt, so the next terminal or cleanup event of the session retires it. Non-Unix builds keep the existing no-directory-sync behavior. + - **Temporary artifacts.** The tracked log was removed and `.claude/skills/sce-next-task/context/tmp/` was added to the root `.gitignore`. + - Test harness paths are canonicalized, because the seam now receives the canonical root. + - Verify: + - New tests: `pre_tool_use_in_a_removed_subdirectory_closes_through_the_canonical_worktree_root`, `an_unsyncable_route_directory_denies_pre_tool_use_and_the_visible_route_is_retired`, and `directory_sync_failure_after_rename_surfaces_and_a_retry_confirms_the_route`. The two sync-failure tests are Unix-only. They skip themselves when the process can open a mode-`0300` directory (for example, as root). + - Commands and results are in the Validation Report. + - Context impact: important. The route target and route durability behavior changed. `context/cli/claude-mutation-scope-routes.md` and `context/cli/claude-mutation-scope-integration.md` were updated. + - Context synchronization: synced + +## Non-goals + +- General cross-harness repository router, registry service, background sweeper, or repository scan. +- Changes to ClickHouse, control-plane, S3, event-DWH, commit-time model attribution, or PR #358. +- Reassigning an existing scope to a new repository when the current working directory changes. +- Guessing a missing route from the newest transcript entry or whichever checkout contains a similarly named tool. +- Modifying the Quint state machine simply to represent an adapter lookup bug. + +## Validation and release + +A correct route must survive separate hook processes and process restart. Synthetic tests without real Git boundaries are insufficient. Run focused adapter, state, and runtime integration tests plus `nix flake check` and `nix run .#pkl-check-generated` after implementation; test only through the repository's Cargo/Nix wrapper. The final live experiment must use disposable repositories and must not sync production data. + +This PR starts as a plan-only draft. Do not claim that the dangling-scope defect is repaired until T02–T04 have landed and AC9 is observed. + +## Validation Report + +**Status:** validated (revalidated after T05) +**Date:** 2026-11-24 + +### Commands run + +- `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_mutation_scope` -> exit 0 (39 passed, 0 failed) +- `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml sync` -> exit 0 (both new directory-sync failure tests ran and passed as uid 1000, not skipped) +- `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml` -> exit 0 (920 passed, 0 failed; includes `mutation_trace::mbt` Quint connect tests) +- `nix develop -c ./scripts/run-cli-cargo.sh clippy --manifest-path cli/Cargo.toml --all-targets -- -D warnings` -> exit 0 (no warnings) +- `nix develop -c ./scripts/run-cli-cargo.sh fmt --manifest-path cli/Cargo.toml --check` -> exit 0 (after applying `rustfmt` to the new tests) +- `nix flake check` -> exit 0 ("all checks passed!"; `cli-tests`, `cli-clippy`, `cli-fmt`, package, and setup-schema checks) +- `git diff --stat 967d27d1 -- spec cli/src/services/mutation_trace cli/migrations 'cli/src/services/hooks/mutation_scope*'` -> only `cli/src/services/mutation_trace/runtime/mod.rs` (+3/-1: re-export of the existing `resolve_worktree_root`) +- `git ls-files | grep -E '\.log$|context/tmp/'` -> only `context/tmp/.gitignore` +- `git check-ignore -v .claude/skills/sce-next-task/context/tmp/x.log` -> matched by `.gitignore` + +The T04 run of `nix run .#pkl-check-generated` (157 files) was not repeated. T05 changes no Pkl source or generated file. + +### Success-criteria verification + +- [x] AC1: Proven anchor -> T01 live probe evidence recorded in **T01 anchor probe findings** (`CLAUDE_PROJECT_DIR` and its Git dir stable across all 19 events); anchor and fallback policy documented. +- [x] AC2: Original target -> `post_tool_use_from_a_nested_repository_closes_the_attempt_in_the_original_repository` and `pre_tool_use_in_a_removed_subdirectory_closes_through_the_canonical_worktree_root` passed on real Git repositories. +- [x] AC3: Multiple target repositories -> `concurrent_tools_in_two_repositories_close_only_their_own_attempts_in_reverse_order` and `main_agent_and_subagent_with_the_same_tool_use_id_do_not_share_a_route` passed. +- [x] AC4: Terminal parity -> `failure_and_permission_denial_terminate_through_the_original_route`, `stop_and_subagent_stop_retire_only_their_own_routed_attempts`, `failed_abandon_keeps_the_route_so_session_end_can_retry`, `worktree_remove_retires_routes_into_the_removed_worktree_only` passed. +- [x] AC5: Crash safety -> Partially evidenced; the rest was accepted by user decision (2026-11-24). Route write, route removal, post-rename directory-sync failure, and failed abandon are tested. `an_unsyncable_route_directory_denies_pre_tool_use_and_the_visible_route_is_retired` covers a route-persist failure during `PreToolUse` at lifecycle level. No lifecycle test injects failure after attempt allocation, on seam `Start`, or on `Close`. +- [x] AC6: Idempotency -> Accepted by user decision (2026-11-24) with route-store evidence: duplicate persist/removal, reused `tool_use_id`, concurrent writers, and a same-key retry after a directory-sync failure. +- [x] AC7: Non-repository `cwd` -> `post_tool_use_outside_every_repository_still_closes_through_the_route` and `a_missing_route_never_closes_a_routed_attempt_but_legacy_attempts_close_by_cwd` passed. +- [x] AC8: Protocol unchanged -> no change in `spec/`, `cli/src/services/mutation_trace/protocol.rs`, generic ingress, or `cli/migrations/`. The only `mutation_trace` change is a one-line re-export of an existing runtime function. The full suite including Quint MBT tests passed. +- [x] AC9: Live rerun -> T04 recorded live Claude Code 2.1.309 rerun evidence: both scopes in A `closed`, no `active` scopes in A or B, route table empty, adapter states clean. It was not repeated after T05. In that run, every `PreToolUse` `cwd` was already a repository root, so T05 does not change the observed target. + +### Failed checks and follow-ups + +- None locally. On GitHub, the `Nix CI (macos-latest)` job for the pre-T05 head `54b84501` was cancelled after 15 minutes without a runner (no steps ran). This was not a test failure. + +### Residual risks + +- AC5/AC6 lifecycle behavior beyond route persistence is accepted by user decision without direct lifecycle test evidence. +- A legacy attempt (no `routed` marker) whose `cwd` changed before completion is still orphaned. +- Accepted same-key race between a terminal event's attempt check and its route removal. +- A route left visible by a failed start or a post-rename sync failure stays as inert bookkeeping if Claude exits without a later terminal or cleanup event. +- Adapter state writes in `state.rs` still treat the directory sync as best-effort. T05 changed only the route store. +- On non-Unix platforms the route store does not sync the directory, as before.