vtcode-core 0.185.1

Core library for VT Code - a Rust-based terminal coding agent
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
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
use std::path::PathBuf;

use serde_json::json;

use crate::config::constants::tools;
use crate::config::types::CapabilityLevel;
use crate::tools::handlers::PlanningWorkflowState;
use crate::tools::handlers::task_tracker::task_tracker_description_for_workflow;
use crate::tools::registry::ToolRegistration;
use crate::tools::registry::ToolRegistry;

/// The registrations the runtime actually ships, built through the pack path.
///
/// Every metadata assertion in this module reads these rather than the old
/// `#[distributed_slice(BUILTIN_TOOLS)]` mirror, which was a parallel
/// implementation of the pack set: an alias, schema, or description present
/// only in the mirror would pass here while never reaching the model.
fn shipped_registrations(plan_state: Option<&PlanningWorkflowState>) -> Vec<ToolRegistration> {
    use crate::tools::registry::distributed::ToolConfigSnapshot;
    use crate::tools::registry::inventory::ToolInventory;

    let temp = tempfile::tempdir().expect("workspace tempdir");
    let inventory = ToolInventory::new(
        temp.path().to_path_buf(),
        std::sync::Arc::new(crate::tools::edited_file_monitor::EditedFileMonitor::new()),
    );
    let owned_state;
    let plan_state = match plan_state {
        Some(state) => state,
        None => {
            owned_state = PlanningWorkflowState::new(temp.path().to_path_buf());
            &owned_state
        }
    };
    futures::executor::block_on(super::super::pack::register_builtin_packs(
        &inventory,
        plan_state,
        &ToolConfigSnapshot::default(),
    ));
    inventory.registrations_snapshot()
}

#[test]
fn tool_backed_builtins_register_native_cgp_factories() {
    let plan_state = PlanningWorkflowState::new(PathBuf::from("/workspace"));
    let registrations = shipped_registrations(Some(&plan_state));

    for tool_name in [tools::REQUEST_USER_INPUT, tools::START_PLANNING, tools::TASK_TRACKER] {
        let registration = registrations
            .iter()
            .find(|registration| registration.name() == tool_name)
            .expect("builtin registration should exist");
        assert!(registration.native_cgp_factory().is_some(), "expected native CGP factory for {tool_name}");
    }

    assert!(
        registrations
            .iter()
            .all(|registration| registration.name() != tools::UNIFIED_SEARCH
                && registration.name() != tools::UNIFIED_FILE
                && registration.name() != tools::UNIFIED_EXEC),
        "removed unified tools must not have builtin registrations"
    );
}

#[test]
fn task_tracker_builtin_registration_matches_workflow_metadata() {
    let plan_state = PlanningWorkflowState::new(PathBuf::from("/workspace"));

    let standard = shipped_registrations(Some(&plan_state))
        .into_iter()
        .find(|registration| registration.name() == tools::TASK_TRACKER)
        .expect("standard task_tracker registration should exist");
    assert_eq!(standard.metadata().description(), Some(task_tracker_description_for_workflow(false)));
    assert_eq!(
        standard.metadata().parameter_schema().expect("standard schema")["properties"]["index"]["minimum"],
        0
    );

    plan_state.enable();
    let planning = shipped_registrations(Some(&plan_state))
        .into_iter()
        .find(|registration| registration.name() == tools::TASK_TRACKER)
        .expect("planning task_tracker registration should exist");
    assert_eq!(planning.metadata().description(), Some(task_tracker_description_for_workflow(true)));
    assert_eq!(
        planning.metadata().parameter_schema().expect("planning schema")["properties"]["index"]["minimum"],
        1
    );
}

#[test]
fn codex_baseline_builtins_are_canonical_public_tools() {
    let plan_state = PlanningWorkflowState::new(PathBuf::from("/workspace"));
    let registrations = shipped_registrations(Some(&plan_state));

    for tool_name in [tools::EXEC_COMMAND, tools::WRITE_STDIN] {
        let registration = registrations
            .iter()
            .find(|registration| registration.name() == tool_name)
            .expect("canonical public registration should exist");
        assert!(registration.expose_in_llm(), "{tool_name} should be public");
        assert!(registration.metadata().aliases().is_empty(), "{tool_name} should not rely on aliases");
    }

    let code_search = registrations
        .iter()
        .find(|registration| registration.name() == tools::CODE_SEARCH)
        .expect("advanced public code_search registration should exist");
    assert!(code_search.expose_in_llm(), "code_search should be public");
    assert!(code_search.metadata().aliases().is_empty(), "code_search should not rely on aliases");
    let schema = code_search.metadata().parameter_schema().expect("code_search schema");
    assert_eq!(schema["required"], json!(["query"]));
    let mut property_names = schema["properties"]
        .as_object()
        .expect("properties")
        .keys()
        .map(String::as_str)
        .collect::<Vec<_>>();
    property_names.sort_unstable();
    assert_eq!(property_names, ["file_types", "max_results", "path", "query", "result_types"]);

    for tool_name in [tools::UNIFIED_SEARCH, tools::UNIFIED_EXEC, tools::UNIFIED_FILE] {
        assert!(
            registrations.iter().all(|registration| registration.name() != tool_name),
            "{tool_name} must not have a builtin registration"
        );
    }
}

