codewhale-tui 0.9.2

Terminal UI for open-source and open-weight coding models
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
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
//! Truthful, bounded inspection of a prepared model-client request's tool field.
//!
//! Capture happens at the request-construction seam and retains only a bounded
//! projection. It never claims that the prepared request was delivered.
//!
//! Two kinds of fact live here, and they are kept apart on purpose:
//!
//! * **Wire facts** come from the prepared request itself — names, schemas,
//!   descriptions, per-tool transport flags, byte accounting, and the
//!   active-tool-catalog digest. The digest is not defined here; it is
//!   [`crate::core::engine::preview::active_tool_catalog_sha256`], the same
//!   function the request manifest publishes, so `/tools` and `/request` cannot
//!   report two different hashes of one catalog.
//! * **Surface facts** come from a [`ToolSurfaceContext`] the engine resolves
//!   once per turn: flattened registry facts, the MCP pool's resolved server
//!   attributions, the engine-injected catalog names, and the provider receipt
//!   taken from the *resolved model client*. When that context is present,
//!   provenance, MCP server identity, capabilities, approval requirement, and
//!   model visibility become available and true. When it is absent they stay
//!   explicitly unknown — the context is optional, never faked.
//!
//! What stays unknowable stays unknown regardless: nothing here observes the
//! provider adapter's wire payload, so it is always reported as unavailable.

use std::collections::BTreeMap;
use std::io::{self, Write};

use serde::Serialize;
use serde_json::Value;

use crate::models::Tool;

const MAX_RENDERED_TOOLS: usize = 32;
const MAX_NAME_CHARS: usize = 256;
const MAX_DESCRIPTION_CHARS: usize = 512;
const MAX_SCHEMA_BYTES: usize = 2_048;
const MAX_AUXILIARY_CHARS: usize = 512;
const MAX_ALLOWED_CALLERS: usize = 16;
const MAX_ALLOWED_CALLER_CHARS: usize = 128;
const MAX_PAYLOAD_MEASUREMENT_BYTES: usize = 1_048_576;

#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct BoundedString {
    pub value: String,
    pub truncated: bool,
}

#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(tag = "status", rename_all = "snake_case")]
pub enum Evidence<T> {
    Known { value: T },
    Unknown { reason: String },
}

#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct BoundedList {
    pub count: usize,
    pub rendered: Vec<BoundedString>,
    pub omitted: usize,
}

#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct CountOnly {
    pub count: usize,
    pub values: &'static str,
}

/// One registry tool flattened to the exact facts this projection may report.
///
/// The engine fills this from `ToolSpec`, so this module never holds a tool
/// object and therefore cannot execute one.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct RegistryFacts {
    pub name: String,
    pub description: String,
    pub model_visible: bool,
    pub capabilities: Vec<String>,
    pub approval: String,
    /// `true` when the tool came from the plugin surface rather than the
    /// built-in registry builder.
    pub plugin: bool,
}

/// Where a tool in the prepared request came from.
///
/// `Unknown` is a real answer, not a fallback guess: it means the surface
/// context resolved no origin for that name.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ToolProvenance {
    /// Registered by the built-in registry builder.
    Builtin,
    /// Loaded from the plugin/tools surface or `config.toml` overrides.
    Plugin,
    /// Contributed by the MCP pool, as attributed by the pool itself.
    Mcp,
    /// Injected into the request catalog by the engine rather than registered
    /// (`tool_search` and its legacy spellings, `code_execution`,
    /// `js_execution`).
    Synthetic,
    /// Present in the request with no resolved origin.
    Unknown,
}

impl ToolProvenance {
    #[must_use]
    pub const fn label(self) -> &'static str {
        match self {
            Self::Builtin => "builtin",
            Self::Plugin => "plugin",
            Self::Mcp => "mcp",
            Self::Synthetic => "synthetic",
            Self::Unknown => "unknown",
        }
    }
}

/// A tool's state relative to the request that was prepared for this step.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ToolVisibility {
    /// In this step's request with its schema included.
    Active,
    /// In this step's request, marked deferred (schema loads on demand).
    Deferred,
    /// In this step's request, with no transport flag to say which.
    InRequest,
    /// Registered and model-visible, but not carried by this step's request.
    RegistryOnly,
    /// Registered but not model-visible (hidden compatibility alias).
    Hidden,
}

impl ToolVisibility {
    #[must_use]
    pub const fn label(self) -> &'static str {
        match self {
            Self::Active => "active",
            Self::Deferred => "deferred",
            Self::InRequest => "in-request",
            Self::RegistryOnly => "registry-only",
            Self::Hidden => "hidden",
        }
    }

    /// Whether this state means the tool's bytes are carried by the prepared
    /// request. The only honest source of this answer is the request itself.
    #[must_use]
    pub const fn in_request(self) -> bool {
        matches!(self, Self::Active | Self::Deferred | Self::InRequest)
    }
}

