Skip to main content

trusty_code/paths/
import.rs

1//! Deterministic, reversible legacy import from `.claude/` into `.trusty-code/`
2//! (#5426, epic #2892).
3//!
4//! Why: switching discovery to `.trusty-code/` would strand every project whose
5//! agents and skills live under `.claude/`. An import has to be observable
6//! before it runs (a plan), it must never overwrite a file the project author
7//! wrote, and it must be undoable — so it reports exactly which files it
8//! created, and nothing else.
9//!
10//! What: [`plan_import`] walks `.claude/agents/`, `.claude/skills/`, and
11//! `.claude/settings.json` and produces a SORTED [`ImportPlan`] naming, for each
12//! source file, the target under `.trusty-code/` and the [`ImportAction`] that
13//! would be taken. [`apply_import`] executes exactly that plan and returns an
14//! [`ImportReport`] listing the files it created. Determinism is what makes the
15//! dry run trustworthy: the same tree always yields the same plan in the same
16//! order, so `--dry-run` output and the real run cannot disagree.
17//!
18//! Four refusals, all producing [`ImportAction::Refuse`] rather than an error
19//! that aborts the whole import:
20//!
21//! - the target already exists (never overwrite a user-authored file);
22//! - the source is, or reaches through, a symlink out of `.claude/`;
23//! - the source carries the executable bit (an imported executable would be
24//!   trusted by every later `.trusty-code/` consumer);
25//! - a `settings.json` whose JSON carries a secret-bearing key
26//!   ([`super::find_secret_key`]).
27//!
28//! Test: `paths::import_tests::*`.
29
30use std::path::{Path, PathBuf};
31
32use super::write_dir::NativeWriteDir;
33use super::{CLAUDE_COMPAT_DIRNAME, SETTINGS_FILENAME, check_native_write_target, native_child};
34
35/// The `.claude/` subtrees an import considers, in plan order.
36///
37/// Why: agents and skills are the authored content #5426 must carry across;
38/// plugins are third-party trees whose provenance this import cannot vouch for,
39/// so they are deliberately NOT copied — a plugin stays discoverable in place
40/// through the compatibility search root.
41/// What: `["agents", "skills"]`.
42/// Test: `paths::import_tests::plan_is_sorted_and_deterministic`.
43pub const IMPORTED_SUBTREES: &[&str] = &["agents", "skills"];
44
45/// What an import would do with one source file.
46///
47/// Why: a plan that only listed copies could not explain a file's absence from
48/// the result, which is the question an operator asks first.
49/// What: [`ImportAction::Copy`] or [`ImportAction::Refuse`] with a
50/// human-readable reason.
51/// Test: `paths::import_tests::existing_target_is_never_overwritten`,
52/// `paths::import_tests::executable_source_is_refused`.
53#[derive(Debug, Clone, PartialEq, Eq)]
54pub enum ImportAction {
55    /// The file will be copied to its target.
56    Copy,
57    /// The file will be skipped; the string says why.
58    Refuse(String),
59}
60
61/// One source file and the target it maps to.
62///
63/// Why: the unit both the dry-run listing and the applied report are built from,
64/// so the two can never describe different work.
65/// What: absolute `from` under `.claude/`, absolute `to` under `.trusty-code/`,
66/// and the [`ImportAction`].
67/// Test: `paths::import_tests::plan_is_sorted_and_deterministic`.
68#[derive(Debug, Clone, PartialEq, Eq)]
69pub struct ImportEntry {
70    /// The source file under `<project>/.claude/`.
71    pub from: PathBuf,
72    /// The target under `<project>/.trusty-code/`.
73    pub to: PathBuf,
74    /// What the import would do with it.
75    pub action: ImportAction,
76}
77
78/// Everything an import would do, in a stable order.
79///
80/// Why: producing the plan and executing it are separate steps precisely so the
81/// operator can read the first before authorising the second.
82/// What: entries sorted by target path.
83/// Test: `paths::import_tests::plan_is_sorted_and_deterministic`.
84#[derive(Debug, Clone, Default, PartialEq, Eq)]
85pub struct ImportPlan {
86    /// The per-file decisions, sorted by [`ImportEntry::to`].
87    pub entries: Vec<ImportEntry>,
88}
89
90impl ImportPlan {
91    /// The entries that would actually be copied.
92    ///
93    /// Why: the count an operator wants before confirming, without re-filtering
94    /// at each call site.
95    /// What: entries whose action is [`ImportAction::Copy`].
96    /// Test: `paths::import_tests::plan_is_sorted_and_deterministic`.
97    pub fn to_copy(&self) -> impl Iterator<Item = &ImportEntry> {
98        self.entries
99            .iter()
100            .filter(|e| e.action == ImportAction::Copy)
101    }
102}
103
104/// What an applied import actually created, and what it declined.
105///
106/// Why: reversibility is a property of the REPORT, not of a flag — deleting
107/// exactly the paths in `created` restores the tree, and nothing else was
108/// touched.
109/// What: `created` holds the files written (sorted); `refused` pairs each
110/// skipped source with its reason.
111/// Test: `paths::import_tests::apply_creates_only_the_planned_files`.
112#[derive(Debug, Clone, Default, PartialEq, Eq)]
113pub struct ImportReport {
114    /// Files this import created, sorted — delete exactly these to undo it.
115    pub created: Vec<PathBuf>,
116    /// Sources not imported, each with the reason.
117    pub refused: Vec<(PathBuf, String)>,
118}
119
120/// Build the import plan for a project root.
121///
122/// Why: the observable half of the import. It touches nothing, so it is safe to
123/// run in a diagnostic.
124/// What: walks each of [`IMPORTED_SUBTREES`] under `<root>/.claude/`, plus
125/// `.claude/settings.json`, mapping every regular file to the same relative path
126/// under `<root>/.trusty-code/` and classifying it per the module docs. Entries
127/// are sorted by target path so the plan is a function of the tree alone. A
128/// missing `.claude/` yields an empty plan, never an error.
129/// Test: `paths::import_tests::plan_is_sorted_and_deterministic`,
130/// `paths::import_tests::missing_claude_dir_yields_empty_plan`,
131/// `paths::import_tests::symlink_escaping_claude_is_refused`.
132pub fn plan_import(project_root: &Path) -> ImportPlan {
133    let claude_root = project_root.join(CLAUDE_COMPAT_DIRNAME);
134    let mut entries = Vec::new();
135
136    for subtree in IMPORTED_SUBTREES {
137        let dir = claude_root.join(subtree);
138        let mut files = Vec::new();
139        collect_files(&dir, &dir, subtree, &mut files);
140        for (relative, from) in files {
141            entries.push(classify(project_root, &claude_root, &relative, &from));
142        }
143    }
144
145    let settings = claude_root.join(SETTINGS_FILENAME);
146    if settings.is_file() {
147        entries.push(classify(
148            project_root,
149            &claude_root,
150            SETTINGS_FILENAME,
151            &settings,
152        ));
153    }
154
155    entries.sort_by(|a, b| a.to.cmp(&b.to));
156    ImportPlan { entries }
157}
158
159/// Recursively collect the regular files under `dir`, relative to `base`.
160///
161/// Why: the plan must cover a skill's whole directory (`SKILL.md` plus its
162/// `references/`), not just its top level.
163/// What: appends `(relative_path_with_prefix, absolute_path)` pairs. A directory
164/// that cannot be read is skipped and logged at `warn` with the path tried —
165/// fail open, since one unreadable subtree must not abort the import of the
166/// rest. Symlinked DIRECTORIES are not descended into; a symlinked file is
167/// collected and refused later by [`classify`], where the reason can be
168/// reported.
169/// Test: `paths::import_tests::plan_is_sorted_and_deterministic`,
170/// `paths::import_tests::unreadable_subtree_is_skipped_with_a_warning`.
171fn collect_files(base: &Path, dir: &Path, prefix: &str, out: &mut Vec<(String, PathBuf)>) {
172    if !dir.is_dir() {
173        return;
174    }
175    let entries = match std::fs::read_dir(dir) {
176        Ok(entries) => entries,
177        Err(e) => {
178            // #5426: fail open — an unreadable subtree loses its files, not the
179            // whole import, and says so.
180            tracing::warn!(
181                path = %dir.display(),
182                error = %e,
183                "could not read a .claude subtree while planning the trusty-code \
184                 import; skipping it and continuing with the rest"
185            );
186            return;
187        }
188    };
189    for entry in entries.flatten() {
190        let path = entry.path();
191        let Ok(meta) = std::fs::symlink_metadata(&path) else {
192            continue;
193        };
194        if meta.is_dir() {
195            collect_files(base, &path, prefix, out);
196        } else if let Ok(rel) = path.strip_prefix(base) {
197            out.push((format!("{prefix}/{}", rel.display()), path.clone()));
198        }
199    }
200}
201
202/// Decide what to do with one source file.
203///
204/// Why: every refusal rule lives here so the plan and the applied run cannot
205/// diverge on a judgement call.
206/// What: applies, in order, the write-target guard (which catches a symlinked
207/// `.trusty-code/` subdirectory pointing out of the project), the
208/// symlink-escape check on the SOURCE, the existing-target check, the
209/// executable-bit check, and — for `settings.json` — the secret-key check.
210/// Test: `paths::import_tests::existing_target_is_never_overwritten`,
211/// `paths::import_tests::executable_source_is_refused`,
212/// `paths::import_tests::symlink_escaping_claude_is_refused`,
213/// `paths::import_tests::secret_bearing_settings_is_refused`.
214fn classify(project_root: &Path, claude_root: &Path, relative: &str, from: &Path) -> ImportEntry {
215    let to = native_child(project_root, relative);
216    let refuse = |reason: String| ImportEntry {
217        from: from.to_path_buf(),
218        to: to.clone(),
219        action: ImportAction::Refuse(reason),
220    };
221
222    if let Err(e) = check_native_write_target(project_root, &to) {
223        return refuse(e.to_string());
224    }
225    if !source_stays_inside(claude_root, from) {
226        return refuse(format!(
227            "source resolves outside {} — refusing to import through a symlink",
228            claude_root.display()
229        ));
230    }
231    if to.exists() {
232        return refuse(format!(
233            "{} already exists — an import never overwrites a user-authored file",
234            to.display()
235        ));
236    }
237    if is_executable(from) {
238        return refuse(
239            "source carries the executable bit — refusing to import an executable \
240             into trusty-code's own configuration tree"
241                .to_string(),
242        );
243    }
244    if relative == SETTINGS_FILENAME
245        && let Some(key) = settings_secret_key(from)
246    {
247        return refuse(format!(
248            "settings carry a secret-bearing key `{key}` — remove it, or set it \
249             in the environment, before importing"
250        ));
251    }
252
253    ImportEntry {
254        from: from.to_path_buf(),
255        to,
256        action: ImportAction::Copy,
257    }
258}
259
260/// Whether a source file really lives inside `.claude/`.
261///
262/// Why: `.claude/agents/leak.md -> ~/.ssh/id_rsa` would otherwise be copied into
263/// a tree the project commits.
264/// What: canonicalises both and tests containment; a source that cannot be
265/// canonicalised (a dangling symlink) is treated as escaping.
266/// Test: `paths::import_tests::symlink_escaping_claude_is_refused`.
267fn source_stays_inside(claude_root: &Path, from: &Path) -> bool {
268    match (claude_root.canonicalize(), from.canonicalize()) {
269        (Ok(root), Ok(file)) => file.starts_with(&root),
270        _ => false,
271    }
272}
273
274/// Whether a file has any executable bit set.
275///
276/// Why: an imported executable would be trusted by every later consumer of
277/// `.trusty-code/`, which is exactly the provenance this import cannot vouch
278/// for.
279/// What: on Unix, any of `0o111`. On other platforms, `false` — there is no
280/// executable bit to inspect, and the extension-based equivalent would be a
281/// different rule wearing the same name.
282/// Test: `paths::import_tests::executable_source_is_refused`.
283#[cfg(unix)]
284fn is_executable(path: &Path) -> bool {
285    use std::os::unix::fs::PermissionsExt;
286    std::fs::metadata(path)
287        .map(|m| m.permissions().mode() & 0o111 != 0)
288        .unwrap_or(false)
289}
290
291/// See the Unix variant — non-Unix targets expose no executable bit.
292#[cfg(not(unix))]
293fn is_executable(_path: &Path) -> bool {
294    false
295}
296
297/// The first secret-bearing key in a settings file, if any.
298///
299/// Why: a settings file that will not parse is not evidence that it is clean, so
300/// an unparseable file is refused too rather than waved through.
301/// What: parses the file as JSON and delegates to [`super::find_secret_key`]; an
302/// I/O or parse failure yields a synthetic reason naming the problem, logged at
303/// `warn` with the path tried.
304/// Test: `paths::import_tests::secret_bearing_settings_is_refused`,
305/// `paths::import_tests::unparseable_settings_is_refused`.
306fn settings_secret_key(path: &Path) -> Option<String> {
307    let raw = match std::fs::read_to_string(path) {
308        Ok(raw) => raw,
309        Err(e) => {
310            tracing::warn!(
311                path = %path.display(),
312                error = %e,
313                "could not read .claude/settings.json while planning the import; \
314                 refusing to import it rather than assuming it holds no secrets"
315            );
316            return Some("<unreadable>".to_string());
317        }
318    };
319    match serde_json::from_str::<serde_json::Value>(&raw) {
320        Ok(value) => super::find_secret_key(&value),
321        Err(e) => {
322            tracing::warn!(
323                path = %path.display(),
324                error = %e,
325                "could not parse .claude/settings.json while planning the import; \
326                 refusing to import it rather than assuming it holds no secrets"
327            );
328            Some("<unparseable>".to_string())
329        }
330    }
331}
332
333/// Execute a plan, creating only the files it marked [`ImportAction::Copy`].
334///
335/// Why: taking the plan as an ARGUMENT (rather than recomputing it) is what
336/// makes `--dry-run` meaningful — the operator authorises the exact list they
337/// read.
338/// What: creates each target's parent directory and copies the file, in plan
339/// order. Returns the [`ImportReport`]. A copy that fails mid-run is reported as
340/// a refusal with the I/O error and does not abort the remaining entries, so one
341/// bad file cannot leave the import half-done with no record of what landed.
342/// Test: `paths::import_tests::apply_creates_only_the_planned_files`,
343/// `paths::import_tests::apply_is_idempotent`,
344/// `paths::import_tests::swapped_target_dir_never_reaches_the_victim`.
345pub fn apply_import(project_root: &Path, plan: &ImportPlan) -> ImportReport {
346    let mut report = ImportReport::default();
347    for entry in &plan.entries {
348        match &entry.action {
349            ImportAction::Refuse(reason) => {
350                report.refused.push((entry.from.clone(), reason.clone()));
351            }
352            ImportAction::Copy => match copy_one(project_root, &entry.from, &entry.to) {
353                Ok(()) => report.created.push(entry.to.clone()),
354                Err(e) => report
355                    .refused
356                    .push((entry.from.clone(), format!("copy failed: {e}"))),
357            },
358        }
359    }
360    report.created.sort();
361    report
362}
363
364/// Copy one file through a pinned handle on its target directory.
365///
366/// Why: #7779. The plan's write-target check ran in [`classify`], and an
367/// operator can sit on a `--dry-run` listing for minutes before authorising it —
368/// the widest check-to-write window in the crate. A `create_dir_all` plus
369/// `std::fs::copy` through the same path string followed whatever had been
370/// swapped in since.
371/// What: re-derives the target's path relative to `<project>/.trusty-code/`,
372/// opens that directory with [`NativeWriteDir`] (which re-applies the membership
373/// rule and then pins the directory), and writes with `create_new` — so the
374/// "never overwrite a user-authored file" rule is decided by `O_EXCL` at the
375/// moment of the write rather than by the plan's `exists()` test.
376/// Test: `paths::import_tests::apply_creates_only_the_planned_files`,
377/// `paths::import_tests::swapped_target_dir_never_reaches_the_victim`.
378fn copy_one(project_root: &Path, from: &Path, to: &Path) -> std::io::Result<()> {
379    let relative = to
380        .strip_prefix(super::native_config_dir(project_root))
381        .map_err(|_| {
382            std::io::Error::other(format!(
383                "{} is not beneath the project's own configuration directory",
384                to.display()
385            ))
386        })?;
387    let (parent, name) = match (
388        relative.parent(),
389        relative.file_name().and_then(|n| n.to_str()),
390    ) {
391        (Some(parent), Some(name)) => (parent, name),
392        _ => {
393            return Err(std::io::Error::other(format!(
394                "{} is not a usable import target",
395                to.display()
396            )));
397        }
398    };
399    let content = std::fs::read(from)?;
400    NativeWriteDir::open(project_root, parent)
401        .and_then(|dir| dir.create_new(name, &content))
402        .map_err(std::io::Error::other)
403}
404
405#[cfg(test)]
406#[path = "import_tests.rs"]
407mod import_tests;