#[test]
fn computer_use_registers_public_prompt_gated_and_fail_closed() {
    let plan_state = PlanningWorkflowState::new(PathBuf::from("/workspace"));
    let registrations = shipped_registrations(Some(&plan_state));

    let computer_use = registrations
        .iter()
        .find(|registration| registration.name() == tools::COMPUTER_USE)
        .expect("computer_use registration should exist");
    assert!(computer_use.expose_in_llm(), "computer_use should be public");
    assert!(computer_use.metadata().aliases().is_empty(), "computer_use should not rely on aliases");
    assert_eq!(
        computer_use.default_permission(),
        Some(crate::tool_policy::ToolPolicy::Prompt),
        "computer control must prompt, never auto-approve"
    );
    let schema = computer_use.metadata().parameter_schema().expect("computer_use schema");
    assert_eq!(schema["required"], json!(["task"]));
    assert!(schema["properties"]["task"].is_object(), "task must be a schema property");
}

#[test]
fn web_search_schema_requires_canonical_query() {
    let registrations = shipped_registrations(None);
    let web_search = registrations
        .iter()
        .find(|registration| registration.name() == tools::WEB_SEARCH)
        .expect("web_search registration should exist");
    let schema = web_search.metadata().parameter_schema().expect("web_search schema");

    assert_eq!(schema["required"], json!(["query"]));
    assert_eq!(schema["additionalProperties"], json!(false));
    assert_eq!(schema["properties"]["query"]["minLength"], json!(1));
    assert_eq!(schema["properties"]["query"]["maxLength"], json!(500));
    let mut property_names = schema["properties"]
        .as_object()
        .expect("properties")
        .keys()
        .map(String::as_str)
        .collect::<Vec<_>>();
    property_names.sort_unstable();
    assert_eq!(property_names, ["max_results", "query"]);
}

#[test]
fn multi_agent_builtins_expose_updated_descriptions() {
    let plan_state = PlanningWorkflowState::new(PathBuf::from("/workspace"));
    let registrations = shipped_registrations(Some(&plan_state));

    let agent = registrations
        .iter()
        .find(|registration| registration.name() == tools::AGENT)
        .expect("agent registration should exist");
    assert!(
        agent
            .metadata()
            .description()
            .expect("agent description")
            .contains("delegated child agents")
    );
    for alias in [
        tools::SPAWN_AGENT,
        tools::SPAWN_BACKGROUND_SUBPROCESS,
        tools::SEND_INPUT,
        tools::RESUME_AGENT,
        tools::WAIT_AGENT,
        tools::CLOSE_AGENT,
    ] {
        assert!(agent.metadata().aliases().iter().any(|candidate| candidate == alias));
    }
}

#[test]
fn web_fetch_builtin_description_guides_agents_to_try_llms_txt_first() {
    let registrations = shipped_registrations(None);
    let web_fetch = registrations
        .iter()
        .find(|registration| registration.name() == tools::WEB_FETCH)
        .expect("web_fetch registration should exist");
    let description = web_fetch.metadata().description().expect("web_fetch description");

    assert!(description.contains("/llms.txt"));
    assert!(description.contains("abc.com"));
    assert!(description.contains("https://abc.com/llms.txt"));
    assert!(description.contains("traverse"));
}

#[test]
fn web_fetch_builtin_description_matches_preview_and_temp_file_result() {
    let registrations = shipped_registrations(None);
    let web_fetch = registrations
        .iter()
        .find(|registration| registration.name() == tools::WEB_FETCH)
        .expect("web_fetch registration should exist");
    let description = web_fetch.metadata().description().expect("web_fetch description");

    // The default mode returns a preview plus a temp_file path; it does
    // not produce an analyzed summary.
    assert!(description.contains("`preview`"));
    assert!(description.contains("`temp_file`"));
    assert!(!description.contains("analyzed summary"));
    assert!(!description.contains("Accepts:"));
    assert!(!description.contains("Do NOT"));
}

