trusty-agents-common 0.9.2

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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
//! Tests for the shared non-canonical-tier ownership classifier (#4442).
//!
//! Why: this predicate is consumed by two surfaces (`tm doctor`'s `asset_tier`
//! probe and the #4448 quarantine), so every branch is pinned here once rather
//! than re-tested at each consumer. Two of these guard the module's stated
//! invariants directly: identity is the frontmatter `name`, and a user-owned
//! ledger entry survives a name collision.
//! What: pure `classify_tier_resident` / `agent_identity` branches plus
//! `audit_agent_tier` against staged temp directories — including the
//! load-bearing pair (a project-tier stub on a bundled name is REPORTED; a
//! project's own agent is NOT).
//! Test: this file.

use std::collections::BTreeSet;

use super::*;
use crate::agents::manifest::{AgentManifest, ManifestEntry, Origin, checksum};
// #4698: the frontmatter authorship claim reconciled against the ledger.
use crate::agents::provenance::Provenance;

/// Build a name set from string literals.
fn roster(names: &[&str]) -> BTreeSet<String> {
    names.iter().map(|s| (*s).to_owned()).collect()
}

/// A minimal agent document declaring `name`.
fn doc(name: &str) -> String {
    format!("---\nname: {name}\nrole: engineer\n---\n\nBody.\n")
}

/// Write a manifest into `dir` claiming `filename` with `origin`.
fn track(dir: &std::path::Path, filename: &str, origin: Origin) {
    let mut manifest = AgentManifest::default();
    manifest.managed.insert(
        filename.to_owned(),
        ManifestEntry {
            source_chain: vec![],
            checksum: checksum("whatever"),
            deployed_at: "2026-07-31T00:00:00Z".to_owned(),
            origin,
        },
    );
    manifest.save(dir).unwrap();
}

// ---------------------------------------------------------------------------
// agent_identity — invariant 1: identity is the frontmatter `name`.
// ---------------------------------------------------------------------------

#[test]
fn identity_prefers_the_frontmatter_name() {
    // The loader keys on `name:`, so a file named anything can BE rust-engineer.
    assert_eq!(
        agent_identity(&doc("rust-engineer"), "helper.md"),
        "rust-engineer"
    );
}

#[test]
fn identity_falls_back_to_the_stem() {
    // No frontmatter at all: the loader resolves such a file by its stem.
    assert_eq!(agent_identity("just prose\n", "helper.md"), "helper");
    assert_eq!(agent_identity("", "qa.md"), "qa");
}

#[test]
fn identity_ignores_a_blank_name() {
    // A declared-but-empty name is not an identity; fall back to the stem.
    assert_eq!(agent_identity("---\nname:   \n---\n", "qa.md"), "qa");
}

#[test]
fn identity_strips_only_one_md_suffix() {
    // `strip_suffix`, not `trim_end_matches`: a repeated suffix must survive.
    assert_eq!(agent_identity("", "weird.md.md"), "weird.md");
}

// ---------------------------------------------------------------------------
// classify_tier_resident
// ---------------------------------------------------------------------------

#[test]
fn classify_bundled_name_shadows() {
    // A name tm ships outranks the canonical tier wherever else it appears.
    let bundled = roster(&["rust-engineer", "qa"]);
    assert_eq!(
        classify_tier_resident("rust-engineer", TierOwnership::Untracked, &bundled),
        TierResidentClass::ShadowsBundled
    );
}

#[test]
fn classify_user_owned_survives_a_bundled_name_collision() {
    // INVARIANT 2. The ledger positively proves the operator owns this file.
    // A bundled-name collision must NOT override that — `retract_framework_agents`
    // preserves this tier, so quarantining it under #4448 would delete the
    // operator's own agent. Fails against a bool-flattened ownership input.
    let bundled = roster(&["qa"]);
    assert_eq!(
        classify_tier_resident("qa", TierOwnership::UserOwned, &bundled),
        TierResidentClass::Custom
    );
    assert!(!TierResidentClass::Custom.is_tm_owned());
}

