Skip to main content

safe_chains/engine/
archetype.rs

1//! Static capability archetypes (`docs/design/behavioral-taxonomy-archetypes.md`). The recurring
2//! facet profiles the Phase-1 subcommand surface classifies against. Each archetype is a fixed
3//! [`Capability`] declared in `archetypes.toml`; a subcommand references one by name (`profile =
4//! "remote-mutate"`) and the resolver emits that capability directly (a static profile — the
5//! sub's facets don't depend on its arguments, unlike the operand-role commands of Phase 0).
6//!
7//! This is the archetype as a *reusable audited bundle*, never a unit of analysis: `profile = …`
8//! expands to the explicit capability here, the researcher still verifies the sub genuinely is
9//! that archetype and cites it (the per-item provenance schema). Facet fields take an EXACT term,
10//! not a bound — these are points in facet-space, not the level predicates of `authoring`.
11
12use std::collections::BTreeMap;
13use std::sync::LazyLock;
14
15use serde::Deserialize;
16
17use super::facet::{Capability, FacetTerm, Operation};
18
19/// The capability an archetype expands to, or `None` if the name is unknown (fail-closed: an
20/// unknown `profile = …` must not silently resolve to nothing).
21pub fn archetype(name: &str) -> Option<&'static Capability> {
22    ARCHETYPES.get(name)
23}
24
25/// Every archetype name, for the `profile = …` closed-set check and the docs.
26pub fn names() -> impl Iterator<Item = &'static str> {
27    ARCHETYPES.keys().map(String::as_str)
28}
29
30static ARCHETYPES: LazyLock<BTreeMap<String, Capability>> =
31    LazyLock::new(|| build_archetypes(include_str!("../../archetypes.toml")).expect("embedded archetypes.toml must compile"));
32
33/// How an archetype is told apart from a confusable neighbour.
34#[derive(Debug, Clone, Deserialize)]
35struct TomlDistinction {
36    #[allow(dead_code)] // authoring metadata, read by the near-neighbour guards
37    archetype: String,
38    /// The dotted facet name that differs, as `Capability::set_facets` spells it.
39    #[allow(dead_code)] // authoring metadata, read by the near-neighbour guards
40    by: String,
41}
42
43/// One archetype's authored disambiguation: its name, the `(other, axis)` pairs it declares itself
44/// distinguished from, and the archetype it declares itself facet-identical to.
45#[cfg(test)]
46type DeclaredDistinction = (String, Vec<(String, String)>, Option<String>);
47
48/// The authored disambiguation for every archetype — checked against the facets themselves by
49/// `near_neighbours_are_declared`.
50#[cfg(test)]
51fn declared_distinctions() -> Vec<DeclaredDistinction> {
52    let set: TomlArchetypeSet = toml::from_str(include_str!("../../archetypes.toml")).expect("archetypes.toml parses");
53    set.archetype
54        .into_iter()
55        .map(|(name, tc)| {
56            let d = tc.distinguished_from.into_iter().map(|x| (x.archetype, x.by)).collect();
57            (name, d, tc.same_point_as)
58        })
59        .collect()
60}
61
62fn build_archetypes(src: &str) -> Result<BTreeMap<String, Capability>, String> {
63    let set: TomlArchetypeSet = toml::from_str(src).map_err(|e| e.to_string())?;
64    set.archetype.into_iter().map(|(name, tc)| build_capability(&name, tc).map(|c| (name, c))).collect()
65}
66
67fn build_capability(name: &str, tc: TomlCapability) -> Result<Capability, String> {
68    let operation =
69        Operation::from_term(&tc.operation).ok_or_else(|| format!("archetype `{name}`: unknown operation `{}`", tc.operation))?;
70    let mut c = Capability::new(operation);
71
72    if let Some(l) = &tc.locus {
73        set_term(name, "locus.local", l.local.as_deref(), &mut c.locus.local)?;
74        set_term(name, "locus.remote", l.remote.as_deref(), &mut c.locus.remote)?;
75        set_term(name, "locus.binding", l.binding.as_deref(), &mut c.locus.binding)?;
76        set_term(name, "locus.provenance", l.provenance.as_deref(), &mut c.locus.provenance)?;
77    }
78    set_term(name, "scale", tc.scale.as_deref(), &mut c.scale)?;
79    set_term(name, "retrieval", tc.retrieval.as_deref(), &mut c.retrieval)?;
80    set_term(name, "authority", tc.authority.as_deref(), &mut c.authority)?;
81    set_term(name, "reversibility", tc.reversibility.as_deref(), &mut c.reversibility)?;
82    if let Some(p) = &tc.persistence {
83        set_term(name, "persistence.level", p.level.as_deref(), &mut c.persistence.level)?;
84    }
85    if let Some(d) = &tc.disclosure {
86        set_term(name, "disclosure.audience", d.audience.as_deref(), &mut c.disclosure.audience)?;
87    }
88    if let Some(s) = &tc.secret {
89        set_term(name, "secret.level", s.level.as_deref(), &mut c.secret.level)?;
90    }
91    if let Some(net) = &tc.network {
92        set_term(name, "network.direction", net.direction.as_deref(), &mut c.network.direction)?;
93        set_term(name, "network.destination", net.destination.as_deref(), &mut c.network.destination)?;
94        set_term(name, "network.payload", net.payload.as_deref(), &mut c.network.payload)?;
95    }
96    set_term(name, "execution", tc.execution.as_deref(), &mut c.execution.trust)?;
97    set_term(name, "cost", tc.cost.as_deref(), &mut c.cost)?;
98
99    if tc.because.trim().is_empty() {
100        return Err(format!("archetype `{name}`: `because` is required"));
101    }
102    c.because = tc.because;
103    Ok(c)
104}
105
106/// Parse an optional term into `slot`, leaving the zero-term default when absent. An unrecognized
107/// term is a compile error naming the archetype and facet (fail-closed, never a silent skip).
108fn set_term<T: FacetTerm>(name: &str, field: &str, s: Option<&str>, slot: &mut T) -> Result<(), String> {
109    if let Some(v) = s {
110        *slot = T::from_term(v).ok_or_else(|| format!("archetype `{name}`: unknown {field} term `{v}`"))?;
111    }
112    Ok(())
113}
114
115#[derive(Deserialize)]
116struct TomlArchetypeSet {
117    #[serde(default)]
118    archetype: BTreeMap<String, TomlCapability>,
119}
120
121#[derive(Deserialize)]
122#[serde(deny_unknown_fields)]
123struct TomlCapability {
124    operation: String,
125    because: String,
126    /// Archetypes this one is easily confused with, and the axis that separates them. Required
127    /// (both ways) for any pair differing on a single facet — see `near_neighbours_are_declared`.
128    #[serde(default)]
129    #[allow(dead_code)] // authoring metadata, read by the near-neighbour guards
130    distinguished_from: Vec<TomlDistinction>,
131    /// An archetype occupying the SAME point in facet space, declared deliberately. The two
132    /// classify identically and differ only in the prose `--explain` shows.
133    #[serde(default)]
134    #[allow(dead_code)] // authoring metadata, read by the near-neighbour guards
135    same_point_as: Option<String>,
136    #[serde(default)]
137    locus: Option<TomlLocus>,
138    #[serde(default)]
139    scale: Option<String>,
140    #[serde(default)]
141    retrieval: Option<String>,
142    #[serde(default)]
143    authority: Option<String>,
144    #[serde(default)]
145    reversibility: Option<String>,
146    #[serde(default)]
147    persistence: Option<TomlPersistence>,
148    #[serde(default)]
149    disclosure: Option<TomlDisclosure>,
150    #[serde(default)]
151    secret: Option<TomlSecret>,
152    #[serde(default)]
153    network: Option<TomlNetwork>,
154    #[serde(default)]
155    execution: Option<String>,
156    #[serde(default)]
157    cost: Option<String>,
158}
159
160#[derive(Deserialize)]
161#[serde(deny_unknown_fields)]
162struct TomlLocus {
163    local: Option<String>,
164    remote: Option<String>,
165    binding: Option<String>,
166    provenance: Option<String>,
167}
168
169#[derive(Deserialize)]
170#[serde(deny_unknown_fields)]
171struct TomlPersistence {
172    level: Option<String>,
173}
174
175#[derive(Deserialize)]
176#[serde(deny_unknown_fields)]
177struct TomlDisclosure {
178    audience: Option<String>,
179}
180
181#[derive(Deserialize)]
182#[serde(deny_unknown_fields)]
183struct TomlSecret {
184    level: Option<String>,
185}
186
187#[derive(Deserialize)]
188#[serde(deny_unknown_fields)]
189struct TomlNetwork {
190    direction: Option<String>,
191    destination: Option<String>,
192    payload: Option<String>,
193}
194
195#[cfg(test)]
196mod tests {
197    use super::*;
198    use crate::engine::authoring::default_levels;
199    use crate::engine::bridge::project;
200    use crate::engine::facet::Profile;
201    use crate::engine::level::Level;
202    use crate::verdict::Verdict;
203
204    fn level(name: &str) -> &'static Level {
205        default_levels().iter().find(|l| l.name == name).expect("level exists")
206    }
207
208    /// The `adjacent` (sibling-workspace) locus lands where the design says, INDEPENDENT of the legacy
209    /// 3-band CLI projection (which collapses editor/developer to SafeWrite). A sibling READ auto-
210    /// approves from reader up; a sibling create/mutate (a "quick patch") is admitted at developer but
211    /// NOT editor (editor's writes stay `<= worktree`); a sibling DESTROY is withheld even at developer
212    /// (conservative — `rm -rf ../otherrepo` is not a patch).
213    #[test]
214    fn sibling_adjacent_locus_reads_at_reader_writes_at_developer_not_editor() {
215        use crate::engine::facet::{Capability, LocalLocus, Operation, PersistenceLevel, Reversibility};
216        let at_adjacent = |op: Operation| {
217            let mut c = Capability::new(op);
218            c.locus.local = LocalLocus::Adjacent;
219            c
220        };
221        let read = Profile::of(vec![at_adjacent(Operation::Observe)]);
222        let patch = Profile::of(vec![{
223            let mut c = at_adjacent(Operation::Mutate);
224            c.reversibility = Reversibility::Recoverable;
225            c.persistence.level = PersistenceLevel::Data;
226            c
227        }]);
228        let destroy = Profile::of(vec![at_adjacent(Operation::Destroy)]);
229
230        assert!(level("reader").admits(&read), "a sibling READ auto-approves from reader");
231        assert!(level("developer").admits(&read), "…and higher");
232        assert!(!level("editor").admits(&patch), "editor does NOT write a sibling (writes stay worktree)");
233        assert!(level("developer").admits(&patch), "developer patches a sibling (create/mutate)");
234        assert!(!level("editor").admits(&destroy), "editor does NOT destroy a sibling");
235        assert!(
236            !level("developer").admits(&destroy),
237            "developer does NOT destroy a sibling (conservative — its destroy clause stays `<= worktree`)"
238        );
239    }
240
241    #[test]
242    fn archetypes_toml_compiles_and_every_capability_is_justified() {
243        // LazyLock forces the parse; a bad term / missing `because` would have panicked.
244        let mut count = 0;
245        for n in names() {
246            let c = archetype(n).expect("listed archetype resolves");
247            assert!(!c.because.is_empty(), "archetype `{n}` has no because");
248            count += 1;
249        }
250        assert!(count >= 10, "expected the full catalog, got {count}");
251        assert!(archetype("does-not-exist").is_none(), "unknown profile fails closed");
252    }
253
254    /// The catalog's "Lands at" column, verified against the real algebra by loading the ACTUAL
255    /// archetype definitions (not hand-built copies): each is admitted by its claimed level and
256    /// refused by the level just below it. Ties archetypes.toml ↔ the catalog doc ↔ the levels.
257    #[test]
258    fn archetypes_land_where_the_catalog_says() {
259        // (archetype, admitted_by, refused_by)
260        let cases: &[(&str, &str, &str)] = &[
261            // A pure remote fetch is a READ — reader admits it; only paranoid (no network) refuses.
262            ("remote-read", "reader", "paranoid"),
263            // A BULK remote export (db dump to stdout) is still a read — reader admits it. `scale`
264            // records the volume but does not gate a read; the -f output file is a SEPARATE cap.
265            ("data-export", "reader", "paranoid"),
266            ("remote-mutate", "network-admin", "developer"),
267            ("remote-create", "network-admin", "developer"),
268            ("remote-destroy-recoverable", "network-admin", "developer"),
269            ("remote-destroy-irreversible", "yolo", "network-admin"),
270            ("remote-authorize", "network-admin", "developer"),
271            ("remote-control", "network-admin", "developer"),
272            ("vcs-sync", "network-admin", "developer"),
273            ("blockchain-txn", "yolo", "network-admin"),
274            ("local-privileged", "local-admin", "developer"),
275            // Transient service control (systemctl restart) — the mildest root-machine op, still local-admin.
276            ("privileged-control", "local-admin", "developer"),
277            // A pinned, scripts-off install runs no foreign code → developer (via the install clause).
278            ("local-install-pinned", "developer", "editor"),
279            // The scripts-on / unpinned install RUNS foreign code (network-sourced) → yolo only.
280            ("supply-chain-build", "yolo", "developer"),
281            // Arbitrary remote code execution (kubectl exec, ssh cmd) — execute op, no level below yolo.
282            ("remote-exec", "yolo", "network-admin"),
283            // Credential material read/mint → yolo (secret > uses-ambient everywhere below yolo).
284            ("credential-read", "yolo", "network-admin"),
285            ("credential-mint", "yolo", "network-admin"),
286            // Decrypt-to-screen (sops -d, age -d, ansible-vault view): a secret read that flows to the
287            // model — same `secret = reads` tier as a credential-store read → yolo, refused below.
288            ("decrypt-read", "yolo", "network-admin"),
289            // Arbitrary stored-object retrieval (s3 get-object): classified by `retrieval =
290            // bulk-content` (§5 #1), it lands at NETWORK-ADMIN — the proportionate bulk-egress tier —
291            // refused by developer. NOT yolo (it is not a credential read) and NOT reader (opaque bulk
292            // content is above the everyday read band).
293            ("bulk-object-read", "network-admin", "developer"),
294            // The LOCAL working-copy quartet — the mirror of the remote one, split on the same
295            // reversibility axis. Both mutates land at editor (differing only in how easily they
296            // undo, which the levels do not yet distinguish); the destroys split editor→developer
297            // →yolo exactly as reversibility worsens.
298            ("local-mutate-trivial", "editor", "reader"),
299            ("local-mutate-recoverable", "editor", "reader"),
300            ("local-destroy-recoverable", "developer", "editor"),
301            ("local-destroy-irreversible", "yolo", "developer"),
302        ];
303        for (name, admitted_by, refused_by) in cases {
304            let p = Profile::of(vec![archetype(name).expect("archetype exists").clone()]);
305            assert!(level(admitted_by).admits(&p), "{name} should be admitted by {admitted_by}");
306            assert!(!level(refused_by).admits(&p), "{name} should be refused by {refused_by}");
307        }
308
309        // COMPLETENESS. Without this, adding an archetype to archetypes.toml and forgetting the
310        // catalog row leaves it with NO level verification at all — it would ship classifying
311        // commands with nobody having checked where it lands. Enumerating the real catalog means a
312        // new archetype fails here until its landing is asserted above.
313        let uncovered: Vec<&str> = names().filter(|n| !cases.iter().any(|(c, _, _)| c == n)).collect();
314        assert!(uncovered.is_empty(), "archetype(s) with no catalog row — add (name, admitted_by, refused_by) above: {uncovered:?}",);
315    }
316
317    /// The whole point of Phase 1 for the WRITE side: every remote archetype that CHANGES remote
318    /// state (mutate/create/destroy/authorize/control), plus vcs-sync and blockchain-txn, is above
319    /// the auto-approve band — denied by CLASSIFICATION, not hand-marking. `remote-read` is the
320    /// deliberate exception: a pure fetch is a reader-level read and auto-approves (SafeRead).
321    #[test]
322    fn every_remote_write_archetype_is_not_auto_approved() {
323        let write_remotes =
324            names().filter(|n| (n.starts_with("remote-") && *n != "remote-read") || *n == "vcs-sync" || *n == "blockchain-txn");
325        for name in write_remotes {
326            let p = Profile::of(vec![archetype(name).expect("archetype").clone()]);
327            assert_eq!(project(&p), Verdict::Denied, "{name} must not auto-approve in the 3-value projection");
328        }
329        // and the read DOES auto-approve — the read/write asymmetry, verified
330        assert_eq!(
331            project(&Profile::of(vec![archetype("remote-read").unwrap().clone()])),
332            Verdict::Allowed(crate::verdict::SafetyLevel::SafeRead),
333            "a pure remote fetch is reader-level",
334        );
335    }
336
337    /// The exposure reframe (behavioral-taxonomy-exposure.md §3, §7): `disclosure.audience = public`
338    /// is a RECORD, not a gate. Publishing content you authored to a public destination (git push to
339    /// a public repo, `npm publish`) is a network-admin operation — NOT held back to yolo by its
340    /// publicness. What still gates to yolo is CONTENT: transmitting a secret off-box. Proves the
341    /// gate moved from "how public the destination is" to "is a secret leaving". Red on the old
342    /// `disclosure = { audience = "<= trusted-remote" }` ceiling (public publish refused everywhere
343    /// below yolo); green on `<= public`.
344    #[test]
345    fn public_disclosure_is_recorded_not_gated_secret_transmission_is() {
346        use crate::engine::facet::{
347            DisclosureAudience, NetDestination, NetDirection, NetPayload, Network, RemoteReach, Reversibility, SecretLevel,
348        };
349
350        let publish_to_public = || {
351            let mut c = Capability::new(Operation::Communicate);
352            c.locus.remote = RemoteReach::Arbitrary;
353            c.reversibility = Reversibility::Effortful;
354            c.disclosure.audience = DisclosureAudience::Public;
355            c.network =
356                Network { direction: NetDirection::Outbound, destination: NetDestination::Arbitrary, payload: NetPayload::SendsHostData };
357            c
358        };
359
360        // Non-secret public publish → a network-admin op, still above the local developer band.
361        let mut publish = publish_to_public();
362        publish.because = "publish authored content to a public destination".into();
363        let publish = Profile::of(vec![publish]);
364        assert!(level("network-admin").admits(&publish), "public non-secret publish is network-admin");
365        assert!(!level("developer").admits(&publish), "outbound remote egress is above developer");
366
367        // Same shape, but it TRANSMITS A SECRET — now the CONTENT gates it up to yolo.
368        let mut exfil = publish_to_public();
369        exfil.secret.level = SecretLevel::Transmits;
370        exfil.because = "transmit a secret off-box".into();
371        let exfil = Profile::of(vec![exfil]);
372        assert!(!level("network-admin").admits(&exfil), "secret transmission is the gate, above network-admin");
373        assert!(level("yolo").admits(&exfil), "yolo admits secret exfil (non-destroy clause)");
374    }
375
376    /// The machine locus SUB-RUNG split (the `restart nginx` vs `/etc/passwd` distinction). ORDINARY
377    /// machine state — a service, an app config — is `machine` → local-admin. The identity/auth/boot/
378    /// loader TRUST substrate is `system-integrity` → ABOVE local-admin, yolo-only. Same operation +
379    /// authority; only the locus rung differs, and that difference is the whole gate: "run the machine
380    /// as admin" vs "own the machine's trust root".
381    #[test]
382    fn system_integrity_is_above_local_admin_ordinary_machine_is_not() {
383        use crate::engine::facet::{Authority, LocalLocus};
384        let (local, yolo) = (level("local-admin"), level("yolo"));
385
386        let root_write_at = |loc| {
387            let mut c = Capability::new(Operation::Mutate);
388            c.locus.local = loc;
389            c.authority = Authority::Root;
390            c.because = "root machine write".into();
391            Profile::of(vec![c])
392        };
393
394        // ordinary machine config (edit /etc/nginx.conf as root) — local-admin admits.
395        assert!(local.admits(&root_write_at(LocalLocus::Machine)), "ordinary machine write is local-admin");
396
397        // the trust substrate (rewrite /etc/passwd as root) — local-admin REFUSES; only yolo.
398        let integrity = root_write_at(LocalLocus::SystemIntegrity);
399        assert!(!local.admits(&integrity), "the system-integrity substrate is above local-admin");
400        assert!(yolo.admits(&integrity), "yolo owns the machine's trust root");
401    }
402
403    /// The developer supply-chain / install clause. A PINNED, SCRIPTS-OFF install (`npm ci
404    /// --ignore-scripts`) fetches packages and writes node_modules but runs NO foreign code —
405    /// `execution = self`, `persistence = installing` → a dev-loop staple, admitted at developer.
406    /// The scripts-ON or UNPINNED install is `execution = network-sourced` (the supply-chain-build
407    /// archetype) → no home below yolo. The resolver picks which shape a command emits; this pins the
408    /// LEVEL boundary. Modeling the safe install as `execution = self` (not a guardrail-gated
409    /// `network-sourced`) is what keeps the clause all-`<=` and facet-monotone.
410    #[test]
411    fn pinned_scripts_off_install_is_developer_the_supply_chain_surface_is_yolo() {
412        use crate::engine::facet::{ExecutionTrust, LocalLocus, NetDirection, NetPayload, PersistenceLevel, Reversibility};
413        let (dev, yolo) = (level("developer"), level("yolo"));
414
415        // `npm ci --ignore-scripts`: install files, execute nothing foreign.
416        let safe_install = {
417            let mut c = Capability::new(Operation::Create);
418            c.locus.local = LocalLocus::Worktree;
419            c.persistence.level = PersistenceLevel::Installing;
420            c.reversibility = Reversibility::Effortful;
421            c.network.direction = NetDirection::Outbound;
422            c.network.payload = NetPayload::Fetches;
423            c.execution.trust = ExecutionTrust::SelfCode;
424            c.because = "pinned, scripts-off install".into();
425            Profile::of(vec![c])
426        };
427        assert!(dev.admits(&safe_install), "a pinned, scripts-off install is developer");
428        assert!(yolo.admits(&safe_install), "and of course yolo");
429
430        // scripts-ON / unpinned: the supply-chain surface (network-sourced execution).
431        let supply_chain = Profile::of(vec![archetype("supply-chain-build").unwrap().clone()]);
432        assert!(!dev.admits(&supply_chain), "network-sourced install (scripts on / unpinned) is above developer");
433        assert!(yolo.admits(&supply_chain), "the supply-chain surface lands at yolo");
434    }
435
436    /// Destination-trust (behavioral-taxonomy-exposure.md §4): the new `locus.provenance` facet.
437    /// A send to a target designated `literal` (a URL typed inline) is a network-admin op — the
438    /// human reviewing at that level SEES the URL; a send to an `opaque` target (from a variable,
439    /// unreviewable) is held to yolo. Proves network-admin's `provenance <= literal` ceiling. Red
440    /// if the ceiling is absent (opaque would leak into network-admin) or set to `established`
441    /// (literal URLs would be wrongly refused); green at `<= literal`.
442    #[test]
443    fn a_literal_send_target_is_network_admin_an_opaque_one_is_yolo() {
444        use crate::engine::facet::{NetDirection, NetPayload, Provenance, RemoteReach};
445
446        let send_to = |prov| {
447            let mut c = Capability::new(Operation::Communicate);
448            c.locus.remote = RemoteReach::Fixed;
449            c.locus.provenance = prov;
450            c.network.direction = NetDirection::Outbound;
451            c.network.payload = NetPayload::SendsHostData;
452            c.because = "send host data to a designated target".into();
453            c
454        };
455
456        let literal = Profile::of(vec![send_to(Provenance::Literal)]);
457        assert!(level("network-admin").admits(&literal), "a visible literal URL is a network-admin send");
458        assert!(!level("developer").admits(&literal), "sends-host-data is above the local developer band");
459
460        let opaque = Profile::of(vec![send_to(Provenance::Opaque)]);
461        assert!(!level("network-admin").admits(&opaque), "an opaque (variable) destination is held above network-admin");
462        assert!(level("yolo").admits(&opaque), "yolo leaves provenance unconstrained");
463    }
464}
465
466#[cfg(test)]
467mod neighbour_tests {
468    use super::*;
469    use std::collections::BTreeMap;
470
471    /// The facets on which two archetypes differ. `set_facets` omits terms sitting at their zero,
472    /// so a facet present in one map and absent from the other IS a difference (present vs default).
473    fn differing_facets(a: &Capability, b: &Capability) -> Vec<&'static str> {
474        let am: BTreeMap<_, _> = a.set_facets().into_iter().collect();
475        let bm: BTreeMap<_, _> = b.set_facets().into_iter().collect();
476        let mut keys: Vec<_> = am.keys().chain(bm.keys()).copied().collect();
477        keys.sort_unstable();
478        keys.dedup();
479        keys.into_iter().filter(|k| am.get(k) != bm.get(k)).collect()
480    }
481
482    /// Any two archetypes within ONE facet of each other must say so, both ways, naming the axis
483    /// that separates them.
484    ///
485    /// Choosing an archetype fixes 27 facets at once and is the most consequential authoring act in
486    /// the repo — yet it is done by picking a name from a flat list of 23, with the differences
487    /// buried in prose. That is not a theoretical hazard: `dynamodb scan` was classified
488    /// `bulk-object-read` when it is a `data-export`, because the two differ ONLY on `retrieval`
489    /// and the sentence saying so lived inside the OTHER archetype's `because`, invisible to
490    /// someone reading this one.
491    ///
492    /// Detection is mechanical rather than authored, so a confusable pair introduced later is
493    /// caught the moment it appears — nobody has to notice it first.
494    #[test]
495    fn near_neighbours_are_declared() {
496        let declared = declared_distinctions();
497        let dist_of = |n: &str| -> Vec<(String, String)> {
498            declared.iter().find(|(name, ..)| name == n).map(|(_, d, _)| d.clone()).unwrap_or_default()
499        };
500        let same_of = |n: &str| -> Option<String> { declared.iter().find(|(name, ..)| name == n).and_then(|(_, _, s)| s.clone()) };
501
502        let names: Vec<&str> = names().collect();
503        let mut problems = Vec::new();
504        for (i, a) in names.iter().enumerate() {
505            for b in &names[i + 1..] {
506                let d = differing_facets(archetype(a).unwrap(), archetype(b).unwrap());
507                match d.len() {
508                    // Same point in facet space: they classify identically, so the choice is pure
509                    // prose. Legitimate, but it has to be deliberate — otherwise an author picks by
510                    // coin-flip and a later facet edit to one silently diverges them. A pair that
511                    // DOES declare it falls through to `_`, which is the no-op.
512                    0 if same_of(a).as_deref() != Some(*b) || same_of(b).as_deref() != Some(*a) => {
513                        problems.push(format!(
514                            "`{a}` and `{b}` are facet-IDENTICAL; both must declare \
515                             `same_point_as` naming the other, or be given a real difference",
516                        ));
517                    }
518                    1 => {
519                        let axis = d[0];
520                        for (x, y) in [(a, b), (b, a)] {
521                            if !dist_of(x).iter().any(|(n, by)| n == *y && by == axis) {
522                                problems.push(format!(
523                                    "`{x}` must declare `distinguished_from = [{{ archetype = \"{y}\", \
524                                     by = \"{axis}\" }}]` — they differ on that axis alone",
525                                ));
526                            }
527                        }
528                    }
529                    _ => {}
530                }
531            }
532        }
533        assert!(problems.is_empty(), "confusable archetypes:\n  {}", problems.join("\n  "));
534    }
535
536    /// A declared distinction must be TRUE: the named axis is really where the two differ. A stale
537    /// annotation is worse than none — it points an author at the wrong facet with authority.
538    #[test]
539    fn declared_distinctions_are_accurate() {
540        let mut problems = Vec::new();
541        for (name, dists, same) in declared_distinctions() {
542            let Some(a) = archetype(&name) else { continue };
543            for (other, by) in dists {
544                let Some(b) = archetype(&other) else {
545                    problems.push(format!("`{name}` names unknown archetype `{other}`"));
546                    continue;
547                };
548                let d = differing_facets(a, b);
549                if !d.contains(&by.as_str()) {
550                    problems.push(format!("`{name}` claims it differs from `{other}` by `{by}`, but they differ on {d:?}",));
551                }
552            }
553            if let Some(other) = same {
554                match archetype(&other) {
555                    None => problems.push(format!("`{name}` names unknown archetype `{other}`")),
556                    Some(b) => {
557                        let d = differing_facets(a, b);
558                        if !d.is_empty() {
559                            problems.push(format!("`{name}` claims `same_point_as = \"{other}\"`, but they differ on {d:?}",));
560                        }
561                    }
562                }
563            }
564        }
565        assert!(problems.is_empty(), "inaccurate distinctions:\n  {}", problems.join("\n  "));
566    }
567}