#[test]
fn web_fetch_schema_rejects_unknown_output_modes() {
    let registrations = shipped_registrations(None);
    let web_fetch = registrations
        .iter()
        .find(|registration| registration.name() == tools::WEB_FETCH)
        .expect("web_fetch registration should exist");
    let schema = web_fetch.metadata().parameter_schema().expect("web_fetch schema");

    // The schema has a single output mode, so `format` is not a property:
    // `additionalProperties: false` rejects it rather than silently ignoring it.
    assert!(schema["properties"].get("format").is_none());
    assert_eq!(schema["additionalProperties"], json!(false));
    let validator = jsonschema::validator_for(schema).expect("web_fetch schema should compile");
    assert!(validator.is_valid(&json!({"url": "https://example.com"})));
    assert!(!validator.is_valid(&json!({"url": "https://example.com", "format": "markdown"})));
}

/// Tool descriptions are part of the prompt and directly drive tool
/// selection accuracy (Section 18.3.4 of the agentic-AI guide). This test
/// enforces a structural contract so that regressions in description
/// quality are caught at `cargo test` time rather than via observed
/// agent misbehavior.
///
/// Every LLM-visible tool with a description must satisfy the rules
/// below. Rules 2 and 3 are checked against the description sent in the
/// default Progressive documentation mode, which must be the complete
/// source description:
/// 1. Length is between 40 and 1500 characters.
/// 2. Contains at least one verb cue ("Use", "Create", "List", "Fetch",
///    "Search", "Send", "Apply", "Read", "Edit", etc.) so the model can
///    recognize the action the tool performs.
/// 3. For tools that mutate state, network-call, schedule work, or
///    require confirmation, the description must contain a constraint cue
///    ("max ", "rate-limit", "session", "blocks", "timeout",
///    "requires approval", etc.) so the model knows the limits and side
///    effects. Prohibition phrasing ("Do NOT", "Avoid", "never") does not
///    satisfy this rule: models that follow descriptions literally
///    over-apply it, so descriptions state the concrete limit instead.
///
/// Tools exempted from rule 3 are simple read-only helpers where the
/// model can safely call them without explicit guard-rails.
#[tokio::test]
async fn tool_descriptions_satisfy_documented_contract() {
    use crate::config::ToolDocumentationMode;
    use crate::tools::handlers::compact::compact_tool_description;
    use crate::tools::handlers::{SessionSurface, SessionToolsConfig, ToolModelCapabilities};
    use std::sync::Arc;

    use crate::tools::registry::distributed::ToolConfigSnapshot;
    use crate::tools::registry::inventory::ToolInventory;

    // Read the descriptions the shipped packs register. The test mirror also
    // carries descriptions, but it is a parallel implementation: this test
    // passed while the shipped `code_search` text had lost a capability the
    // runtime supports, because it was reading the mirror's copy.
    let plan_state = PlanningWorkflowState::new(PathBuf::from("/workspace"));
    let temp = tempfile::tempdir().unwrap();
    let inventory = ToolInventory::new(
        temp.path().to_path_buf(),
        Arc::new(crate::tools::edited_file_monitor::EditedFileMonitor::new()),
    );
    super::super::pack::register_builtin_packs(&inventory, &plan_state, &ToolConfigSnapshot::default()).await;
    let registrations = inventory.registrations_snapshot();

    let verb_cues = [
        "Use ",
        "Create ",
        "Control ",
        "List ",
        "Fetch ",
        "Search ",
        "Send ",
        "Apply ",
        "Read ",
        "Write ",
        "Edit ",
        "Patch ",
        "Delete ",
        "Move ",
        "Copy ",
        "Spawn ",
        "Launch ",
        "Close ",
        "Resume ",
        "Wait ",
        "Connect ",
        "Disconnect ",
        "Schedule ",
        "Inspect ",
        "Persist ",
        "Request ",
        "Open ",
        "Stop ",
        "Run ",
        "Track ",
        "Update ",
    ];
    let constraint_cues = [
        "max ",
        "rate-limit",
        "rate limit",
        "session",
        "blocks",
        "timeout",
        "cap ",
        "outlives",
        "inherits",
        "expires",
        "limited to",
        "max_bytes",
        "max_results",
        "max_lines",
        "max chars",
        "max size",
        "once per",
        "requires ",
        "requires approval",
        "permission",
        "approval",
        "exceeds",
        "scoped",
    ];
    // Read-only / single-action helpers where a constraint cue is not
    // strictly required. Entries are registration names; aliases such as
    // cron_list or mcp_search_tools never reach this check.
    let rule3_allowlist: &[&str] = &[
        tools::REQUEST_USER_INPUT,
        tools::SEARCH_TOOLS,
        tools::TASK_TRACKER,
        tools::START_PLANNING,
        tools::CODE_SEARCH,
    ];

    for allowed in rule3_allowlist {
        assert!(
            registrations.iter().any(|registration| registration.name() == *allowed),
            "rule3 allowlist entry {allowed} is not a builtin registration name"
        );
    }

    // Rules 2 and 3 are checked against the text the model receives in
    // the default Progressive documentation mode, not just the source
    // string, so a projection that drops later sentences cannot hide a
    // missing cue. Read through `ToolRegistry` so the projection the model
    // receives is the one asserted.
    let registry = ToolRegistry::new_for_schema(temp.path().to_path_buf()).await;
    let progressive_entries = registry
        .schema_entries(SessionToolsConfig::full_public(
            SessionSurface::Interactive,
            CapabilityLevel::CodeSearch,
            ToolDocumentationMode::Progressive,
            ToolModelCapabilities::default(),
        ))
        .await;
    assert!(!progressive_entries.is_empty(), "Progressive catalog must expose builtin tools");

    for registration in &registrations {
        if !registration.expose_in_llm() {
            continue;
        }
        let Some(source_description) = registration.metadata().description() else {
            continue;
        };
        let tool_name = registration.name();

        // Rule 1: length of the source description.
        let len = source_description.chars().count();
        assert!((40..=1500).contains(&len), "{tool_name}: description length {len} outside [40, 1500]");

        let projected = compact_tool_description(source_description, ToolDocumentationMode::Progressive, None);
        let sent = progressive_entries
            .iter()
            .find(|entry| entry.name == tool_name)
            .map_or(projected.as_str(), |entry| entry.description.as_str());
        assert_eq!(
            sent,
            compact_tool_description(source_description, ToolDocumentationMode::Full, None),
            "{tool_name}: Progressive mode must send the complete builtin description"
        );
        let description = sent;

        // Rule 2: the description opens with an action verb.
        //
        // The cue list below is illustrative, not exhaustive: a description
        // that opens with any capitalised word followed by lowercase text is
        // an imperative sentence ("Manage a durable local task matrix.").
        // Checking only the list rejected a valid verb the list had not
        // happened to include, so a new tool's description would fail for
        // wording rather than for behavior.
        let starts_with_imperative = description.split_whitespace().next().is_some_and(|word| {
            let mut chars = word.chars();
            chars.next().is_some_and(char::is_uppercase)
                && chars.next().is_some_and(char::is_lowercase)
                && word.trim_end_matches(|c: char| !c.is_alphabetic()).len() > 2
        });
        let has_verb = starts_with_imperative || verb_cues.iter().any(|cue| description.contains(cue));
        assert!(
            has_verb,
            "{tool_name}: description must open with an action verb or contain a cue like 'Use ', 'Create ', 'Fetch ', etc.\nDescription: {description}"
        );

        // Rule 3: constraint cue for side-effect tools.
        if rule3_allowlist.contains(&tool_name) {
            continue;
        }
        let has_constraint = constraint_cues.iter().any(|cue| description.contains(cue));
        assert!(
            has_constraint,
            "{tool_name}: side-effect description must state a concrete constraint cue ('max ', 'rate-limit', \
             'session', 'timeout', 'requires approval', 'inherits', ...).\nDescription: {description}"
        );
    }
}
#[tokio::test]
async fn default_config_exposed_tool_count_within_cap() {
    // Regression guard for the tool-consolidation work: the number of tools
    // the model actually receives must stay bounded so it does not waste
    // attention choosing between near-duplicates. Any new registration must
    // either consolidate an existing tool, be deferred behind the
    // deferred-loading path, or deliberately raise this cap in review.
    //
    // This measures the shipped catalog through `ToolRegistry`, which applies
    // the deferred-loading policy and the runtime access gates (`matrix`
    // is stripped unless the session coordinates or runs a matrix). Counting
    // raw `expose_in_llm()` registrations instead was a drifted proxy: it
    // reported 19 against a cap of 15 while the model received 5.
    use crate::config::ToolDocumentationMode;
    use crate::tools::handlers::{SessionSurface, SessionToolsConfig, ToolModelCapabilities};

    let temp = tempfile::tempdir().unwrap();
    let registry = ToolRegistry::new_for_schema(temp.path().to_path_buf()).await;

    let mut worst = 0usize;
    for surface in [
        SessionSurface::Interactive,
        SessionSurface::AgentRunner,
        SessionSurface::Acp,
    ] {
        for planning_active in [false, true] {
            for documentation_mode in [ToolDocumentationMode::Full, ToolDocumentationMode::Progressive] {
                let config = SessionToolsConfig {
                    planning_active,
                    ..SessionToolsConfig::full_public(
                        surface,
                        CapabilityLevel::CodeSearch,
                        documentation_mode,
                        ToolModelCapabilities::default(),
                    )
                };
                let tools = registry.model_tools(config.clone()).await;
                let declarations = registry.function_declarations(config).await;
                assert_eq!(
                    tools.len(),
                    declarations.len(),
                    "{surface:?} planning={planning_active}: model_tools and function_declarations must agree"
                );
                worst = worst.max(tools.len());
            }
        }
    }

    // Measured 5 across every surface, planning mode, and documentation mode.
    // Headroom admits one more always-eager tool without letting the count
    // creep back toward the pre-deferral surface.
    assert!(
        worst <= 8,
        "the model receives {worst} builtin tools in the widest configuration; expected <= 8. \
         Consolidate, defer, or raise the cap in review."
    );
}