/// Provider/route availability, derived from the resolved model client taken at
/// the request seam — never from the existence of a tool registry.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
#[serde(tag = "status", rename_all = "snake_case")]
pub enum ProviderAvailability {
    /// No client receipt was taken, because no surface context was captured.
    #[default]
    Unknown,
    /// A model client was resolved and this request was built for it.
    Available { provider: String, model: String },
    /// The seam was reached with no resolved model client. The reason is a safe
    /// label, never a URL or credential.
    Unavailable { reason: String },
}

impl ProviderAvailability {
    #[must_use]
    pub const fn is_available(&self) -> bool {
        matches!(self, Self::Available { .. })
    }

    #[must_use]
    pub const fn label(&self) -> &'static str {
        match self {
            Self::Unknown => "unknown",
            Self::Available { .. } => "available",
            Self::Unavailable { .. } => "unavailable",
        }
    }
}

/// Everything outside the prepared request that this projection is allowed to
/// report, resolved once per turn by the engine.
///
/// Plain data only: no registry, no client, no credentials. Resolving it once
/// per turn is what keeps the per-step seam from re-locking the MCP pool.
#[derive(Debug, Clone, Default)]
pub struct ToolSurfaceContext {
    /// The real registry, flattened. Sorted by name by the producer.
    pub registry: Vec<RegistryFacts>,
    /// Model tool name -> MCP server name, only for names the real pool
    /// resolved. Absent names stay unknown rather than being split apart.
    pub mcp_servers: BTreeMap<String, String>,
    /// Request-catalog names the engine injects rather than registering.
    pub synthetic_names: Vec<String>,
    /// Receipt from the resolved model client for this turn.
    pub provider: ProviderAvailability,
}

impl ToolSurfaceContext {
    fn provenance(&self, name: &str) -> ToolProvenance {
        if let Some(facts) = self.registry.iter().find(|facts| facts.name == name) {
            if facts.plugin {
                return ToolProvenance::Plugin;
            }
            if self.mcp_servers.contains_key(name) {
                return ToolProvenance::Mcp;
            }
            return ToolProvenance::Builtin;
        }
        if self.mcp_servers.contains_key(name) {
            return ToolProvenance::Mcp;
        }
        if self.synthetic_names.iter().any(|entry| entry == name) {
            return ToolProvenance::Synthetic;
        }
        ToolProvenance::Unknown
    }
}

#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct ToolProjection {
    pub ordinal: usize,
    pub name: BoundedString,
    pub tool_type: Evidence<BoundedString>,
    pub description: BoundedString,
    pub input_schema_json: BoundedString,
    pub allowed_callers: Evidence<BoundedList>,
    pub defer_loading: Evidence<bool>,
    pub input_examples: Evidence<CountOnly>,
    pub strict: Evidence<bool>,
    pub cache_control_type: Evidence<BoundedString>,
    /// Where this tool came from. Known only when a surface context was
    /// captured; `ToolProvenance::Unknown` inside `Known` means the context was
    /// captured and still resolved no origin.
    pub provenance: Evidence<ToolProvenance>,
    /// Owning MCP server, only when the real pool attributed this exact model
    /// tool name.
    pub mcp_server: Evidence<BoundedString>,
    /// Declared capabilities from the registry, sorted. Known-and-empty means
    /// "declares none"; unknown means "not in the registry".
    pub capabilities: Evidence<BoundedList>,
    /// Declared approval requirement from the registry.
    pub approval: Evidence<BoundedString>,
    /// Registry model visibility. A tool can be registered but hidden.
    pub model_visible: Evidence<bool>,
    /// State relative to this prepared request. Always known: the request is
    /// the evidence.
    pub visibility: ToolVisibility,
}

/// Bounded evidence from a prepared model-client request.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct ToolInspectionSnapshot {
    pub schema_version: u32,
    pub capture_source: &'static str,
    pub delivery_status: &'static str,
    pub turn_id: BoundedString,
    pub step: u32,
    pub tools_field_present: bool,
    pub tool_count: usize,
    pub rendered_tool_count: usize,
    pub omitted_tool_count: usize,
    pub payload_json_bytes: Option<usize>,
    pub payload_measurement_status: String,
    /// The active-tool-catalog digest, computed by the *same* function the
    /// request manifest uses for `active_tool_catalog_sha256`. Absent only when
    /// the request carried no tools field at all. Covers tool name,
    /// description, and canonical input schema — not transport-only fields —
    /// exactly as the manifest does.
    pub active_tool_catalog_sha256: Option<String>,
    /// Facts nothing on this path can observe for this request. Shrinks when a
    /// surface context supplies registry- and client-derived truth; never
    /// empties, because the provider adapter's wire payload is never visible
    /// here.
    pub unavailable_for_this_request: Vec<&'static str>,
    /// Provider receipt from the resolved model client, or `Unknown` when no
    /// surface context was captured.
    pub provider: ProviderAvailability,
    /// Whether registry-derived facts were captured at all. Absent stays
    /// distinct from an empty registry.
    pub registry_facts_present: bool,
    /// Size of the flattened registry, when it was captured.
    pub registry_tool_count: Evidence<usize>,
    /// Registered, model-visible tools this request does *not* carry. Bounded,
    /// with an explicit omission count.
    pub registry_only_tools: Evidence<BoundedList>,
    pub tools: Vec<ToolProjection>,
}

