trusty-agents-common 0.8.3

Stable agent-plugin surface (ToolExecutor, AgentPlugin, ToolResult) shared by trusty-agents and external agent crates.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
//! Which files in a NON-canonical agent tier are tm's? (issue #4442)
//!
//! Why: since #4409/#4437 bundled agents deploy into exactly one directory —
//! [`crate::agents::deployer`]'s target, `$CLAUDE_CONFIG_DIR/agents/`. Every
//! OTHER `.claude/agents/` directory on the machine is now a leftover, and a
//! leftover is not inert: Claude Code resolves the PROJECT tier before the user
//! tier, so a stale copy silently wins over the canonical deploy. That is
//! #4408 verbatim — a 32-byte project-tier stub beat the real 25 KB
//! `rust-engineer`, delegation kept "working", and nothing reported it.
//!
//! What: the reusable half of that detection — the agent-identity rule
//! ([`agent_identity`]), a canonical bundled-name roster
//! ([`bundled_agent_names`]), a pure per-file verdict
//! ([`classify_tier_resident`]), and a read-only directory scan
//! ([`audit_agent_tier`]). Nothing here writes, deletes, or renames anything.
//!
//! CONTRACT — this module is the SINGLE definition of "tm owns this file"
//! outside the canonical tier, deliberately shared by two consumers: `tm
//! doctor`'s `asset_tier` probe (#4442), which REPORTS what it returns, and
//! [`crate::agents::quarantine`] (#4448), which MOVES a SUBSET of it.
//!
//! Report and repair must agree file-for-file on this predicate. If either side
//! re-derives it locally they will drift, and the drift is asymmetric harm:
//! doctor flags a file the repair refuses to touch (noise operators learn to
//! ignore), or repair quarantines a file doctor never flagged (a project's own
//! agent silently disappears). Extend this module; do not fork it.
//!
//! A SUBSET, not the whole set, because moving is a higher bar than reporting.
//! The quarantine adds two further gates of its own — is the file git-tracked
//! (#4448 gate 3, standing in for the closed `Origin::Project`), and is its
//! frontmatter tm's own composer output rather than claude-mpm's (#4448 gate 4)
//! — and refuses on either. Those gates live there, not here, precisely because
//! doctor SHOULD still report a shadowing file it declines to move: the
//! operator needs to know about it either way. The direction of the difference
//! is fixed and load-bearing: everything the quarantine moves, doctor reports;
//! never the reverse.
//!
//! Two invariants make that second hazard structurally hard, not merely
//! documented:
//!
//! 1. AGENT IDENTITY IS THE FRONTMATTER `name`, NOT THE FILENAME. Every
//!    consumer resolves agents by the declared `name:`, falling back to the
//!    stem only when it is absent (`trusty-agents`'
//!    `agents::claude_mpm_loader::parse_agent_file`). Keying on the stem would
//!    both MISS a real shadowing (`helper.md` declaring `name: rust-engineer`)
//!    and FALSELY flag a project's own agent (`rust-engineer.md` declaring
//!    `name: acme-custom`). [`agent_identity`] is applied to BOTH sides of the
//!    comparison — roster and candidate — so the two cannot key differently.
//! 2. A USER-OWNED LEDGER ENTRY OUTRANKS A NAME COLLISION. Ownership is
//!    [`TierOwnership`], a three-state value, never a bool: collapsing
//!    "untracked" and "tracked as the operator's" into one flag throws away the
//!    only positive PROOF that a file is not tm's, and a name collision then
//!    condemns it. Parity with
//!    [`crate::agents::deployer::retract_framework_agents`] is HALF, not whole,
//!    and the missing half is load-bearing for #4448. A USER-OWNED file is
//!    preserved by both: retraction skips it, and [`classify_tier_resident`]
//!    returns [`TierResidentClass::Custom`] for it BEFORE any name is compared.
//!    An UNTRACKED file is preserved by retraction — which can only see ledger
//!    entries — but is deliberately NOT preserved here:
//!    `classify_tier_resident("qa", Untracked, {"qa"})` is
//!    [`TierResidentClass::ShadowsBundled`], pinned by the
//!    `classify_bundled_name_shadows` test. That asymmetry IS the feature — an
//!    untracked copy on a bundled name is exactly what retraction cannot reach
//!    and what #4448 exists to quarantine. Do not read this invariant as a
//!    proof that untracked files are safe from the sweep; only the user-owned
//!    ledger entry is such a proof HERE. The sweep itself adds two more
//!    (`crate::agents::vcs_claim`, `crate::agents::agent_schema`), but they are
//!    the MOVER's gates and nothing in this module may be read as promising
//!    them.
//!
//! [`TierResidentClass::Custom`] is the exclusion seam for everything else.
//! Project-tier agents tm never authored are legitimate — hand-placed today,
//! first-class once #4443 lands project-custom agents — and are classified, not
//! merely filtered, so a future category (e.g. a registry-sourced project
//! agent) is added as a variant here and BOTH consumers inherit the exclusion.
//!
//! Test: `tier_audit_tests.rs`.