#[tokio::test]
async fn public_decision_is_available_in_interactive_and_headless_planning_and_execution() {
    use crate::config::ToolDocumentationMode;
    use crate::tools::handlers::{SessionSurface, SessionToolsConfig, ToolModelCapabilities};
    // Assert the surface the model actually receives, not the test mirror.
    let temp = tempfile::tempdir().unwrap();
    let registry = ToolRegistry::new_for_schema(temp.path().to_path_buf()).await;
    for surface in [SessionSurface::Interactive, SessionSurface::AgentRunner] {
        for planning in [false, true] {
            let config = SessionToolsConfig::full_public(
                surface,
                CapabilityLevel::CodeSearch,
                ToolDocumentationMode::Full,
                ToolModelCapabilities::default(),
            )
            .with_planning_active(planning);
            let names: Vec<String> = registry
                .schema_entries(config)
                .await
                .into_iter()
                .map(|entry| entry.name)
                .collect();
            assert!(
                names.iter().any(|name| name == tools::RECORD_DECISION),
                "decision missing on {surface:?}, planning={planning}; got {names:?}"
            );
        }
    }
}

/// Emit a reproducible offline catalog baseline for the harness audit.
#[tokio::test]
async fn model_tool_catalog_baseline_by_mode() {
    use crate::config::ToolDocumentationMode;
    use crate::tools::handlers::{SessionSurface, SessionToolsConfig, ToolModelCapabilities};
    use vtcode_llm::providers::tool_format::{ProviderFamily, ProviderToolFormatter, formatter};

    let workspace = tempfile::tempdir().expect("workspace");
    let registry = ToolRegistry::new_for_schema(workspace.path().to_path_buf()).await;
    for mode in [
        ToolDocumentationMode::Minimal,
        ToolDocumentationMode::Progressive,
        ToolDocumentationMode::Full,
    ] {
        for planning in [false, true] {
            let config = SessionToolsConfig::full_public(
                SessionSurface::Interactive,
                CapabilityLevel::CodeSearch,
                mode,
                ToolModelCapabilities::default(),
            )
            .with_planning_active(planning);
            let entries = registry.schema_entries(config.clone()).await;
            assert!(!entries.is_empty(), "catalog must not be empty");
            assert!(entries.iter().any(|entry| entry.name == tools::EXEC_COMMAND));
            assert_eq!(entries.iter().any(|entry| entry.name == tools::APPLY_PATCH), !planning);
            assert_eq!(entries.iter().any(|entry| entry.name == tools::CODE_SEARCH), planning);
            let bytes = serde_json::to_vec(&entries).expect("serialize catalog").len();
            let model_tools = registry.model_tools(config).await;
            let model_bytes = serde_json::to_vec(&model_tools).expect("serialize model tools").len();
            eprintln!(
                "{mode:?} planning={planning}: {} entries, {bytes} bytes; {} model tools, {model_bytes} bytes",
                entries.len(),
                model_tools.len()
            );
            for entry in &entries {
                let size = serde_json::to_vec(entry).expect("serialize entry").len();
                eprintln!("  {} {size}", entry.name);
            }
            for family in [
                ProviderFamily::OpenAIChat,
                ProviderFamily::OpenAIResponses,
                ProviderFamily::Anthropic,
                ProviderFamily::Gemini,
            ] {
                let formatted = formatter(family)
                    .format_tools(&model_tools, "offline-fixture")
                    .expect("format tools")
                    .expect("nonempty provider tools");
                let json = serde_json::to_vec(&formatted).expect("serialize provider tools");
                assert!(String::from_utf8_lossy(&json).contains(tools::EXEC_COMMAND));
                eprintln!("  {family:?} formatted: {} bytes", json.len());
                // Context-pressure accounting measures pre-format definitions, so
                // formatted wire bytes must track the internal JSON within 2x.
                assert!(
                    json.len() * 2 >= model_bytes && json.len() <= model_bytes * 2,
                    "{family:?} formatted bytes {} diverged from internal {model_bytes}",
                    json.len()
                );
            }
        }
    }
}