impl ToolInspectionSnapshot {
    /// Wire facts only. Provenance, attribution, capabilities, approval, and
    /// provider identity stay explicitly unknown.
    #[must_use]
    pub fn from_prepared_request(turn_id: &str, step: u32, tools: Option<&[Tool]>) -> Self {
        Self::from_prepared_request_with_surface(turn_id, step, tools, None)
    }

    /// Wire facts joined against the turn's resolved surface context.
    ///
    /// The context is what turns "unavailable" into truth: it is derived from
    /// the real registry, the real MCP pool's own attribution, the engine's own
    /// synthetic-name list, and the resolved model client. Passing `None`
    /// reproduces the wire-only projection exactly.
    #[must_use]
    pub fn from_prepared_request_with_surface(
        turn_id: &str,
        step: u32,
        tools: Option<&[Tool]>,
        surface: Option<&ToolSurfaceContext>,
    ) -> Self {
        let tool_count = tools.map_or(0, <[Tool]>::len);
        let projected = tools
            .unwrap_or_default()
            .iter()
            .take(MAX_RENDERED_TOOLS)
            .enumerate()
            .map(|(index, tool)| project_tool(index, tool, surface))
            .collect::<Vec<_>>();
        let (payload_json_bytes, payload_measurement_status) = measure_payload(tools);

        let request_names = tools
            .unwrap_or_default()
            .iter()
            .map(|tool| tool.name.as_str())
            .collect::<std::collections::BTreeSet<_>>();
        let registry_only_tools = surface.map_or_else(
            || unknown("registry facts not captured for this request"),
            |surface| {
                let names = surface
                    .registry
                    .iter()
                    .filter(|facts| {
                        facts.model_visible && !request_names.contains(facts.name.as_str())
                    })
                    .map(|facts| facts.name.as_str())
                    .collect::<Vec<_>>();
                let rendered = names
                    .iter()
                    .take(MAX_RENDERED_TOOLS)
                    .map(|name| bounded_chars(name, MAX_NAME_CHARS))
                    .collect::<Vec<_>>();
                Evidence::Known {
                    value: BoundedList {
                        count: names.len(),
                        omitted: names.len().saturating_sub(rendered.len()),
                        rendered,
                    },
                }
            },
        );

        let mut unavailable_for_this_request = vec!["provider_wire_payload"];
        if surface.is_none() {
            unavailable_for_this_request.extend([
                "provider",
                "model",
                "approval",
                "provenance",
                "capabilities",
            ]);
        } else if !surface.is_some_and(|surface| surface.provider.is_available()) {
            unavailable_for_this_request.extend(["provider", "model"]);
        }

        Self {
            schema_version: 1,
            capture_source: "prepared model-client request",
            delivery_status: "unknown (capture does not prove provider delivery)",
            turn_id: bounded_chars(turn_id, MAX_AUXILIARY_CHARS),
            step,
            tools_field_present: tools.is_some(),
            tool_count,
            rendered_tool_count: projected.len(),
            omitted_tool_count: tool_count.saturating_sub(projected.len()),
            payload_json_bytes,
            payload_measurement_status,
            active_tool_catalog_sha256: tools
                .map(crate::core::engine::preview::active_tool_catalog_sha256),
            unavailable_for_this_request,
            provider: surface.map_or(ProviderAvailability::Unknown, |surface| {
                surface.provider.clone()
            }),
            registry_facts_present: surface.is_some(),
            registry_tool_count: surface.map_or_else(
                || unknown("registry facts not captured for this request"),
                |surface| Evidence::Known {
                    value: surface.registry.len(),
                },
            ),
            registry_only_tools,
            tools: projected,
        }
    }

