Skip to main content

trusty_code/agents/
deploy.rs

1//! Materialize the embedded agent roster to `<project>/.trusty-code/agents/`
2//! with a manifest and recorded provenance (#2074, epic #2892).
3//!
4//! Why: before this, `crate::assets::DEFAULT_AGENTS` existed only in memory.
5//! An operator could not read the prompt an agent actually runs, diff it, or
6//! edit it, and nothing on disk recorded which files Trusty Code wrote versus
7//! which the project owns. #2074 requires source provenance for every shipped
8//! role, and provenance needs a file and a ledger to attach to.
9//!
10//! What: [`ensure_roster_deployed`] stages the compiled-in agent sources into a
11//! throwaway directory and hands that directory to
12//! `trusty_agents_common::agents::deployer::deploy_agents_filtered` — the same
13//! writer trusty-mpm's `~/.claude/agents/` deploy uses, unchanged. That
14//! deployer already takes `source_dir`/`target_dir` as plain parameters, so
15//! reusing it needed no shared-library change. It brings the strict-YAML
16//! validation of every composed agent, the per-agent compose-failure isolation,
17//! the `.trusty-mpm-manifest.json` ledger with a recorded checksum and
18//! [`Origin`], and the refusal to proceed on a corrupt ledger.
19//!
20//! ## Three policies this module adds on top of the shared deployer
21//!
22//! **A compatibility root that currently wins is never shadowed.** `.claude/`
23//! and `.open-mpm/` remain readable discovery INPUTS (#5426), and
24//! `crate::paths::agents_dir` prefers `.trusty-code/agents` over both. Writing
25//! the roster into `.trusty-code/agents` while a project's `.claude/agents/`
26//! holds its real catalog would silently demote that catalog, so the deploy is
27//! skipped in that case — [`SkipReason::CompatRootWins`].
28//!
29//! **A hand-edited deployed file is authoritative.** The shared deployer treats
30//! a checksum mismatch on an [`Origin::Bundled`] entry as corruption and repairs
31//! it (#4408) — correct for trusty-mpm's machine-global `~/.claude/agents/`,
32//! wrong for a project-local directory whose whole contract is
33//! `load_all_agents`' "disk wins, never merged". This module therefore selects
34//! against the ledger before deploying: a tracked file whose on-disk content no
35//! longer matches its recorded checksum is deselected, so the deployer never
36//! composes or writes it. Pristine files still refresh, and an UNTRACKED file is
37//! left to the deployer's own adopt-or-skip branch. No deployer change was
38//! needed for either policy. Since #7779 the policy covers REAL files only: a
39//! symlinked entry in the agents directory refuses the deploy instead of being
40//! read through, because the pinned handle opens every entry `O_NOFOLLOW` (the
41//! `write_dir` module header states why that is uniform rather than per-tree).
42//!
43//! **Every write reaches the project through a pinned directory handle.** The
44//! shared deployer writes through plain paths — correct for trusty-mpm's
45//! machine-global `~/.claude/agents/`, where a symlinked `~/.claude` is a
46//! legitimate setup, and wrong for a project directory a racing writer can swap
47//! (#7779). It therefore runs against a private scratch copy, and the ledger and
48//! the files it produced are published back `openat`-relative to
49//! [`crate::paths::write_dir::NativeWriteDir`]. The project's own ledger lock is
50//! taken through that same handle, so cross-process serialisation is unchanged.
51//!
52//! Test: `agents::deploy::deploy_tests::*`,
53//! `tests/roster_deploy_e2e.rs`.
54//!
55//! [`Origin`]: trusty_agents_common::agents::manifest::Origin
56//! [`Origin::Bundled`]: trusty_agents_common::agents::manifest::Origin::Bundled
57
58use std::collections::HashSet;
59use std::path::{Path, PathBuf};
60
61use trusty_agents_common::agents::builder::AgentBuildError;
62use trusty_agents_common::agents::deployer::{DeployResult, deploy_agents_filtered};
63use trusty_agents_common::agents::manifest::{AgentManifest, MANIFEST_FILE, ManifestLoad};
64
65use crate::agents::skill_refs::SKILL_REFS_DIRNAME;
66use crate::assets::{DEFAULT_AGENTS, EmbeddedAgent};
67use crate::paths::write_dir::NativeWriteDir;
68use crate::paths::{self, WriteTargetError};
69
70/// The `agents` subdirectory name, shared by every configuration root.
71///
72/// Why: named once so the write target cannot drift from the read target
73/// `crate::paths::agents_dir` resolves.
74/// What: `"agents"`.
75/// Test: `roster_target_is_under_the_native_config_dir`.
76pub const AGENTS_DIRNAME: &str = "agents";
77
78/// Why a roster deploy could not run.
79///
80/// Why: each variant has a different fix, and collapsing them into one string
81/// would hide which. A refused write target means the project layout is wrong; a
82/// corrupt ledger means ownership cannot be established and must be repaired
83/// before anything is written.
84/// What: the four failure modes [`ensure_roster_deployed`] can return.
85/// Test: `corrupt_manifest_is_reported_and_nothing_is_written`.
86#[derive(Debug, thiserror::Error)]
87pub enum RosterDeployError {
88    /// The computed target is not a legal Trusty Code write target.
89    #[error("refusing to materialize the agent roster: {0}")]
90    WriteTarget(#[from] WriteTargetError),
91    /// The deployed-agent ledger exists but could not be read as one.
92    #[error(
93        "the deployed-agent manifest at {path} could not be read ({detail}); \
94         refusing to deploy, because treating it as empty would reclassify every \
95         managed file as user-owned. Repair or delete that file to continue."
96    )]
97    ManifestCorrupt {
98        /// The ledger's path.
99        path: PathBuf,
100        /// The underlying parse or I/O failure.
101        detail: String,
102    },
103    /// Staging the compiled-in sources into a scratch directory failed.
104    #[error("staging the embedded agent roster failed: {0}")]
105    Stage(#[source] std::io::Error),
106    /// A file the deploy produced could not be read back out of the scratch
107    /// directory, so it could not be published (#7779).
108    #[error(
109        "the deployed agent roster could not be published: {name} was not readable in the \
110         scratch directory ({source}); refusing to publish, because a ledger recording a \
111         file that was never written reports a deploy that did not happen."
112    )]
113    Publish {
114        /// The scratch file that could not be read.
115        name: String,
116        /// The underlying I/O failure.
117        #[source]
118        source: std::io::Error,
119    },
120    /// The shared deployer itself failed.
121    #[error("deploying the embedded agent roster failed: {0}")]
122    Deploy(#[source] AgentBuildError),
123    /// The shared agent texts could not be loaded from instructional content
124    /// (#9011); the message names `tm content install`.
125    #[error("the agent roster could not be deployed: {0}")]
126    Content(#[from] trusty_agents_common::agent_content::AgentContentError),
127}
128
129/// Why a deploy was skipped rather than attempted.
130///
131/// Why: "nothing was written" is a legitimate outcome the caller must be able to
132/// log accurately, and it is not an error.
133/// What: the single skip condition today — a compatibility root currently
134/// resolves the agents directory.
135/// Test: `deploy_is_skipped_when_claude_agents_dir_wins`.
136#[derive(Debug, Clone, Copy, PartialEq, Eq)]
137pub enum SkipReason {
138    /// `.claude/agents/` or `.open-mpm/agents/` currently wins discovery.
139    CompatRootWins,
140}
141
142/// What one [`ensure_roster_deployed`] call did.
143///
144/// Why: the caller logs a different line for each, and a test asserts on which
145/// branch ran rather than inferring it from the filesystem.
146/// What: either a skip with its reason, or the deployer's own
147/// [`DeployResult`] alongside the directory it wrote into.
148/// Test: `fresh_project_materializes_the_whole_roster`,
149/// `deploy_is_skipped_when_claude_agents_dir_wins`.
150#[derive(Debug)]
151pub enum RosterDeploy {
152    /// Nothing was written.
153    Skipped(SkipReason),
154    /// The shared deployer ran against `target`.
155    Deployed {
156        /// `<project>/.trusty-code/agents`.
157        target: PathBuf,
158        /// The deployer's per-file outcome lists. Boxed because
159        /// `DeployResult` is two orders of magnitude larger than the skip
160        /// variant, which `clippy::large_enum_variant` denies.
161        result: Box<DeployResult>,
162    },
163}
164
165/// What the deployed-agent ledger looks like right now.
166///
167/// Why: `tcode paths show` answers "which root wins"; after #2074 it must also
168/// answer "is there a deployed roster, and is its ledger readable" — the
169/// question an operator debugging a stale or hand-edited agent asks next.
170/// What: absent (nothing deployed yet), present with a managed-file count, or
171/// corrupt with the underlying detail.
172/// Test: `manifest_status_reports_absent_then_present`.
173#[derive(Debug, Clone, PartialEq, Eq)]
174pub enum ManifestStatus {
175    /// No ledger file exists — the roster has not been deployed here.
176    Absent,
177    /// The ledger parsed; `managed` files are tracked.
178    Present {
179        /// How many deployed files the ledger tracks.
180        managed: usize,
181    },
182    /// The ledger exists but could not be read.
183    Corrupt {
184        /// The underlying parse or I/O failure.
185        detail: String,
186    },
187}
188
189impl ManifestStatus {
190    /// A stable lowercase token for logs, JSON diagnostics, and CLI output.
191    ///
192    /// Why: the human and JSON renderings of `tcode paths show` must agree, and
193    /// a `Debug` rendering is not a wire contract.
194    /// What: `"absent"`, `"present"`, `"corrupt"`.
195    /// Test: `manifest_status_reports_absent_then_present`.
196    pub fn as_str(&self) -> &'static str {
197        match self {
198            Self::Absent => "absent",
199            Self::Present { .. } => "present",
200            Self::Corrupt { .. } => "corrupt",
201        }
202    }
203}
204
205/// The ledger path and its current state for a project.
206///
207/// Why: `tcode paths show` needs both, and deriving the path a second time at
208/// the call site would be a second implementation of the layout rule.
209/// What: `<project>/.trusty-code/agents/.trusty-mpm-manifest.json` and what
210/// reading it yields. Absence is distinguished from an empty ledger by testing
211/// the file itself — `AgentManifest::load_checked` reports both as `Ok`.
212/// Test: `manifest_status_reports_absent_then_present`,
213/// `manifest_status_reports_corrupt`.
214pub fn roster_manifest_status(project_root: &Path) -> (PathBuf, ManifestStatus) {
215    let path = roster_target(project_root).join(MANIFEST_FILE);
216    if !path.exists() {
217        return (path, ManifestStatus::Absent);
218    }
219    let status = match AgentManifest::load_checked(&roster_target(project_root)) {
220        ManifestLoad::Ok(m) => ManifestStatus::Present {
221            managed: m.managed.len(),
222        },
223        ManifestLoad::Corrupt(detail) => ManifestStatus::Corrupt { detail },
224    };
225    (path, status)
226}
227
228/// `<project>/.trusty-code/agents` — the only directory this module writes.
229///
230/// Why: the write target is deliberately NOT `crate::paths::agents_dir`'s
231/// result, which may legitimately resolve into `.claude/`. The read path and the
232/// write path are different functions on purpose (#5426).
233/// What: [`crate::paths::native_child`] for [`AGENTS_DIRNAME`].
234/// Test: `roster_target_is_under_the_native_config_dir`.
235pub fn roster_target(project_root: &Path) -> PathBuf {
236    paths::native_child(project_root, AGENTS_DIRNAME)
237}
238
239/// Materialize the embedded roster into `<project>/.trusty-code/agents/`.
240///
241/// Why: #2074's provenance requirement — every shipped role needs a file, a
242/// recorded checksum, and an [`Origin`] on disk, not just an in-memory
243/// projection. `crate::agents::load_embedded_default_agents` stays the zero-disk
244/// fallback for a projectless session, which has no project root to write to.
245///
246/// What, in order:
247/// 1. Skip when `.claude/agents/` or `.open-mpm/agents/` currently wins
248///    discovery — see this module's docs.
249/// 2. Stage every source into a scratch directory, including the five `BASE-*`
250///    templates so the deployer's own `extends:` composer resolves the chains
251///    from disk exactly as it does for trusty-mpm. The shared texts come from
252///    content (#9011); with none, this fails before anything below creates the
253///    agents directory or its lock (D5).
254/// 3. PIN the agents directory with [`crate::paths::write_dir::NativeWriteDir`],
255///    which applies the unchanged ADR-0044 membership rule and then holds the
256///    directory open on a descriptor. Every write below is `openat`-relative to
257///    it, so a symlink swapped in afterwards cannot redirect one (#7779).
258/// 4. Take the project's ledger lock through the pinned handle, so concurrent
259///    `tcode` daemons still serialise on the same sidecar the shared deployer
260///    would have used. It is a blocking `LOCK_EX` held across the whole
261///    mirror/compose/publish sequence — wider than the shared deployer's,
262///    which takes it around the compose only, and deliberately so: the mirror
263///    that decides "hand-edited" and the publish that acts on that decision have
264///    to see the same directory.
265/// 5. Refuse to proceed on a corrupt ledger, naming the file. Never reset it.
266/// 6. PIN the skill-refs tree — after step 5, so a refused deploy leaves no
267///    empty directory behind — and materialize the roster's skill pointers.
268/// 7. Deploy into a second scratch directory seeded from the pinned handle,
269///    selecting the dispatchable roster only and deselecting any tracked file
270///    the user has since edited, then publish the result back through the handle.
271///
272/// Test: `fresh_project_materializes_the_whole_roster`,
273/// `hand_edited_agent_survives_a_second_deploy`,
274/// `corrupt_manifest_is_reported_and_nothing_is_written`,
275/// `symlinked_roster_file_is_refused_before_any_write`,
276/// `deploy_is_skipped_when_claude_agents_dir_wins`,
277/// `base_templates_are_never_deployed`,
278/// `symlinked_skill_refs_dir_is_refused_before_any_write`,
279/// `symlinked_skill_folder_is_refused_before_any_write`,
280/// `symlinked_skill_ref_file_is_refused_before_any_write`,
281/// `tests/roster_deploy_e2e.rs`,
282/// `no_content_writes_no_agents_dir_and_no_lock` (`tests/no_content_e2e.rs`).
283///
284/// [`Origin`]: trusty_agents_common::agents::manifest::Origin
285pub fn ensure_roster_deployed(project_root: &Path) -> Result<RosterDeploy, RosterDeployError> {
286    if !paths::agents_dir(project_root).source.is_native() {
287        return Ok(RosterDeploy::Skipped(SkipReason::CompatRootWins));
288    }
289
290    // #9011 D5: load content BEFORE pinning anything. Pinning creates the agents
291    // directory and the lock, so with no content those were left behind empty.
292    let staged = stage_embedded_sources()?;
293
294    // #7779: both write targets are PINNED here, not merely checked. Opening
295    // them creates every missing component with `mkdirat`/`O_NOFOLLOW`, so the
296    // `create_dir_all` a racing writer used to beat is gone and every write
297    // below resolves against the descriptor rather than the path.
298    let agents = NativeWriteDir::open(project_root, Path::new(AGENTS_DIRNAME))?;
299    let target = agents.path().to_path_buf();
300
301    // #7779: the shared deployer serialises writers on this sidecar. It now runs
302    // against a scratch directory, so the PROJECT's lock is taken here instead —
303    // dropping it would silently unserialise two concurrent `tcode` daemons.
304    let _ledger = agents.lock_exclusive(&format!("{MANIFEST_FILE}.lock"))?;
305
306    // #7779: the deployer writes through plain paths, which is correct for
307    // trusty-mpm's machine-global `~/.claude/agents` but reopens this race on a
308    // project directory. It therefore runs against a private scratch copy of the
309    // ledger and the roster files it may read, and everything it produced is
310    // published back through the pinned handle.
311    let shadow = tempfile::tempdir().map_err(RosterDeployError::Stage)?;
312    mirror_into_scratch(&agents, shadow.path())?;
313
314    // Establish ownership BEFORE staging or writing anything. The deployer makes
315    // the same check under its own lock; doing it here too is what lets a
316    // corrupt ledger be reported without a scratch directory ever being built.
317    let manifest = match AgentManifest::load_checked(shadow.path()) {
318        ManifestLoad::Ok(m) => m,
319        ManifestLoad::Corrupt(detail) => {
320            return Err(RosterDeployError::ManifestCorrupt {
321                path: target.join(MANIFEST_FILE),
322                detail,
323            });
324        }
325    };
326
327    let roster: HashSet<&str> = DEFAULT_AGENTS.iter().map(EmbeddedAgent::name).collect();
328
329    // #7779: pinned only now. Opening a handle CREATES its directory, so pinning
330    // this one beside the agents dir left an empty `skill-refs/` behind whenever
331    // the corrupt-ledger refusal above fired — and `paths::resolve_project_entry`
332    // reads an empty readable directory as Usable.
333    let skill_refs = NativeWriteDir::open(project_root, Path::new(SKILL_REFS_DIRNAME))?;
334
335    // #7727: the roster's skill pointers resolve to files this project holds.
336    super::skill_refs::materialize_skill_refs(&skill_refs)?;
337    let result = deploy_agents_filtered(staged.path(), shadow.path(), skill_refs.path(), |stem| {
338        roster.contains(stem) && !is_user_edited(&manifest, shadow.path(), stem)
339    })
340    .map_err(RosterDeployError::Deploy)?;
341    publish_from_scratch(&agents, shadow.path(), &result)?;
342
343    Ok(RosterDeploy::Deployed {
344        target,
345        result: Box::new(result),
346    })
347}
348
349/// Copy the ledger and every roster file the deployer may read into `scratch`.
350///
351/// Why: the deployer decides adopt / refresh / preserve by reading the target
352/// directory, so running it against an empty scratch tree would reclassify every
353/// existing file as new and overwrite a hand-edited agent.
354/// What: reads `<MANIFEST_FILE>` and `<name>.md` for every roster name through
355/// the PINNED handle — the same descriptor the publish writes back through, so
356/// the snapshot and the publish cannot disagree about which directory they mean.
357/// Absent entries are simply not copied.
358///
359/// A SYMLINKED entry refuses the whole deploy rather than being followed, which
360/// narrows this module's "a hand-edited deployed file is authoritative" policy
361/// to real files (#7779 round 2; rationale in the `write_dir` module header).
362/// Test: `agents::deploy::deploy_tests::hand_edited_agent_survives_a_second_deploy`,
363/// `agents::deploy::deploy_tests::symlinked_roster_file_is_refused_before_any_write`.
364fn mirror_into_scratch(agents: &NativeWriteDir, scratch: &Path) -> Result<(), RosterDeployError> {
365    let mut names = vec![MANIFEST_FILE.to_string()];
366    names.extend(DEFAULT_AGENTS.iter().map(|a| format!("{}.md", a.name())));
367    for name in names {
368        if let Some(bytes) = agents.read(&name)? {
369            std::fs::write(scratch.join(&name), bytes).map_err(RosterDeployError::Stage)?;
370        }
371    }
372    Ok(())
373}
374
375/// Publish what the deploy produced back through the pinned handle.
376///
377/// Why: the only writes that reach the project directory. Doing them
378/// `openat`-relative to the validated descriptor is what makes "the path
379/// validated is the path written" true for the agents directory (#7779).
380/// What: the ledger (always — an adoption changes it without rewriting a file)
381/// plus every file the deployer reported as deployed. Files it left alone are
382/// not republished, so a preserved hand-edit is not even rewritten with its own
383/// bytes. A swap detected mid-publish aborts with
384/// [`WriteTargetError::Unpinned`]; nothing was written outside the directory.
385///
386/// Every file is READ before any is written. #7779: a `continue` on an
387/// unreadable scratch file dropped that file while the ledger published its
388/// checksum anyway, so [`ensure_roster_deployed`] returned `Deployed` and
389/// [`deploy_and_log`] logged a file that is not on disk — fail-open. Reading
390/// first makes the run all-or-nothing up to the first `atomic_write`.
391/// Test: `agents::deploy::deploy_tests::fresh_project_materializes_the_whole_roster`,
392/// `agents::deploy::deploy_tests::swapped_agents_dir_never_reaches_the_victim`,
393/// `agents::deploy::deploy_tests::unreadable_scratch_file_fails_the_publish`.
394fn publish_from_scratch(
395    agents: &NativeWriteDir,
396    scratch: &Path,
397    result: &DeployResult,
398) -> Result<(), RosterDeployError> {
399    let mut names: Vec<&str> = result.deployed.iter().map(String::as_str).collect();
400    names.push(MANIFEST_FILE);
401    let mut pending = Vec::with_capacity(names.len());
402    for name in names {
403        let bytes =
404            std::fs::read(scratch.join(name)).map_err(|source| RosterDeployError::Publish {
405                name: name.to_string(),
406                source,
407            })?;
408        pending.push((name, bytes));
409    }
410    for (name, bytes) in pending {
411        agents.atomic_write(name, &bytes)?;
412    }
413    Ok(())
414}
415
416/// Run [`ensure_roster_deployed`] for a bound project and log what happened.
417///
418/// Why: two entry points materialize the roster — the daemon's router build and
419/// the legacy in-process `run-task` — and both want the same behaviour: deploy
420/// if we can, report loudly if we cannot, and never abort the run. A failed
421/// deploy is recoverable, because `crate::agents::load_embedded_default_agents`
422/// still answers every resolution from memory; aborting would turn a repairable
423/// ledger into an unusable harness.
424/// What: `None` when `project_root` is `None` (a projectless session writes
425/// nothing and keeps the in-memory embed). Otherwise the outcome, with a
426/// `tracing::error!` naming the failure when one occurred. #2074. No content
427/// installed is reported once per process with the loader's line (#9011 D4).
428/// Test: `deploy_and_log_is_a_no_op_without_a_project`,
429/// `deploy_and_log_reports_a_corrupt_ledger_without_panicking`.
430pub fn deploy_and_log(project_root: Option<&Path>) -> Option<RosterDeploy> {
431    let root = project_root?;
432    match ensure_roster_deployed(root) {
433        Ok(RosterDeploy::Skipped(reason)) => {
434            tracing::debug!(
435                project = %root.display(),
436                ?reason,
437                "agent roster not materialized"
438            );
439            Some(RosterDeploy::Skipped(reason))
440        }
441        Ok(RosterDeploy::Deployed { target, result }) => {
442            tracing::info!(
443                target = %target.display(),
444                deployed = result.deployed.len(),
445                unchanged = result.unchanged.len(),
446                preserved = result.skipped.len(),
447                failed = result.failed.len(),
448                "agent roster materialized (#2074)"
449            );
450            Some(RosterDeploy::Deployed { target, result })
451        }
452        // #9011 D4: no content at all is reported once per process.
453        Err(RosterDeployError::Content(e))
454            if trusty_agents_common::agent_content::report_not_installed(
455                &e,
456                "tcode could not materialize its agent roster",
457            ) =>
458        {
459            None
460        }
461        Err(e) => {
462            tracing::error!(
463                project = %root.display(),
464                "could not materialize the agent roster; continuing with the \
465                 in-memory embedded roster: {e}"
466            );
467            None
468        }
469    }
470}
471
472/// Whether a tracked deployed file has been edited since Trusty Code wrote it.
473///
474/// Why: the "hand-edited file is authoritative" policy from this module's docs.
475/// The shared deployer would repair such a file (#4408); a project-local
476/// directory must preserve it instead.
477/// What: `true` only when the ledger tracks `<stem>.md` AND the file on disk no
478/// longer matches its recorded checksum. An untracked file returns `false` so
479/// the deployer's own adopt-or-skip branch decides; an unreadable or absent file
480/// returns `false` so it is (re)deployed.
481/// Test: `hand_edited_agent_survives_a_second_deploy`,
482/// `untracked_file_is_left_to_the_deployer`.
483fn is_user_edited(manifest: &AgentManifest, target: &Path, stem: &str) -> bool {
484    let filename = format!("{stem}.md");
485    if !manifest.is_managed(&filename) {
486        return false;
487    }
488    match std::fs::read_to_string(target.join(&filename)) {
489        Ok(current) => !manifest.checksum_matches(&filename, &current),
490        Err(_) => false,
491    }
492}
493
494/// Write every compiled-in agent source into a throwaway directory.
495///
496/// Why: the shared deployer composes from a source DIRECTORY, and tcode's roster
497/// is a set of `&'static str`s. Staging them is what lets the deployer be reused
498/// verbatim instead of growing a second, pre-composed entry point — a shared
499/// library change this slice deliberately avoided.
500/// What: loads the catalog once ([`crate::assets::load_tm_agent_sources`],
501/// #9011; a content error is [`RosterDeployError::Content`] and nothing is
502/// staged), then one `.md` per entry (keyed by its filename, so
503/// `extends: base-qa` resolves against `BASE-QA.md`) plus
504/// one per [`EmbeddedAgent::Direct`] in [`DEFAULT_AGENTS`]. The `TempDir` is
505/// returned so the caller keeps it alive across the deploy; dropping it removes
506/// the scratch tree.
507/// Test: `staged_sources_cover_every_roster_name_and_base_template`.
508fn stage_embedded_sources() -> Result<tempfile::TempDir, RosterDeployError> {
509    let catalog = crate::assets::load_tm_agent_sources()?;
510    let dir = tempfile::tempdir().map_err(RosterDeployError::Stage)?;
511    for (filename, content) in &catalog {
512        std::fs::write(dir.path().join(filename), content).map_err(RosterDeployError::Stage)?;
513    }
514    for embedded in DEFAULT_AGENTS {
515        if let EmbeddedAgent::Direct { name, md } = embedded {
516            std::fs::write(dir.path().join(format!("{name}.md")), md)
517                .map_err(RosterDeployError::Stage)?;
518        }
519    }
520    Ok(dir)
521}
522
523#[cfg(test)]
524#[path = "deploy_tests.rs"]
525mod deploy_tests;