wm-tools 9.1.5

Curated tool implementations for the WhiteMagic MCP server.
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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
//! Tool surface profiles — curated release surfaces for the tool registry.
//!
//! 229 tools is an archive, not a v1 product. Profiles curate which tools the
//! `wm` meta-tool can route to (and which are registered at the boundary) so
//! `wm serve --profile curated` presents the differentiated surface — the
//! learned memory hierarchy — instead of everything.
//!
//! The full registry is always built first (internal subsystems like the
//! karma ledger, friction logging and the governance pipeline need their
//! tools regardless), then filtered before the meta-tools are layered on.

#![forbid(unsafe_code)]

use wm_dispatch::{ToolRegistry, ToolRegistryBuilder};

/// A named tool surface. `prefixes` are tool-name prefixes; a tool matches
/// if its name starts with any prefix. `["*"]` means no filtering.
#[derive(Debug, Clone, Copy)]
pub struct ToolProfile {
    /// Profile name (`full`, `curated`, `minimal`, or `allowlist`).
    pub name: &'static str,
    /// Matching prefixes, or `["*"]` for the full surface.
    pub prefixes: &'static [&'static str],
}

/// The full surface — every tool registered. Library/daemon default.
pub static PROFILE_FULL: ToolProfile = ToolProfile {
    name: "full",
    prefixes: &["*"],
};

/// The memory-hierarchy product surface: memory, sessions, transactions,
/// the claims ledger, and read-only galaxy/observability helpers.
///
/// `tools.list` and `gnosis` need no prefix here: `tools.list` is layered
/// on with the meta-tools *after* filtering, and `gnosis` matches its own
/// base tool. (The contract check flags a stale `tools.list` prefix as a
/// dead route — that is how it was found, 2026-08-29.)
///
/// Deliberately excludes: destructive galaxy operations (purge/transfer/
/// restore), the RSI friction/redteam/improve loop, sangha mesh, self-play,
/// imagination, and polyglot/cyberbrain internals — those stay reachable
/// under `--profile full`.
pub static PROFILE_CURATED: ToolProfile = ToolProfile {
    name: "curated",
    prefixes: &["memory", "session", "claims", "transaction", "gnosis"],
};

/// The tightest surface: create/read/list/query/search/chat + discovery.
pub static PROFILE_MINIMAL: ToolProfile = ToolProfile {
    name: "minimal",
    prefixes: &[
        "memory.create",
        "memory.read",
        "memory.list",
        "memory.query",
        "memory.search",
        "memory.chat",
        "memory.associate",
        "memory.associations",
        "gnosis",
    ],
};

/// The ultimate single-tool PRAY meta-tool surface: zero schema bloat.
/// (PRAY = Polymorphic Resonant Adaptive Yoga; renamed from PRAT in v9.2.)
pub static PROFILE_PRAY: ToolProfile = ToolProfile {
    name: "pray",
    prefixes: &["whitemagic"],
};

/// Deprecated alias kept for back-compat — renamed to [`PROFILE_PRAY`] in v9.2.
#[deprecated(since = "9.2.0", note = "renamed to PROFILE_PRAY")]
pub use self::PROFILE_PRAY as PROFILE_PRAT;

/// A named, task-focused tool pack (Q04-HER.P2).
///
/// Packs are a thin data layer over the profile/allowlist mechanism: each
/// pack declares tool-name prefixes and resolves to an `allowlist`-style
/// surface. They do not add a second registry, and they are not advertised
/// as a supported surface until a release carries them.
#[derive(Debug, Clone, Copy)]
pub struct ToolPack {
    /// Pack name (`continuity`, `research`, `coding`, `ops`).
    pub name: &'static str,
    /// One-line task description.
    pub description: &'static str,
    /// Matching tool-name prefixes.
    pub prefixes: &'static [&'static str],
}

/// Capture and resume: the memory hierarchy plus session continuity.
pub static PACK_CONTINUITY: ToolPack = ToolPack {
    name: "continuity",
    description: "capture, search, resume, replay and checkpoint sessions",
    prefixes: &["memory", "session", "gnosis"],
};