    #[must_use]
    pub fn render_text(&self) -> String {
        let mut out = String::new();
        out.push_str("Prepared Model-Client Tool Request (read-only)\n");
        out.push_str(&format!("Capture source: {}\n", self.capture_source));
        out.push_str(&format!("Delivery: {}\n", self.delivery_status));
        out.push_str(&format!(
            "Turn: {}\nTurn truncated: {}\n",
            json_string(&self.turn_id.value),
            yes_no(self.turn_id.truncated)
        ));
        out.push_str(&format!("Step: {}\n", self.step));
        out.push_str(&format!(
            "Tools field: {}\nTool count: {}\n",
            if self.tools_field_present {
                "present"
            } else {
                "absent"
            },
            self.tool_count
        ));
        out.push_str(&format!(
            "Rendered tools: {}; omitted by render bound: {}\n",
            self.rendered_tool_count, self.omitted_tool_count
        ));
        out.push_str(&format!(
            "Model-client payload measurement: {}\n",
            self.payload_measurement_status
        ));
        out.push_str(&format_optional_usize(
            "Model-client tool JSON bytes",
            self.payload_json_bytes,
        ));
        out.push_str(&format_optional_string(
            "Active tool catalog digest (same digest as the request manifest)",
            self.active_tool_catalog_sha256.as_deref(),
        ));
        out.push_str(
            "Provider-wire tool payload: unavailable (the provider adapter may transform or omit model-client fields)\n",
        );
        match &self.provider {
            ProviderAvailability::Available { provider, model } => out.push_str(&format!(
                "Provider: {} (resolved model client)\nModel: {}\n",
                json_string(provider),
                json_string(model)
            )),
            ProviderAvailability::Unavailable { reason } => {
                out.push_str(&format!("Provider: unavailable ({reason})\n"));
            }
            ProviderAvailability::Unknown => {
                out.push_str("Provider: unknown (no model-client receipt captured)\n");
            }
        }
        out.push_str(&format!(
            "Registry facts: {}\n",
            if self.registry_facts_present {
                "captured"
            } else {
                "not captured"
            }
        ));
        match &self.registry_tool_count {
            Evidence::Known { value } => {
                out.push_str(&format!("Registered tools: {value}\n"));
            }
            Evidence::Unknown { reason } => {
                out.push_str(&format!("Registered tools: unknown ({reason})\n"));
            }
        }
        match &self.registry_only_tools {
            Evidence::Known { value } => {
                let rendered = value
                    .rendered
                    .iter()
                    .map(|entry| entry.value.as_str())
                    .collect::<Vec<_>>();
                out.push_str(&format!(
                    "Model-visible tools not in this request: {}\n  names: {}\n  omitted by render bound: {}\n",
                    value.count,
                    serde_json::to_string(&rendered).unwrap_or_else(|_| "unavailable".to_string()),
                    value.omitted
                ));
            }
            Evidence::Unknown { reason } => {
                out.push_str(&format!(
                    "Model-visible tools not in this request: unknown ({reason})\n"
                ));
            }
        }
        out.push_str(&format!(
            "Unavailable for this request: {}\n",
            self.unavailable_for_this_request.join(", ")
        ));

        for tool in &self.tools {
            out.push_str(&format!(
                "\n{}. {}\n",
                tool.ordinal,
                json_string(&tool.name.value)
            ));
            out.push_str(&format!(
                "   name truncated: {}\n",
                yes_no(tool.name.truncated)
            ));
            render_bounded_evidence(&mut out, "type", &tool.tool_type);
            out.push_str(&format!(
                "   description: {}\n   description truncated: {}\n",
                json_string(&tool.description.value),
                yes_no(tool.description.truncated)
            ));
            out.push_str(&format!(
                "   input schema JSON: {}\n   input schema truncated: {}\n",
                tool.input_schema_json.value,
                yes_no(tool.input_schema_json.truncated)
            ));
            match &tool.allowed_callers {
                Evidence::Known { value } => {
                    let rendered = value
                        .rendered
                        .iter()
                        .map(|entry| entry.value.as_str())
                        .collect::<Vec<_>>();
                    out.push_str(&format!(
                        "   allowed callers: {}\n   allowed callers count: {}\n   allowed callers omitted: {}\n   allowed callers truncated: {}\n",
                        serde_json::to_string(&rendered).unwrap_or_else(|_| "unavailable".to_string()),
                        value.count,
                        value.omitted,
                        yes_no(value.rendered.iter().any(|entry| entry.truncated))
                    ));
                }
                Evidence::Unknown { reason } => {
                    out.push_str(&format!("   allowed callers: unknown ({reason})\n"));
                }
            }
            render_bool_evidence(&mut out, "deferred loading", &tool.defer_loading);
            render_bool_evidence(&mut out, "strict", &tool.strict);
            match &tool.input_examples {
                Evidence::Known { value } => out.push_str(&format!(
                    "   input examples: present ({} value(s), {})\n",
                    value.count, value.values
                )),
                Evidence::Unknown { reason } => {
                    out.push_str(&format!("   input examples: unknown ({reason})\n"));
                }
            }
            render_bounded_evidence(&mut out, "cache control type", &tool.cache_control_type);
            out.push_str(&format!(
                "   request state: {}\n   in request: {}\n",
                tool.visibility.label(),
                yes_no(tool.visibility.in_request())
            ));
            match &tool.provenance {
                Evidence::Known { value } => {
                    out.push_str(&format!("   provenance: {}\n", value.label()));
                }
                Evidence::Unknown { reason } => {
                    out.push_str(&format!("   provenance: unknown ({reason})\n"));
                }
            }
            render_bounded_evidence(&mut out, "MCP server", &tool.mcp_server);
            match &tool.capabilities {
                Evidence::Known { value } => {
                    let rendered = value
                        .rendered
                        .iter()
                        .map(|entry| entry.value.as_str())
                        .collect::<Vec<_>>();
                    out.push_str(&format!(
                        "   capabilities: {}\n   capabilities count: {}\n   capabilities omitted: {}\n",
                        serde_json::to_string(&rendered)
                            .unwrap_or_else(|_| "unavailable".to_string()),
                        value.count,
                        value.omitted
                    ));
                }
                Evidence::Unknown { reason } => {
                    out.push_str(&format!("   capabilities: unknown ({reason})\n"));
                }
            }
            render_bounded_evidence(&mut out, "approval", &tool.approval);
            render_bool_evidence(&mut out, "model visible", &tool.model_visible);
        }
        out
    }

