Skip to main content

trusty_code/workstreams/
path.rs

1//! Storage-path derivation for the workstream store (DOC-48 §3.1).
2//!
3//! Why: the spec pins the filename shape (`workstreams-{project_slug}-{hash}.json`)
4//! to the daemon's OWN [`ProjectBinding`] — never a caller-supplied label —
5//! so two daemons bound to the same project always agree on one file, and
6//! two different projects (even same-named checkouts) never collide.
7//! What: [`store_filename`] derives the filesystem-safe slug + a truncated
8//! SHA-256 fingerprint of the canonical root from a [`ProjectBinding`];
9//! [`store_path`] joins it under a data directory; [`default_data_dir`]
10//! resolves `~/.trusty-code` (mirrors trusty-mpm's `~/.trusty-mpm`
11//! precedent, `crates/trusty-mpm/src/core/paths.rs`).
12//! Test: `path_tests`.
13
14use std::path::{Path, PathBuf};
15
16use sha2::{Digest, Sha256};
17
18use crate::binding::ProjectBinding;
19
20/// Number of hex characters kept from the SHA-256 digest (§3.1: "truncated
21/// to 8 chars").
22const HASH_LEN: usize = 8;
23
24/// Fixed filename used when the daemon is projectless (`ProjectBinding::None`).
25///
26/// Why: DOC-48 §2.3/§3.1 only specify the filename shape for a BOUND
27/// project; a projectless daemon has no path to slug or hash. Rather than
28/// fabricate a fake root, this ticket resolves the ambiguity with one fixed,
29/// documented filename — a projectless daemon has at most one workstream
30/// store regardless of which directory `tcode serve` happened to start in.
31const PROJECTLESS_FILENAME: &str = "workstreams-projectless.json";
32
33/// Resolve `~/.trusty-code`, creating it at mode `0700` and tightening it if a
34/// previous run left it permissive.
35///
36/// Why: mirrors `trusty-mpm`'s `~/.trusty-mpm` precedent
37/// (`crates/trusty-mpm/src/core/paths.rs`) rather than inventing a new
38/// resolution convention. #5426 moved the resolution itself into
39/// [`crate::paths::private_state`], which also owns the `0700` mode this
40/// directory must carry — a workstream store sitting beside transcripts and
41/// logs is private state, not an independent location. #6999: this function is
42/// the ONE place every private-state writer resolves that root — the workstream
43/// store, `serve`'s router, and `agent_loop::telemetry`'s own `default_data_dir`
44/// all end here — so the mode guarantee is applied here rather than at each
45/// writer's own `create_dir_all`, which would apply the process umask and leave
46/// `0755`. Applying it anywhere else would be a second copy of the rule.
47/// What: delegates to [`crate::paths::private_state::ensure_private_state_dir`]:
48/// `dirs::home_dir()/.trusty-code`, created if missing and chmod'd to `0700` if
49/// any group or other bit is set. On an I/O failure it falls back to the plain
50/// [`crate::paths::private_state::private_state_dir`] path, logging at `warn` —
51/// a harness that cannot create its state directory should still report what it
52/// tried, not panic. Never panics.
53/// Test: `path_tests::default_data_dir_is_dot_trusty_code`,
54/// `path_tests::ensure_or_report_creates_and_tightens_a_permissive_dir`,
55/// `tests/cli_e2e.rs::a_non_import_command_tightens_a_permissive_private_state_dir`,
56/// `paths::private_state::private_state_tests::private_state_dir_matches_home_when_available`.
57pub fn default_data_dir() -> PathBuf {
58    // #6999: the README promised an existing permissive `~/.trusty-code` is
59    // tightened on the next run; before this, only `tcode paths import` did it.
60    // `private_state_dir` owns home resolution, including the no-home fallback.
61    ensure_or_report(crate::paths::private_state::private_state_dir())
62}
63
64/// Create and tighten an already-resolved private-state root, or report why not.
65///
66/// Why: the hermetic core of [`default_data_dir`] (#6999), mirroring
67/// [`crate::paths::private_state::private_state_dir_at`]'s reason for existing —
68/// a test drives it with a temp directory, so no test creates, chmods, or
69/// reports on the developer's real `~/.trusty-code`.
70/// What: [`crate::paths::private_state::ensure_dir`], returning `dir` either
71/// way. On failure — the path is a regular file, the home directory is
72/// read-only, the filesystem is full — it logs at `warn` with the path and the
73/// error and hands back the same path, so a harness that cannot create its state
74/// directory still runs and still says what it tried. Never panics.
75/// Test: `path_tests::ensure_or_report_creates_and_tightens_a_permissive_dir`,
76/// `path_tests::ensure_or_report_falls_back_when_the_path_is_a_file`,
77/// `tests/cli_e2e.rs::an_unusable_private_state_path_warns_instead_of_panicking`.
78pub(crate) fn ensure_or_report(dir: PathBuf) -> PathBuf {
79    if let Err(e) = crate::paths::private_state::ensure_dir(&dir) {
80        tracing::warn!(
81            path = %dir.display(),
82            error = %e,
83            "could not create the trusty-code private state directory; \
84             continuing with the resolved path, which may not exist or may \
85             be readable by other users on this machine"
86        );
87    }
88    dir
89}
90
91/// Turn an arbitrary string into a filesystem-safe, lowercase, hyphenated
92/// slug.
93///
94/// Why: a project's directory basename may contain characters unsafe for a
95/// filename component (spaces, underscores, mixed case); the slug must be
96/// stable and readable.
97/// What: keeps ASCII alphanumerics (lowercased), collapses any run of other
98/// characters into a single `-`, and trims leading/trailing `-`. An
99/// all-non-alphanumeric input slugs to `"project"` rather than an empty
100/// string.
101/// Test: `path_tests::slugify_*`.
102fn slugify(raw: &str) -> String {
103    let mut slug = String::with_capacity(raw.len());
104    let mut last_was_dash = false;
105    for ch in raw.chars() {
106        if ch.is_ascii_alphanumeric() {
107            slug.push(ch.to_ascii_lowercase());
108            last_was_dash = false;
109        } else if !last_was_dash && !slug.is_empty() {
110            slug.push('-');
111            last_was_dash = true;
112        }
113    }
114    while slug.ends_with('-') {
115        slug.pop();
116    }
117    if slug.is_empty() {
118        "project".to_string()
119    } else {
120        slug
121    }
122}
123
124/// Deterministic 8-hex-char fingerprint of a project root path.
125///
126/// Why: disambiguates multiple checkouts that share a directory basename
127/// (§3.1: "to handle multiple checkouts of the same project").
128/// What: SHA-256 of the path's platform string, truncated to
129/// [`HASH_LEN`] lowercase hex characters. Deterministic for a given path,
130/// unlike a per-process `RandomState`-seeded hasher.
131/// Test: `path_tests::project_hash_is_deterministic`,
132/// `path_tests::project_hash_differs_for_different_paths`.
133fn project_hash(root: &Path) -> String {
134    let mut hasher = Sha256::new();
135    hasher.update(root.to_string_lossy().as_bytes());
136    let digest = hasher.finalize();
137    let mut hex = String::with_capacity(digest.len() * 2);
138    for byte in digest {
139        hex.push_str(&format!("{byte:02x}"));
140    }
141    hex.truncate(HASH_LEN);
142    hex
143}
144
145/// Derive the workstream store's filename from a daemon's project binding
146/// (DOC-48 §3.1).
147///
148/// Why: the ONE place the filename shape is assembled, so the store and any
149/// future inspection tooling can never disagree on it.
150/// What: for a bound project, `workstreams-{slug}-{hash}.json` where `slug`
151/// comes from the root's basename and `hash` fingerprints the full root
152/// path (§3.1). For [`ProjectBinding::None`], the fixed
153/// [`PROJECTLESS_FILENAME`] (see its docs for why).
154/// Test: `path_tests::store_filename_for_bound_project`,
155/// `path_tests::store_filename_for_projectless`.
156pub fn store_filename(binding: &ProjectBinding) -> String {
157    match binding.root() {
158        Some(root) => {
159            let basename = root
160                .file_name()
161                .map(|n| n.to_string_lossy().to_string())
162                .unwrap_or_else(|| root.display().to_string());
163            let slug = slugify(&basename);
164            let hash = project_hash(root);
165            format!("workstreams-{slug}-{hash}.json")
166        }
167        None => PROJECTLESS_FILENAME.to_string(),
168    }
169}
170
171/// Join [`store_filename`] under a data directory to get the full store path.
172///
173/// Why: the single entry point `WorkstreamStore::load_for_binding` (and any
174/// future daemon boot code) calls to resolve where the store file lives.
175/// What: `data_dir.join(store_filename(binding))`.
176/// Test: `path_tests::store_path_joins_data_dir_and_filename`.
177pub fn store_path(data_dir: &Path, binding: &ProjectBinding) -> PathBuf {
178    data_dir.join(store_filename(binding))
179}
180
181#[cfg(test)]
182#[path = "path_tests.rs"]
183mod path_tests;