/// Model-surface inventory for the harness audit: entry names per surface
/// from the real builtin packs. Prints the inventory (`--no-capture`) and
/// pins that removed/hidden file tools never reach any model surface.
#[tokio::test]
async fn model_surface_inventory_by_surface() {
    use crate::config::ToolDocumentationMode;
    use crate::tools::handlers::{SessionSurface, SessionToolsConfig, ToolModelCapabilities};

    // No pack registers `grep_file`: it must stay absent from every surface.
    let registrations = shipped_registrations(None);
    assert!(
        registrations.iter().all(|registration| registration.name() != tools::GREP_FILE),
        "grep_file must have no builtin registration"
    );

    let workspace = tempfile::tempdir().expect("workspace");
    let registry = ToolRegistry::new_for_schema(workspace.path().to_path_buf()).await;
    for surface in [
        SessionSurface::Interactive,
        SessionSurface::AgentRunner,
        SessionSurface::Acp,
    ] {
        for planning in [false, true] {
            let config = SessionToolsConfig::full_public(
                surface,
                CapabilityLevel::CodeSearch,
                ToolDocumentationMode::Progressive,
                ToolModelCapabilities::default(),
            )
            .with_planning_active(planning);
            let mut names: Vec<_> = registry
                .schema_entries(config)
                .await
                .iter()
                .map(|entry| entry.name.clone())
                .collect();
            names.sort();
            eprintln!("{surface:?} planning={planning}: {}", names.join(", "));
            for absent in [tools::GREP_FILE, tools::READ_FILE, tools::LIST_FILES] {
                assert!(!names.iter().any(|name| name == absent), "{absent} must not be model-visible on {surface:?}");
            }
            // Pin the primary (Interactive) surface exactly: any exposure change
            // must update this census and the audit ledger deliberately.
            if matches!(surface, SessionSurface::Interactive) {
                let expected: &[&str] = if planning {
                    &["code_search", "exec_command", "record_decision", "request_user_input"]
                } else {
                    &[
                        "apply_patch",
                        "exec_command",
                        "record_decision",
                        "search_tools",
                        "write_stdin",
                    ]
                };
                let actual: Vec<&str> = names.iter().map(String::as_str).collect();
                assert_eq!(actual, expected, "Interactive catalog changed; update the ledger baseline");
            }
        }
    }
}