#[test]
fn classify_manifest_framework_owned_is_stranded() {
    // Retired/renamed bundled agent: no longer in the roster, but the ledger
    // proves tm wrote it, so no deploy will ever refresh it again.
    let bundled = roster(&["qa"]);
    assert_eq!(
        classify_tier_resident("legacy-agent", TierOwnership::FrameworkOwned, &bundled),
        TierResidentClass::StrandedFrameworkOwned
    );
}

#[test]
fn classify_unknown_name_is_custom() {
    // The exclusion seam: a project's own agent is never tm's to touch.
    let bundled = roster(&["qa"]);
    assert_eq!(
        classify_tier_resident("acme-internal", TierOwnership::Untracked, &bundled),
        TierResidentClass::Custom
    );
}

#[test]
fn classify_prefers_shadowing_over_stranded() {
    // Shadowing is a property of the NAME, not of the ledger — a tm-tracked
    // file whose name is still bundled reports as shadowing, the stronger,
    // actionable verdict.
    let bundled = roster(&["qa"]);
    assert_eq!(
        classify_tier_resident("qa", TierOwnership::FrameworkOwned, &bundled),
        TierResidentClass::ShadowsBundled
    );
}

#[test]
fn tm_owned_is_true_for_exactly_the_two_owned_classes() {
    assert!(TierResidentClass::ShadowsBundled.is_tm_owned());
    assert!(TierResidentClass::StrandedFrameworkOwned.is_tm_owned());
    assert!(!TierResidentClass::Custom.is_tm_owned());
}

#[test]
fn ownership_of_reads_the_manifest_entry() {
    // The three states must come from one place, or a caller re-derives a bool.
    let mut manifest = AgentManifest::default();
    for (file, origin) in [
        ("bundled.md", Origin::Bundled),
        ("mine.md", Origin::User),
        ("pulled.md", Origin::Registry),
    ] {
        manifest.managed.insert(
            file.to_owned(),
            ManifestEntry {
                source_chain: vec![],
                checksum: checksum("x"),
                deployed_at: "2026-07-31T00:00:00Z".to_owned(),
                origin,
            },
        );
    }
    assert_eq!(
        ownership_of(&manifest, "bundled.md"),
        TierOwnership::FrameworkOwned
    );
    assert_eq!(ownership_of(&manifest, "mine.md"), TierOwnership::UserOwned);
    // Registry is conservatively user-owned — the operator pulled it.
    assert_eq!(
        ownership_of(&manifest, "pulled.md"),
        TierOwnership::UserOwned
    );
    assert_eq!(
        ownership_of(&manifest, "absent.md"),
        TierOwnership::Untracked
    );
}

// ---------------------------------------------------------------------------
// bundled_agent_names
// ---------------------------------------------------------------------------

#[test]
fn bundled_names_use_the_frontmatter_name() {
    // The bundle really does ship files whose stem and name differ
    // (`BASE-AGENT.md` declares `name: base-agent`), so the roster must be
    // keyed the way the loader keys it.
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("BASE-AGENT.md"), doc("base-agent")).unwrap();
    std::fs::write(tmp.path().join("qa.md"), doc("qa")).unwrap();
    std::fs::write(tmp.path().join("nameless.md"), "prose only").unwrap();
    std::fs::write(tmp.path().join("notes.txt"), "x").unwrap();

    assert_eq!(
        bundled_agent_names(tmp.path()),
        roster(&["base-agent", "qa", "nameless"])
    );
}

#[test]
fn bundled_names_missing_dir_is_empty() {
    let tmp = tempfile::tempdir().unwrap();
    assert!(bundled_agent_names(&tmp.path().join("nope")).is_empty());
}

// ---------------------------------------------------------------------------
// audit_agent_tier
// ---------------------------------------------------------------------------

