mur_common/paths.rs
1//! Directory names under `<mur_home>` that a fleet / deep-research run writes.
2//!
3//! One list, two readers that must never disagree: `mur-core` creates and
4//! writes these while a run executes, and `mur-agent-runtime` carves exactly
5//! these into the kernel sandbox for an agent-triggered run (`fleet_run`).
6//! They lived as two separate literals and drifted — `runs/` was writable by
7//! the CLI and denied to the sandbox, so every agent-triggered run failed to
8//! register itself and `mur fleet status` reported nothing for a run that was
9//! live (fleet develop-rust, 2026-09-09). The list lives here because the
10//! runtime must not depend on `mur-core`.
11
12use std::path::{Path, PathBuf};
13
14/// Run-status records of runs that belong to no fleet (`parallel_jobs`,
15/// workflows): `<mur_home>/runs/<run_id>/run.json`.
16///
17/// A FLEET run's directory is never here — it is
18/// [`fleet_run_dir`], inside the per-fleet carve-in. `runs/` is writable by
19/// writable by no sandboxed agent since #2320, but it was before, so
20/// anything a fleet resume trusts still must not be read from it (#2316).
21/// Runs an agent dispatches go to [`agent_runs_dir`] instead.
22pub const RUNS: &str = "runs";
23
24/// Fleet definitions: `<mur_home>/fleets/<name>/fleet.yaml`, plus the
25/// operator's `.stopped` kill-switch and the daemon's `.last_run` stamp.
26///
27/// Configuration, not run state — deliberately absent from
28/// [`RUN_STATE_DIRS`]. A run that could write here could rewrite its own
29/// fleet's members, limits and HITL pre-approvals, or clear its own
30/// kill-switch.
31pub const FLEETS: &str = "fleets";
32
33/// What a fleet's runs write, per fleet: `<mur_home>/fleet-state/<name>/`
34/// (job queue, progress record, event log, parallel-track state).
35///
36/// Its own tree, not `runs/`: that store is keyed by run_id and lists every
37/// directory in it as a run, so a fleet name dropped in there reads as a
38/// phantom run. Not `fleets/`: that is configuration (see [`FLEETS`]).
39pub const FLEET_STATE: &str = "fleet-state";
40
41/// The fleet's single progress record, inside [`fleet_state_dir`]. Kept after
42/// a run as the last-run record; overwritten by the next run. Read by both
43/// the CLI and the runtime's `fleet_run` live-run guard, so named once here.
44pub const FLEET_PROGRESS_FILE: &str = ".run_progress.json";
45
46/// Exclusive advisory lock held for the life of a fleet run, inside
47/// [`fleet_state_dir`]. Liveness is whether the lock can be taken, never a
48/// stored pid. The holder's self-description lives in [`FLEET_RUN_OWNER_FILE`]
49/// because Windows locks are mandatory and a held file cannot be read.
50pub const FLEET_RUN_LOCK_FILE: &str = "run.lock";
51
52/// Display-only owner record (pid, start time, host) beside the run lock.
53pub const FLEET_RUN_OWNER_FILE: &str = "run.owner";
54
55/// Every directory an in-sandbox fleet run must be able to write.
56///
57/// Add here FIRST, then use it. A directory the runner writes but this list
58/// omits fails only in the sandboxed path — the one nobody runs by hand.
59///
60/// [`FLEET_STATE`] is listed for the CLI side and for tests; the sandbox
61/// carves in only the `fleet_run.fleets` subdirectories of it (see
62/// `mur-agent-runtime` `sandbox/policy/build.rs`), so an agent cannot queue work
63/// for a fleet the operator never let it run.
64///
65/// `commander/` is deliberately absent: it holds the commander's private key
66/// and `.env`, and its public keys are trust anchors. A run writes nothing
67/// there; the sandbox grants read on the two public key files instead.
68///
69/// [`RUNS`] is deliberately absent (#2320): it holds the operator's own
70/// non-fleet runs, and a whole-tree grant let every allowlisted agent rewrite
71/// every other agent's records. An agent's own runs go to
72/// [`agent_runs_dir`], inside its home.
73pub const RUN_STATE_DIRS: [&str; 3] = [FLEET_STATE, "conversations", "artifacts"];
74
75/// Agent homes: `<mur_home>/agents/<name>/`.
76pub const AGENTS: &str = "agents";
77
78/// Env var naming the agent a child process runs for, set by the agent
79/// runtime on its bash and MCP children. A run recorded by that child goes to
80/// [`agent_runs_dir`] of this agent.
81///
82/// Not a credential: the path it names is the agent's own home, which the
83/// kernel sandbox lets no other agent write. A forged value only makes the
84/// record fail to write.
85pub const RUN_OWNER_ENV: &str = "MUR_RUN_OWNER";
86
87/// `<mur_home>/agents/<agent>/runs/` — the non-fleet runs (`parallel_jobs`,
88/// workflows) `agent` dispatched (#2320). Inside the agent's home, so only
89/// that agent (and the operator) can write them.
90pub fn agent_runs_dir(mur_home: &Path, agent: &str) -> PathBuf {
91 mur_home.join(AGENTS).join(agent).join(RUNS)
92}
93
94/// The run owner named by [`RUN_OWNER_ENV`], if set to a valid agent name.
95/// An invalid name is ignored rather than joined: it becomes a path segment.
96pub fn run_owner_from_env() -> Option<String> {
97 std::env::var(RUN_OWNER_ENV)
98 .ok()
99 .filter(|n| crate::agent_name::validate_agent_name(n).is_ok())
100}
101
102/// `<mur_home>/fleet-state/<name>/` — every file a run of `name` writes.
103pub fn fleet_state_dir(mur_home: &Path, name: &str) -> PathBuf {
104 mur_home.join(FLEET_STATE).join(name)
105}
106
107/// `<mur_home>/fleet-state/<name>/runs/` — the run directories of `name`'s
108/// runs (`run.json`, `sidecar.json`, `checkpoint.json`, logs, the daemon's
109/// `dispatch.json`). Inside [`fleet_state_dir`] so only an agent allowed to
110/// run `name` can write them (#2316).
111pub fn fleet_runs_dir(mur_home: &Path, name: &str) -> PathBuf {
112 fleet_state_dir(mur_home, name).join(RUNS)
113}
114
115/// `<mur_home>/fleet-state/<name>/runs/<run_id>/`.
116pub fn fleet_run_dir(mur_home: &Path, name: &str, run_id: &str) -> PathBuf {
117 fleet_runs_dir(mur_home, name).join(run_id)
118}
119
120/// Is `s` safe to join as ONE path segment under a runs directory? Letters,
121/// digits, `-` and `_` only — the same alphabet `mur fleet run --run-id`
122/// accepts — so no `/`, `..`, or empty segment can steer a lookup elsewhere.
123pub fn is_single_segment(s: &str) -> bool {
124 !s.is_empty()
125 && s.len() <= RUN_ID_MAX_LEN
126 && s.chars()
127 .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
128}
129
130/// Longest run id accepted as a path segment.
131pub const RUN_ID_MAX_LEN: usize = 96;
132
133/// Read `<run_dir>/<file>` only when both are what they look like: `run_dir`
134/// is a real directory and `file` a regular file with one link. Anything a
135/// resume or pause TRUSTS is read through this (#2316).
136///
137/// A fleet run directory sits in the fleet's sandbox carve-in, but the path
138/// alone does not make its bytes the fleet's: a symlink, or a hard link to a
139/// file elsewhere, reads through the trusted path into a tree every agent can
140/// write (`runs/`, before the one-time migration moved it). Both are refused
141/// as `InvalidData`; a missing file is still `NotFound`, so callers keep
142/// their "no record" answer. Windows has no stable link count, so there only
143/// symlinks are refused.
144pub fn read_unlinked(run_dir: &Path, file: &str) -> std::io::Result<Vec<u8>> {
145 use std::io::Read;
146 let refuse = |what: &str, p: &Path| {
147 std::io::Error::new(
148 std::io::ErrorKind::InvalidData,
149 format!("{} is {what}; refusing to trust it", p.display()),
150 )
151 };
152 if std::fs::symlink_metadata(run_dir)?.file_type().is_symlink() {
153 return Err(refuse("a symlink", run_dir));
154 }
155 let path = run_dir.join(file);
156 let mut f = open_no_follow(&path).map_err(|e| {
157 if std::fs::symlink_metadata(&path).is_ok_and(|m| m.file_type().is_symlink()) {
158 refuse("a symlink", &path)
159 } else {
160 e
161 }
162 })?;
163 let meta = f.metadata()?;
164 if !meta.is_file() {
165 return Err(refuse("not a regular file", &path));
166 }
167 if link_count(&meta) > 1 {
168 return Err(refuse("a hard link to another file", &path));
169 }
170 let mut out = Vec::new();
171 f.read_to_end(&mut out)?;
172 Ok(out)
173}
174
175#[cfg(unix)]
176fn open_no_follow(path: &Path) -> std::io::Result<std::fs::File> {
177 use std::os::unix::fs::OpenOptionsExt;
178 std::fs::OpenOptions::new()
179 .read(true)
180 .custom_flags(libc::O_NOFOLLOW)
181 .open(path)
182}
183
184#[cfg(not(unix))]
185fn open_no_follow(path: &Path) -> std::io::Result<std::fs::File> {
186 // No O_NOFOLLOW: check, then open. The window is the caller's own tree.
187 if std::fs::symlink_metadata(path)?.file_type().is_symlink() {
188 return Err(std::io::Error::new(
189 std::io::ErrorKind::InvalidData,
190 "symlink",
191 ));
192 }
193 std::fs::File::open(path)
194}
195
196#[cfg(unix)]
197fn link_count(meta: &std::fs::Metadata) -> u64 {
198 std::os::unix::fs::MetadataExt::nlink(meta)
199}
200
201#[cfg(not(unix))]
202fn link_count(_meta: &std::fs::Metadata) -> u64 {
203 1
204}
205
206/// Does the tree at `dir` hold anything [`read_unlinked`] would refuse — a
207/// symlink anywhere, or a regular file with more than one link? `dir` itself
208/// is checked without following it. An unreadable tree answers `true`: the
209/// caller is deciding whether to trust it.
210pub fn holds_links(dir: &Path) -> bool {
211 let Ok(meta) = std::fs::symlink_metadata(dir) else {
212 return true;
213 };
214 if meta.file_type().is_symlink() {
215 return true;
216 }
217 if meta.is_file() {
218 return link_count(&meta) > 1;
219 }
220 if !meta.is_dir() {
221 return true;
222 }
223 let Ok(entries) = std::fs::read_dir(dir) else {
224 return true;
225 };
226 entries
227 .map(|e| e.map(|e| holds_links(&e.path())))
228 .any(|r| r.unwrap_or(true))
229}
230
231/// Directory holding the daemon's agent-readable heartbeat (#2116).
232///
233/// Not `murmurd.lock`: a sealed agent must know the daemon is up before it
234/// queues a request only the daemon serves, and on Linux it reads only what
235/// Landlock grants. A file grant is pinned to the inode present at seal time
236/// and is skipped outright when the file does not exist yet (the daemon has
237/// not started), so the grant is on this DIRECTORY, which the sandbox builder
238/// creates before sealing; the daemon replaces the file inside it with
239/// tmp + rename. Only a daemon that sweeps the fleet-dispatch inbox writes
240/// it, so an older daemon reads as "down" — correctly, since it would never
241/// serve the request.
242pub const DAEMON_HEARTBEAT_DIR: &str = "daemon-heartbeat";
243
244/// The heartbeat file inside [`DAEMON_HEARTBEAT_DIR`]: JSON carrying an
245/// RFC 3339 `heartbeat_at`.
246pub const DAEMON_HEARTBEAT_FILE: &str = "heartbeat.json";
247
248/// `<mur_home>/daemon-heartbeat/heartbeat.json`.
249pub fn daemon_heartbeat_path(mur_home: &Path) -> PathBuf {
250 mur_home
251 .join(DAEMON_HEARTBEAT_DIR)
252 .join(DAEMON_HEARTBEAT_FILE)
253}
254
255#[cfg(test)]
256mod tests {
257 use super::*;
258
259 #[test]
260 fn read_unlinked_reads_a_plain_file_and_reports_a_missing_one() {
261 let tmp = tempfile::tempdir().unwrap();
262 std::fs::write(tmp.path().join("f"), b"ok").unwrap();
263 assert_eq!(read_unlinked(tmp.path(), "f").unwrap(), b"ok");
264 let missing = read_unlinked(tmp.path(), "nope").unwrap_err();
265 assert_eq!(missing.kind(), std::io::ErrorKind::NotFound);
266 assert!(!holds_links(tmp.path()));
267 }
268
269 #[cfg(unix)]
270 #[test]
271 fn read_unlinked_refuses_a_symlinked_file_or_directory() {
272 let tmp = tempfile::tempdir().unwrap();
273 let outside = tmp.path().join("outside");
274 std::fs::create_dir(&outside).unwrap();
275 std::fs::write(outside.join("f"), b"forged").unwrap();
276
277 let dir = tmp.path().join("run");
278 std::fs::create_dir(&dir).unwrap();
279 std::os::unix::fs::symlink(outside.join("f"), dir.join("f")).unwrap();
280 let e = read_unlinked(&dir, "f").unwrap_err();
281 assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
282 assert!(holds_links(&dir));
283
284 let linked_dir = tmp.path().join("run2");
285 std::os::unix::fs::symlink(&outside, &linked_dir).unwrap();
286 let e = read_unlinked(&linked_dir, "f").unwrap_err();
287 assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
288 assert!(holds_links(&linked_dir));
289 }
290
291 #[cfg(unix)]
292 #[test]
293 fn read_unlinked_refuses_a_hard_link_to_a_file_elsewhere() {
294 let tmp = tempfile::tempdir().unwrap();
295 std::fs::write(tmp.path().join("elsewhere"), b"forged").unwrap();
296 let dir = tmp.path().join("run");
297 std::fs::create_dir(&dir).unwrap();
298 std::fs::hard_link(tmp.path().join("elsewhere"), dir.join("f")).unwrap();
299 let e = read_unlinked(&dir, "f").unwrap_err();
300 assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
301 assert!(holds_links(&dir));
302 }
303
304 #[test]
305 fn runs_is_not_run_state() {
306 // #2320: fleet runs live under `fleet-state/` and an agent's own runs
307 // under its home, so nothing a sandboxed run writes needs `runs/` —
308 // and granting it whole let one agent rewrite another's records.
309 assert!(!RUN_STATE_DIRS.contains(&RUNS));
310 }
311
312 #[test]
313 fn agent_runs_live_in_the_agent_home() {
314 let d = agent_runs_dir(Path::new("/m"), "bob");
315 assert_eq!(d, Path::new("/m").join(AGENTS).join("bob").join(RUNS));
316 }
317
318 #[test]
319 fn fleet_definitions_are_not_run_state() {
320 // The whole point of FLEET_STATE: a run writes there, never into
321 // the tree that holds the fleet's own definition and kill-switch.
322 assert!(!RUN_STATE_DIRS.contains(&FLEETS));
323 assert!(RUN_STATE_DIRS.contains(&FLEET_STATE));
324 assert_ne!(FLEET_STATE, RUNS);
325 }
326
327 #[test]
328 fn commander_is_not_run_state() {
329 // A grant on `commander/` reaches the commander's private key, its
330 // `.env` and the pinned public keys directives are verified against.
331 assert!(!RUN_STATE_DIRS.contains(&crate::commander::COMMANDER_DIR));
332 }
333
334 #[test]
335 fn fleet_definitions_are_not_an_authoring_grant() {
336 // Same boundary, the other writer: the seeded concierge gets write on
337 // every AUTHORING_DIRS entry, so `fleets/` there hands it the fleet's
338 // members, limits, HITL pre-approvals and `.stopped` kill-switch.
339 assert!(!crate::agent::AUTHORING_DIRS.contains(&FLEETS));
340 assert!(!crate::agent::AUTHORING_DIRS.contains(&FLEET_STATE));
341 }
342}