#[tokio::test]
async fn decision_tool_hosted_deferral_and_minimal_description() {
    use crate::config::ToolDocumentationMode;
    use crate::tools::handlers::{DeferredToolPolicy, SessionSurface, SessionToolsConfig, ToolModelCapabilities};

    let workspace = tempfile::tempdir().expect("workspace");
    let registry = ToolRegistry::new_for_schema(workspace.path().to_path_buf()).await;
    for planning in [false, true] {
        let config = SessionToolsConfig::full_public(
            SessionSurface::Interactive,
            CapabilityLevel::CodeSearch,
            ToolDocumentationMode::Minimal,
            ToolModelCapabilities::default(),
        )
        .with_planning_active(planning);
        let entries = registry.schema_entries(config.clone()).await;
        let decision = entries
            .iter()
            .find(|entry| entry.name == tools::RECORD_DECISION)
            .expect("decision schema");
        assert!(decision.description.contains("consequential choices"));
        assert!(!decision.description.contains("ordinary commands"));

        for (policy, deferred) in [
            (DeferredToolPolicy::default(), false),
            (DeferredToolPolicy::client_local(Vec::new()), false),
            (DeferredToolPolicy::openai_hosted(Vec::new()), true),
            (DeferredToolPolicy::openai_hosted(vec![tools::RECORD_DECISION.to_string()]), false),
        ] {
            let definitions = registry.model_tools(config.clone().with_deferred_tool_policy(policy)).await;
            let decision = definitions
                .iter()
                .find(|tool| tool.function_name() == tools::RECORD_DECISION)
                .expect("decision definition");
            assert_eq!(decision.defer_loading == Some(true), deferred, "planning={planning}");
        }
    }
}