#[test]
fn audit_reports_a_shadowing_stub() {
    // #4408 reproduced: a 32-byte project-tier stub sitting on a bundled name.
    // The scan must find it — this is the case the whole probe exists for.
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("rust-engineer.md"), doc("rust-engineer")).unwrap();

    let found = audit_agent_tier(tmp.path(), &roster(&["rust-engineer"])).unwrap();
    assert_eq!(found.len(), 1, "found: {found:?}");
    assert_eq!(found[0].name, "rust-engineer");
    assert_eq!(found[0].class, TierResidentClass::ShadowsBundled);
    assert_eq!(found[0].path, tmp.path().join("rust-engineer.md"));
}

#[test]
fn audit_flags_a_renamed_file_that_declares_a_bundled_name() {
    // The MISS a stem-keyed predicate produces: the file is called `helper.md`
    // but the harness resolves it as `rust-engineer`, so it shadows.
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("helper.md"), doc("rust-engineer")).unwrap();

    let found = audit_agent_tier(tmp.path(), &roster(&["rust-engineer"])).unwrap();
    assert_eq!(found.len(), 1, "found: {found:?}");
    assert_eq!(found[0].name, "rust-engineer");
    assert_eq!(found[0].path, tmp.path().join("helper.md"));
}

#[test]
fn audit_ignores_a_bundled_filename_that_declares_a_custom_name() {
    // The FALSE POSITIVE a stem-keyed predicate produces: the filename collides
    // but the harness resolves this as `acme-custom`, which shadows nothing.
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("rust-engineer.md"), doc("acme-custom")).unwrap();

    assert!(
        audit_agent_tier(tmp.path(), &roster(&["rust-engineer"]))
            .unwrap()
            .is_empty()
    );
}

#[test]
fn audit_ignores_a_custom_agent() {
    // The noise guard: a project agent tm never authored must produce NOTHING,
    // even sitting in the same directory as a real shadowing file.
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("acme-internal.md"), doc("acme-internal")).unwrap();
    std::fs::write(tmp.path().join("qa.md"), doc("qa")).unwrap();

    let found = audit_agent_tier(tmp.path(), &roster(&["qa"])).unwrap();
    assert_eq!(found.len(), 1, "found: {found:?}");
    assert_eq!(found[0].name, "qa");
}

#[test]
fn audit_ignores_a_user_owned_entry_on_a_bundled_name() {
    // INVARIANT 2, end to end: the operator's own `qa.md`, tracked `Origin::User`,
    // on a name tm also ships. Reporting it would hand #4448 a file to rename
    // out from under its author.
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("qa.md"), doc("qa")).unwrap();
    track(tmp.path(), "qa.md", Origin::User);

    assert!(
        audit_agent_tier(tmp.path(), &roster(&["qa"]))
            .unwrap()
            .is_empty()
    );
}

#[test]
fn audit_reports_a_stranded_framework_entry() {
    // Tracked framework-owned but no longer bundled: reported, because no
    // deploy will refresh it and no operator knows it is there.
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("legacy-agent.md"), doc("legacy-agent")).unwrap();
    track(tmp.path(), "legacy-agent.md", Origin::Bundled);

    let found = audit_agent_tier(tmp.path(), &roster(&["qa"])).unwrap();
    assert_eq!(found.len(), 1, "found: {found:?}");
    assert_eq!(found[0].class, TierResidentClass::StrandedFrameworkOwned);
}

#[test]
fn audit_ignores_a_user_owned_manifest_entry() {
    // A tracked USER-origin file outside the roster stays invisible too.
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("mine.md"), doc("mine")).unwrap();
    track(tmp.path(), "mine.md", Origin::User);

    assert!(
        audit_agent_tier(tmp.path(), &roster(&["qa"]))
            .unwrap()
            .is_empty()
    );
}

#[test]
fn audit_missing_dir_is_empty() {
    // #5626 kept this benign: a tier directory that does not exist holds
    // nothing, and "nothing" is a real answer. Only a scan that FAILED is an
    // error.
    let tmp = tempfile::tempdir().unwrap();
    assert!(
        audit_agent_tier(&tmp.path().join("nope"), &roster(&["qa"]))
            .expect("an absent tier is not an error")
            .is_empty()
    );
}

