trusty_code/agents/describe.rs
1//! `agents.describe` — the effective configuration, provenance, and warnings
2//! for ONE agent (#2074, epic #2892).
3//!
4//! Why: `agents.list` answers "what could I dispatch?" with four fields per row
5//! — name, tier, description, model. An operator debugging drift needs the next
6//! question answered: which file on disk is this, did Trusty Code write it, has
7//! anyone edited it since, and what is actually in the prompt. Slice 1 put a
8//! file, a checksum, and an [`Origin`] on disk for every shipped role
9//! (`crate::agents::deploy`); this module is what reads them back out.
10//!
11//! What: [`describe_agent`] resolves one name through
12//! [`crate::agents::resolve_agent`] — the SAME disk-wins/embedded-fallback/
13//! plugin chain dispatch uses, never a second copy of it — and pairs the
14//! resolved config with the deployed-agent ledger sitting beside the file.
15//! [`load_ledger`] reads that ledger once per request, and
16//! [`disk_entry_has_warnings`] lets `agents.list` reuse the same judgement for
17//! its per-row `has_warnings` flag without a second ledger parse.
18//!
19//! ## What this surface deliberately does NOT report
20//!
21//! Trusty Code has no capability-grant model yet: an agent's declared authority
22//! is the flat `tools.allowed` allowlist
23//! ([`crate::agents::config::ToolsConfig`]) and nothing else. #2074's
24//! write/shell/network/credential/delegation grants are a later slice, so this
25//! payload reports the allowlist that exists and carries NO `grants` key.
26//! An absent field is the honest answer; a fabricated one would tell an
27//! operator the runtime enforces something it does not.
28//!
29//! Test: `crate::agents::describe::tests::*`.
30//!
31//! [`Origin`]: trusty_agents_common::agents::manifest::Origin
32
33use std::path::{Path, PathBuf};
34
35use serde_json::{Value, json};
36use trusty_agents_common::agents::manifest::{AgentManifest, MANIFEST_FILE, ManifestLoad, Origin};
37// #4698: the file's own `provenance:` claim, reported beside the ledger's origin.
38use trusty_agents_common::agents::metadata::agent_metadata_from_str;
39use trusty_agents_common::agents::provenance::Provenance;
40
41use crate::jsonrpc::RpcError;
42use crate::paths::TRUSTY_CODE_DIRNAME;
43
44use super::deploy::AGENTS_DIRNAME;
45use super::{ResolveAgentError, resolve_agent};
46
47/// The deployed-agent ledger's state for one agents directory.
48///
49/// Why: `AgentManifest::load_checked` reports a MISSING ledger and an EMPTY one
50/// identically (`Ok`), and the two mean different things here — a missing
51/// ledger in Trusty Code's own roster directory is an anomaly worth a warning,
52/// while an empty one is a deploy that tracked nothing. Testing the file itself
53/// is what separates them, exactly as `crate::agents::deploy::
54/// roster_manifest_status` already does for `tcode paths show`.
55/// What: absent, parsed, or unreadable-with-detail.
56/// Test: `absent_ledger_in_the_native_roster_dir_warns`,
57/// `corrupt_ledger_is_reported_as_a_warning`.
58pub(crate) enum LedgerState {
59 /// No ledger file exists in this directory.
60 Absent,
61 /// The ledger parsed.
62 Ok(AgentManifest),
63 /// The ledger exists but could not be read; carries the underlying detail.
64 Corrupt(String),
65}
66
67/// Read the deployed-agent ledger in `dir` once.
68///
69/// Why: `agents.list` describes up to a whole roster in one call. Loading the
70/// ledger per row would re-parse the same JSON once per agent; hoisting it to
71/// the caller keeps the listing one parse regardless of roster size.
72/// What: distinguishes an absent file from an empty ledger by testing the file,
73/// then defers to `AgentManifest::load_checked` for the parse.
74/// Test: `absent_ledger_in_the_native_roster_dir_warns`,
75/// `deployed_pristine_agent_reports_framework_origin_and_no_warnings`.
76pub(crate) fn load_ledger(dir: &Path) -> LedgerState {
77 if !dir.join(MANIFEST_FILE).exists() {
78 return LedgerState::Absent;
79 }
80 match AgentManifest::load_checked(dir) {
81 ManifestLoad::Ok(manifest) => LedgerState::Ok(manifest),
82 ManifestLoad::Corrupt(detail) => LedgerState::Corrupt(detail),
83 }
84}
85
86/// What the ledger records about one agent file, plus anything wrong with it.
87///
88/// Why: the JSON shape and the warning list are derived from the same three
89/// facts (is the ledger readable, does it track this file, does the file still
90/// match its recorded checksum), so they are computed together rather than by
91/// two passes that could disagree.
92/// What: a stable `manifest` token plus the ledger entry's fields when there is
93/// one, and the human-readable warnings those facts imply.
94/// Test: `deployed_pristine_agent_reports_framework_origin_and_no_warnings`,
95/// `hand_edited_agent_reports_a_checksum_mismatch_and_warns`,
96/// `untracked_disk_file_warns_that_trusty_code_did_not_write_it`.
97struct DiskProvenance {
98 /// `"absent"`, `"present"`, or `"corrupt"`.
99 manifest: &'static str,
100 /// The ledger's recorded origin, when it tracks this file.
101 origin: Option<Origin>,
102 /// `Origin::is_framework_owned` for that origin.
103 framework_owned: Option<bool>,
104 /// `"match"` or `"mismatch"`, when a checksum comparison was possible.
105 checksum: Option<&'static str>,
106 /// The ledger's RFC3339 deploy timestamp, when recorded.
107 deployed_at: Option<String>,
108 /// The resolved `extends:` chain the deploy composed, base-first.
109 source_chain: Vec<String>,
110 /// The `provenance:` the FILE declares about itself (#4698), independent of
111 /// the ledger. `None` when the file declares none or could not be read — an
112 /// absent field means user-authored, per #4698's design note.
113 declared_provenance: Option<Provenance>,
114 /// Everything an operator should know that is not simply "this is fine".
115 warnings: Vec<String>,
116}
117
118impl DiskProvenance {
119 /// The wire shape, with every absent fact rendered as an explicit `null`.
120 ///
121 /// Why: a client reading `provenance.origin` must be able to tell "not
122 /// recorded" from "key missing because the server is older" — so the keys
123 /// are always present and it is the VALUES that go null.
124 /// What: a fixed seven-key object. `warnings` is not included here; the
125 /// caller merges them into the response's single top-level `warnings` list
126 /// so a client has one place to look.
127 fn to_json(&self) -> Value {
128 json!({
129 "manifest": self.manifest,
130 "origin": self.origin.map(origin_token),
131 "framework_owned": self.framework_owned,
132 "checksum": self.checksum,
133 "deployed_at": self.deployed_at,
134 "source_chain": self.source_chain,
135 // #4698: the file's own claim, beside the ledger's. A client
136 // comparing the two sees a hand-edit the checksum alone would not
137 // explain; the ledger stays authoritative either way.
138 "declared_provenance": self.declared_provenance.map(Provenance::as_str),
139 })
140 }
141}
142
143/// The stable lowercase token for an [`Origin`].
144///
145/// Why: the manifest's own serde rendering is lowercase; matching it by hand
146/// here keeps the JSON-RPC payload identical to the on-disk ledger's spelling
147/// without depending on a `Serialize` round-trip through a `Value`.
148/// What: `"bundled"`, `"registry"`, `"user"`.
149/// Test: `deployed_pristine_agent_reports_framework_origin_and_no_warnings`.
150fn origin_token(origin: Origin) -> &'static str {
151 match origin {
152 Origin::Bundled => "bundled",
153 Origin::Registry => "registry",
154 Origin::User => "user",
155 }
156}
157
158/// The provenance placeholder for an agent with no file on disk.
159///
160/// Why: an embedded or plugin agent has no ledger entry and never will, which
161/// is not the same condition as a missing ledger. Naming it keeps a client from
162/// reading `"absent"` as "something is wrong".
163/// What: the same seven keys [`DiskProvenance::to_json`] emits, with
164/// `manifest: "not-applicable"`.
165/// Test: `embedded_agent_has_no_disk_path_and_no_warnings`.
166fn not_applicable_provenance() -> Value {
167 json!({
168 "manifest": "not-applicable",
169 "origin": Value::Null,
170 "framework_owned": Value::Null,
171 "checksum": Value::Null,
172 "deployed_at": Value::Null,
173 "source_chain": [],
174 "declared_provenance": Value::Null,
175 })
176}
177
178/// Whether `dir` is Trusty Code's OWN `<project>/.trusty-code/agents`.
179///
180/// Why: a missing ledger means different things in different roots. In the
181/// native root it means the roster deploy has not run (or its ledger was
182/// deleted) — worth saying. In a `.claude/agents` compatibility root, no ledger
183/// is expected at all, and warning there would flag every hand-authored project
184/// agent as suspect.
185/// What: the last two path components, compared against
186/// [`crate::paths::TRUSTY_CODE_DIRNAME`] and
187/// [`crate::agents::deploy::AGENTS_DIRNAME`] — the same two names the deploy
188/// target is built from, never a re-spelled literal.
189/// Test: `absent_ledger_in_the_native_roster_dir_warns`,
190/// `absent_ledger_in_a_compat_root_does_not_warn`.
191fn is_native_roster_dir(dir: &Path) -> bool {
192 dir.file_name().is_some_and(|n| n == AGENTS_DIRNAME)
193 && dir
194 .parent()
195 .and_then(Path::file_name)
196 .is_some_and(|n| n == TRUSTY_CODE_DIRNAME)
197}
198
199/// Read the ledger's record of `<name>.md` in `dir`, and what is wrong with it.
200///
201/// Why: this is the whole of #2074's "source provenance" requirement for a
202/// disk-backed agent — did Trusty Code write this file, when, from which
203/// compose chain, and does its content still match what was written.
204/// What: four terminal cases, in order — an unreadable ledger, no ledger, a
205/// ledger that does not track this file, and a tracked file whose on-disk bytes
206/// either match its recorded checksum or no longer do. Checksum comparison
207/// reuses `AgentManifest::checksum_matches`, the same call
208/// `crate::agents::deploy::ensure_roster_deployed` selects against, so
209/// "diverges" means exactly what the deployer means by it.
210/// Test: `deployed_pristine_agent_reports_framework_origin_and_no_warnings`,
211/// `hand_edited_agent_reports_a_checksum_mismatch_and_warns`,
212/// `untracked_disk_file_warns_that_trusty_code_did_not_write_it`,
213/// `corrupt_ledger_is_reported_as_a_warning`.
214fn provenance_for(dir: &Path, ledger: &LedgerState, name: &str) -> DiskProvenance {
215 let filename = format!("{name}.md");
216 let mut provenance = DiskProvenance {
217 manifest: "absent",
218 origin: None,
219 framework_owned: None,
220 checksum: None,
221 deployed_at: None,
222 source_chain: Vec::new(),
223 declared_provenance: None,
224 warnings: Vec::new(),
225 };
226
227 let manifest = match ledger {
228 LedgerState::Corrupt(detail) => {
229 provenance.manifest = "corrupt";
230 provenance.warnings.push(format!(
231 "the deployed-agent manifest in {} could not be read ({detail}); the provenance \
232 of '{name}' is unavailable until that file is repaired or deleted",
233 dir.display()
234 ));
235 return provenance;
236 }
237 LedgerState::Absent => {
238 if is_native_roster_dir(dir) {
239 provenance.warnings.push(format!(
240 "manifest missing: no deployed-agent manifest in {}, so '{name}' has no \
241 recorded origin or checksum. Start Trusty Code against this project to \
242 materialize the roster.",
243 dir.display()
244 ));
245 }
246 return provenance;
247 }
248 LedgerState::Ok(manifest) => manifest,
249 };
250
251 provenance.manifest = "present";
252 let Some(entry) = manifest.managed.get(&filename) else {
253 provenance.warnings.push(format!(
254 "'{filename}' is not tracked by the deployed-agent manifest in {}; Trusty Code did \
255 not write this file, so it has no recorded origin or checksum",
256 dir.display()
257 ));
258 return provenance;
259 };
260
261 provenance.origin = Some(entry.origin);
262 provenance.framework_owned = Some(entry.origin.is_framework_owned());
263 provenance.deployed_at = Some(entry.deployed_at.clone());
264 provenance.source_chain = entry.source_chain.clone();
265
266 match std::fs::read_to_string(dir.join(&filename)) {
267 Ok(current) if manifest.checksum_matches(&filename, ¤t) => {
268 // #4698: report what the file says about its own author beside what
269 // the ledger recorded, so a client sees both records.
270 provenance.declared_provenance = agent_metadata_from_str(¤t).provenance;
271 provenance.checksum = Some("match");
272 }
273 Ok(current) => {
274 provenance.declared_provenance = agent_metadata_from_str(¤t).provenance;
275 provenance.checksum = Some("mismatch");
276 provenance.warnings.push(format!(
277 "the disk copy of '{name}' diverges from the bundled roster: its content no \
278 longer matches the checksum the manifest recorded. That file is what runs, and \
279 Trusty Code will not overwrite it."
280 ));
281 }
282 Err(e) => provenance.warnings.push(format!(
283 "'{filename}' is tracked by the deployed-agent manifest but could not be read ({e}); \
284 its checksum could not be verified"
285 )),
286 }
287
288 provenance
289}
290
291/// Whether `agents.list` should flag this disk row for an operator's attention.
292///
293/// Why: the listing's `has_warnings` flag and `agents.describe`'s `warnings`
294/// array must never disagree — a row flagged clean that describes with three
295/// warnings is worse than no flag at all. Both read this one function.
296/// What: `true` when [`provenance_for`] produced any warning. A row whose file
297/// failed to PARSE is flagged by its caller instead, which is where the parse
298/// error is known.
299/// Test: `list_flags_a_hand_edited_row_and_leaves_pristine_rows_clean`.
300pub(crate) fn disk_entry_has_warnings(dir: &Path, ledger: &LedgerState, name: &str) -> bool {
301 !provenance_for(dir, ledger, name).warnings.is_empty()
302}
303
304/// The `<dir>/<name>.md` this agent resolves from, when there is one.
305///
306/// Why: the tier, the reported path, and whether provenance applies all hinge
307/// on this single question, so it is asked once.
308/// What: `None` for a namespaced `<plugin>:<name>` (plugin agents live under
309/// `.claude/plugins/`, not in `dir`) and `None` when no such file exists. The
310/// separator rejection is defense in depth — every caller validates the name
311/// through `crate::agents::protocol::validate_agent_name` first, which already
312/// makes a traversing name unreachable.
313/// Test: `embedded_agent_has_no_disk_path_and_no_warnings`,
314/// `deployed_pristine_agent_reports_framework_origin_and_no_warnings`.
315fn disk_file(dir: &Path, name: &str) -> Option<PathBuf> {
316 if name.contains(':') || name.contains('/') || name.contains('\\') || name.contains("..") {
317 return None;
318 }
319 let path = dir.join(format!("{name}.md"));
320 path.is_file().then_some(path)
321}
322
323/// Describe one agent: effective config, provenance, and warnings.
324///
325/// Why: #2074's "expose effective instructions, model routing, tools, skills,
326/// source provenance, and warnings through agent inspection".
327///
328/// What, in order:
329/// 1. Resolve `name` through [`crate::agents::resolve_agent`], so describe and
330/// dispatch can never disagree about which definition wins.
331/// 2. Label the tier from where it resolved: `disk_tier` (`"project"` or
332/// `"user"`) when a file in `dir` backs it, `"plugin"` for a namespaced
333/// name, `"embedded"` otherwise, and `"broken"` when a file exists but
334/// failed to parse or compose.
335/// 3. Attach the ledger's provenance for a disk-backed agent, or the
336/// `"not-applicable"` placeholder for one that has no file.
337/// 4. Report the resolved instruction text's length; include the text itself
338/// only when `include_instructions` is set, because a composed roster prompt
339/// runs to tens of kilobytes and a catalog client does not want it by
340/// default.
341///
342/// A name that resolves nowhere is a typed `-32002 not_found` carrying
343/// `resolve_agent`'s own available-agents list — never a panic. A name whose
344/// FILE is broken is NOT an error: it returns a normal payload with
345/// `tier: "broken"` and the parse failure in `warnings`, because an operator
346/// debugging why a name fell back needs to see the reason, not a bare RPC
347/// error (the same rule `agents.list` already applies to a broken row).
348///
349/// Test: `deployed_pristine_agent_reports_framework_origin_and_no_warnings`,
350/// `hand_edited_agent_reports_a_checksum_mismatch_and_warns`,
351/// `unknown_name_is_a_typed_not_found`,
352/// `unparseable_disk_agent_is_broken_with_the_parse_error`,
353/// `embedded_agent_has_no_disk_path_and_no_warnings`,
354/// `instructions_text_is_omitted_by_default_and_returned_on_request`,
355/// `describe_reports_the_tools_allowlist_and_declared_skills`.
356pub(crate) fn describe_agent(
357 dir: &Path,
358 disk_tier: &str,
359 name: &str,
360 include_instructions: bool,
361) -> Result<Value, RpcError> {
362 let disk_path = disk_file(dir, name);
363 let mut warnings: Vec<String> = Vec::new();
364
365 let (tier, cfg) = match resolve_agent(dir, name) {
366 Ok(cfg) => {
367 let tier = if disk_path.is_some() {
368 disk_tier
369 } else if name.contains(':') {
370 "plugin"
371 } else {
372 "embedded"
373 };
374 (tier, Some(cfg))
375 }
376 // #2074: a file that exists but will not load is reported, not raised —
377 // this is the "why did my override fall back?" case.
378 Err(ResolveAgentError::Load { source, .. }) => {
379 warnings.push(format!("parse error: {source:#}"));
380 ("broken", None)
381 }
382 Err(e @ ResolveAgentError::NotFound { .. }) => {
383 return Err(RpcError::not_found(e.to_string()));
384 }
385 };
386
387 let provenance = if disk_path.is_some() {
388 let mut p = provenance_for(dir, &load_ledger(dir), name);
389 warnings.append(&mut p.warnings);
390 p.to_json()
391 } else {
392 not_applicable_provenance()
393 };
394
395 let instructions = cfg.as_ref().map(|c| {
396 let text = &c.system_prompt.content;
397 let mut value = json!({ "length_bytes": text.len() });
398 if include_instructions {
399 value["text"] = json!(text);
400 }
401 value
402 });
403
404 Ok(json!({
405 "name": cfg.as_ref().map_or_else(|| name.to_string(), |c| c.agent.name.clone()),
406 "tier": tier,
407 "path": disk_path.as_ref().map(|p| p.display().to_string()),
408 "role": cfg.as_ref().and_then(|c| c.agent.role.clone()),
409 "description": cfg.as_ref().and_then(|c| c.agent.description.clone()),
410 "model": cfg.as_ref().and_then(|c| c.agent.model.clone()),
411 "tools": cfg.as_ref().map(|c| {
412 json!({ "allowed": c.tools.as_ref().and_then(|t| t.allowed.clone()) })
413 }),
414 "skills": cfg
415 .as_ref()
416 .map(|c| c.system_prompt.append_skills.clone())
417 .unwrap_or_default(),
418 "instructions": instructions,
419 "provenance": provenance,
420 "warnings": warnings,
421 }))
422}
423
424#[cfg(test)]
425#[path = "describe_tests.rs"]
426mod tests;