/// Evidence-oriented retrieval: search/read with claims and gnosis.
pub static PACK_RESEARCH: ToolPack = ToolPack {
    name: "research",
    description: "evidence-oriented search, reads, claims and gnosis",
    prefixes: &[
        "memory.search",
        "memory.read",
        "memory.hybrid_recall",
        "memory.query",
        "session.continuity",
        "session.replay",
        "claims",
        "gnosis",
    ],
};

/// Project work: create/update memories, sessions, transaction snapshots.
pub static PACK_CODING: ToolPack = ToolPack {
    name: "coding",
    description: "project memory writes, sessions and transaction snapshots",
    prefixes: &[
        "memory.create",
        "memory.update",
        "memory.read",
        "memory.search",
        "session",
        "transaction",
    ],
};

/// Operational visibility: telemetry, breakers and continuity reads.
pub static PACK_OPS: ToolPack = ToolPack {
    name: "ops",
    description: "telemetry records/rollups/retention, breakers, continuity reads",
    prefixes: &[
        "telemetry",
        "breaker",
        "memory.search",
        "memory.read",
        "session.continuity",
    ],
};

/// All shipped packs.
pub static PACKS: &[&ToolPack] = &[&PACK_CONTINUITY, &PACK_RESEARCH, &PACK_CODING, &PACK_OPS];

/// Look up a pack by name (case-insensitive).
#[must_use]
pub fn pack_from_name(name: &str) -> Option<&'static ToolPack> {
    let name = name.trim().to_ascii_lowercase();
    PACKS.iter().copied().find(|pack| pack.name == name)
}

/// The available pack names, for refusal messages.
#[must_use]
pub fn pack_names() -> Vec<&'static str> {
    PACKS.iter().map(|pack| pack.name).collect()
}

/// Resolve a pack to an allowlist-style profile. The returned name is
/// `pack:<name>` so contracts disclose which pack produced the surface.
#[must_use]
pub fn profile_from_pack(pack: &ToolPack) -> &'static ToolProfile {
    Box::leak(Box::new(ToolProfile {
        name: Box::leak(format!("pack:{}", pack.name).into_boxed_str()),
        prefixes: pack.prefixes,
    }))
}

/// Resolve the active tool surface with packs in the precedence chain:
///
/// 1. `WM_TOOL_ALLOWLIST` — an explicit prefix allowlist always wins.
/// 2. `WM_TOOL_PACK` (or `wm serve --pack`) — a task-focused pack.
/// 3. CLI `--profile` / `WM_TOOL_PROFILE`.
/// 4. Caller default.
///
/// Unknown pack names warn and fall through to profile resolution.
#[must_use]
pub fn resolve_tool_surface(
    cli_profile: Option<&str>,
    env_profile: Option<&str>,
    env_allowlist: Option<&str>,
    env_pack: Option<&str>,
) -> &'static ToolProfile {
    if let Some(allow) = env_allowlist {
        if let Some(profile) = allowlist_from_env(allow) {
            tracing::info!(
                allowlist = %allow,
                "WM_TOOL_ALLOWLIST tool surface in effect"
            );
            return Box::leak(Box::new(profile));
        }
    }
    if let Some(name) = env_pack {
        if let Some(pack) = pack_from_name(name) {
            tracing::info!(pack = pack.name, "WM_TOOL_PACK tool surface in effect");
            return profile_from_pack(pack);
        }
        tracing::warn!(
            pack = name,
            available = ?pack_names(),
            "unknown tool pack — falling back to profile resolution"
        );
    }
    resolve_tool_profile(cli_profile, env_profile, None)
}

/// Look up a profile by name (`full`, `curated`, `minimal`, `pray`; `prat` kept as a deprecated alias).
#[must_use]
pub fn profile_from_name(name: &str) -> Option<&'static ToolProfile> {
    match name.trim().to_ascii_lowercase().as_str() {
        "full" => Some(&PROFILE_FULL),
        "curated" => Some(&PROFILE_CURATED),
        "minimal" => Some(&PROFILE_MINIMAL),
        "pray" => Some(&PROFILE_PRAY),
        // Deprecated alias: pre-v9.2 configs used `--profile prat`.
        "prat" => Some(&PROFILE_PRAY),
        _ => None,
    }
}