#[test]
#[cfg(unix)]
fn audit_unscannable_dir_is_an_error() {
    // #5626, ADR-0045: `let Ok(entries) = read_dir(dir) else { Vec::new() }`
    // returned the same empty vec for "scanned, found nothing" and "could not
    // scan", and `doctor_asset_tier` rendered that as
    // `no tm-owned agent files … (scanned: <dir>)` — asserting a scan that
    // never ran. The directory here holds a real shadowing stub.
    use std::os::unix::fs::PermissionsExt;

    let tmp = tempfile::tempdir().unwrap();
    let tier = tmp.path().join("agents");
    std::fs::create_dir(&tier).unwrap();
    std::fs::write(tier.join("qa.md"), doc("qa")).unwrap();

    std::fs::set_permissions(&tier, std::fs::Permissions::from_mode(0o000)).unwrap();
    let result = audit_agent_tier(&tier, &roster(&["qa"]));
    std::fs::set_permissions(&tier, std::fs::Permissions::from_mode(0o755)).unwrap();

    let err = result.expect_err("an unscannable tier must not report an empty scan");
    let TierAuditError::Unscannable { path, source } = &err;
    assert_eq!(path, &tier);
    assert_eq!(source.kind(), std::io::ErrorKind::PermissionDenied);
}

#[test]
fn audit_tolerates_a_corrupt_manifest() {
    // A corrupt ledger must not silence the roster-based verdict — that would
    // be a presence-only check reporting green through a real shadowing.
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(tmp.path().join("qa.md"), doc("qa")).unwrap();
    std::fs::write(
        tmp.path().join(crate::agents::manifest::MANIFEST_FILE),
        "{ not json",
    )
    .unwrap();

    let found = audit_agent_tier(tmp.path(), &roster(&["qa"])).unwrap();
    assert_eq!(found.len(), 1, "found: {found:?}");
    assert_eq!(found[0].class, TierResidentClass::ShadowsBundled);
}

#[test]
fn audit_is_sorted_by_name() {
    // Stable output so doctor messages and quarantine logs are diffable.
    let tmp = tempfile::tempdir().unwrap();
    for name in ["qa", "engineer", "rust-engineer"] {
        std::fs::write(tmp.path().join(format!("{name}.md")), doc(name)).unwrap();
    }

    let found =
        audit_agent_tier(tmp.path(), &roster(&["qa", "engineer", "rust-engineer"])).unwrap();
    let names: Vec<&str> = found.iter().map(|f| f.name.as_str()).collect();
    assert_eq!(names, vec!["engineer", "qa", "rust-engineer"]);
}

// ---------------------------------------------------------------------------
// #4698: `provenance:` that contradicts the ledger, reported not swallowed.
// ---------------------------------------------------------------------------

/// Write `<dir>/<file_name>` declaring `provenance: <declared>` and track it in
/// the ledger under `origin`.
fn staged(dir: &std::path::Path, file_name: &str, declared: Option<&str>, origin: Origin) {
    let line = declared
        .map(|d| format!("provenance: {d}\n"))
        .unwrap_or_default();
    std::fs::write(
        dir.join(file_name),
        format!("---\nname: qa\nrole: qa\n{line}---\n\nBODY\n"),
    )
    .unwrap();
    track(dir, file_name, origin);
}