use std::collections::BTreeSet;
use std::path::{Path, PathBuf};

use thiserror::Error;

use crate::agents::deployer::is_agent_file;
use crate::agents::manifest::{AgentManifest, ManifestLoad};
use crate::agents::metadata::agent_metadata_from_str;
// #4698: the file's own authorship claim, reconciled against the ledger.
use crate::agents::provenance::{Provenance, reconcile_with_ledger};

/// Why [`audit_agent_tier`] could not answer for a directory.
///
/// Why (#5626, [ADR-0045]): the scan's empty vec is what `tm doctor` renders as
/// `no tm-owned agent files outside the canonical tier … (scanned: <dir>)` — a
/// positive claim about a directory. `let Ok(entries) = read_dir(dir) else {
/// return Vec::new() }` produced that same claim for a directory the process
/// could not enumerate, so the probe asserted a scan it never performed. A
/// separate value is what lets the consumer say "undetermined" instead.
/// What: one variant. The directory being ABSENT is not an error — an
/// unprovisioned tier holds nothing, which is a real answer — so only a
/// non-`NotFound` `read_dir` failure lands here.
/// Test: `audit_unscannable_dir_is_an_error`, `audit_missing_dir_is_empty`.
///
/// [ADR-0045]: https://github.com/bobmatnyc/trusty-tools/blob/main/docs/adr/0045-distinguish-absent-from-undeterminable-on-destructive-paths.md
#[derive(Debug, Error)]
pub enum TierAuditError {
    /// The tier directory exists (or its state is unknown) but could not be
    /// enumerated.
    #[error("cannot scan agent tier {path}: {source}")]
    Unscannable {
        /// The directory the scan was asked for.
        path: PathBuf,
        /// The underlying `read_dir` failure.
        #[source]
        source: std::io::Error,
    },
}

/// What this directory's ownership ledger says about one file.
///
/// Why: three states, never a bool. "Untracked" and "tracked as the
/// operator's" are both "not tm's", but only the second is positive PROOF —
/// and it is exactly the proof that must survive a name collision, or the
/// classifier condemns a file the deployer itself would preserve.
/// What: [`Untracked`](Self::Untracked) — no manifest entry;
/// [`FrameworkOwned`](Self::FrameworkOwned) — tracked with an origin
/// [`crate::agents::manifest::Origin::is_framework_owned`] accepts (the
/// `Overwrite` tier); [`UserOwned`](Self::UserOwned) — tracked with a
/// user-owned origin (the `SeedOnce` tier: `User` and, conservatively,
/// `Registry`).
/// Test: `ownership_of_reads_the_manifest_entry`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TierOwnership {
    /// No ledger entry names this file.
    Untracked,
    /// The ledger records tm as the author.
    FrameworkOwned,
    /// The ledger records the OPERATOR as the owner.
    UserOwned,
}