/// End-to-end regression for the first-request token budget: the actual
/// builtin tool schemas sent in Progressive mode must fit in a small
/// token envelope, leaving room for the system prompt and conversation.
///
/// Measured through `ToolRegistry`, which applies the deferred-loading policy
/// and the runtime access gates. The earlier version measured a catalog built
/// straight from the test mirror, which has no access gates: it happened to
/// land on the same number only because the mirror never declares `matrix`,
/// the 911-token schema a default session is stripped of anyway.
#[tokio::test]
async fn emitted_model_tool_schema_fits_within_first_request_budget() {
    use crate::config::ToolDocumentationMode;
    use crate::tools::handlers::{SessionSurface, SessionToolsConfig, ToolModelCapabilities};

    let temp = tempfile::tempdir().unwrap();
    let registry = ToolRegistry::new_for_schema(temp.path().to_path_buf()).await;

    use serde::Serialize;

    #[derive(Serialize)]
    struct ToolSchemaEstimate<'a> {
        name: &'a str,
        description: &'a str,
        parameters: &'a serde_json::Value,
    }

    let config = SessionToolsConfig::full_public(
        SessionSurface::Interactive,
        CapabilityLevel::CodeSearch,
        ToolDocumentationMode::Progressive,
        ToolModelCapabilities::default(),
    );

    let schema_entries = registry.schema_entries(config).await;
    let total_tokens: usize = schema_entries
        .iter()
        .map(|entry| {
            let estimate = ToolSchemaEstimate {
                name: &entry.name,
                description: &entry.description,
                parameters: &entry.parameters,
            };
            serde_json::to_string(&estimate).map(|s| s.len() / 4).unwrap_or(0)
        })
        .sum();

    // Progressive mode sends complete builtin tool descriptions and keeps
    // parameter descriptions (trimming only long tails), because models
    // that follow tool definitions literally act on the whole text. The
    // cap is the harness-tax gate (HarnessTax): keep the emitted schema
    // envelope tight so first-call fixed overhead stays low.
    //
    // Measured 2,470 once `monitor_filter` joined the exec schema. That
    // parameter costs ~73 fixed tokens but removes full-output polls on
    // long quiet commands, so it pays for itself within a single run; the
    // ceiling moves to 2,500 to admit it while keeping the envelope bound.
    // The previous 2,400 cap had drifted to 2,397 measured (3 tokens of
    // headroom), so any new parameter would have failed regardless of how
    // tersely it was documented — raise the cap only with a measured
    // number, never to silence a specific failure.
    assert!(
        total_tokens <= 2_500,
        "emitted model tool schema tokens in Progressive mode is {total_tokens}; expected <= 2_500. \
         This is a harness-tax budget: trim or merge parameter descriptions instead of raising the cap \
         without a measured rationale."
    );
}