/// The finding names the file and BOTH records — the whole point of carrying it
/// out of `reconcile_with_ledger` instead of only logging it.
#[test]
fn audit_provenance_reports_a_contradicting_declaration() {
    let tmp = tempfile::tempdir().unwrap();
    staged(tmp.path(), "qa.md", Some("user-authored"), Origin::Bundled);

    let found = audit_provenance(tmp.path()).unwrap();
    assert_eq!(found.len(), 1, "one disagreement: {found:?}");
    assert_eq!(found[0].path, tmp.path().join("qa.md"));
    assert_eq!(found[0].declared, Provenance::UserAuthored);
    assert!(
        found[0].ledger_framework_owned,
        "the ledger's value travels too"
    );
    assert!(
        found[0].detail.contains("qa.md"),
        "names the file: {}",
        found[0].detail
    );
    assert!(
        found[0].detail.contains("user-authored"),
        "names the declaration: {}",
        found[0].detail
    );
    assert!(
        found[0].detail.contains("framework-owned"),
        "names the ledger's record: {}",
        found[0].detail
    );
}

/// The mirror: a file claiming the framework wrote it while the ledger records
/// the operator as its author.
#[test]
fn audit_provenance_reports_the_mirrored_contradiction() {
    let tmp = tempfile::tempdir().unwrap();
    staged(tmp.path(), "mine.md", Some("framework-owned"), Origin::User);

    let found = audit_provenance(tmp.path()).unwrap();
    assert_eq!(found.len(), 1, "{found:?}");
    assert_eq!(found[0].declared, Provenance::FrameworkOwned);
    assert!(!found[0].ledger_framework_owned);
}

#[test]
fn audit_provenance_is_silent_when_records_agree() {
    let tmp = tempfile::tempdir().unwrap();
    staged(
        tmp.path(),
        "qa.md",
        Some("framework-owned"),
        Origin::Bundled,
    );
    assert!(audit_provenance(tmp.path()).unwrap().is_empty());
}

/// An absent ledger entry is not a disagreement — a declaration anybody can
/// type must never stand in for one (invariant 2).
#[test]
fn audit_provenance_ignores_an_untracked_file() {
    let tmp = tempfile::tempdir().unwrap();
    std::fs::write(
        tmp.path().join("qa.md"),
        "---\nname: qa\nprovenance: framework-owned\n---\n\nBODY\n",
    )
    .unwrap();
    assert!(audit_provenance(tmp.path()).unwrap().is_empty());
}

/// Every file written before #4698 declares nothing; that is not an anomaly.
#[test]
fn audit_provenance_ignores_a_file_declaring_nothing() {
    let tmp = tempfile::tempdir().unwrap();
    staged(tmp.path(), "qa.md", None, Origin::Bundled);
    assert!(audit_provenance(tmp.path()).unwrap().is_empty());
}

#[test]
fn audit_provenance_missing_dir_is_empty() {
    let tmp = tempfile::tempdir().unwrap();
    let absent = tmp.path().join("nope");
    assert!(audit_provenance(&absent).unwrap().is_empty());
}

/// #5626's rule, applied to this scan too: a directory that exists but cannot
/// be read has established nothing, and must not read as "found nothing".
#[test]
#[cfg(unix)]
fn audit_provenance_unscannable_dir_is_an_error() {
    use std::os::unix::fs::PermissionsExt;
    let tmp = tempfile::tempdir().unwrap();
    let locked = tmp.path().join("locked");
    std::fs::create_dir(&locked).unwrap();
    std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).unwrap();
    let result = audit_provenance(&locked);
    std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755)).unwrap();
    assert!(
        matches!(result, Err(TierAuditError::Unscannable { .. })),
        "{result:?}"
    );
}

/// The placement verdict is untouched by a declaration — the ledger still wins
/// for ownership, so a contradicting file classifies exactly as before.
#[test]
fn audit_verdict_is_unchanged_by_a_contradicting_declaration() {
    let tmp = tempfile::tempdir().unwrap();
    staged(tmp.path(), "qa.md", Some("user-authored"), Origin::Bundled);

    let bundled: BTreeSet<String> = ["qa".to_string()].into_iter().collect();
    let found = audit_agent_tier(tmp.path(), &bundled).unwrap();
    assert_eq!(found.len(), 1, "still reported: {found:?}");
    assert_eq!(found[0].class, TierResidentClass::ShadowsBundled);
}