locode_host/lib.rs
1//! locode-host — the one place the system touches the OS (ADR-0008).
2//!
3//! Every side effect funnels through the [`Host`]: a path jail, shell execution with a
4//! timeout + output cap, jailed filesystem helpers, and the shared
5//! post-processes. Tools never call `std::fs`/`Command` directly —
6//! they go through a `Host`. This crate is a *sibling* of `locode-tools`, so it defines
7//! its own plain error types; the harness pack (which depends on both) maps them to
8//! `ToolError::Respond`.
9
10mod fs;
11mod home;
12mod path;
13mod rg;
14mod root;
15mod session_dirs;
16mod settings;
17mod shell;
18mod trace;
19mod walk;
20
21pub use fs::{DirEntry, FileRead, FileStat, FsError};
22pub use home::{default_locode_home, locode_home, resolve_home_from};
23pub use path::PathError;
24pub use rg::rg_program;
25pub use root::find_root_from_markers;
26pub use session_dirs::{decode_cwd_dirname, encode_cwd_dirname};
27pub use settings::{
28 Settings, SettingsLoad, SkillsExtraEntry, load_settings, load_settings_from,
29 update_user_setting,
30};
31pub use shell::{
32 ExecError, ExecOutput, ExecRequest, FrontBackCapture, FrontBackSpec, SPILL_RETAIN_MAX,
33 ShellSpec,
34};
35pub use trace::{
36 GitMeta, RolloutContents, SessionMeta, TRACE_SCHEMA_VERSION, TraceExtras, TraceWriter,
37 find_latest_rollout, find_rollout_by_id, read_rollout,
38};
39pub use walk::{WalkEntry, WalkOptions};
40
41use std::path::{Path, PathBuf};
42use std::time::Duration;
43
44/// Whether the filesystem tools are jailed to the workspace root (ADR-0008 amendment).
45///
46/// The jail is the **default** posture, not a hard wall — every studied harness offers a
47/// full-access mode, and since we are headless (no permission prompt) a caller must be
48/// able to opt out (`--dangerously-skip-permissions` / `--yolo`). The shell tool is never
49/// path-jailed regardless; only the structured FS tools consult this.
50#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
51pub enum PathPolicy {
52 /// Resolve FS-tool paths under `workspace_root`; reject `..`/absolute/symlink escapes.
53 #[default]
54 Jailed,
55 /// Resolve relative paths against `cwd`, allow absolute / out-of-root paths (the
56 /// `--dangerously-skip-permissions` / `--yolo` behavior).
57 Unrestricted,
58}
59
60/// Limits on shell execution. Defaults mirror Grok Build (the primary model).
61#[derive(Debug, Clone)]
62pub struct ExecLimits {
63 /// Timeout used when a call passes none (grok/codex default = 10s).
64 pub default_timeout: Duration,
65 /// Hard ceiling; a caller-supplied timeout is clamped to this.
66 pub max_timeout: Duration,
67 /// Max retained output bytes per stream before truncation (grok = `30_000`).
68 pub max_output_bytes: usize,
69 /// Grace between `SIGTERM` and `SIGKILL` when killing a timed-out/cancelled command.
70 pub kill_grace: Duration,
71}
72
73impl Default for ExecLimits {
74 fn default() -> Self {
75 Self {
76 default_timeout: Duration::from_secs(10),
77 max_timeout: Duration::from_mins(10),
78 max_output_bytes: 30_000,
79 kill_grace: Duration::from_secs(2),
80 }
81 }
82}
83
84/// Construction-time configuration for a [`Host`].
85#[derive(Debug, Clone)]
86pub struct HostConfig {
87 /// The path-jail root (canonicalized at [`Host::new`]).
88 pub workspace_root: PathBuf,
89 /// Additional jail roots (`--add-dir`), canonicalized at [`Host::new`].
90 ///
91 /// A jailed path is accepted when it resolves under `workspace_root` **or** any
92 /// of these. Empty by default — the jail stays single-rooted unless a caller
93 /// explicitly widens it (ADR-0008 amendment 2026-07-25).
94 pub extra_roots: Vec<PathBuf>,
95 /// Whether FS tools are jailed to `workspace_root` (default [`PathPolicy::Jailed`]).
96 pub path_policy: PathPolicy,
97 /// Shell execution limits.
98 pub exec: ExecLimits,
99 /// The shell program to run commands through (default `bash`). A configurable field
100 /// so a later pack / shell-detection can override it.
101 pub shell_program: String,
102 /// Run the shell as a login shell (`-lc`, loads the user's profile/RC — matches all
103 /// four studied harnesses) rather than `-c`. Default `true`.
104 pub login_shell: bool,
105}
106
107impl HostConfig {
108 /// A config for `workspace_root` with all defaults (jailed, `bash -lc`, grok limits).
109 pub fn new(workspace_root: impl Into<PathBuf>) -> Self {
110 Self {
111 workspace_root: workspace_root.into(),
112 extra_roots: Vec::new(),
113 path_policy: PathPolicy::default(),
114 exec: ExecLimits::default(),
115 shell_program: "bash".to_string(),
116 login_shell: true,
117 }
118 }
119}
120
121/// The injectable side-effect seam (ADR-0008). Construct once per session, share behind
122/// an `Arc`; holds the jail root + policy and the exec/truncation limits.
123#[derive(Debug, Clone)]
124pub struct Host {
125 pub(crate) workspace_root: PathBuf,
126 /// Extra jail roots. Behind a lock because `/add-dir` widens the jail on a
127 /// **running** session: tools already hold `Arc<Host>`, so the alternative
128 /// is rebuilding the session — which would discard the conversation. Claude
129 /// Code keeps its `additionalWorkingDirectories` mutable for the same
130 /// reason. Shared across clones, so every tool sees one list.
131 pub(crate) extra_roots: std::sync::Arc<std::sync::RwLock<Vec<PathBuf>>>,
132 /// Every jail root in its **as-given** (lexically normalized, not
133 /// symlink-resolved) form. macOS `/var` → `/private/var` is the everyday
134 /// case, and a monorepo reached through a symlinked path is the one that
135 /// matters: without this the lexical pre-check rejects an absolute path the
136 /// canonical check would then have accepted. Claude Code checks the same
137 /// two forms (`permissions/filesystem.ts:688`). The canonical lists above
138 /// remain the authoritative gate.
139 pub(crate) roots_as_given: std::sync::Arc<std::sync::RwLock<Vec<PathBuf>>>,
140 pub(crate) path_policy: PathPolicy,
141 pub(crate) limits: ExecLimits,
142 pub(crate) shell_program: String,
143 pub(crate) login_shell: bool,
144 /// Lazily-built workspace gitignore matcher (Task 26 Slice 0).
145 pub(crate) gitignore: walk::GitignoreCache,
146 /// Once-probed login-shell PATH (Task 26 Slice 0b; grok's PATH probe).
147 pub(crate) login_path: std::sync::Arc<tokio::sync::OnceCell<Option<String>>>,
148}
149
150impl Host {
151 /// Widen the jail with another root at runtime (`/add-dir`).
152 ///
153 /// Returns the canonicalized root on success. Both forms are recorded, for
154 /// the same reason [`Host::new`] records both: a root behind a symlink must
155 /// still satisfy the lexical pre-check. Adding an already-present root is a
156 /// no-op rather than an error, so repeating the command is harmless.
157 ///
158 /// # Errors
159 /// [`PathError::InvalidRoot`] when `dir` does not exist or cannot be
160 /// canonicalized — the jail is left untouched.
161 pub fn add_root(&self, dir: &Path) -> Result<PathBuf, PathError> {
162 let canonical = std::fs::canonicalize(dir)
163 .map_err(|e| PathError::InvalidRoot(format!("{}: {e}", dir.display())))?;
164 let mut roots = self
165 .extra_roots
166 .write()
167 .unwrap_or_else(std::sync::PoisonError::into_inner);
168 if !roots.contains(&canonical) {
169 roots.push(canonical.clone());
170 }
171 drop(roots);
172 let mut as_given = self
173 .roots_as_given
174 .write()
175 .unwrap_or_else(std::sync::PoisonError::into_inner);
176 let lexical = crate::path::normalize_lexical_pub(dir);
177 if !as_given.contains(&lexical) {
178 as_given.push(lexical);
179 }
180 Ok(canonical)
181 }
182
183 /// Build a host, canonicalizing `workspace_root` (the jail root must be a real,
184 /// symlink-resolved absolute path).
185 ///
186 /// # Errors
187 /// [`PathError::InvalidRoot`] if `workspace_root` does not exist or cannot be
188 /// canonicalized.
189 pub fn new(config: HostConfig) -> Result<Self, PathError> {
190 let workspace_root = std::fs::canonicalize(&config.workspace_root).map_err(|e| {
191 PathError::InvalidRoot(format!("{}: {e}", config.workspace_root.display()))
192 })?;
193 // Every extra root must exist too — a typo'd `--add-dir` should fail loudly
194 // at startup, not silently narrow the jail back to one root.
195 let extra_roots = config
196 .extra_roots
197 .iter()
198 .map(|dir| {
199 std::fs::canonicalize(dir)
200 .map_err(|e| PathError::InvalidRoot(format!("{}: {e}", dir.display())))
201 })
202 .collect::<Result<Vec<_>, _>>()?;
203 let roots_as_given = std::iter::once(&config.workspace_root)
204 .chain(config.extra_roots.iter())
205 .map(|p| crate::path::normalize_lexical_pub(p))
206 .collect();
207 Ok(Self {
208 workspace_root,
209 extra_roots: std::sync::Arc::new(std::sync::RwLock::new(extra_roots)),
210 roots_as_given: std::sync::Arc::new(std::sync::RwLock::new(roots_as_given)),
211 path_policy: config.path_policy,
212 limits: config.exec,
213 shell_program: config.shell_program,
214 login_shell: config.login_shell,
215 gitignore: walk::GitignoreCache::new(),
216 login_path: std::sync::Arc::new(tokio::sync::OnceCell::new()),
217 })
218 }
219
220 /// The canonicalized jail root.
221 #[must_use]
222 pub fn workspace_root(&self) -> &Path {
223 &self.workspace_root
224 }
225
226 /// The active path policy.
227 #[must_use]
228 pub fn path_policy(&self) -> PathPolicy {
229 self.path_policy
230 }
231
232 /// The shell execution limits.
233 #[must_use]
234 pub fn limits(&self) -> &ExecLimits {
235 &self.limits
236 }
237}
238
239#[cfg(test)]
240pub(crate) fn test_host(root: &Path, policy: PathPolicy, login: bool) -> Host {
241 let mut config = HostConfig::new(root);
242 config.path_policy = policy;
243 config.login_shell = login;
244 Host::new(config).expect("test host")
245}