/// How one file in a non-canonical agent tier relates to tm's ownership.
///
/// Why: "delete every `.md` in `.claude/agents/`" is the wrong rule — it eats
/// a project's own agents. Ownership has to be established per file, from
/// evidence, and the evidence differs by case, so each case is named rather
/// than collapsed into a bool.
/// What: [`ShadowsBundled`](Self::ShadowsBundled) and
/// [`StrandedFrameworkOwned`](Self::StrandedFrameworkOwned) are tm-owned (report
/// them, and — for #4448 — quarantine them); [`Custom`](Self::Custom) is not
/// tm's and must never be reported or moved.
/// Test: `classify_*` cases in `tier_audit_tests.rs`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TierResidentClass {
    /// The file resolves to a name tm currently ships, so this copy OUTRANKS
    /// and shadows the canonical user-tier deploy. The #4408 failure exactly.
    ShadowsBundled,
    /// Not a name tm currently ships, but this directory's ownership manifest
    /// records tm as the author. A retired or renamed bundled agent that an
    /// older binary wrote here and no deploy will ever refresh again.
    StrandedFrameworkOwned,
    /// Neither — a project-custom, hand-placed, or ledger-proven user-owned
    /// agent. Legitimate; excluded.
    Custom,
}

impl TierResidentClass {
    /// Whether this class means "tm authored this file".
    ///
    /// Why: both consumers need the same one-line answer, and encoding it here
    /// keeps a future variant from defaulting to the wrong side at two
    /// independent call sites.
    /// What: `true` for [`ShadowsBundled`](Self::ShadowsBundled) and
    /// [`StrandedFrameworkOwned`](Self::StrandedFrameworkOwned); `false` for
    /// [`Custom`](Self::Custom).
    /// Test: `tm_owned_is_true_for_exactly_the_two_owned_classes`.
    pub fn is_tm_owned(self) -> bool {
        !matches!(self, Self::Custom)
    }
}

/// One tm-owned file found outside the canonical tier.
///
/// Why: consumers report or move the file, so the path (to act on), the name
/// it resolves under (to explain), and the reason (to choose a severity) travel
/// together.
/// What: the path as scanned, the agent name per [`agent_identity`] — which is
/// NOT necessarily the filename stem — and the classification, never
/// [`TierResidentClass::Custom`], which [`audit_agent_tier`] filters out.
/// Test: `audit_reports_a_shadowing_stub`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MisplacedAgent {
    /// Full path of the offending file.
    pub path: PathBuf,
    /// The name this file resolves under — frontmatter `name:`, else the stem.
    pub name: String,
    /// Why this file is tm's.
    pub class: TierResidentClass,
}

/// The name an agent file resolves under.
///
/// Why: invariant 1 of this module's contract. Every consumer keys agents by
/// the declared `name:` (see `trusty-agents`'
/// `agents::claude_mpm_loader::parse_agent_file`), so a filename-based
/// predicate is wrong in both directions — it misses `helper.md` declaring
/// `name: rust-engineer` and falsely flags `rust-engineer.md` declaring
/// `name: acme-custom`. Applied to the roster AND the candidate so both sides
/// of the comparison are keyed identically by construction.
/// What: the trimmed frontmatter `name:` when the document declares a
/// non-empty one, else `file_name` with any `.md` suffix stripped. Frontmatter
/// is read with trusty-mpm's own lenient grammar via
/// [`agent_metadata_from_str`] — the same reader #4509 settled on for this
/// tier — and a malformed or absent block simply yields the stem rather than
/// an error, since a file that declares nothing IS resolved by its stem.
/// Test: `identity_prefers_the_frontmatter_name`,
/// `identity_falls_back_to_the_stem`, `identity_ignores_a_blank_name`.
pub fn agent_identity(content: &str, file_name: &str) -> String {
    let stem = file_name.strip_suffix(".md").unwrap_or(file_name);
    agent_metadata_from_str(content)
        .name
        .map(|n| n.trim().to_owned())
        .filter(|n| !n.is_empty())
        .unwrap_or_else(|| stem.to_owned())
}

