tinyharness_lib/paths.rs
1//! Central resolution of every filesystem location TinyHarness touches.
2//!
3//! Previously each module hard-coded its own `~/.config/tinyharness/...` or
4//! `~/.local/share/tinyharness/...` path by reading `$HOME` inline, which made
5//! the library impossible to drive against an alternate root (tests, embedded
6//! use, portable installs, a second profile). Every such location now lives in
7//! [`Paths`], and every subsystem accepts a `&Paths` (or an explicit `Path`).
8//!
9//! # Resolution rules
10//!
11//! | Logical location | Default |
12//! |---|---|
13//! | config dir | `$XDG_CONFIG_HOME/tinyharness` → `$HOME/.config/tinyharness` → `.config/tinyharness` |
14//! | data dir | `$XDG_DATA_HOME/tinyharness` → `$HOME/.local/share/tinyharness` → `.local/share/tinyharness` |
15//! | project dir | process CWD → `.` |
16//!
17//! The relative fallbacks preserve the pre-existing behaviour when `HOME` is
18//! unset (the old code did `home.unwrap_or(".")`, yielding `./.config/...`), so
19//! a caller with no home directory still gets a writable, self-consistent tree
20//! instead of a panic.
21//!
22//! Per the XDG spec, `XDG_*_HOME` values that are empty or relative are
23//! ignored (a relative path is not an absolute path, so it cannot be resolved
24//! predictably against a project root); the `$HOME` fallback is used instead.
25//!
26//! # Legacy locations
27//!
28//! Personal skills historically lived in `~/.tinyharness/skills`. That
29//! directory is still searched, *after* `config_dir/skills`, so an existing
30//! install keeps working while the documented XDG location takes precedence.
31//! See [`Paths::personal_skills_dirs`].
32//!
33//! # Example
34//!
35//! ```no_run
36//! use std::path::PathBuf;
37//! use tinyharness_lib::paths::Paths;
38//!
39//! // Drive the library against a sandbox root instead of the real home dir.
40//! let paths = Paths::with_home(PathBuf::from("/tmp/th-profile"));
41//! let store = tinyharness_lib::session::SessionStore::from_paths(&paths);
42//! ```
43
44use std::path::{Path, PathBuf};
45
46/// Directory name appended to the XDG config/data roots.
47const APP_DIR: &str = "tinyharness";
48
49/// Legacy personal dot-directory name (`~/.tinyharness`).
50const LEGACY_DOT_DIR: &str = ".tinyharness";
51
52/// Fallback config root when neither `XDG_CONFIG_HOME` nor `HOME` is usable.
53const FALLBACK_CONFIG_ROOT: &str = ".config";
54
55/// Fallback data root when neither `XDG_DATA_HOME` nor `HOME` is usable.
56const FALLBACK_DATA_ROOT: &str = ".local/share";
57
58/// Every filesystem location TinyHarness needs, fully injectable.
59///
60/// Construct with [`Paths::default`] (real environment), [`Paths::with_home`]
61/// (a single root, ideal for tests and portable installs), [`Paths::from_env`]
62/// (an injected environment map, for hermetic tests), or [`Paths::new`] plus
63/// the `with_*` builders for arbitrary layouts.
64///
65/// All getters derive their paths on demand, so overriding one root
66/// automatically re-derives every file beneath it.
67#[derive(Debug, Clone, PartialEq, Eq)]
68pub struct Paths {
69 home: Option<PathBuf>,
70 config_dir: PathBuf,
71 data_dir: PathBuf,
72 project_dir: PathBuf,
73}
74
75impl Default for Paths {
76 /// Resolve from the real process environment and CWD.
77 fn default() -> Self {
78 Self::from_env(|key| std::env::var(key).ok())
79 }
80}
81
82impl Paths {
83 /// Build from an injected environment lookup.
84 ///
85 /// `env` returns `None` for unset variables. This is the seam for hermetic
86 /// tests: no process-global `set_var` (and its parallel-test races) needed.
87 ///
88 /// `HOME`, `USERPROFILE`, and the `XDG_*` roots must be absolute, following
89 /// the XDG rule that a relative root is ignored. Absoluteness is
90 /// platform-dependent — `Path::is_absolute` treats `/home/u` as *relative*
91 /// on Windows — so a POSIX-style value inherited from an MSYS/Git Bash
92 /// parent shell is rejected there. Note that the lookup is `HOME` then
93 /// `USERPROFILE`, and the absolute check happens *after*: a `HOME` that is
94 /// set but unusable leaves `home()` as `None` rather than falling through
95 /// to `USERPROFILE`, and the config/data roots degrade to the `.`-relative
96 /// fallback. `Paths` itself never fails, so the tree stays self-consistent.
97 ///
98 /// The project directory always comes from the process CWD — it is a
99 /// working location, not a configuration value — falling back to `.` if it
100 /// cannot be determined.
101 pub fn from_env<F>(env: F) -> Self
102 where
103 F: Fn(&str) -> Option<String>,
104 {
105 let home = env("HOME")
106 .or_else(|| env("USERPROFILE"))
107 .map(PathBuf::from)
108 .filter(|p| p.is_absolute());
109
110 let config_dir = xdg_dir(&env, "XDG_CONFIG_HOME")
111 .map(|root| root.join(APP_DIR))
112 .unwrap_or_else(|| {
113 home.as_ref()
114 .map(|h| h.join(FALLBACK_CONFIG_ROOT))
115 .unwrap_or_else(|| PathBuf::from(FALLBACK_CONFIG_ROOT))
116 .join(APP_DIR)
117 });
118
119 let data_dir = xdg_dir(&env, "XDG_DATA_HOME")
120 .map(|root| root.join(APP_DIR))
121 .unwrap_or_else(|| {
122 home.as_ref()
123 .map(|h| h.join(FALLBACK_DATA_ROOT))
124 .unwrap_or_else(|| PathBuf::from(FALLBACK_DATA_ROOT))
125 .join(APP_DIR)
126 });
127
128 let project_dir = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
129
130 Paths {
131 home,
132 config_dir,
133 data_dir,
134 project_dir,
135 }
136 }
137
138 /// Derive every location from a single home directory.
139 ///
140 /// Ignores `XDG_*` entirely: config goes to `<home>/.config/tinyharness`
141 /// and data to `<home>/.local/share/tinyharness`. This is the simplest way
142 /// to point the library at a disposable root.
143 ///
144 /// The project directory is set to `home` itself, so the resulting layout
145 /// is fully self-contained: nothing outside `home` is read. Note the
146 /// consequence — `<home>/.tinyharness/` then acts as *both* the legacy
147 /// personal-skills root and the project `.tinyharness/` directory. Use
148 /// [`Paths::new`] + [`Paths::with_legacy_home`] to keep those distinct, as
149 /// a real install does.
150 pub fn with_home(home: impl Into<PathBuf>) -> Self {
151 let home = home.into();
152 Paths {
153 config_dir: home.join(FALLBACK_CONFIG_ROOT).join(APP_DIR),
154 data_dir: home.join(FALLBACK_DATA_ROOT).join(APP_DIR),
155 project_dir: home.clone(),
156 home: Some(home),
157 }
158 }
159
160 /// Build from explicit roots, with no implicit home.
161 ///
162 /// Because there is no `home`, the legacy `~/.tinyharness/skills` directory
163 /// is not searched — only `<config_dir>/skills`. Use
164 /// [`Paths::with_legacy_home`] if you also need the legacy location.
165 pub fn new(config_dir: PathBuf, data_dir: PathBuf, project_dir: PathBuf) -> Self {
166 Paths {
167 home: None,
168 config_dir,
169 data_dir,
170 project_dir,
171 }
172 }
173
174 /// Override the config directory (default: `<home>/.config/tinyharness`).
175 pub fn with_config_dir(mut self, dir: impl Into<PathBuf>) -> Self {
176 self.config_dir = dir.into();
177 self
178 }
179
180 /// Override the data directory (default: `<home>/.local/share/tinyharness`).
181 pub fn with_data_dir(mut self, dir: impl Into<PathBuf>) -> Self {
182 self.data_dir = dir.into();
183 self
184 }
185
186 /// Override the project directory that `.tinyharness/` discovery starts from.
187 pub fn with_project_dir(mut self, dir: impl Into<PathBuf>) -> Self {
188 self.project_dir = dir.into();
189 self
190 }
191
192 /// Record a home directory so the legacy `~/.tinyharness/skills` location
193 /// is searched, without changing any other root.
194 pub fn with_legacy_home(mut self, home: impl Into<PathBuf>) -> Self {
195 self.home = Some(home.into());
196 self
197 }
198
199 // ── Roots ───────────────────────────────────────────────────────────
200
201 /// The app's config directory (e.g. `~/.config/tinyharness`).
202 pub fn config_dir(&self) -> &Path {
203 &self.config_dir
204 }
205
206 /// The app's data directory (e.g. `~/.local/share/tinyharness`).
207 pub fn data_dir(&self) -> &Path {
208 &self.data_dir
209 }
210
211 /// Directory that `.tinyharness/` project discovery walks up from.
212 pub fn project_dir(&self) -> &Path {
213 &self.project_dir
214 }
215
216 /// Resolved home directory, if one was available.
217 ///
218 /// `None` for layouts built via [`Paths::new`] with no home, or when the
219 /// environment exposed no usable `HOME`.
220 pub fn home(&self) -> Option<&Path> {
221 self.home.as_deref()
222 }
223
224 // ── Global (per-user) files ──────────────────────────────────────────
225
226 /// `~/.config/tinyharness/settings.json`
227 pub fn settings_file(&self) -> PathBuf {
228 self.config_dir.join("settings.json")
229 }
230
231 /// `~/.config/tinyharness/prompts/`
232 pub fn prompts_dir(&self) -> PathBuf {
233 self.config_dir.join("prompts")
234 }
235
236 /// `~/.config/tinyharness/custom_tools.json`
237 pub fn custom_tools_file(&self) -> PathBuf {
238 self.config_dir.join("custom_tools.json")
239 }
240
241 /// `~/.local/share/tinyharness/sessions/`
242 pub fn sessions_dir(&self) -> PathBuf {
243 self.data_dir.join("sessions")
244 }
245
246 /// Directory holding the readline history file.
247 ///
248 /// Same as [`Paths::data_dir`]; exposed separately so callers express
249 /// intent instead of reaching into the data root.
250 pub fn history_dir(&self) -> PathBuf {
251 self.data_dir.clone()
252 }
253
254 /// `~/.local/share/tinyharness/audit.jsonl`
255 pub fn audit_log_file(&self) -> PathBuf {
256 self.data_dir.join("audit.jsonl")
257 }
258
259 /// `~/.local/share/tinyharness/backups/`
260 pub fn backups_dir(&self) -> PathBuf {
261 self.data_dir.join("backups")
262 }
263
264 /// Personal skill directories, in increasing precedence order.
265 ///
266 /// `<config_dir>/skills` first (the documented location), then the legacy
267 /// `~/.tinyharness/skills` when a home directory is known. Duplicates are
268 /// collapsed, so a layout where both resolve to the same path yields a
269 /// single entry. Earlier entries win on name collisions — see
270 /// [`crate::skill::discover_skills_in`].
271 pub fn personal_skills_dirs(&self) -> Vec<PathBuf> {
272 let mut dirs = vec![self.config_dir.join("skills")];
273 if let Some(home) = self.home.as_deref() {
274 let legacy = home.join(LEGACY_DOT_DIR).join("skills");
275 if !dirs.contains(&legacy) {
276 dirs.push(legacy);
277 }
278 }
279 dirs
280 }
281
282 // ── Project-scoped files ─────────────────────────────────────────────
283
284 /// `<project_dir>/.tinyharness/`
285 pub fn project_config_root(&self) -> PathBuf {
286 self.project_dir.join(LEGACY_DOT_DIR)
287 }
288
289 /// Starting point for the `.tinyharness/config.json` walk-up.
290 ///
291 /// Discovery itself walks ancestors, so the returned path is only the
292 /// seed — see [`crate::config::discover_project_settings`].
293 pub fn project_settings_file(&self) -> PathBuf {
294 self.project_config_root().join("config.json")
295 }
296
297 /// Starting point for the `.tinyharness/custom_tools.json` walk-up.
298 pub fn project_custom_tools_file(&self) -> PathBuf {
299 self.project_config_root().join("custom_tools.json")
300 }
301
302 /// `<project_dir>/.tinyharness/skills/`
303 pub fn project_skills_dir(&self) -> PathBuf {
304 self.project_config_root().join("skills")
305 }
306}
307
308/// Read an XDG root, honouring the spec's "unset or empty means default" and
309/// "must be absolute" rules.
310fn xdg_dir<F>(env: &F, key: &str) -> Option<PathBuf>
311where
312 F: Fn(&str) -> Option<String>,
313{
314 env(key)
315 .map(|value| (value.trim().to_string(), PathBuf::from(&value)))
316 .filter(|(raw, path)| !raw.is_empty() && path.is_absolute())
317 .map(|(_, path)| path)
318}
319
320#[cfg(test)]
321mod tests {
322 use super::*;
323 use std::collections::HashMap;
324
325 /// Build an immutable env map so tests never mutate process globals.
326 /// The returned closure owns its map, so it is `'static`.
327 fn env_map(entries: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
328 let map: HashMap<String, String> = entries
329 .iter()
330 .map(|(k, v)| ((*k).to_string(), (*v).to_string()))
331 .collect();
332 move |key: &str| map.get(key).cloned()
333 }
334
335 fn abs(path: &str) -> PathBuf {
336 PathBuf::from(path)
337 }
338
339 /// Build a root that is absolute on *this* platform.
340 ///
341 /// `Path::is_absolute` is platform-dependent: `/home/u` is relative on
342 /// Windows, and `C:/u` is relative on Linux. `Paths::from_env` rejects
343 /// relative `HOME`/`USERPROFILE`/`XDG_*` values (the XDG spec requires
344 /// ignoring non-absolute roots), so a hard-coded POSIX fixture does not
345 /// merely look wrong on Windows — it is silently discarded and every
346 /// assertion collapses onto the `./.config` fallback. Deriving fixtures
347 /// from the CWD keeps them absolute everywhere.
348 ///
349 /// Nothing is created on disk: `Paths` only computes strings.
350 fn host_root(tag: &str) -> PathBuf {
351 std::env::current_dir()
352 .expect("CWD is absolute on every supported platform")
353 .join(format!("th-{tag}"))
354 }
355
356 /// [`host_root`] as an environment-variable value.
357 fn env_value(root: &Path) -> &str {
358 root.to_str().expect("fixtures are valid UTF-8")
359 }
360
361 #[test]
362 fn home_fallback_when_no_xdg() {
363 let home = host_root("home");
364 let paths = Paths::from_env(env_map(&[("HOME", env_value(&home))]));
365 assert_eq!(paths.config_dir(), home.join(".config/tinyharness"));
366 assert_eq!(paths.data_dir(), home.join(".local/share/tinyharness"));
367 assert_eq!(paths.home(), Some(home.as_path()));
368 }
369
370 #[test]
371 fn xdg_roots_take_precedence_over_home() {
372 let home = host_root("home");
373 let config = host_root("xdg-config");
374 let data = host_root("xdg-data");
375 let paths = Paths::from_env(env_map(&[
376 ("HOME", env_value(&home)),
377 ("XDG_CONFIG_HOME", env_value(&config)),
378 ("XDG_DATA_HOME", env_value(&data)),
379 ]));
380 assert_eq!(paths.config_dir(), config.join("tinyharness"));
381 assert_eq!(paths.data_dir(), data.join("tinyharness"));
382 }
383
384 #[test]
385 fn empty_or_relative_xdg_is_ignored() {
386 let home = host_root("home");
387 let empty = Paths::from_env(env_map(&[
388 ("HOME", env_value(&home)),
389 ("XDG_CONFIG_HOME", " "),
390 // Relative on every supported platform, so this exercises the
391 // "must be absolute" rule rather than platform quirks.
392 ("XDG_DATA_HOME", "relative/data"),
393 ]));
394 assert_eq!(empty.config_dir(), home.join(".config/tinyharness"));
395 assert_eq!(empty.data_dir(), home.join(".local/share/tinyharness"));
396 }
397
398 #[test]
399 fn missing_home_uses_dot_prefixed_fallbacks() {
400 // Preserves the historical `unwrap_or(".")` behaviour: the tree stays
401 // self-consistent and writable rather than panicking.
402 let paths = Paths::from_env(env_map(&[]));
403 assert_eq!(paths.config_dir(), abs(".config/tinyharness"));
404 assert_eq!(paths.data_dir(), abs(".local/share/tinyharness"));
405 assert_eq!(paths.home(), None);
406 assert_eq!(
407 paths.settings_file(),
408 abs(".config/tinyharness/settings.json")
409 );
410 }
411
412 #[test]
413 fn userprofile_is_home_fallback() {
414 let home = host_root("userprofile-home");
415 let paths = Paths::from_env(env_map(&[("USERPROFILE", env_value(&home))]));
416 assert_eq!(paths.config_dir(), home.join(".config/tinyharness"));
417 assert_eq!(paths.home(), Some(home.as_path()));
418 }
419
420 #[test]
421 fn home_takes_precedence_over_userprofile() {
422 let home = host_root("home");
423 let windows_home = host_root("userprofile");
424 let paths = Paths::from_env(env_map(&[
425 ("HOME", env_value(&home)),
426 ("USERPROFILE", env_value(&windows_home)),
427 ]));
428 assert_eq!(paths.config_dir(), home.join(".config/tinyharness"));
429 assert_eq!(paths.home(), Some(home.as_path()));
430 }
431
432 #[test]
433 fn relative_home_is_rejected() {
434 let paths = Paths::from_env(env_map(&[("HOME", "relative/home")]));
435 assert_eq!(paths.home(), None);
436 assert_eq!(paths.config_dir(), abs(".config/tinyharness"));
437 }
438
439 #[test]
440 fn relative_home_does_not_fall_through_to_userprofile() {
441 // Locks the documented lookup order: HOME is preferred when it is
442 // *set*, and the absolute check runs after the fallback, so an
443 // unusable HOME suppresses home resolution entirely instead of
444 // yielding to a perfectly usable USERPROFILE.
445 let windows_home = host_root("userprofile");
446 let paths = Paths::from_env(env_map(&[
447 ("HOME", "relative/home"),
448 ("USERPROFILE", env_value(&windows_home)),
449 ]));
450 assert_eq!(paths.home(), None);
451 assert_eq!(paths.config_dir(), abs(".config/tinyharness"));
452 assert_eq!(paths.data_dir(), abs(".local/share/tinyharness"));
453 }
454
455 #[test]
456 fn with_home_derives_every_location() {
457 let paths = Paths::with_home("/tmp/profile");
458 assert_eq!(
459 paths.settings_file(),
460 abs("/tmp/profile/.config/tinyharness/settings.json")
461 );
462 assert_eq!(
463 paths.prompts_dir(),
464 abs("/tmp/profile/.config/tinyharness/prompts")
465 );
466 assert_eq!(
467 paths.custom_tools_file(),
468 abs("/tmp/profile/.config/tinyharness/custom_tools.json")
469 );
470 assert_eq!(
471 paths.sessions_dir(),
472 abs("/tmp/profile/.local/share/tinyharness/sessions")
473 );
474 assert_eq!(
475 paths.history_dir(),
476 abs("/tmp/profile/.local/share/tinyharness")
477 );
478 // project_dir seeds at the root so in-home projects still resolve
479 assert_eq!(
480 paths.project_config_root(),
481 abs("/tmp/profile/.tinyharness")
482 );
483 }
484
485 #[test]
486 fn personal_skills_dirs_prefer_xdg_then_legacy() {
487 let paths = Paths::with_home("/tmp/profile");
488 assert_eq!(
489 paths.personal_skills_dirs(),
490 vec![
491 abs("/tmp/profile/.config/tinyharness/skills"),
492 abs("/tmp/profile/.tinyharness/skills"),
493 ]
494 );
495 }
496
497 #[test]
498 fn personal_skills_dirs_dedupes_when_legacy_matches_config() {
499 // A caller that points config_dir straight at the legacy dot-dir
500 // should not have it scanned twice.
501 let paths = Paths::with_home("/tmp/profile").with_config_dir("/tmp/profile/.tinyharness");
502 assert_eq!(
503 paths.personal_skills_dirs(),
504 vec![abs("/tmp/profile/.tinyharness/skills")]
505 );
506 }
507
508 #[test]
509 fn personal_skills_dirs_omit_legacy_without_home() {
510 let paths = Paths::new(abs("/cfg"), abs("/data"), abs("/proj"));
511 assert_eq!(paths.personal_skills_dirs(), vec![abs("/cfg/skills")]);
512 assert_eq!(paths.home(), None);
513 }
514
515 #[test]
516 fn with_legacy_home_restores_legacy_scan_only() {
517 let paths = Paths::new(abs("/cfg"), abs("/data"), abs("/proj")).with_legacy_home("/home/u");
518 assert_eq!(paths.config_dir(), abs("/cfg"));
519 assert_eq!(
520 paths.personal_skills_dirs(),
521 vec![abs("/cfg/skills"), abs("/home/u/.tinyharness/skills")]
522 );
523 }
524
525 #[test]
526 fn builders_override_individual_roots() {
527 let paths = Paths::with_home("/tmp/profile")
528 .with_config_dir("/custom/cfg")
529 .with_data_dir("/custom/data")
530 .with_project_dir("/custom/proj");
531 assert_eq!(paths.settings_file(), abs("/custom/cfg/settings.json"));
532 assert_eq!(paths.sessions_dir(), abs("/custom/data/sessions"));
533 assert_eq!(
534 paths.project_settings_file(),
535 abs("/custom/proj/.tinyharness/config.json")
536 );
537 assert_eq!(
538 paths.project_custom_tools_file(),
539 abs("/custom/proj/.tinyharness/custom_tools.json")
540 );
541 assert_eq!(
542 paths.project_skills_dir(),
543 abs("/custom/proj/.tinyharness/skills")
544 );
545 }
546
547 #[test]
548 fn overrides_re_derive_dependent_paths() {
549 // Guards against caching derived file paths at construction time.
550 let base = Paths::with_home("/tmp/profile");
551 let moved = base.clone().with_data_dir("/elsewhere/data");
552 assert_ne!(base.sessions_dir(), moved.sessions_dir());
553 assert_eq!(moved.sessions_dir(), abs("/elsewhere/data/sessions"));
554 }
555
556 #[test]
557 fn default_reads_process_env() {
558 // Only structural guarantees: whatever the ambient environment says,
559 // the derived paths must agree with each other.
560 let paths = Paths::default();
561 assert!(paths.settings_file().ends_with("settings.json"));
562 assert!(paths.sessions_dir().ends_with("sessions"));
563 assert_eq!(
564 paths.project_settings_file(),
565 paths.project_dir().join(".tinyharness/config.json")
566 );
567 assert!(!paths.personal_skills_dirs().is_empty());
568 }
569}