safe_chains/pathctx.rs
1//! The directory context the harness supplies (HP-19): the working directory a command
2//! runs in, and the project root. It exists to make relative-path classification honest —
3//! `cd /etc && echo > ./x` must be seen as writing `/etc/x`, not a worktree file.
4//!
5//! The context is **ambient** for one command evaluation: a single `cwd`/`root` pair threads
6//! logically through the whole recursive verdict tree (script → pipeline → cmd → redirect →
7//! leaf). Rather than add a pass-through parameter to ~15 recursive functions across `cst`,
8//! `handlers`, and `engine`, it lives in a scoped thread-local, installed by
9//! [`enter`] at the top of an evaluation and read at exactly two leaves: legacy
10//! `is_safe_write_target` and engine `classify_locus`, both via [`resolve`].
11//!
12//! Everything is fail-open to *today's* behavior: with no `cwd`/`root` (or an unresolvable
13//! path) [`resolve`] returns the path unchanged, so the classifiers behave exactly as before
14//! — the signal tightens when present, never a regression when absent.
15
16use std::borrow::Cow;
17use std::cell::RefCell;
18
19/// The working directory and project root for the command under evaluation. Both optional:
20/// a harness may supply neither (e.g. opencode), and classification falls back to the
21/// relative-is-worktree assumption.
22#[derive(Clone, Default)]
23pub struct PathCtx {
24 pub cwd: Option<String>,
25 pub root: Option<String>,
26 /// The harness's session id, when it supplies one. Only used to recognize this session's
27 /// SCRATCHPAD — see [`in_session_scratchpad`].
28 pub session_id: Option<String>,
29}
30
31thread_local! {
32 static CURRENT: RefCell<PathCtx> = RefCell::new(PathCtx::default());
33}
34
35/// Install `ctx` as the ambient context for the duration of the returned guard; the previous
36/// context is restored on drop (panic-safe, so a failing test can't leak into the next).
37#[must_use]
38pub fn enter(ctx: PathCtx) -> Guard {
39 Guard(CURRENT.with(|c| c.replace(ctx)))
40}
41
42/// Restores the previous [`PathCtx`] when dropped.
43pub struct Guard(PathCtx);
44
45impl Drop for Guard {
46 fn drop(&mut self) {
47 CURRENT.with(|c| *c.borrow_mut() = std::mem::take(&mut self.0));
48 }
49}
50
51/// Run `f` with the ambient `cwd` temporarily replaced (root unchanged) — used by intra-line
52/// `cd` tracking as it walks a chain's statements. Restored on drop.
53#[must_use]
54pub fn enter_cwd(cwd: Option<String>) -> Guard {
55 Guard(CURRENT.with(|c| {
56 let mut b = c.borrow_mut();
57 // `session_id` is carried through unchanged: a `cd` mid-chain must not drop scratchpad
58 // recognition (the session is the same session whatever directory it walks into).
59 PathCtx { cwd: std::mem::replace(&mut b.cwd, cwd), root: b.root.clone(), session_id: b.session_id.clone() }
60 }))
61}
62
63/// The ambient working directory, if known.
64pub fn cwd() -> Option<String> {
65 CURRENT.with(|c| c.borrow().cwd.clone())
66}
67
68/// The workspace ROOT (project dir), if known — falling back to `cwd` (the hook defaults root to
69/// cwd). Used by the adjacent-sibling classifier to find the workspace's parent.
70pub fn root() -> Option<String> {
71 CURRENT.with(|c| {
72 let b = c.borrow();
73 b.root.clone().or_else(|| b.cwd.clone())
74 })
75}
76
77/// Whether `path` lies inside THIS session's scratchpad — the harness's own per-session working
78/// directory (e.g. Claude Code's `/private/tmp/claude-<uid>/<project-slug>/<session-id>/scratchpad`).
79///
80/// The anchor is the **session id as a whole path component**, not the surrounding layout. That is
81/// deliberate and is what makes this safe *and* durable:
82///
83/// - **Unforgeable.** The session id arrives in the harness's own hook envelope, never from the
84/// agent's shell. An attacker cannot pre-plant `/tmp/<this-session-id>/evil.sh` because the id is
85/// unknown until the session exists (and it is unique per session). Compare a *layout* pattern
86/// ("anything under `/tmp/claude-*`"), which anyone can create.
87/// - **Durable.** It survives the harness reorganizing the parts around the id — the uid suffix,
88/// the slug, `/tmp` vs `/private/tmp`, the trailing directory name. Those are internal details
89/// (Claude Code does not document or expose the scratchpad path, and declined to; see
90/// docs/design/agent-scratchpad.md), so matching them exactly would be brittle.
91/// - **Fail-closed.** No session id, or a path that does not contain it, simply does not match:
92/// the path keeps its ordinary classification (`/tmp` → `temp`, i.e. foreign). A harness that
93/// supplies no id, or whose scratchpad omits it, is exactly as restricted as before — never worse.
94///
95/// Requiring a TEMP-root prefix as well keeps the id from blessing something outside the scratch
96/// area on a harness that happens to embed the id elsewhere (a log path under `$HOME`, say).
97pub fn in_session_scratchpad(path: &str) -> bool {
98 let Some(id) = CURRENT.with(|c| c.borrow().session_id.clone()) else {
99 return false;
100 };
101 // A short or trivial id could collide with an ordinary directory name; require something
102 // id-shaped before trusting it as an anchor.
103 if id.len() < 8 || !id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') {
104 return false;
105 }
106 if !under_temp_root(path) {
107 return false;
108 }
109 path.split('/').any(|seg| seg == id)
110}
111
112/// Whether `path` is under a temporary-filesystem root. macOS's `/tmp` is a symlink to
113/// `/private/tmp`, and harnesses report either spelling, so both are accepted (as is `$TMPDIR`).
114pub fn under_temp_root(path: &str) -> bool {
115 const ROOTS: &[&str] = &["/tmp/", "/private/tmp/", "/var/tmp/", "/private/var/tmp/"];
116 if ROOTS.iter().any(|r| path.starts_with(r)) {
117 return true;
118 }
119 std::env::var("TMPDIR").ok().is_some_and(|t| {
120 let t = t.trim_end_matches('/');
121 !t.is_empty() && t.starts_with('/') && path.starts_with(&format!("{t}/"))
122 })
123}
124
125/// A bound `for` loop variable: `$name` in the body inherits the loop's `in`-list locus (the
126/// `find … {}`→path binding, one layer up). Read and write representatives can differ — a list
127/// like `/etc/hosts ~/notes` reads worst at `~/notes` but writes worst at `/etc/hosts`.
128struct LoopVar {
129 name: String,
130 read_repr: String,
131 write_repr: String,
132}
133
134thread_local! {
135 static LOOP_VARS: RefCell<Vec<LoopVar>> = const { RefCell::new(Vec::new()) };
136}
137
138/// A bound `VAR=value` assignment or a function positional (`$1`). Unlike a loop var, a certain
139/// literal value has ONE representative for both read and write.
140struct VarBinding {
141 name: String,
142 value: String,
143}
144
145thread_local! {
146 static VARS: RefCell<Vec<VarBinding>> = const { RefCell::new(Vec::new()) };
147}
148
149/// Bind `name` to a CERTAIN literal `value` (a `VAR=/path` assignment, or `$1` at a function call)
150/// for the duration of the guard; consulted by `expand_vars` AFTER loop vars, so the innermost/latest
151/// binding wins. The caller binds only values it is certain of — an uncertain value (`VAR=$(cmd)`,
152/// `VAR=$UNBOUND`) is bound to the unpinnable sentinel so `$VAR` still fail-closes rather than
153/// resolving to a stale or dropped value.
154#[must_use]
155pub fn enter_var(name: String, value: String) -> VarGuard {
156 VARS.with(|v| v.borrow_mut().push(VarBinding { name, value }));
157 VarGuard
158}
159
160pub struct VarGuard;
161
162impl Drop for VarGuard {
163 fn drop(&mut self) {
164 VARS.with(|v| {
165 v.borrow_mut().pop();
166 });
167 }
168}
169
170/// Bind loop variable `name` to its list's representative items for the duration of the guard
171/// (the loop body's classification). Nested loops stack; the innermost binding of a name wins.
172#[must_use]
173pub fn enter_loop_var(name: String, read_repr: String, write_repr: String) -> LoopGuard {
174 LOOP_VARS.with(|v| v.borrow_mut().push(LoopVar { name, read_repr, write_repr }));
175 LoopGuard
176}
177
178/// Pops the loop binding when dropped.
179pub struct LoopGuard;
180
181impl Drop for LoopGuard {
182 fn drop(&mut self) {
183 LOOP_VARS.with(|v| {
184 v.borrow_mut().pop();
185 });
186 }
187}
188
189thread_local! {
190 static STDIN_REPR: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
191}
192
193/// Bind the representative PATH of the items arriving on stdin, for the duration of the guard —
194/// set by the pipeline walker to the previous stage's output-path locus. An operand-injecting
195/// consumer (`xargs`) reads it so `find / | xargs cat` gates the injected operand at `/`, while
196/// `find ./src | xargs cat` gates it at the workspace (mirrors `find -exec`'s `{}` binding).
197#[must_use]
198pub fn enter_stdin_repr(repr: String) -> StdinReprGuard {
199 STDIN_REPR.with(|v| v.borrow_mut().push(repr));
200 StdinReprGuard
201}
202
203/// The current stdin-item representative, or `None` when the source is unknown (no pipe / an
204/// unmodeled producer) — in which case the consumer worst-cases the injected operand.
205pub fn stdin_item_repr() -> Option<String> {
206 STDIN_REPR.with(|v| v.borrow().last().cloned())
207}
208
209pub struct StdinReprGuard;
210
211impl Drop for StdinReprGuard {
212 fn drop(&mut self) {
213 STDIN_REPR.with(|v| {
214 v.borrow_mut().pop();
215 });
216 }
217}
218
219/// Expand any bound loop variable (`$name` / `${name}`) in `path` to its representative list
220/// item — the read representative when `want_write` is false, the write representative when
221/// true. Unbound `$…` is left untouched (so it still fail-closes to machine). Returns `path`
222/// unchanged when nothing is bound.
223pub fn expand_vars(path: &str, want_write: bool) -> Cow<'_, str> {
224 if !path.contains('$') {
225 return Cow::Borrowed(path);
226 }
227 let replaced = LOOP_VARS.with(|lv| {
228 VARS.with(|v| {
229 let loops = lv.borrow();
230 let vars = v.borrow();
231 if loops.is_empty() && vars.is_empty() { None } else { expand_with(path, &loops, &vars, want_write) }
232 })
233 });
234 replaced.map_or(Cow::Borrowed(path), Cow::Owned)
235}
236
237fn expand_with(path: &str, loops: &[LoopVar], vars: &[VarBinding], want_write: bool) -> Option<String> {
238 let mut out = String::with_capacity(path.len());
239 let mut rest = path;
240 let mut replaced = false;
241 while let Some(dollar) = rest.find('$') {
242 out.push_str(&rest[..dollar]);
243 let after = &rest[dollar + 1..];
244 match parse_var(after) {
245 Some((name, consumed)) => {
246 // Loop bindings first (they carry read/write reprs), then assignment/positional
247 // bindings; innermost/latest wins in each. Unbound in BOTH → left untouched.
248 if let Some(lv) = loops.iter().rev().find(|v| v.name == name) {
249 out.push_str(if want_write { &lv.write_repr } else { &lv.read_repr });
250 replaced = true;
251 } else if let Some(vb) = vars.iter().rev().find(|v| v.name == name) {
252 out.push_str(&vb.value);
253 replaced = true;
254 } else {
255 out.push('$');
256 out.push_str(&after[..consumed]);
257 }
258 rest = &after[consumed..];
259 }
260 None => {
261 out.push('$');
262 rest = after;
263 }
264 }
265 }
266 out.push_str(rest);
267 replaced.then_some(out)
268}
269
270/// Parse a shell variable name immediately after a `$`: `name`, `{name}`, a single-digit positional
271/// (`$1`; bash reads `$12` as `$1` then `2`), or a braced positional (`${10}`). Returns the name and
272/// how many bytes of `after` it consumed, or `None` if it isn't a variable reference.
273fn parse_var(after: &str) -> Option<(&str, usize)> {
274 if let Some(braced) = after.strip_prefix('{') {
275 let close = braced.find('}')?;
276 let name = &braced[..close];
277 is_var_name(name).then_some((name, close + 2)) // '{' + name + '}'
278 } else if after.as_bytes().first().is_some_and(u8::is_ascii_digit) {
279 Some((&after[..1], 1)) // unbraced positional: exactly one digit
280 } else {
281 let len = after.bytes().take_while(|&b| b.is_ascii_alphanumeric() || b == b'_').count();
282 let name = &after[..len];
283 is_var_name(name).then_some((name, len))
284 }
285}
286
287/// A `${…}` interior is a variable name — an identifier (`[A-Za-z_][A-Za-z0-9_]*`) OR an all-digit
288/// positional (`${10}`).
289fn is_var_name(s: &str) -> bool {
290 if s.is_empty() {
291 return false;
292 }
293 if s.bytes().all(|b| b.is_ascii_digit()) {
294 return true;
295 }
296 let mut bytes = s.bytes();
297 matches!(bytes.next(), Some(b) if b.is_ascii_alphabetic() || b == b'_') && bytes.all(|b| b.is_ascii_alphanumeric() || b == b'_')
298}
299
300/// Resolve a path argument for classification against the ambient `cwd`/`root`. Returns a
301/// path the *existing* classifiers (`classify_locus`, `is_safe_write_target`) can score
302/// unchanged. When `cwd` and `root` are both known and absolute, a **relative** path is lexically
303/// joined onto `cwd` (no filesystem access) and an **absolute** path is normalized in place; then
304/// either way, if the result is inside `root` it comes back as a **root-relative** path (so the
305/// classifiers see "worktree"), and if it escaped `root` (e.g. `cwd` is `/etc`, or an absolute
306/// `/etc/hosts`) it comes back **absolute** (so they see `machine`/etc.). This makes the absolute
307/// and relative spellings of the SAME in-root file classify identically — safety on the OPERATION,
308/// not the SYNTAX. A `~` (home) or `$`-unpinnable path, or no context, is returned as-is.
309pub fn resolve(path: &str) -> Cow<'_, str> {
310 // Home (`~`) is handled by the classifiers directly; a `$` path can't be joined at all.
311 if path.is_empty() || path.starts_with('~') || path.contains('$') {
312 return Cow::Borrowed(path);
313 }
314 let resolved = CURRENT.with(|c| {
315 let ctx = c.borrow();
316 match (ctx.cwd.as_deref(), ctx.root.as_deref()) {
317 (Some(cwd), Some(root)) if cwd.starts_with('/') && root.starts_with('/') => {
318 // Relative → join onto cwd; absolute → normalize in place. Then express relative
319 // to root if inside (worktree), else absolute.
320 let abs = if path.starts_with('/') { lexical_join("/", path) } else { lexical_join(cwd, path) };
321 Some(express_relative_to_root(&abs, root))
322 }
323 _ => None,
324 }
325 });
326 resolved.map_or(Cow::Borrowed(path), Cow::Owned)
327}
328
329/// The cwd after a `cd` whose target cannot be pinned. It looks like a path AND is unpinnable, so
330/// every later relative path resolved against it worst-cases in both gate layers.
331pub(crate) const UNRESOLVED_CWD: &str = "/__SAFE_CHAINS_CMDSUB__";
332
333/// Resolve a `cd` target to a new working directory. `cur` is the current cwd, needed for a
334/// *relative* target. Used by intra-line `cd` tracking (HP-19 #2).
335///
336/// A target that cannot be pinned yields `UNRESOLVED_CWD`, NOT `None`. This used to return `None`
337/// for `~…` and `$VAR`, and the caller reads `None` as "no cd happened" and keeps the previous cwd
338/// — so the `cd` was silently ignored and every later relative path was judged against a workspace
339/// the shell had already left. `cd ~/.aws && cat credentials` and `cd ~/.claude && echo … >
340/// settings.json` both auto-approved that way, the second writing the very file the allowlist
341/// bridge trusts. `None` now means only what the caller can act on: `cd_target` already returned
342/// `None` for "not a cd" (bare `cd`, `cd -`), so reaching here means the shell definitely moved.
343///
344/// `~`/`~/…` are EXPANDED rather than blanket-refused, because they are pinnable — that keeps
345/// `cd ~/.aws && cat credentials` gated as the credential read it is instead of coarsely denying
346/// everything downstream.
347pub fn join_cwd(cur: Option<&str>, target: &str) -> Option<String> {
348 let expanded = match expand_home(target) {
349 Some(t) => t,
350 None => return Some(UNRESOLVED_CWD.to_string()), // `~` with no HOME
351 };
352 // Another user's home, a variable, an UNDECLARED substitution: the shell moved somewhere we
353 // cannot name. Fail closed rather than pretend it stayed put.
354 //
355 // A DECLARED substitution (`cd $(pwd)`) is deliberately not in that set. Its sentinel carries a
356 // locus, so letting it through the joins below keeps the cwd at that locus — `cd $(pwd) && cat
357 // f` stays a worktree read, while `cd $(fd d /etc) && cat f` is a machine one. Refusing both
358 // would have been sound but needlessly coarse.
359 if expanded.starts_with('~') || expanded.contains('$') || crate::cst::check::is_opaque_value(&expanded) {
360 return Some(UNRESOLVED_CWD.to_string());
361 }
362 if expanded.starts_with('/') {
363 return Some(lexical_join("/", &expanded)); // absolute — normalize
364 }
365 // Relative with no known base: the base was already unknown before the `cd`, so this changes
366 // nothing about how later paths are judged. Left as "no update" rather than tightened, so the
367 // fix stays aimed at the hole (a cd to a KNOWN-elsewhere place being dropped).
368 cur.filter(|c| c.starts_with('/')).map(|c| lexical_join(c, &expanded))
369}
370
371/// `~` / `~/rest` expanded against `$HOME`. `~user` is left alone (we cannot resolve another user's
372/// home); `None` only when `~` is used and `$HOME` is unusable.
373fn expand_home(target: &str) -> Option<Cow<'_, str>> {
374 let rest = match target {
375 "~" => "",
376 t => match t.strip_prefix("~/") {
377 Some(r) => r,
378 None => return Some(Cow::Borrowed(target)),
379 },
380 };
381 let home = std::env::var("HOME").ok().filter(|h| h.starts_with('/'))?;
382 Some(Cow::Owned(if rest.is_empty() { home } else { format!("{home}/{rest}") }))
383}
384
385/// Express an absolute `abs` path relative to `root`: `.` if it IS the root, a root-relative path
386/// if it's inside (classified as worktree), or the absolute path unchanged if it escaped (classified
387/// as machine/etc.). The `inside.starts_with('/')` guard prevents a sibling like `/proj-evil` from
388/// matching root `/proj` by bare string prefix.
389fn express_relative_to_root(abs: &str, root: &str) -> String {
390 let root = root.trim_end_matches('/');
391 if abs == root {
392 return ".".to_string(); // the project root itself
393 }
394 match abs.strip_prefix(root) {
395 Some(inside) if inside.starts_with('/') => inside.trim_start_matches('/').to_string(),
396 _ => abs.to_string(),
397 }
398}
399
400/// Join a relative path onto an absolute base, resolving `.` and `..` purely lexically. A
401/// `..` that would climb above `/` is clamped there.
402fn lexical_join(base: &str, rel: &str) -> String {
403 let mut parts: Vec<&str> = base.split('/').filter(|s| !s.is_empty()).collect();
404 for seg in rel.split('/') {
405 match seg {
406 "" | "." => {}
407 ".." => {
408 parts.pop();
409 }
410 s => parts.push(s),
411 }
412 }
413 format!("/{}", parts.join("/"))
414}
415
416#[cfg(test)]
417mod tests {
418 use super::*;
419
420 const SID: &str = "7676dbc5-a265-43b3-a0f8-49666792bd9b";
421
422 fn with_session<T>(id: Option<&str>, f: impl FnOnce() -> T) -> T {
423 let _g = enter(PathCtx { cwd: Some("/home/u/proj".into()), root: Some("/home/u/proj".into()), session_id: id.map(str::to_string) });
424 f()
425 }
426
427 /// The recognition rule is a SECURITY boundary: matching a path that is not really this
428 /// session's scratchpad would hand `sandbox-scope` (and therefore EXECUTE) to foreign code. So
429 /// enumerate the spoofing class rather than one example — every way a hostile or unrelated path
430 /// could try to look like the scratchpad must fail, and every legitimate spelling must match.
431 #[test]
432 fn only_this_sessions_scratchpad_is_recognized() {
433 let scratch = format!("/private/tmp/claude-501/-Users-u-proj/{SID}/scratchpad");
434 let matching: &[String] = &[
435 format!("{scratch}/build.sh"),
436 format!("{scratch}/nested/deep/gen.py"),
437 scratch.clone(),
438 // layout around the id varies by harness/platform — the id is the anchor, not the shape
439 format!("/tmp/{SID}/x.sh"),
440 format!("/tmp/some-other-harness/{SID}/work/x.sh"),
441 format!("/var/tmp/{SID}/x.sh"),
442 ];
443 let rejected: &[String] = &[
444 // a DIFFERENT session's scratchpad — same layout, wrong id
445 "/private/tmp/claude-501/-Users-u-proj/00000000-1111-2222-3333-444444444444/scratchpad/x.sh".into(),
446 // the id as a SUBSTRING of a component, not a component (the prefix/suffix attack)
447 format!("/tmp/{SID}-evil/x.sh"),
448 format!("/tmp/evil-{SID}/x.sh"),
449 format!("/tmp/a{SID}/x.sh"),
450 // right id, but OUTSIDE any temp root — the id must not bless arbitrary locations
451 format!("/home/u/{SID}/x.sh"),
452 format!("~/.ssh/{SID}/id_rsa"),
453 format!("/etc/{SID}/passwd"),
454 // anonymous temp files carry no id at all
455 "/tmp/evil.sh".into(),
456 "/private/tmp/downloaded.sh".into(),
457 ];
458 with_session(Some(SID), || {
459 for p in matching {
460 assert!(in_session_scratchpad(p), "should be recognized: {p}");
461 }
462 for p in rejected {
463 assert!(!in_session_scratchpad(p), "must NOT be recognized: {p}");
464 }
465 });
466 }
467
468 /// Fail closed on every degenerate session id: no harness id, or one too short/odd to be a
469 /// trustworthy anchor, must recognize NOTHING — never widen a path.
470 #[test]
471 fn a_missing_or_unusable_session_id_recognizes_nothing() {
472 let path = format!("/tmp/{SID}/x.sh");
473 with_session(None, || {
474 assert!(!in_session_scratchpad(&path), "no session id → no recognition");
475 });
476 for weak in ["", "abc", "1234567", "..", "/", "a/b", "id with space", "x*y"] {
477 with_session(Some(weak), || {
478 assert!(!in_session_scratchpad(&format!("/tmp/{weak}/x.sh")), "weak id {weak:?} must not anchor recognition",);
479 });
480 }
481 }
482
483 #[test]
484 fn no_context_leaves_paths_unchanged() {
485 assert_eq!(resolve("./x"), "./x");
486 assert_eq!(resolve("config"), "config");
487 assert_eq!(resolve("/etc/x"), "/etc/x");
488 }
489
490 #[test]
491 fn relative_inside_the_project_stays_worktree_relative() {
492 let _g = enter(PathCtx { cwd: Some("/home/u/proj/sub".into()), root: Some("/home/u/proj".into()), ..Default::default() });
493 assert_eq!(resolve("x"), "sub/x", "cwd under root → root-relative");
494 assert_eq!(resolve("./y"), "sub/y");
495 assert_eq!(resolve("../z"), "z", ".. that stays inside root");
496 }
497
498 #[test]
499 fn relative_outside_the_project_becomes_absolute() {
500 let _g = enter(PathCtx { cwd: Some("/etc".into()), root: Some("/home/u/proj".into()), ..Default::default() });
501 assert_eq!(resolve("x"), "/etc/x", "cd /etc → the real target");
502 assert_eq!(resolve("passwd"), "/etc/passwd");
503 assert_eq!(resolve("*"), "/etc/*");
504 }
505
506 #[test]
507 fn dotdot_escaping_the_project_becomes_absolute() {
508 let _g = enter(PathCtx { cwd: Some("/home/u/proj".into()), root: Some("/home/u/proj".into()), ..Default::default() });
509 assert_eq!(resolve("../../../etc/x"), "/etc/x");
510 }
511
512 #[test]
513 fn absolute_in_root_becomes_root_relative_outside_stays_absolute() {
514 let _g = enter(PathCtx { cwd: Some("/home/u/proj/sub".into()), root: Some("/home/u/proj".into()), ..Default::default() });
515 // absolute INSIDE root → root-relative (worktree), matching the relative spelling
516 assert_eq!(resolve("/home/u/proj/main.rs"), "main.rs");
517 assert_eq!(resolve("/home/u/proj/sub/x"), "sub/x");
518 assert_eq!(resolve("/home/u/proj/a/../b"), "b", "normalized in place");
519 assert_eq!(resolve("/home/u/proj"), ".", "the project root itself");
520 // absolute OUTSIDE root → unchanged (classified as machine)
521 assert_eq!(resolve("/usr/bin/x"), "/usr/bin/x");
522 assert_eq!(resolve("/home/u/proj/../../etc/x"), "/home/etc/x", "climbs to /home, still outside root");
523 assert_eq!(resolve("/home/u/proj/../../../etc/x"), "/etc/x", "escapes to /etc via ..");
524 assert_eq!(
525 resolve("/home/u/proj-evil/secret"),
526 "/home/u/proj-evil/secret",
527 "a sibling dir is not confused for inside by bare string prefix",
528 );
529 // home / unpinnable → returned as-is (the classifiers handle these)
530 assert_eq!(resolve("$HOME/x"), "$HOME/x");
531 assert_eq!(resolve("~/x"), "~/x");
532 }
533
534 #[test]
535 fn loop_var_expands_to_its_representative_per_face() {
536 let _g = enter_loop_var("f".into(), "read_item".into(), "write_item".into());
537 assert_eq!(expand_vars("$f", false), "read_item");
538 assert_eq!(expand_vars("$f", true), "write_item");
539 assert_eq!(expand_vars("${f}", false), "read_item");
540 assert_eq!(expand_vars("$f.bak", false), "read_item.bak", "compound suffix");
541 assert_eq!(expand_vars("pre/$f", false), "pre/read_item");
542 assert_eq!(expand_vars("$foo", false), "$foo", "$foo is not $f");
543 assert_eq!(expand_vars("$g", false), "$g", "unbound var untouched");
544 assert_eq!(expand_vars("plain", false), "plain");
545 }
546
547 #[test]
548 fn loop_var_binding_is_scoped_and_nests() {
549 assert_eq!(expand_vars("$f", false), "$f", "no binding");
550 {
551 let _outer = enter_loop_var("f".into(), "outer".into(), "outer".into());
552 {
553 let _inner = enter_loop_var("f".into(), "inner".into(), "inner".into());
554 assert_eq!(expand_vars("$f", false), "inner", "innermost wins");
555 }
556 assert_eq!(expand_vars("$f", false), "outer", "inner popped on drop");
557 }
558 assert_eq!(expand_vars("$f", false), "$f", "all popped");
559 }
560
561 #[test]
562 fn the_guard_restores_on_drop() {
563 {
564 let _g = enter(PathCtx { cwd: Some("/etc".into()), root: Some("/r".into()), ..Default::default() });
565 assert_eq!(resolve("x"), "/etc/x");
566 }
567 assert_eq!(resolve("x"), "x", "context cleared after the guard drops");
568 }
569}