    pub fn render_json(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(self)
    }
}

fn project_tool(index: usize, tool: &Tool, surface: Option<&ToolSurfaceContext>) -> ToolProjection {
    let facts = surface.and_then(|surface| {
        surface
            .registry
            .iter()
            .find(|facts| facts.name == tool.name)
    });
    let no_surface = "surface context not captured for this request";
    let not_registered = "tool is not in the registry";
    ToolProjection {
        ordinal: index + 1,
        name: bounded_chars(&tool.name, MAX_NAME_CHARS),
        tool_type: optional_bounded(tool.tool_type.as_deref()),
        description: bounded_chars(&tool.description, MAX_DESCRIPTION_CHARS),
        input_schema_json: bounded_json(&tool.input_schema, MAX_SCHEMA_BYTES),
        allowed_callers: tool.allowed_callers.as_ref().map_or_else(
            || unknown("request field absent"),
            |values| {
                let rendered = values
                    .iter()
                    .take(MAX_ALLOWED_CALLERS)
                    .map(|value| bounded_chars(value, MAX_ALLOWED_CALLER_CHARS))
                    .collect::<Vec<_>>();
                Evidence::Known {
                    value: BoundedList {
                        count: values.len(),
                        omitted: values.len().saturating_sub(rendered.len()),
                        rendered,
                    },
                }
            },
        ),
        defer_loading: optional_copy(tool.defer_loading.as_ref()),
        input_examples: tool.input_examples.as_ref().map_or_else(
            || unknown("request field absent"),
            |values| Evidence::Known {
                value: CountOnly {
                    count: values.len(),
                    values: "values omitted from bounded projection",
                },
            },
        ),
        strict: optional_copy(tool.strict.as_ref()),
        cache_control_type: optional_bounded(
            tool.cache_control
                .as_ref()
                .map(|value| value.cache_type.as_str()),
        ),
        provenance: surface.map_or_else(
            || unknown(no_surface),
            |surface| Evidence::Known {
                value: surface.provenance(&tool.name),
            },
        ),
        mcp_server: surface.map_or_else(
            || unknown(no_surface),
            |surface| {
                surface.mcp_servers.get(&tool.name).map_or_else(
                    || unknown("the MCP pool did not attribute this tool name"),
                    |server| Evidence::Known {
                        value: bounded_chars(server, MAX_AUXILIARY_CHARS),
                    },
                )
            },
        ),
        capabilities: match (surface, facts) {
            (None, _) => unknown(no_surface),
            (Some(_), None) => unknown(not_registered),
            (Some(_), Some(facts)) => {
                let rendered = facts
                    .capabilities
                    .iter()
                    .take(MAX_ALLOWED_CALLERS)
                    .map(|value| bounded_chars(value, MAX_ALLOWED_CALLER_CHARS))
                    .collect::<Vec<_>>();
                Evidence::Known {
                    value: BoundedList {
                        count: facts.capabilities.len(),
                        omitted: facts.capabilities.len().saturating_sub(rendered.len()),
                        rendered,
                    },
                }
            }
        },
        approval: match (surface, facts) {
            (None, _) => unknown(no_surface),
            (Some(_), None) => unknown(not_registered),
            (Some(_), Some(facts)) => Evidence::Known {
                value: bounded_chars(&facts.approval, MAX_AUXILIARY_CHARS),
            },
        },
        model_visible: match (surface, facts) {
            (None, _) => unknown(no_surface),
            (Some(_), None) => unknown(not_registered),
            (Some(_), Some(facts)) => Evidence::Known {
                value: facts.model_visible,
            },
        },
        // Every projected tool is carried by this prepared request; the
        // transport flag only says whether its schema rides along now.
        visibility: match tool.defer_loading {
            Some(true) => ToolVisibility::Deferred,
            Some(false) => ToolVisibility::Active,
            None => ToolVisibility::InRequest,
        },
    }
}

/// Byte accounting only. The digest is deliberately *not* computed here: it is
/// the request path's [`crate::core::engine::preview::active_tool_catalog_sha256`],
/// so this projection never defines a second catalog hash.
fn measure_payload(tools: Option<&[Tool]>) -> (Option<usize>, String) {
    let Some(tools) = tools else {
        return (None, "unavailable (tools field absent)".to_string());
    };
    let mut writer = BoundedWriter::new(MAX_PAYLOAD_MEASUREMENT_BYTES);
    match serde_json::to_writer(&mut writer, tools) {
        Ok(()) => (
            Some(writer.bytes.len()),
            "exact (within 1048576-byte measurement bound)".to_string(),
        ),
        Err(_) if writer.exceeded => (
            None,
            "unavailable (payload exceeds 1048576-byte measurement bound)".to_string(),
        ),
        Err(_) => (None, "unavailable (serialization failed)".to_string()),
    }
}