/// Resolve the active tool profile with explicit precedence:
///
/// 1. `WM_TOOL_ALLOWLIST` — an explicit prefix allowlist always wins.
/// 2. CLI `--profile` flag.
/// 3. `WM_TOOL_PROFILE` environment variable.
/// 4. Default: `full` (library / `wm daemon`). `wm serve` overlays
///    curated when flag and env are both absent.
///
/// Unknown profile names log a warning and fall back to the full surface.
#[must_use]
pub fn resolve_tool_profile(
    cli_profile: Option<&str>,
    env_profile: Option<&str>,
    env_allowlist: Option<&str>,
) -> &'static ToolProfile {
    if let Some(allow) = env_allowlist {
        if let Some(profile) = allowlist_from_env(allow) {
            tracing::info!(
                allowlist = %allow,
                "WM_TOOL_ALLOWLIST tool surface in effect"
            );
            return Box::leak(Box::new(profile));
        }
    }
    match cli_profile.or(env_profile) {
        Some(name) => profile_from_name(name).unwrap_or_else(|| {
            tracing::warn!(
                profile = name,
                "unknown tool surface profile — using full tool surface"
            );
            &PROFILE_FULL
        }),
        None => &PROFILE_FULL,
    }
}

/// Build a profile from a comma-separated allowlist of tool-name prefixes
/// (e.g. `memory,session,claims`). Empty segments are ignored.
#[must_use]
pub fn allowlist_from_env(spec: &str) -> Option<ToolProfile> {
    let prefixes: Vec<&'static str> = spec
        .split(',')
        .map(str::trim)
        .filter(|p| !p.is_empty())
        .collect::<Vec<_>>()
        .into_iter()
        .map(|p| Box::leak(p.to_string().into_boxed_str()) as &'static str)
        .collect();
    if prefixes.is_empty() {
        return None;
    }
    Some(ToolProfile {
        name: "allowlist",
        prefixes: Box::leak(prefixes.into_boxed_slice()),
    })
}

/// Filter a registry to a profile. `["*"]` profiles pass the registry
/// through untouched (zero-copy — the registry is Arc-backed).
#[must_use]
pub fn apply_profile(registry: ToolRegistry, profile: &ToolProfile) -> ToolRegistry {
    if profile.prefixes.contains(&"*") {
        return registry;
    }
    let mut builder = ToolRegistryBuilder::new();
    for tool in registry.all() {
        if matches_prefixes(tool.name(), profile.prefixes) {
            builder.register(tool);
        }
    }
    builder.build()
}

/// Whether a tool name matches any of a profile's prefixes.
#[must_use]
pub fn matches_prefixes(name: &str, prefixes: &[&str]) -> bool {
    prefixes.iter().any(|p| name.starts_with(p))
}

/// The profile contract — proof that the advertised surface is the
/// declared surface.
///
/// Computed at server startup from the pre-filter ("full") registry and
/// the post-filter (registered) registry. `ok == false` means surface
/// drift: the boundary is advertising or routing something the declared
/// profile does not cover, or declares prefixes that match nothing (the
/// dead-route class the curated `galaxy.list` regression came from).
/// Persisted as `profile_contract.json` in the store root so `wm doctor`
/// can grade the last server start against it.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ProfileContract {
    /// Declared profile name (`full`, `curated`, `minimal`, `allowlist`).
    pub profile: String,
    /// Declared prefixes (`["*"]` for full).
    pub prefixes: Vec<String>,
    /// Tools the declared profile should register.
    pub expected_count: usize,
    /// Tools actually registered post-filter.
    pub registered_count: usize,
    /// Declared prefixes matching zero tools (dead routes).
    pub dead_prefixes: Vec<String>,
    /// Registered tools the declared profile does not cover (drift).
    pub unexpected_tools: Vec<String>,
    /// Destructive tools on the registered surface. Informational —
    /// destructive effects are confirm-gated in the dispatch pipeline;
    /// curated deliberately includes `memory.delete` and friends.
    pub destructive_tools: Vec<String>,
    /// RFC 3339 timestamp of the check (`wm_core::time`).
    pub verified_at: String,
    /// Package version of the binary that computed the contract.
    /// `None` = pre-P-PROV-5 contract (serde default keeps them readable).
    #[serde(default)]
    pub binary_version: Option<String>,
    /// Surface pin (P-PROV-5, 2026-09-10, rug-pull tripwire): hex SHA-256
    /// over the sorted registered tool names (see [`surface_hash`]). Any
    /// tool added, removed, or renamed changes the pin; `wm doctor`
    /// discloses it so a reviewed release surface can be pinned externally.
    /// `None` = pre-P-PROV-5 contract.
    #[serde(default)]
    pub surface_hash: Option<String>,
    /// `true` iff the registered surface is exactly the declared one.
    pub ok: bool,
}