/// End-to-end regression for the combined first-request token budget:
/// the effective-default system prompt (Minimal) plus Progressive tool
/// schemas, instruction appendix, and welcome addendum must stay under
/// 6k tokens with no MCP, and under 8k tokens with 5 simulated MCP servers.
#[tokio::test]
async fn first_request_total_token_budget_within_limit() {
    use crate::config::ToolDocumentationMode;
    use crate::config::types::SystemPromptMode;
    use crate::prompts::system::static_profile_prompt;
    use crate::tools::handlers::{SessionSurface, SessionToolsConfig, ToolModelCapabilities};
    use serde::Serialize;

    #[derive(Serialize)]
    struct ToolSchemaEstimate<'a> {
        name: &'a str,
        description: &'a str,
        parameters: &'a serde_json::Value,
    }

    // Measure the shipped catalog through `ToolRegistry`, which applies the
    // deferred-loading policy and the runtime access gates. Building the
    // catalog straight from the test mirror under-reports this budget: the
    // mirror never declares `matrix`, so it happened to land on the same
    // number the gated path produces.
    let temp = tempfile::tempdir().unwrap();
    let registry = ToolRegistry::new_for_schema(temp.path().to_path_buf()).await;
    let config = SessionToolsConfig::full_public(
        SessionSurface::Interactive,
        CapabilityLevel::CodeSearch,
        ToolDocumentationMode::Progressive,
        ToolModelCapabilities::default(),
    );

    let schema_entries = registry.schema_entries(config).await;
    let tool_schema_tokens: usize = schema_entries
        .iter()
        .map(|entry| {
            let estimate = ToolSchemaEstimate {
                name: &entry.name,
                description: &entry.description,
                parameters: &entry.parameters,
            };
            serde_json::to_string(&estimate).map(|s| s.len() / 4).unwrap_or(0)
        })
        .sum();

    // Measure the configured default profile (Minimal after lean-defaults).
    let system_prompt = static_profile_prompt(SystemPromptMode::default());
    let system_prompt_tokens = system_prompt.len() / 4;

    let instruction_appendix_tokens = 250;
    let welcome_addendum_tokens = 200;

    let total_no_mcp =
        system_prompt_tokens + tool_schema_tokens + instruction_appendix_tokens + welcome_addendum_tokens;

    assert!(
        total_no_mcp <= 6_000,
        "first-request token budget exceeded: {total_no_mcp} tokens (system={system_prompt_tokens}, tools={tool_schema_tokens}, instructions={instruction_appendix_tokens}, addendum={welcome_addendum_tokens}); expected <= 6_000"
    );

    let mcp_tool_count = 5;
    let estimated_mcp_schema_tokens = mcp_tool_count * 300;
    let total_with_mcp = total_no_mcp + estimated_mcp_schema_tokens;

    assert!(
        total_with_mcp <= 8_000,
        "first-request token budget with MCP exceeded: {total_with_mcp} tokens; expected <= 8_000"
    );

    // Explicit Default-mode profile must also stay inside the no-MCP
    // ceiling when selected (S2-prompt).
    let default_prompt = static_profile_prompt(SystemPromptMode::Default);
    let total_default_mode =
        default_prompt.len() / 4 + tool_schema_tokens + instruction_appendix_tokens + welcome_addendum_tokens;
    assert!(
        total_default_mode <= 6_000,
        "Default-mode first-request budget exceeded: {total_default_mode} tokens; expected <= 6_000"
    );
}

/// Cache-stability guard: building the same system prompt + Progressive
/// tool schema twice must produce byte-identical output. Any non-determinism
/// (random ordering, uninitialized memory, race) invalidates provider
/// prompt caches and re-pays full input cost on every turn.
///
/// Runs against the shipped catalog. The inventory stores registrations in an
/// `FxHashMap`, so this is exactly where ordering could vary; a catalog built
/// from the test mirror would never exercise that iteration.
#[tokio::test]
async fn system_prompt_and_tools_prefix_is_byte_stable_across_rebuilds() {
    use std::collections::hash_map::DefaultHasher;
    use std::hash::{Hash, Hasher};

    use crate::config::ToolDocumentationMode;
    use crate::prompts::system::default_system_prompt;
    use crate::tools::handlers::{SessionSurface, SessionToolsConfig, ToolModelCapabilities};
    use serde::Serialize;

    #[derive(Serialize)]
    struct ToolSchemaEstimate<'a> {
        name: &'a str,
        description: &'a str,
        parameters: &'a serde_json::Value,
    }

    async fn hash_system_prompt_and_tools() -> u64 {
        let mut hasher = DefaultHasher::new();

        let system_prompt = default_system_prompt();
        system_prompt.hash(&mut hasher);

        let temp = tempfile::tempdir().expect("workspace tempdir");
        let registry = ToolRegistry::new_for_schema(temp.path().to_path_buf()).await;
        let config = SessionToolsConfig::full_public(
            SessionSurface::Interactive,
            CapabilityLevel::CodeSearch,
            ToolDocumentationMode::Progressive,
            ToolModelCapabilities::default(),
        );

        let schema_entries = registry.schema_entries(config).await;
        for entry in &schema_entries {
            let estimate = ToolSchemaEstimate {
                name: &entry.name,
                description: &entry.description,
                parameters: &entry.parameters,
            };
            if let Ok(json) = serde_json::to_string(&estimate) {
                json.hash(&mut hasher);
            }
        }

        hasher.finish()
    }

    let hash1 = hash_system_prompt_and_tools().await;
    let hash2 = hash_system_prompt_and_tools().await;

    assert_eq!(hash1, hash2, "system prompt + tool schema prefix is not byte-stable across rebuilds");
}