fn bounded_json(value: &Value, limit: usize) -> BoundedString {
    let mut writer = BoundedWriter::new(limit);
    let result = serde_json::to_writer(&mut writer, value);
    BoundedString {
        value: String::from_utf8_lossy(&writer.bytes).into_owned(),
        truncated: result.is_err() && writer.exceeded,
    }
}

struct BoundedWriter {
    bytes: Vec<u8>,
    limit: usize,
    exceeded: bool,
}

impl BoundedWriter {
    fn new(limit: usize) -> Self {
        Self {
            bytes: Vec::with_capacity(limit.min(8_192)),
            limit,
            exceeded: false,
        }
    }
}

impl Write for BoundedWriter {
    fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
        let remaining = self.limit.saturating_sub(self.bytes.len());
        let accepted = buffer.len().min(remaining);
        self.bytes.extend_from_slice(&buffer[..accepted]);
        if accepted < buffer.len() {
            self.exceeded = true;
            return Err(io::Error::other("inspection bound exceeded"));
        }
        Ok(accepted)
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

fn bounded_chars(value: &str, limit: usize) -> BoundedString {
    let mut chars = value.chars();
    let value = chars.by_ref().take(limit).collect::<String>();
    BoundedString {
        value,
        truncated: chars.next().is_some(),
    }
}

fn optional_bounded(value: Option<&str>) -> Evidence<BoundedString> {
    value.map_or_else(
        || unknown("request field absent"),
        |value| Evidence::Known {
            value: bounded_chars(value, MAX_AUXILIARY_CHARS),
        },
    )
}

fn optional_copy<T: Copy>(value: Option<&T>) -> Evidence<T> {
    value.map_or_else(
        || unknown("request field absent"),
        |value| Evidence::Known { value: *value },
    )
}

fn unknown<T>(reason: &str) -> Evidence<T> {
    Evidence::Unknown {
        reason: reason.to_string(),
    }
}

fn render_bounded_evidence(out: &mut String, label: &str, evidence: &Evidence<BoundedString>) {
    match evidence {
        Evidence::Known { value } => out.push_str(&format!(
            "   {label}: {}\n   {label} truncated: {}\n",
            json_string(&value.value),
            yes_no(value.truncated)
        )),
        Evidence::Unknown { reason } => {
            out.push_str(&format!("   {label}: unknown ({reason})\n"));
        }
    }
}

fn render_bool_evidence(out: &mut String, label: &str, evidence: &Evidence<bool>) {
    match evidence {
        Evidence::Known { value } => out.push_str(&format!("   {label}: {value}\n")),
        Evidence::Unknown { reason } => {
            out.push_str(&format!("   {label}: unknown ({reason})\n"));
        }
    }
}

fn json_string(value: &str) -> String {
    serde_json::to_string(value).unwrap_or_else(|_| "\"unavailable\"".to_string())
}

fn format_optional_usize(label: &str, value: Option<usize>) -> String {
    value.map_or_else(
        || format!("{label}: unavailable\n"),
        |value| format!("{label}: {value}\n"),
    )
}

fn format_optional_string(label: &str, value: Option<&str>) -> String {
    value.map_or_else(
        || format!("{label}: unavailable\n"),
        |value| format!("{label}: {value}\n"),
    )
}

const fn yes_no(value: bool) -> &'static str {
    if value { "yes" } else { "no" }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    fn tool(name: &str) -> Tool {
        Tool {
            tool_type: Some("function".to_string()),
            name: name.to_string(),
            description: "Read a file".to_string(),
            input_schema: json!({"type": "object"}),
            allowed_callers: None,
            defer_loading: Some(false),
            input_examples: None,
            strict: Some(true),
            cache_control: None,
        }
    }

    #[test]
    fn absent_field_stays_distinct_from_present_empty_array() {
        let absent = ToolInspectionSnapshot::from_prepared_request("turn", 1, None);
        let empty = ToolInspectionSnapshot::from_prepared_request("turn", 1, Some(&[]));
        assert!(!absent.tools_field_present);
        assert_eq!(absent.payload_json_bytes, None);
        assert!(absent.active_tool_catalog_sha256.is_none());
        assert!(empty.tools_field_present);
        assert_eq!(empty.payload_json_bytes, Some(2));
        assert!(empty.active_tool_catalog_sha256.is_some());
    }

    #[test]
    fn catalog_digest_is_the_request_manifest_digest_not_a_second_definition() {
        let tools = vec![tool("read_file"), tool("write_file")];
        let snapshot = ToolInspectionSnapshot::from_prepared_request("turn", 1, Some(&tools));

        // Same prepared request, same accounting object: the value the request
        // manifest publishes as `active_tool_catalog_sha256`.
        assert_eq!(
            snapshot.active_tool_catalog_sha256.as_deref(),
            Some(crate::core::engine::preview::active_tool_catalog_sha256(&tools).as_str()),
        );

        // And it is a catalog digest, not an incidental byte hash: reordering
        // the same tools changes it.
        let reordered = vec![tools[1].clone(), tools[0].clone()];
        let reordered = ToolInspectionSnapshot::from_prepared_request("turn", 1, Some(&reordered));
        assert_ne!(
            snapshot.active_tool_catalog_sha256,
            reordered.active_tool_catalog_sha256
        );
    }