/// Compute the surface pin: hex SHA-256 over sorted tool names.
///
/// Order-insensitive, content-sensitive — the same surface always pins
/// identically regardless of registration order.
#[must_use]
pub fn surface_hash(registered: &[&str]) -> String {
    use sha2::{Digest, Sha256};
    use std::fmt::Write as _;
    let mut names: Vec<&str> = registered.to_vec();
    names.sort_unstable();
    let mut h = Sha256::new();
    for n in names {
        h.update(n.as_bytes());
        h.update(b"\n");
    }
    // Byte-wise hex (sha2 0.11's digest output has no LowerHex impl).
    h.finalize().iter().fold(
        String::with_capacity(sha2::Sha256::output_size() * 2),
        |mut out, b| {
            let _ = write!(out, "{b:02x}");
            out
        },
    )
}

/// Compute the profile contract for a server start.
#[must_use]
pub fn profile_contract(
    full: &ToolRegistry,
    filtered: &ToolRegistry,
    profile: &ToolProfile,
) -> ProfileContract {
    let full_names: Vec<&str> = full.all_ref().iter().map(|t| t.name()).collect();
    let registered: Vec<&str> = filtered.all_ref().iter().map(|t| t.name()).collect();

    let star = profile.prefixes.contains(&"*");
    let matches = |name: &str| star || profile.prefixes.iter().any(|p| name.starts_with(p));
    let expected_count = full_names.iter().filter(|n| matches(n)).count();
    let unexpected_tools: Vec<String> = registered
        .iter()
        .filter(|n| !matches(n))
        .map(|n| (*n).to_string())
        .collect();
    let dead_prefixes: Vec<String> = profile
        .prefixes
        .iter()
        .filter(|p| **p != "*" && !full_names.iter().any(|n| n.starts_with(**p)))
        .map(|p| (*p).to_string())
        .collect();
    let destructive_tools: Vec<String> = filtered
        .all_ref()
        .iter()
        .filter(|t| t.effects().destructive)
        .map(|t| t.name().to_string())
        .collect();

    let ok = expected_count == registered.len()
        && unexpected_tools.is_empty()
        && dead_prefixes.is_empty();

    ProfileContract {
        profile: profile.name.to_string(),
        prefixes: profile.prefixes.iter().map(|p| (*p).to_string()).collect(),
        expected_count,
        registered_count: registered.len(),
        dead_prefixes,
        unexpected_tools,
        destructive_tools,
        verified_at: wm_core::time::now_rfc3339(),
        binary_version: Some(env!("CARGO_PKG_VERSION").to_string()),
        surface_hash: Some(surface_hash(&registered)),
        ok,
    }
}