/// The canonical bundled agent roster, as resolved NAMES.
///
/// Why: "does this file resolve to a name tm ships?" must be answered from the
/// SOURCE tm actually deploys from, not a hard-coded list that silently rots
/// the first time an agent is added or renamed. Names, not stems: the bundle
/// itself carries files whose two differ (`BASE-AGENT.md` declares
/// `name: base-agent`).
/// What: [`agent_identity`] applied to every `.md` file directly under
/// `source_dir` (typically `FrameworkPaths::agent_source_dir()`). A missing or
/// unreadable directory yields an EMPTY set — the same "missing source is a
/// no-op, not an error" convention `deploy_agents` uses. Callers must treat an
/// empty roster as "cannot classify by name", never as "nothing is bundled":
/// concluding the latter would clear every shadowing file at once.
/// Test: `bundled_names_use_the_frontmatter_name`,
/// `bundled_names_missing_dir_is_empty`.
pub fn bundled_agent_names(source_dir: &Path) -> BTreeSet<String> {
    let Ok(entries) = std::fs::read_dir(source_dir) else {
        return BTreeSet::new();
    };
    entries
        .flatten()
        .filter_map(|entry| {
            let file_name = entry.file_name().to_str()?.to_owned();
            if !is_agent_file(&file_name) {
                return None;
            }
            let content = std::fs::read_to_string(entry.path()).unwrap_or_default();
            Some(agent_identity(&content, &file_name))
        })
        .collect()
}

/// What `manifest` says about `file_name`.
///
/// Why: the three-state read is the whole point of [`TierOwnership`]; doing it
/// in one place keeps a caller from re-deriving it as a bool and losing the
/// user-owned proof again.
/// What: [`TierOwnership::Untracked`] when no entry exists, else
/// `FrameworkOwned`/`UserOwned` per
/// [`crate::agents::manifest::Origin::is_framework_owned`] — the same predicate
/// the deployer and `retract_framework_agents` branch on.
/// Test: `ownership_of_reads_the_manifest_entry`.
pub fn ownership_of(manifest: &AgentManifest, file_name: &str) -> TierOwnership {
    match manifest.managed.get(file_name) {
        None => TierOwnership::Untracked,
        Some(entry) if entry.origin.is_framework_owned() => TierOwnership::FrameworkOwned,
        Some(_) => TierOwnership::UserOwned,
    }
}

/// Classify one file in a non-canonical tier. Pure — no I/O.
///
/// Why: the verdict is the shared contract between #4442 and #4448, so it is
/// separated from the scan that feeds it: both consumers can unit-test every
/// branch without staging a directory, and neither can quietly re-implement it.
/// What: a [`TierOwnership::UserOwned`] ledger entry wins FIRST and yields
/// [`TierResidentClass::Custom`] — the operator's own agent stays theirs even
/// when its name collides with a bundled one, matching
/// [`crate::agents::deployer::retract_framework_agents`], which preserves that
/// tier. Otherwise [`TierResidentClass::ShadowsBundled`] when `bundled`
/// contains `identity` (a shadowing file is shadowing whether or not the ledger
/// tracks it); otherwise [`TierResidentClass::StrandedFrameworkOwned`] when the
/// ledger records tm as the author; otherwise [`TierResidentClass::Custom`].
/// Test: `classify_bundled_name_shadows`,
/// `classify_user_owned_survives_a_bundled_name_collision`,
/// `classify_manifest_framework_owned_is_stranded`,
/// `classify_unknown_name_is_custom`,
/// `classify_prefers_shadowing_over_stranded`.
pub fn classify_tier_resident(
    identity: &str,
    ownership: TierOwnership,
    bundled: &BTreeSet<String>,
) -> TierResidentClass {
    if ownership == TierOwnership::UserOwned {
        return TierResidentClass::Custom;
    }
    if bundled.contains(identity) {
        return TierResidentClass::ShadowsBundled;
    }
    if ownership == TierOwnership::FrameworkOwned {
        return TierResidentClass::StrandedFrameworkOwned;
    }
    TierResidentClass::Custom
}