    #[test]
    fn projection_preserves_known_false_and_marks_unknown() {
        let snapshot =
            ToolInspectionSnapshot::from_prepared_request("turn", 3, Some(&[tool("read_file")]));
        let text = snapshot.render_text();
        assert!(text.contains("deferred loading: false"), "{text}");
        assert!(text.contains("strict: true"), "{text}");
        assert!(text.contains("allowed callers: unknown (request field absent)"));
        assert!(text.contains("Delivery: unknown"));
        assert!(text.contains("Provider-wire tool payload: unavailable"));
    }

    fn facts(name: &str, plugin: bool, model_visible: bool) -> RegistryFacts {
        RegistryFacts {
            name: name.to_string(),
            description: format!("{name} registry description"),
            model_visible,
            capabilities: vec!["ReadOnly".to_string()],
            approval: "Auto".to_string(),
            plugin,
        }
    }

    fn surface() -> ToolSurfaceContext {
        ToolSurfaceContext {
            registry: vec![
                facts("read_file", false, true),
                facts("plugin_tool", true, true),
                facts("hidden_alias", false, false),
                facts("not_sent", false, true),
            ],
            mcp_servers: BTreeMap::from([(
                "mcp_my_server_read_file".to_string(),
                "my_server".to_string(),
            )]),
            synthetic_names: vec!["tool_search".to_string()],
            provider: ProviderAvailability::Available {
                provider: "Deepseek".to_string(),
                model: "deepseek-chat".to_string(),
            },
        }
    }

    #[test]
    fn surface_context_turns_provenance_and_attribution_into_truth() {
        let tools = vec![
            tool("read_file"),
            tool("plugin_tool"),
            tool("mcp_my_server_read_file"),
            tool("tool_search"),
            tool("stranger"),
        ];
        let surface = surface();
        let snapshot = ToolInspectionSnapshot::from_prepared_request_with_surface(
            "turn",
            1,
            Some(&tools),
            Some(&surface),
        );

        let provenance = |name: &str| {
            snapshot
                .tools
                .iter()
                .find(|entry| entry.name.value == name)
                .map(|entry| entry.provenance.clone())
                .expect("projected tool")
        };
        for (name, expected) in [
            ("read_file", ToolProvenance::Builtin),
            ("plugin_tool", ToolProvenance::Plugin),
            ("mcp_my_server_read_file", ToolProvenance::Mcp),
            ("tool_search", ToolProvenance::Synthetic),
            // Captured context, no resolved origin: unknown is the answer.
            ("stranger", ToolProvenance::Unknown),
        ] {
            assert_eq!(
                provenance(name),
                Evidence::Known { value: expected },
                "provenance for {name}"
            );
        }

        let mcp = snapshot
            .tools
            .iter()
            .find(|entry| entry.name.value == "mcp_my_server_read_file")
            .expect("mcp tool");
        // Attribution comes from the pool, not from splitting on `_`.
        assert_eq!(
            mcp.mcp_server,
            Evidence::Known {
                value: BoundedString {
                    value: "my_server".to_string(),
                    truncated: false,
                }
            }
        );

        let read_file = snapshot
            .tools
            .iter()
            .find(|entry| entry.name.value == "read_file")
            .expect("read_file");
        assert!(matches!(read_file.capabilities, Evidence::Known { .. }));
        assert_eq!(
            read_file.approval,
            Evidence::Known {
                value: BoundedString {
                    value: "Auto".to_string(),
                    truncated: false,
                }
            }
        );
        assert_eq!(read_file.model_visible, Evidence::Known { value: true });

        // Unregistered tools stay unknown rather than being reported as "none".
        let stranger = snapshot
            .tools
            .iter()
            .find(|entry| entry.name.value == "stranger")
            .expect("stranger");
        assert!(matches!(stranger.capabilities, Evidence::Unknown { .. }));
        assert!(matches!(stranger.approval, Evidence::Unknown { .. }));

        // The unavailable set shrinks to what nothing here can observe.
        assert_eq!(
            snapshot.unavailable_for_this_request,
            vec!["provider_wire_payload"]
        );
        assert!(snapshot.provider.is_available());
        assert!(snapshot.registry_facts_present);
        assert_eq!(snapshot.registry_tool_count, Evidence::Known { value: 4 });

        let text = snapshot.render_text();
        assert!(text.contains("provenance: synthetic"), "{text}");
        assert!(text.contains("MCP server: \"my_server\""), "{text}");
        assert!(text.contains("Provider: \"Deepseek\""), "{text}");
        assert!(
            text.contains("Provider-wire tool payload: unavailable"),
            "{text}"
        );
    }

