Skip to main content

agentmux_bashwrap/
cwd_state.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Where an agent's Bash calls start: the working directory a call ends in is
5//! kept for the next one, per instance and, for a Claude Code subagent, per
6//! subagent (docs/specs/SPEC_BASHWRAP_PER_AGENT_CWD_2026_10_18.md). Moved out
7//! of `bash_wrap.rs`, which runs the calls.
8
9use std::path::{Path, PathBuf};
10use std::time::Duration;
11
12// ─────────────────────────────────────────────────────────────────────────────
13// Cwd persistence across one-shot `exec` invocations
14//
15// Every Bash tool call the PreToolUse hook rewrites spawns a brand-new,
16// disposable `agentmux-bashwrap exec` process (see main.rs's module doc —
17// there is no daemon). Historically the inner bash's starting directory was
18// seeded from `std::env::current_dir()`, i.e. THIS process's own inherited
19// cwd, which is always the agent's fixed home directory (nothing in this
20// process tree ever chdirs it). A `cd` run by the wrapped command only ever
21// affected that one throwaway inner bash; the moment it exited, the change
22// was gone, and the NEXT call started over at the same fixed directory again
23// — every time, not intermittently. Claude Code's own Bash tool expects `cd`
24// continuity across calls within a session and (at least on Windows, where
25// this rewrite always applies) surfaces the mismatch as a
26// "Shell cwd was reset to ..." notice on effectively every call. See
27// docs/retro/RETRO_BASH_CWD_RESET_NOTICE_WINDOWS_2026_08_02.md for the full
28// investigation.
29//
30// The fix: persist the shell's ending `$PWD` to a small per-agent state file
31// after each call, and restore it as the starting directory of the next
32// call. This doesn't change what Claude Code itself believes (that's opaque,
33// out of process) but it does make the ACTUAL directory a `cd` in one Bash
34// call leaves the agent in survive to the next call, which is the part that
35// was silently broken.
36// ─────────────────────────────────────────────────────────────────────────────
37
38/// Env var bashwrap sets on the *child* bash process (never interpolated
39/// into the script text, so no path-quoting concerns) pointing at the state
40/// file `append_cwd_capture`'s appended script writes the ending `$PWD` to.
41pub(crate) const CWD_STATE_ENV: &str = "AGENTMUX_BASHWRAP_CWD_STATE";
42
43/// Optional override of the state file's own path, read from bashwrap's own
44/// process env (distinct from `CWD_STATE_ENV`, which bashwrap sets rather
45/// than reads). Exists so tests can point persistence at a tempdir instead
46/// of a real agent's `~/.agentmux` state, and as an escape hatch for manual
47/// debugging.
48pub(crate) const CWD_STATE_FILE_OVERRIDE_ENV: &str = "AGENTMUX_BASHWRAP_CWD_STATE_FILE";
49
50/// Resolves the cwd-persistence file location and any previously-restored
51/// starting directory once per `exec` invocation.
52pub(crate) struct CwdState {
53    /// Where the ending `$PWD` gets written after this command runs, for the
54    /// *next* `exec` invocation to pick up. `None` if we couldn't resolve a
55    /// location or create its parent dir — persistence is then simply
56    /// skipped for this call (never a hard failure; falls back to today's
57    /// pre-fix behavior).
58    pub(crate) path: Option<PathBuf>,
59    /// The directory to actually start this command's shell in: the
60    /// previously-persisted directory if one was found and still exists,
61    /// otherwise this process's own (fixed, inherited) cwd — the same
62    /// default used before this fix existed.
63    pub(crate) start_dir: Option<PathBuf>,
64}
65
66impl CwdState {
67    /// [`CwdState::load`], or, when the call's agent can't be told
68    /// (`Args::agent_unknown`), the directory the shell was started in and
69    /// nothing written: any agent's would be a guess.
70    pub(crate) fn for_call(agent: Option<&str>, agent_unknown: bool) -> Self {
71        if agent_unknown {
72            return Self { path: None, start_dir: std::env::current_dir().ok() };
73        }
74        Self::load(agent)
75    }
76
77    /// `agent`: the subagent that made the call, if any. A subagent keeps
78    /// its own state file next to the instance's: it starts where it last
79    /// left off, or, on its first call, where the main agent is; and its
80    /// `cd` is written only to its own file. Before this, the main agent and
81    /// every subagent shared the instance's file, so a subagent's `cd` moved
82    /// the main agent's next command into the subagent's checkout, where a
83    /// `git commit` committed the subagent's work
84    /// (docs/specs/SPEC_BASHWRAP_PER_AGENT_CWD_2026_10_18.md).
85    pub(crate) fn load(agent: Option<&str>) -> Self {
86        let mut path = cwd_state_path();
87        if let Some(dir) = path.as_deref().and_then(Path::parent) {
88            if let Err(e) = std::fs::create_dir_all(dir) {
89                tracing::warn!(
90                    target: "bashwrap",
91                    error = %e,
92                    dir = %dir.display(),
93                    "failed to create cwd-state dir; cwd persistence disabled for this call",
94                );
95                // reagentx P2 (re-review): the log line above claims
96                // persistence is disabled, but `path` used to stay `Some`
97                // here regardless — restore_cwd below would still attempt
98                // (and silently fail) a read, and the child would still get
99                // CWD_STATE_ENV pointed at a directory that doesn't exist,
100                // so append_cwd_capture's write would silently fail on
101                // every single call forever instead of being skipped once,
102                // as documented. Actually clear it so both sides honor the
103                // "disabled" contract `path`'s own doc comment promises.
104                path = None;
105            }
106        }
107        let agent = agent.map(str::trim).filter(|a| !a.is_empty());
108        let own = path.as_deref().zip(agent).map(|(p, a)| agent_state_path(p, a));
109        let start_dir = own
110            .as_deref()
111            .and_then(restore_cwd)
112            .or_else(|| path.as_deref().and_then(restore_cwd))
113            .or_else(|| std::env::current_dir().ok());
114        // Subagents come and go; the main agent's calls clear out the files of
115        // ones long gone.
116        if agent.is_none() {
117            if let Some(dir) = path.as_deref().and_then(Path::parent) {
118                sweep_agent_state_files(dir, AGENT_STATE_MAX_AGE);
119            }
120        }
121        Self { path: own.or(path), start_dir }
122    }
123}
124
125/// A subagent's state file: the instance's, with the agent in its name
126/// (`<instance>.agent-<agent>.cwd`), so it sorts and sweeps with it.
127fn agent_state_path(instance_file: &Path, agent: &str) -> PathBuf {
128    let stem = instance_file.file_stem().and_then(|s| s.to_str()).unwrap_or("bashwrap");
129    instance_file.with_file_name(format!("{stem}{AGENT_STATE_MARK}{}.cwd", sanitize_state_key(agent)))
130}
131
132const AGENT_STATE_MARK: &str = ".agent-";
133
134/// A subagent's state file untouched this long belongs to one that ended.
135const AGENT_STATE_MAX_AGE: Duration = Duration::from_secs(7 * 24 * 60 * 60);
136
137/// Delete subagents' state files in `dir` not written for `max_age`. Never
138/// an instance's own file (no agent mark), and never fatal.
139fn sweep_agent_state_files(dir: &Path, max_age: Duration) {
140    let Ok(entries) = std::fs::read_dir(dir) else { return };
141    for entry in entries.flatten() {
142        let name = entry.file_name();
143        let name = name.to_string_lossy();
144        if !name.contains(AGENT_STATE_MARK) || !name.ends_with(".cwd") {
145            continue;
146        }
147        let old = entry
148            .metadata()
149            .and_then(|m| m.modified())
150            .ok()
151            .and_then(|t| t.elapsed().ok())
152            .is_some_and(|age| age >= max_age);
153        if old {
154            let _ = std::fs::remove_file(entry.path());
155        }
156    }
157}
158
159/// Per-*instance* state file path. Keyed by `AGENTMUX_INSTANCE_SLUG` — set by
160/// `agent-model.ts` to a per-launch slug that also seeds that instance's own
161/// unique working directory (`${agentmuxHome()}/agents/${instanceSlug}`) —
162/// NOT `AGENTMUX_AGENT_ID`, which is the definition-wide slug shared by every
163/// named instance launched from the same agent definition (codex P1 on this
164/// PR: keying by `AGENTMUX_AGENT_ID` made two concurrently-running instances
165/// of the same definition silently share one cwd file, so one instance's
166/// `cd` could redirect the other's next command into the wrong worktree).
167/// Falls back to `AGENTMUX_AGENT_ID` for older callers that only set that,
168/// then to a sanitized form of this process's own cwd (always the instance's
169/// fixed home directory either way) for the rare case neither is set, e.g. a
170/// manual invocation outside AgentMux.
171fn cwd_state_path() -> Option<PathBuf> {
172    if let Ok(over) = std::env::var(CWD_STATE_FILE_OVERRIDE_ENV) {
173        if !over.is_empty() {
174            return Some(PathBuf::from(over));
175        }
176    }
177    let dir = dirs::home_dir()?
178        .join(".agentmux")
179        .join("state")
180        .join("bashwrap-cwd");
181    let non_empty = |s: String| (!s.is_empty()).then_some(s);
182    let key = std::env::var("AGENTMUX_INSTANCE_SLUG")
183        .ok()
184        .and_then(non_empty)
185        .or_else(|| std::env::var("AGENTMUX_AGENT_ID").ok().and_then(non_empty))
186        .or_else(|| {
187            std::env::current_dir()
188                .ok()
189                .map(|p| p.to_string_lossy().into_owned())
190        })?;
191    Some(dir.join(format!("{}.cwd", sanitize_state_key(&key))))
192}
193
194/// Filesystem-safe form of an arbitrary key for use as a filename component.
195fn sanitize_state_key(raw: &str) -> String {
196    raw.chars()
197        .map(|c| {
198            if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
199                c
200            } else {
201                '_'
202            }
203        })
204        .collect()
205}
206
207/// Read back a previously-persisted cwd, if the file exists, is non-empty,
208/// and still names a real directory (it may not — the directory could have
209/// been deleted since, or this is the first call for this agent).
210fn restore_cwd(state_path: &Path) -> Option<PathBuf> {
211    let contents = std::fs::read_to_string(state_path).ok()?;
212    let trimmed = contents.trim();
213    if trimmed.is_empty() {
214        return None;
215    }
216    let path = PathBuf::from(trimmed);
217    path.is_dir().then_some(path)
218}
219
220/// Appends bookkeeping to `command_block` that (1) captures its real exit
221/// code before running anything else, (2) persists the shell's ending
222/// `$PWD` to `$AGENTMUX_BASHWRAP_CWD_STATE` if that env var is set (skipped
223/// entirely otherwise — e.g. when `CwdState::path` was `None`), written via
224/// a temp-file-then-rename so a mid-write crash can't leave a half-written
225/// state file, and (3) re-exits with the captured code so this bookkeeping
226/// never changes the command's real exit status. `command_block` must be a
227/// brace group or bare command, not something that already ends in its own
228/// `exit`.
229///
230/// The temp file is suffixed with `$$` (this bash's own PID), not a fixed
231/// name — reagentx P2 on this PR: two Bash tool calls for the same
232/// agent/instance can run concurrently (Claude issues parallel tool calls),
233/// and a shared fixed temp name meant two concurrent writers could
234/// interleave writes to the *same* temp file before either renamed it,
235/// corrupting the persisted cwd. Per-PID temp names make each writer's
236/// temp-then-rename independent; the only remaining race is which
237/// completed rename lands last, which is an inherent, expected ambiguity
238/// for genuinely concurrent `cd`s (no different from two parallel shells
239/// racing to `cd` a shared session) — not data corruption.
240pub(crate) fn append_cwd_capture(command_block: &str) -> String {
241    // `pwd` alone prints MSYS-style paths under Git Bash (`/c/Users/...`),
242    // which Rust's `std::fs`/`Path::is_dir()` on native Windows can't
243    // resolve (it looks for a literal `\c\Users\...` under the current
244    // drive root). `-W` is Git Bash's own flag for "print the Windows-
245    // native form instead" (`C:/Users/...`), which both `restore_cwd`'s
246    // `is_dir()` check and `cmd.cwd()`/`cmd.current_dir()` understand
247    // correctly. Not a POSIX `pwd` flag — Unix has no such mismatch to
248    // work around, so plain `pwd` is correct there.
249    let pwd_cmd = if cfg!(windows) { "pwd -W" } else { "pwd" };
250    format!(
251        "{command_block}\n\
252__agentmux_bashwrap_rc=$?\n\
253if [ -n \"${CWD_STATE_ENV}\" ]; then\n\
254  __agentmux_bashwrap_cwd_tmp=\"${CWD_STATE_ENV}.tmp.$$\"\n\
255  {pwd_cmd} > \"$__agentmux_bashwrap_cwd_tmp\" 2>/dev/null && mv -f \"$__agentmux_bashwrap_cwd_tmp\" \"${CWD_STATE_ENV}\" 2>/dev/null\n\
256fi\n\
257exit $__agentmux_bashwrap_rc"
258    )
259}
260
261#[cfg(test)]
262mod tests {
263    use super::*;
264    use crate::test_env_lock::{unique_temp_dir, EnvVarGuard, ENV_LOCK};
265
266    // ── cwd persistence tests ───────────────────────────────────────────────
267    // See docs/retro/RETRO_BASH_CWD_RESET_NOTICE_WINDOWS_2026_08_02.md for
268    // the bug this exists to fix: each `exec` invocation used to always seed
269    // its inner bash's cwd from this process's own (fixed) cwd, silently
270    // discarding whatever directory a previous call's `cd` left the agent
271    // in.
272
273    #[test]
274    fn sanitize_state_key_replaces_unsafe_chars() {
275        assert_eq!(sanitize_state_key("agent3-0630k"), "agent3-0630k");
276        assert_eq!(sanitize_state_key("Agent With Spaces"), "Agent_With_Spaces");
277        assert_eq!(sanitize_state_key(r"C:\Users\user"), "C__Users_user");
278    }
279
280    /// SPEC_BASHWRAP_PER_AGENT_CWD_2026_10_18.md: the main agent and its
281    /// subagents share one instance, and used to share one state file, so a
282    /// subagent's `cd` into its own checkout moved the main agent's next
283    /// command there. Each subagent now has its own file; its first call
284    /// starts where the main agent is.
285    #[test]
286    fn a_subagents_cd_never_moves_the_main_agent() {
287        let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
288        let scratch = unique_temp_dir("per-agent-cwd");
289        let (main_dir, sub_dir) = (scratch.join("main"), scratch.join("sub"));
290        std::fs::create_dir_all(&main_dir).unwrap();
291        std::fs::create_dir_all(&sub_dir).unwrap();
292        let main_file = scratch.join("inst.cwd");
293        std::fs::write(&main_file, main_dir.to_string_lossy().as_bytes()).unwrap();
294        let _override = EnvVarGuard::set(CWD_STATE_FILE_OVERRIDE_ENV, main_file.to_str().unwrap());
295
296        // A new subagent starts where the main agent is, and writes its own file.
297        let first = CwdState::load(Some("sub-1"));
298        assert_eq!(first.start_dir.as_deref(), Some(main_dir.as_path()));
299        let sub_file = first.path.clone().unwrap();
300        assert_ne!(sub_file, main_file);
301        assert!(sub_file.to_string_lossy().ends_with("inst.agent-sub-1.cwd"), "{sub_file:?}");
302
303        // It cds (its command's bookkeeping writes its own file).
304        std::fs::write(&sub_file, sub_dir.to_string_lossy().as_bytes()).unwrap();
305        assert_eq!(CwdState::load(Some("sub-1")).start_dir.as_deref(), Some(sub_dir.as_path()));
306        // The main agent, and another subagent, are where they were.
307        let main = CwdState::load(None);
308        assert_eq!(main.start_dir.as_deref(), Some(main_dir.as_path()));
309        assert_eq!(main.path.as_deref(), Some(main_file.as_path()));
310        assert_eq!(CwdState::load(Some("sub-2")).start_dir.as_deref(), Some(main_dir.as_path()));
311        // An empty agent id is the main agent.
312        assert_eq!(CwdState::load(Some("  ")).path.as_deref(), Some(main_file.as_path()));
313        drop(_override);
314        let _ = std::fs::remove_dir_all(&scratch);
315    }
316
317    /// A call whose agent can't be told uses no agent's file, and writes none.
318    #[test]
319    fn a_call_of_unknown_agent_uses_and_writes_no_state() {
320        let state = CwdState::for_call(Some("sub-1"), true);
321        assert_eq!(state.path, None);
322        assert_eq!(state.start_dir, std::env::current_dir().ok());
323    }
324
325    #[test]
326    fn subagent_state_files_are_swept_but_an_instances_own_never_is() {
327        let scratch = unique_temp_dir("sweep-agent-cwd");
328        for name in ["inst.cwd", "inst.agent-a.cwd", "other.agent-b.cwd", "notes.txt"] {
329            std::fs::write(scratch.join(name), b"x").unwrap();
330        }
331        sweep_agent_state_files(&scratch, Duration::from_secs(3600));
332        assert!(scratch.join("inst.agent-a.cwd").exists(), "a recent subagent file stays");
333        sweep_agent_state_files(&scratch, Duration::ZERO);
334        let mut left: Vec<String> =
335            std::fs::read_dir(&scratch).unwrap().flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect();
336        left.sort();
337        assert_eq!(left, vec!["inst.cwd", "notes.txt"]);
338        let _ = std::fs::remove_dir_all(&scratch);
339    }
340
341    #[test]
342    fn cwd_state_path_honors_explicit_override() {
343        let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
344        let scratch = unique_temp_dir("override");
345        let target = scratch.join("explicit.cwd");
346        unsafe {
347            std::env::set_var(CWD_STATE_FILE_OVERRIDE_ENV, &target);
348        }
349        let resolved = cwd_state_path();
350        unsafe {
351            std::env::remove_var(CWD_STATE_FILE_OVERRIDE_ENV);
352        }
353        let _ = std::fs::remove_dir_all(&scratch);
354        assert_eq!(resolved, Some(target));
355    }
356
357    #[test]
358    fn cwd_state_path_derives_from_agent_id_when_no_override_or_instance_slug() {
359        let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
360        let _override = EnvVarGuard::unset(CWD_STATE_FILE_OVERRIDE_ENV);
361        let _instance = EnvVarGuard::unset("AGENTMUX_INSTANCE_SLUG");
362        let _agent = EnvVarGuard::set("AGENTMUX_AGENT_ID", "Test-Agent-42");
363
364        let resolved = cwd_state_path().expect("home dir should resolve in any test environment");
365        assert!(resolved.ends_with("Test-Agent-42.cwd"), "{resolved:?}");
366        assert!(resolved.to_string_lossy().contains(".agentmux"));
367    }
368
369    /// codex P1 on this PR: keying solely by `AGENTMUX_AGENT_ID` (the
370    /// definition-wide slug) made two concurrently-running *instances* of
371    /// the same agent definition share one cwd file — a `cd` in instance A
372    /// would redirect instance B's next command into A's directory, even
373    /// though each instance has its own distinct working directory. The
374    /// fix: prefer `AGENTMUX_INSTANCE_SLUG` (per-launch, unique per running
375    /// instance — see `agent-model.ts`) whenever it's set.
376    #[test]
377    fn cwd_state_path_prefers_instance_slug_over_agent_id() {
378        let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
379        let _override = EnvVarGuard::unset(CWD_STATE_FILE_OVERRIDE_ENV);
380        let _agent = EnvVarGuard::set("AGENTMUX_AGENT_ID", "shared-definition-slug");
381        let _instance_a = EnvVarGuard::set("AGENTMUX_INSTANCE_SLUG", "shared-definition-slug-20260101-000000");
382
383        let resolved_a =
384            cwd_state_path().expect("home dir should resolve in any test environment");
385        assert!(
386            resolved_a.ends_with("shared-definition-slug-20260101-000000.cwd"),
387            "{resolved_a:?}"
388        );
389
390        // A second, concurrently-running instance of the SAME definition
391        // (same AGENTMUX_AGENT_ID, different AGENTMUX_INSTANCE_SLUG) must
392        // resolve to a DIFFERENT file.
393        let _instance_b = EnvVarGuard::set("AGENTMUX_INSTANCE_SLUG", "shared-definition-slug-20260101-000001");
394        let resolved_b =
395            cwd_state_path().expect("home dir should resolve in any test environment");
396        assert_ne!(resolved_a, resolved_b);
397        assert!(
398            resolved_b.ends_with("shared-definition-slug-20260101-000001.cwd"),
399            "{resolved_b:?}"
400        );
401    }
402
403    /// reagentx re-review finding: when the state dir can't be created,
404    /// `CwdState::load()` used to leave `path` as `Some` anyway, so
405    /// `restore_cwd` and the child's write would both silently keep failing
406    /// against a directory that doesn't exist on every subsequent call,
407    /// instead of cleanly disabling persistence once as the doc comment
408    /// promises. Forces the failure by pointing the override at a path
409    /// whose *parent* is a plain file, not a directory — `create_dir_all`
410    /// cannot create a directory there.
411    #[test]
412    fn cwd_state_load_clears_path_when_state_dir_cannot_be_created() {
413        let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
414        let scratch = unique_temp_dir("uncreatable-parent");
415        let blocking_file = scratch.join("not-a-directory");
416        std::fs::write(&blocking_file, b"blocks create_dir_all").unwrap();
417        let unreachable_state_file = blocking_file.join("state.cwd");
418
419        let _override = EnvVarGuard::set(
420            CWD_STATE_FILE_OVERRIDE_ENV,
421            unreachable_state_file.to_str().unwrap(),
422        );
423        let state = CwdState::load(None);
424        let _ = std::fs::remove_dir_all(&scratch);
425
426        assert_eq!(
427            state.path, None,
428            "path must be cleared (not just logged-as-disabled) when its parent dir can't be created"
429        );
430        assert!(state.start_dir.is_some(), "must still fall back to a start dir");
431    }
432
433    #[test]
434    fn restore_cwd_none_when_file_missing() {
435        let scratch = unique_temp_dir("missing");
436        let missing = scratch.join("does-not-exist.cwd");
437        assert_eq!(restore_cwd(&missing), None);
438        let _ = std::fs::remove_dir_all(&scratch);
439    }
440
441    #[test]
442    fn restore_cwd_none_when_persisted_dir_no_longer_exists() {
443        let scratch = unique_temp_dir("stale");
444        let state_file = scratch.join("state.cwd");
445        let gone = scratch.join("deleted-dir");
446        std::fs::create_dir_all(&gone).unwrap();
447        std::fs::write(&state_file, gone.to_string_lossy().as_bytes()).unwrap();
448        std::fs::remove_dir_all(&gone).unwrap();
449        assert_eq!(restore_cwd(&state_file), None);
450        let _ = std::fs::remove_dir_all(&scratch);
451    }
452
453    #[test]
454    fn restore_cwd_some_when_persisted_dir_exists() {
455        let scratch = unique_temp_dir("valid");
456        let state_file = scratch.join("state.cwd");
457        std::fs::write(&state_file, scratch.to_string_lossy().as_bytes()).unwrap();
458        assert_eq!(restore_cwd(&state_file), Some(scratch.clone()));
459        let _ = std::fs::remove_dir_all(&scratch);
460    }
461
462    #[test]
463    fn restore_cwd_ignores_blank_file() {
464        let scratch = unique_temp_dir("blank");
465        let state_file = scratch.join("state.cwd");
466        std::fs::write(&state_file, b"   \n").unwrap();
467        assert_eq!(restore_cwd(&state_file), None);
468        let _ = std::fs::remove_dir_all(&scratch);
469    }
470
471    #[test]
472    fn append_cwd_capture_preserves_exit_code_and_gates_on_env() {
473        let script = append_cwd_capture("false");
474        // The real command's exit code must survive the appended
475        // bookkeeping regardless of whether the state env var is set.
476        assert!(script.contains("__agentmux_bashwrap_rc=$?"));
477        assert!(script.trim_end().ends_with("exit $__agentmux_bashwrap_rc"));
478        // The write is gated on the env var being non-empty, and uses a
479        // per-PID temp-then-rename so a crash mid-write can't corrupt the
480        // file, and two concurrent invocations never write the same temp
481        // file (reagentx P2 on this PR).
482        assert!(script.contains(&format!("-n \"${CWD_STATE_ENV}\"")));
483        assert!(script.contains(&format!("${CWD_STATE_ENV}.tmp.$$")));
484        assert!(script.contains("mv -f"));
485    }
486}