/// Scan one non-canonical agent tier and return the tm-owned files in it.
///
/// Why: the shared scan both consumers run, so "what doctor flags" and "what
/// repair quarantines" are the same list by construction.
/// What: READ-ONLY. Lists `.md` files directly under `dir` (never recursing —
/// the tier is flat), reads each one's frontmatter for [`agent_identity`] and
/// this directory's ownership manifest for [`ownership_of`], classifies with
/// [`classify_tier_resident`], and returns the
/// non-[`TierResidentClass::Custom`] results sorted by name for stable output.
/// An ABSENT `dir` returns an empty vec — an unprovisioned tier holds nothing.
/// A `dir` that exists but cannot be enumerated returns
/// [`TierAuditError::Unscannable`] (#5626): the empty vec is what the consumer
/// renders as "scanned, found nothing", and a scan that failed has established
/// no such thing.
///
/// A CORRUPT or unreadable manifest degrades to [`TierOwnership::Untracked`] for
/// every file rather than failing: shadowing is established by the roster alone,
/// so the load-bearing signal survives. Note the asymmetry that makes that safe
/// — an unreadable ledger can only LOSE the user-owned exemption, so the result
/// can only over-report, never under-report; #4448 must re-read the ledger under
/// its own write lock before moving anything, and this read-only probe does not
/// hold one. Never call this on the canonical deploy directory — every file
/// there would classify as tm-owned, correctly and uselessly.
/// Test: `audit_reports_a_shadowing_stub`, `audit_ignores_a_custom_agent`,
/// `audit_ignores_a_user_owned_entry_on_a_bundled_name`,
/// `audit_reports_a_stranded_framework_entry`, `audit_missing_dir_is_empty`,
/// `audit_unscannable_dir_is_an_error`, `audit_tolerates_a_corrupt_manifest`,
/// `audit_flags_a_renamed_file_that_declares_a_bundled_name`,
/// `audit_ignores_a_bundled_filename_that_declares_a_custom_name`.
pub fn audit_agent_tier(
    dir: &Path,
    bundled: &BTreeSet<String>,
) -> Result<Vec<MisplacedAgent>, TierAuditError> {
    let entries = match std::fs::read_dir(dir) {
        Ok(entries) => entries,
        // #5626: an absent tier is a real answer; anything else is not.
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(source) => {
            return Err(TierAuditError::Unscannable {
                path: dir.to_path_buf(),
                source,
            });
        }
    };
    let manifest = match AgentManifest::load_checked(dir) {
        ManifestLoad::Ok(m) => m,
        // intentional fail-open (ADR-0045 §4): an undetermined ledger can only
        // widen this read-only report, never narrow it — it loses the user-owned
        // exemption and nothing else. Refusing instead would drop the
        // roster-based shadowing verdict, which needs no ledger at all. The
        // mover (#4448) re-reads under its own lock and refuses there.
        ManifestLoad::Corrupt(_) => AgentManifest::default(),
    };

    let mut found: Vec<MisplacedAgent> = entries
        .flatten()
        .filter_map(|entry| {
            let file_name = entry.file_name().to_str()?.to_owned();
            if !is_agent_file(&file_name) || !entry.path().is_file() {
                return None;
            }
            let content = std::fs::read_to_string(entry.path()).unwrap_or_default();
            let name = agent_identity(&content, &file_name);
            let class = classify_tier_resident(&name, ownership_of(&manifest, &file_name), bundled);
            class.is_tm_owned().then(|| MisplacedAgent {
                path: entry.path(),
                name,
                class,
            })
        })
        .collect();
    found.sort_by(|a, b| a.name.cmp(&b.name));
    Ok(found)
}