/// Persist the contract to `<store-root>/profile_contract.json` (atomic
/// rename, same discipline as the other root state files). Best-effort:
/// a persistence failure warns and never blocks the server start.
pub fn save_contract(root: &std::path::Path, contract: &ProfileContract) {
    let path = root.join("profile_contract.json");
    let tmp = root.join(".profile_contract.json.tmp");
    let write = serde_json::to_string_pretty(contract)
        .map(|body| std::fs::write(&tmp, body).and_then(|()| std::fs::rename(&tmp, &path)));
    if let Err(e) = write {
        tracing::warn!(
            path = %path.display(),
            error = %e,
            "could not persist profile contract"
        );
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::Arc;
    use wm_core::Tool;

    #[test]
    fn profile_names_resolve() {
        assert_eq!(profile_from_name("full").map(|p| p.name), Some("full"));
        assert_eq!(
            profile_from_name("CURATED").map(|p| p.name),
            Some("curated")
        );
        assert_eq!(
            profile_from_name("minimal").map(|p| p.name),
            Some("minimal")
        );
        assert!(profile_from_name("bogus").is_none());
    }

    #[test]
    fn curated_has_no_dead_routes() {
        // Regression: the curated profile once contained a `galaxy.list`
        // prefix that matched no registered tool.
        assert!(
            !PROFILE_CURATED
                .prefixes
                .iter()
                .any(|p| p.starts_with("galaxy")),
            "curated profile must not include galaxy prefixes"
        );
    }

    #[test]
    fn curated_is_the_product_surface() {
        assert_eq!(
            PROFILE_CURATED.prefixes,
            &["memory", "session", "claims", "transaction", "gnosis"]
        );
        assert!(
            !PROFILE_CURATED
                .prefixes
                .iter()
                .any(|p| *p == "nlu.shadow_report" || *p == "tools.usage_report"),
            "observability tools belong on the full surface"
        );
    }

    #[test]
    fn allowlist_parses_and_rejects_empty() {
        assert!(allowlist_from_env("").is_none());
        assert!(allowlist_from_env(" , ").is_none());
        let profile = allowlist_from_env("memory, claims , session").unwrap();
        assert_eq!(profile.name, "allowlist");
        assert_eq!(profile.prefixes, &["memory", "claims", "session"]);
    }

    #[test]
    fn full_profile_is_passthrough() {
        let registry = ToolRegistry::new();
        let out = apply_profile(registry, &PROFILE_FULL);
        assert_eq!(out.len(), 0);
    }

    #[test]
    fn resolve_profile_precedence() {
        // CLI flag wins over the environment variable.
        assert_eq!(
            resolve_tool_profile(Some("curated"), Some("minimal"), None).name,
            "curated"
        );
        // Environment is used when the CLI flag is absent.
        assert_eq!(
            resolve_tool_profile(None, Some("minimal"), None).name,
            "minimal"
        );
        // An explicit allowlist wins over both.
        let resolved =
            resolve_tool_profile(Some("curated"), Some("minimal"), Some("memory,session"));
        assert_eq!(resolved.name, "allowlist");
        assert_eq!(resolved.prefixes, &["memory", "session"]);
        // All absent → full surface.
        assert_eq!(resolve_tool_profile(None, None, None).name, "full");
        // Unknown names fall back to full.
        assert_eq!(resolve_tool_profile(Some("bogus"), None, None).name, "full");
        assert_eq!(resolve_tool_profile(None, Some("bogus"), None).name, "full");
    }

    struct ContractMock {
        name: String,
        effects: wm_core::EffectRow,
        stats: wm_core::ToolStats,
    }

    #[async_trait::async_trait]
    impl wm_core::Tool for ContractMock {
        fn name(&self) -> &str {
            &self.name
        }
        fn gana(&self) -> wm_core::Gana {
            wm_core::Gana::Horn
        }
        fn effects(&self) -> &wm_core::EffectRow {
            &self.effects
        }
        fn stats(&self) -> &wm_core::ToolStats {
            &self.stats
        }
        async fn call(
            &self,
            _ctx: &mut wm_core::Context,
            _args: wm_core::Args,
        ) -> wm_core::Result<wm_core::Output> {
            Ok(serde_json::json!({"ok": true}))
        }
    }

    fn contract_tool(name: &str, destructive: bool) -> Arc<dyn Tool> {
        let effects = if destructive {
            wm_core::EffectRow {
                destructive: true,
                ..wm_core::EffectRow::default()
            }
        } else {
            wm_core::EffectRow::default()
        };
        Arc::new(ContractMock {
            name: name.into(),
            effects,
            stats: wm_core::ToolStats::default(),
        })
    }

    fn contract_registry(tools: &[Arc<dyn Tool>]) -> ToolRegistry {
        let mut builder = ToolRegistryBuilder::new();
        for tool in tools {
            builder.register(Arc::clone(tool));
        }
        builder.build()
    }

    /// Build a registry covering every `PROFILE_MINIMAL` prefix so the
    /// dead-prefix check has nothing to flag.
    fn minimal_registry(tools: &[Arc<dyn Tool>]) -> ToolRegistry {
        let prefix_tools: Vec<Arc<dyn Tool>> = [
            "memory.create",
            "memory.read",
            "memory.list",
            "memory.query",
            "memory.search",
            "memory.chat",
            "memory.associate",
            "memory.associations",
            "gnosis",
        ]
        .iter()
        .map(|n| contract_tool(n, false) as Arc<dyn Tool>)
        .collect();
        let mut all = prefix_tools;
        all.extend(tools.iter().cloned());
        contract_registry(&all)
    }

    #[test]
    fn contract_ok_when_surface_is_exact() {
        let full = minimal_registry(&[]);
        let filtered = contract_registry(&full.all());
        let c = profile_contract(&full, &filtered, &PROFILE_MINIMAL);
        assert!(c.ok);
        assert_eq!(c.expected_count, 9);
        assert_eq!(c.registered_count, 9);
        assert!(c.dead_prefixes.is_empty());
        assert!(c.unexpected_tools.is_empty());
    }

    #[test]
    fn contract_detects_dead_prefixes_and_unexpected_tools() {
        let alpha = contract_tool("alpha.one", false);
        let sneaky = contract_tool("sneaky.tool", false);
        let full = contract_registry(std::slice::from_ref(&alpha));
        // Post-filter registry carries a tool the profile does not declare.
        let filtered = contract_registry(&[alpha, sneaky]);
        let c = profile_contract(
            &full,
            &filtered,
            &allowlist_from_env("alpha,gamma").unwrap(),
        );
        assert!(!c.ok);
        assert_eq!(c.dead_prefixes, vec!["gamma".to_string()]);
        assert_eq!(c.unexpected_tools, vec!["sneaky.tool".to_string()]);
        assert_eq!(c.expected_count, 1);
        assert_eq!(c.registered_count, 2);
    }

    #[test]
    fn contract_reports_destructive_tools_informationally() {
        let full = minimal_registry(&[]);
        let filtered = contract_registry(&full.all());
        let c = profile_contract(&full, &filtered, &PROFILE_MINIMAL);
        assert!(
            c.ok,
            "destructive presence is informational, not a violation"
        );
        assert!(c.destructive_tools.is_empty());

        // Curated-style surface, computed through the real filter path:
        // memory.delete rides the `memory` prefix by design — it must be
        // listed, and must not fail the contract; galaxy.purge must not.
        let curated_tools: Vec<Arc<dyn Tool>> = [
            "memory.create",
            "session.start",
            "claims.list",
            "transaction.begin",
            "gnosis",
            "tools.list",
            "memory.delete",
            "galaxy.purge",
        ]
        .iter()
        .map(|n| contract_tool(n, *n == "memory.delete" || *n == "galaxy.purge") as Arc<dyn Tool>)
        .collect();
        let full2 = contract_registry(&curated_tools);
        let filtered2 = apply_profile(full2.clone(), &PROFILE_CURATED);
        let c2 = profile_contract(&full2, &filtered2, &PROFILE_CURATED);
        assert_eq!(c2.destructive_tools, vec!["memory.delete".to_string()]);
        assert!(c2.ok);
        assert_eq!(c2.expected_count, 6);
        assert_eq!(c2.registered_count, 6);
    }

    #[test]
    fn full_profile_contract_counts_everything() {
        let tools: Vec<Arc<dyn Tool>> = vec![
            contract_tool("memory.create", false),
            contract_tool("galaxy.purge", true),
        ];
        let full = contract_registry(&tools);
        let filtered = contract_registry(&full.all().iter().map(Arc::clone).collect::<Vec<_>>());
        let c = profile_contract(&full, &filtered, &PROFILE_FULL);
        assert!(c.ok);
        assert_eq!(c.expected_count, 2);
        assert_eq!(c.registered_count, 2);
        assert!(c.dead_prefixes.is_empty());
    }

    // P-PROV-5 (2026-09-10, rug-pull tripwire): the surface pin must be
    // order-insensitive (registration order is not surface content) and
    // content-sensitive (any add/remove/rename repins).
    #[test]
    fn surface_hash_is_order_insensitive_but_content_sensitive() {
        let a = surface_hash(&["memory.create", "session.start", "gnosis"]);
        let b = surface_hash(&["gnosis", "memory.create", "session.start"]);
        assert_eq!(a, b, "registration order must not move the pin");
        assert_eq!(a.len(), 64, "hex SHA-256 shape");
        assert_ne!(
            a,
            surface_hash(&["memory.create", "session.start"]),
            "removal must repin"
        );
        assert_ne!(
            a,
            surface_hash(&["memory.create", "session.start", "gnosis", "sneaky.tool"]),
            "addition must repin"
        );
        assert_ne!(
            a,
            surface_hash(&["memory.create", "session.start", "gnosis2"]),
            "rename must repin"
        );
    }

    #[test]
    fn contract_carries_binary_identity_and_surface_pin() {
        let full = minimal_registry(&[]);
        let filtered = contract_registry(&full.all());
        let c = profile_contract(&full, &filtered, &PROFILE_MINIMAL);
        assert!(c.ok);
        assert_eq!(
            c.binary_version.as_deref(),
            Some(env!("CARGO_PKG_VERSION")),
            "contract must name the binary that produced it"
        );
        let names: Vec<&str> = filtered.all_ref().iter().map(|t| t.name()).collect();
        assert_eq!(
            c.surface_hash.as_deref(),
            Some(surface_hash(&names).as_str()),
            "pin must cover exactly the registered surface"
        );
    }

    #[test]
    fn legacy_contract_without_pin_fields_deserializes() {
        // Pre-P-PROV-5 contracts have neither pin field; serde defaults
        // must admit them (store roots hold live history).
        let legacy = serde_json::json!({
            "profile": "curated",
            "prefixes": ["memory"],
            "expected_count": 1,
            "registered_count": 1,
            "dead_prefixes": [],
            "unexpected_tools": [],
            "destructive_tools": [],
            "verified_at": "2026-08-29T00:00:00Z",
            "ok": true,
        });
        let c: ProfileContract = serde_json::from_value(legacy).unwrap();
        assert!(c.ok);
        assert_eq!(c.binary_version, None);
        assert_eq!(c.surface_hash, None);
    }

    #[test]
    fn pray_profile_is_single_surface() {
        assert_eq!(PROFILE_PRAY.prefixes, &["whitemagic"]);
        assert_eq!(profile_from_name("pray").unwrap().name, "pray");
        // Deprecated `prat` alias keeps resolving to the same surface.
        assert_eq!(profile_from_name("prat").unwrap().name, "pray");
    }

    #[test]
    fn packs_resolve_and_are_unique() {
        assert_eq!(
            pack_from_name("Continuity").map(|p| p.name),
            Some("continuity")
        );
        assert!(pack_from_name("bogus").is_none());
        assert_eq!(
            pack_names(),
            vec!["continuity", "research", "coding", "ops"]
        );
        for pack in PACKS {
            assert!(!pack.prefixes.is_empty(), "{} has prefixes", pack.name);
            assert!(
                !pack.description.is_empty(),
                "{} has a description",
                pack.name
            );
        }
    }

    #[test]
    fn pack_precedence_and_unknown_fallback() {
        // Explicit allowlist wins over a pack.
        let allow = resolve_tool_surface(None, None, Some("memory,session"), Some("continuity"));
        assert_eq!(allow.name, "allowlist");
        // Pack wins over the CLI profile and environment profile.
        let pack = resolve_tool_surface(Some("minimal"), Some("minimal"), None, Some("continuity"));
        assert_eq!(pack.name, "pack:continuity");
        assert!(pack.prefixes.contains(&"session"));
        // Unknown pack warns and falls back to profile resolution.
        let fallback = resolve_tool_surface(Some("minimal"), None, None, Some("bogus"));
        assert_eq!(fallback.name, "minimal");
        // No pack → unchanged behavior.
        assert_eq!(
            resolve_tool_surface(Some("curated"), None, None, None).name,
            "curated"
        );
    }
}