    #[test]
    fn registry_only_tools_are_counted_without_expanding_the_projection() {
        let tools = vec![tool("read_file")];
        let surface = surface();
        let snapshot = ToolInspectionSnapshot::from_prepared_request_with_surface(
            "turn",
            1,
            Some(&tools),
            Some(&surface),
        );

        // Only the request's tools are projected; the rest are counted.
        assert_eq!(snapshot.tools.len(), 1);
        let Evidence::Known { value } = &snapshot.registry_only_tools else {
            panic!("registry-only tools must be known when facts were captured");
        };
        // `hidden_alias` is not model-visible, so it is not a missing tool.
        assert_eq!(value.count, 2);
        let rendered = value
            .rendered
            .iter()
            .map(|entry| entry.value.as_str())
            .collect::<Vec<_>>();
        // Order follows the registry facts as supplied; the producer sorts.
        assert_eq!(rendered, vec!["plugin_tool", "not_sent"]);

        // Everything projected is in the request; the request is the evidence.
        assert!(snapshot.tools.iter().all(|entry| {
            entry.visibility.in_request() && entry.visibility == ToolVisibility::Active
        }));
    }

    #[test]
    fn absent_surface_keeps_every_registry_derived_field_unknown() {
        let tools = vec![tool("read_file")];
        let snapshot = ToolInspectionSnapshot::from_prepared_request("turn", 1, Some(&tools));

        assert_eq!(snapshot.provider, ProviderAvailability::Unknown);
        assert!(!snapshot.registry_facts_present);
        assert!(matches!(
            snapshot.registry_tool_count,
            Evidence::Unknown { .. }
        ));
        assert!(matches!(
            snapshot.registry_only_tools,
            Evidence::Unknown { .. }
        ));
        assert_eq!(
            snapshot.unavailable_for_this_request,
            vec![
                "provider_wire_payload",
                "provider",
                "model",
                "approval",
                "provenance",
                "capabilities",
            ]
        );
        let entry = &snapshot.tools[0];
        for evidence in [
            matches!(entry.provenance, Evidence::Unknown { .. }),
            matches!(entry.mcp_server, Evidence::Unknown { .. }),
            matches!(entry.capabilities, Evidence::Unknown { .. }),
            matches!(entry.approval, Evidence::Unknown { .. }),
            matches!(entry.model_visible, Evidence::Unknown { .. }),
        ] {
            assert!(evidence);
        }
        // Wire facts are still exact without a surface context.
        assert!(entry.visibility.in_request());
        assert!(snapshot.active_tool_catalog_sha256.is_some());
    }

    #[test]
    fn provider_receipt_records_an_unresolved_client_without_borrowing_registry_truth() {
        let tools = vec![tool("read_file")];
        let surface = ToolSurfaceContext {
            registry: vec![facts("read_file", false, true)],
            provider: ProviderAvailability::Unavailable {
                reason: "no model client resolved for this turn".to_string(),
            },
            ..ToolSurfaceContext::default()
        };
        let snapshot = ToolInspectionSnapshot::from_prepared_request_with_surface(
            "turn",
            1,
            Some(&tools),
            Some(&surface),
        );

        // A full registry does not make a provider available.
        assert!(!snapshot.provider.is_available());
        assert_eq!(snapshot.provider.label(), "unavailable");
        assert!(snapshot.unavailable_for_this_request.contains(&"provider"));
        // Registry-derived truth is unaffected by the missing client.
        assert!(
            !snapshot
                .unavailable_for_this_request
                .contains(&"provenance")
        );
        assert_eq!(
            snapshot.tools[0].provenance,
            Evidence::Known {
                value: ToolProvenance::Builtin
            }
        );
    }

    #[test]
    fn capture_and_rendering_are_bounded_with_explicit_receipts() {
        let mut tools = (0..40)
            .map(|index| {
                let mut value = tool(&format!("tool_{index}"));
                value.description = "x".repeat(MAX_DESCRIPTION_CHARS + 10);
                value.input_schema = json!({"large": "y".repeat(MAX_SCHEMA_BYTES * 600)});
                value
            })
            .collect::<Vec<_>>();
        tools[0].allowed_callers = Some(
            (0..20)
                .map(|caller| format!("caller-{caller}-{}", "z".repeat(200)))
                .collect(),
        );
        let snapshot = ToolInspectionSnapshot::from_prepared_request(
            &"t".repeat(MAX_AUXILIARY_CHARS + 1),
            1,
            Some(&tools),
        );
        assert_eq!(snapshot.rendered_tool_count, MAX_RENDERED_TOOLS);
        assert_eq!(snapshot.omitted_tool_count, 8);
        assert!(snapshot.turn_id.truncated);
        assert!(snapshot.tools[0].description.truncated);
        assert!(snapshot.tools[0].input_schema_json.truncated);
        assert_eq!(snapshot.payload_json_bytes, None);
        assert!(snapshot.payload_measurement_status.contains("exceeds"));
        // The catalog digest is fixed-width, so it survives the byte bound.
        assert!(snapshot.active_tool_catalog_sha256.is_some());
        let json = snapshot.render_json().expect("bounded JSON");
        // 160 KiB: the per-tool evidence fields (provenance, MCP server,
        // capabilities, approval, visibility) each carry an explicit reason
        // string when unresolved, which is the point — the cap moved, the
        // bound did not disappear.
        assert!(
            json.len() < 163_840,
            "projection grew to {} bytes",
            json.len()
        );
    }
}