/// One file whose declared `provenance:` contradicts its ledger entry (#4698).
///
/// Why: `provenance:` and the ownership ledger are two independent records of
/// the same fact, so they can disagree once anybody edits a deployed file. The
/// ledger wins for every OWNERSHIP decision — see
/// [`crate::agents::provenance::reconcile_with_ledger`] — but the operator
/// still needs to be told, and a `tracing::warn!` alone reaches no `tm doctor`
/// report. This is the value that travels to one.
/// What: the file, both records, and the rendered explanation. `detail` is
/// [`crate::agents::provenance::Reconciled::disagreement`] verbatim, so the log
/// line and the doctor finding cannot drift apart.
/// Test: `audit_provenance_reports_a_contradicting_declaration`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProvenanceDisagreement {
    /// Full path of the file whose declaration contradicts the ledger.
    pub path: PathBuf,
    /// What the file declares about its own author.
    pub declared: Provenance,
    /// What the ledger records — the value that WINS.
    pub ledger_framework_owned: bool,
    /// The rendered explanation, naming the file and both records.
    pub detail: String,
}

/// Scan any agent directory for files whose `provenance:` contradicts the
/// ledger (#4698).
///
/// Why: deliberately NOT folded into [`audit_agent_tier`], for two reasons that
/// both point the same way. [`audit_agent_tier`] answers "is this file
/// MISPLACED?", and a disagreement is a different question about a file that
/// may be perfectly placed — folding them would put an unrelated fact inside
/// [`MisplacedAgent`], which every consumer reads as "move or delete this".
/// More decisively, [`audit_agent_tier`] must never run on the canonical deploy
/// directory (every file there is tm-owned, correctly and uselessly), and the
/// canonical directory is exactly where a hand-edited DEPLOYED agent lives.
/// A disagreement check that could not look there would miss the case it exists
/// for.
/// What: READ-ONLY. Lists `.md` files directly under `dir`, reads this
/// directory's ownership manifest, and returns one entry per file whose
/// declaration contradicts its ledger row, sorted by path for stable output.
/// A file with NO ledger entry yields nothing: an absent entry is not a
/// disagreement, and a declaration cannot stand in for one (invariant 2 above).
/// A file declaring nothing yields nothing — that is every file written before
/// #4698. An ABSENT `dir` returns an empty vec; a `dir` that exists but cannot
/// be enumerated returns [`TierAuditError::Unscannable`], matching
/// [`audit_agent_tier`]. A corrupt or unreadable ledger yields nothing: with no
/// second record to read, no contradiction can be established.
/// Test: `audit_provenance_reports_a_contradicting_declaration`,
/// `audit_provenance_is_silent_when_records_agree`,
/// `audit_provenance_ignores_an_untracked_file`,
/// `audit_provenance_ignores_a_file_declaring_nothing`,
/// `audit_provenance_missing_dir_is_empty`,
/// `audit_provenance_unscannable_dir_is_an_error`.
pub fn audit_provenance(dir: &Path) -> Result<Vec<ProvenanceDisagreement>, TierAuditError> {
    let entries = match std::fs::read_dir(dir) {
        Ok(entries) => entries,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(source) => {
            return Err(TierAuditError::Unscannable {
                path: dir.to_path_buf(),
                source,
            });
        }
    };
    let manifest = match AgentManifest::load_checked(dir) {
        ManifestLoad::Ok(m) => m,
        ManifestLoad::Corrupt(_) => return Ok(Vec::new()),
    };

    let mut found: Vec<ProvenanceDisagreement> = entries
        .flatten()
        .filter_map(|entry| {
            let file_name = entry.file_name().to_str()?.to_owned();
            if !is_agent_file(&file_name) || !entry.path().is_file() {
                return None;
            }
            let ledger = manifest.managed.get(&file_name)?;
            let content = std::fs::read_to_string(entry.path()).ok()?;
            let declared = agent_metadata_from_str(&content).provenance?;
            let ledger_framework_owned = ledger.origin.is_framework_owned();
            let detail = reconcile_with_ledger(&file_name, ledger_framework_owned, Some(declared))
                .disagreement?;
            Some(ProvenanceDisagreement {
                path: entry.path(),
                declared,
                ledger_framework_owned,
                detail,
            })
        })
        .collect();
    found.sort_by(|a, b| a.path.cmp(&b.path));
    Ok(found)
}

#[cfg(test)]
#[path = "tier_audit_tests.rs"]
mod tests;