perspt-core 0.6.6

Core types and LLM provider abstraction for Perspt
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
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
//! Configuration types for Perspt.
//!
//! The on-disk configuration is TOML. Every field is optional so that a missing
//! or partial config file never errors; effective values are computed by merging
//! the file with environment-based detection and built-in defaults.

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use perspt_sdk::{EffectKind, FootprintSpec, ProposalBinding, RiskClass};

/// Placeholder shown instead of a real API key in `config --show`.
const MASKED_API_KEY: &str = "***";

/// One entry of the `[providers.<id>]` table (PSP-9 system 1).
///
/// A provider record describes *resolution policy*, not embedded secrets:
/// `api_key_env` names an environment variable; a literal `api_key` is
/// accepted for local development but masked on display. Vertex entries may
/// omit a static key entirely and use the per-request ADC token resolver.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct ProviderEntry {
    /// genai adapter kind. Defaults to the table key, so
    /// `[providers.anthropic]` needs no explicit adapter while
    /// `[providers.local]` can say `adapter = "ollama"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub adapter: Option<String>,
    /// Environment variable holding the API key.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub api_key_env: Option<String>,
    /// Literal API key. Prefer `api_key_env`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub api_key: Option<String>,
    /// Base URL override for OpenAI-compatible / local endpoints.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub base_url: Option<String>,
    /// Google Cloud project id (Vertex only; ADC discovery when absent).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub project_id: Option<String>,
    /// Vertex location; defaults to `global` via the existing resolver.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub location: Option<String>,
}

impl ProviderEntry {
    /// The adapter this entry binds, defaulting to the table key.
    pub fn adapter_or<'a>(&'a self, key: &'a str) -> &'a str {
        self.adapter.as_deref().unwrap_or(key)
    }
}

/// The `[models]` table: fully qualified `provider::model` route values per
/// tier (PSP-9 system 1). Values stay fully qualified so identity,
/// calibration, and replay never depend on an ambient default provider.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct ModelsConfig {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub architect: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub actuator: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub verifier: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub speculator: Option<String>,
    /// Optional adjudication route (PSP-9 system 8).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub adjudicator: Option<String>,
    /// Hard wall-clock deadline for one model turn, in seconds (default
    /// 120). A turn that exceeds it is an ordinary transport failure: it
    /// consumes sticky failover instead of hanging the session.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub turn_timeout_secs: Option<u64>,
}

/// Product surface allowed to create a lifecycle for an external server.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ExternalToolMode {
    Agent,
    Chat,
}

fn default_external_modes() -> Vec<ExternalToolMode> {
    vec![ExternalToolMode::Agent]
}

/// MCP transports supported by Perspt 0.6.6.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ExternalToolTransport {
    Stdio,
    StreamableHttp,
}

fn default_external_timeout_ms() -> u64 {
    30_000
}

fn default_external_result_bytes() -> usize {
    1_048_576
}

fn default_external_stderr_bytes() -> usize {
    65_536
}

fn default_subscriptions() -> bool {
    true
}

fn default_tasks() -> bool {
    true
}

fn default_task_wait_ms() -> u64 {
    300_000
}

fn default_sampling_tokens() -> u32 {
    4096
}

/// One filesystem root that an MCP server may learn through ``roots/list``.
/// Roots are never inferred: each URI is an explicit disclosure boundary.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct McpRootConfig {
    pub uri: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
}

/// Locally trusted governance declaration for one discovered remote tool.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct ExternalToolPolicy {
    /// Omission fails closed to `RunShell`.
    pub effect: Option<EffectKind>,
    pub risk: Option<RiskClass>,
    /// Omission fails closed to an opaque workspace footprint.
    pub footprint: Option<FootprintSpec>,
    pub proposal_bindings: Vec<ProposalBinding>,
}

/// One `[[external_tools]]` server. Secret values are never stored here:
/// environment maps contain destination/header names and source variable names.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ExternalToolConfig {
    pub id: String,
    pub transport: ExternalToolTransport,
    /// Direct argv. Element zero is the program; no shell parsing occurs.
    pub command: Vec<String>,
    pub url: Option<String>,
    /// Child variable -> source environment variable, for stdio servers.
    pub env_from_env: BTreeMap<String, String>,
    /// HTTP header -> source environment variable.
    pub headers_from_env: BTreeMap<String, String>,
    #[serde(default = "default_external_timeout_ms")]
    pub timeout_ms: u64,
    #[serde(default = "default_external_result_bytes")]
    pub max_result_bytes: usize,
    #[serde(default = "default_external_stderr_bytes")]
    pub max_stderr_bytes: usize,
    #[serde(default = "default_external_modes")]
    pub modes: Vec<ExternalToolMode>,
    /// Explicit roots returned to server-initiated ``roots/list`` requests.
    /// An empty list means that the roots capability is not advertised.
    pub roots: Vec<McpRootConfig>,
    /// Allow server-initiated model sampling. This is opt-in because it spends
    /// the configured provider's model budget.
    pub sampling: bool,
    /// Allow server-initiated elicitation. A product surface must also install
    /// an interactive handler; otherwise connection fails closed.
    pub elicitation: bool,
    /// Open the MCP 2026-07-28 ``subscriptions/listen`` stream for advertised
    /// list-change notifications and the resource URIs below.
    #[serde(default = "default_subscriptions")]
    pub subscriptions: bool,
    pub resource_subscriptions: Vec<String>,
    /// Advertise and drive the official tasks extension for long-running calls.
    #[serde(default = "default_tasks")]
    pub tasks: bool,
    /// Overall deadline for one asynchronous MCP task, across every poll and
    /// input-required round. Individual requests still use ``timeout_ms``.
    #[serde(default = "default_task_wait_ms")]
    pub max_task_wait_ms: u64,
    /// Local upper bound on a server sampling request.
    #[serde(default = "default_sampling_tokens")]
    pub max_sampling_tokens: u32,
    pub tools: BTreeMap<String, ExternalToolPolicy>,
}

impl Default for ExternalToolConfig {
    fn default() -> Self {
        Self {
            id: String::new(),
            transport: ExternalToolTransport::Stdio,
            command: Vec::new(),
            url: None,
            env_from_env: BTreeMap::new(),
            headers_from_env: BTreeMap::new(),
            timeout_ms: default_external_timeout_ms(),
            max_result_bytes: default_external_result_bytes(),
            max_stderr_bytes: default_external_stderr_bytes(),
            modes: default_external_modes(),
            roots: Vec::new(),
            sampling: false,
            elicitation: false,
            subscriptions: default_subscriptions(),
            resource_subscriptions: Vec::new(),
            tasks: default_tasks(),
            max_task_wait_ms: default_task_wait_ms(),
            max_sampling_tokens: default_sampling_tokens(),
            tools: BTreeMap::new(),
        }
    }
}

impl ExternalToolConfig {
    pub fn supports(&self, mode: ExternalToolMode) -> bool {
        self.modes.contains(&mode)
    }

    fn validate(&self) -> Result<()> {
        anyhow::ensure!(
            !self.id.is_empty()
                && self.id.chars().all(|character| {
                    character.is_ascii_alphanumeric() || matches!(character, '-' | '_')
                }),
            "external tool server id {:?} must contain only ASCII letters, digits, '-' or '_'",
            self.id
        );
        anyhow::ensure!(
            self.timeout_ms > 0,
            "external tool {:?}: timeout_ms must be positive",
            self.id
        );
        anyhow::ensure!(
            self.max_result_bytes > 0 && self.max_stderr_bytes > 0,
            "external tool {:?}: result and stderr caps must be positive",
            self.id
        );
        self.validate_mcp()?;
        anyhow::ensure!(
            !self.modes.is_empty(),
            "external tool {:?}: modes cannot be empty",
            self.id
        );
        let unique_modes: std::collections::BTreeSet<_> =
            self.modes.iter().map(|mode| format!("{mode:?}")).collect();
        anyhow::ensure!(
            unique_modes.len() == self.modes.len(),
            "external tool {:?}: duplicate mode",
            self.id
        );
        match self.transport {
            ExternalToolTransport::Stdio => anyhow::ensure!(
                !self.command.is_empty() && self.url.is_none(),
                "external tool {:?}: stdio requires command argv and forbids url",
                self.id
            ),
            ExternalToolTransport::StreamableHttp => anyhow::ensure!(
                self.command.is_empty() && self.url.is_some(),
                "external tool {:?}: Streamable HTTP requires url and forbids command",
                self.id
            ),
        }
        Ok(())
    }

    fn validate_mcp(&self) -> Result<()> {
        anyhow::ensure!(
            self.max_sampling_tokens > 0,
            "external tool {:?}: max_sampling_tokens must be positive",
            self.id
        );
        anyhow::ensure!(
            self.max_task_wait_ms > 0,
            "external tool {:?}: max_task_wait_ms must be positive",
            self.id
        );
        for root in &self.roots {
            let uri = url::Url::parse(&root.uri)
                .with_context(|| format!("external tool {:?}: invalid MCP root URI", self.id))?;
            anyhow::ensure!(
                uri.scheme() == "file" && uri.path().starts_with('/'),
                "external tool {:?}: MCP roots must be absolute file:// URIs",
                self.id
            );
        }
        for uri in &self.resource_subscriptions {
            anyhow::ensure!(
                url::Url::parse(uri).is_ok(),
                "external tool {:?}: invalid resource subscription URI {uri:?}",
                self.id
            );
        }
        Ok(())
    }
}

/// Main configuration struct.
///
/// All fields are optional. Documented aliases are accepted on load so that
/// older field names keep working (`provider_type`, `default_provider`,
/// `default_model`).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct Config {
    /// Provider id, e.g. `openai`, `anthropic`, `gemini`, `vertex`, `ollama`.
    #[serde(
        alias = "provider_type",
        alias = "default_provider",
        skip_serializing_if = "Option::is_none"
    )]
    pub provider: Option<String>,

    /// Default chat/simple-chat model.
    #[serde(alias = "default_model", skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,

    /// API key for the configured provider. Optional; may also come from env.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub api_key: Option<String>,

    /// Optional base URL override for OpenAI-compatible / local endpoints.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub base_url: Option<String>,

    /// Google Cloud project id for Vertex AI. Optional; may also come from
    /// `VERTEX_PROJECT_ID` or Google Cloud project environment variables.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub vertex_project_id: Option<String>,

    /// Vertex AI location. Optional; may also come from `VERTEX_LOCATION`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub vertex_location: Option<String>,

    /// Preferred package manager for greenfield project init. Optional and
    /// fully plugin-driven: the active language plugin maps it to its own init
    /// command and default (e.g. Python → `uv`, JS → `npm`). Unknown values fall
    /// back to each plugin's default. Examples: `uv`, `poetry`, `pdm`, `pipenv`
    /// (Python); `pnpm`, `yarn` (JS).
    #[serde(
        skip_serializing_if = "Option::is_none",
        alias = "python_package_manager"
    )]
    pub package_manager: Option<String>,

    /// Agent Architect-tier model override.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub architect_model: Option<String>,

    /// Agent Actuator-tier model override.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub actuator_model: Option<String>,

    /// Agent Verifier-tier model override.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub verifier_model: Option<String>,

    /// Agent Speculator-tier model override.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub speculator_model: Option<String>,

    /// The `[providers.<id>]` table: several credentials coexisting in one
    /// process (PSP-9 system 1). Empty for single-provider configurations,
    /// which continue to use the flat fields above.
    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
    pub providers: BTreeMap<String, ProviderEntry>,

    /// The `[models]` table: per-tier fully qualified `provider::model`
    /// routes. When present it takes precedence over the flat
    /// `*_model` fields.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub models: Option<ModelsConfig>,

    /// Shared MCP server configuration. Omitted modes default to agent-only.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub external_tools: Vec<ExternalToolConfig>,

    /// Detector for the removed PSP-9 `[ensemble]` block. Deserialization
    /// only: a present block fails validation with a pointed migration
    /// error naming `[exploration]` (PSP-10 cutover), never a silent
    /// ignore.
    #[serde(default, skip_serializing)]
    pub ensemble: Option<toml::Value>,

    /// Verification acceptance-stage options (`[verification]`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub verification: Option<VerificationConfig>,

    /// Bounded search configuration (`[exploration]`; PSP-10 system 20).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub exploration: Option<ExplorationConfig>,

    /// Prompt bundles and activation bounds (`[prompts]`; PSP-10
    /// system 25).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub prompts: Option<PromptsConfig>,

    /// Resident-context reserves (`[context]`; PSP-10 Definition 6).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub context: Option<ContextConfig>,
}

/// The `[context]` block (PSP-10 Definition 6): reserves and working-set
/// bounds for the paged resident context.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct ContextConfig {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub working_set_turns: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub synopsis_frame_tokens: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output_reserve_tokens: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub guard_reserve_tokens: Option<u64>,
}

impl ContextConfig {
    /// Startup validation: every configured reserve must be positive.
    pub fn validate(&self) -> Result<()> {
        for (name, value) in [
            ("working_set_turns", self.working_set_turns.map(u64::from)),
            ("synopsis_frame_tokens", self.synopsis_frame_tokens),
            ("output_reserve_tokens", self.output_reserve_tokens),
            ("guard_reserve_tokens", self.guard_reserve_tokens),
        ] {
            if value == Some(0) {
                anyhow::bail!("[context] {name} must be positive");
            }
        }
        Ok(())
    }
}

/// The `[verification]` acceptance-stage options.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct VerificationConfig {
    /// Permit verifier, inspection, and LSP processes to run without an OS
    /// sandbox when the current platform has no registered backend. This is
    /// an explicit reduced-isolation mode; false by default.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub allow_unisolated: Option<bool>,
    /// How project tests contribute to acceptance. `evolving` is the normal
    /// development policy: the resulting code, tests, and configuration are
    /// verified together. Stronger policies are explicit because historical
    /// tests are not universally valid after an intentional contract change.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub test_policy: Option<TestPolicy>,
    /// Protected acceptance material used only by `external-oracle`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub external_oracle: Option<ExternalOracleConfig>,
    /// Declare the plugin `format` verifier stage (e.g. `cargo fmt --check`)
    /// as an acceptance sensor. Off by default.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub require_format: Option<bool>,
    /// Wall-clock limit for every governed verifier stage (default 180).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stage_timeout_secs: Option<u64>,
    /// Per-stage overrides of `stage_timeout_secs`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub syntax_timeout_secs: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub build_timeout_secs: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub test_timeout_secs: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub lint_timeout_secs: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub format_timeout_secs: Option<u64>,
}

impl VerificationConfig {
    pub fn validate(&self) -> Result<()> {
        for (name, value) in [
            ("stage_timeout_secs", self.stage_timeout_secs),
            ("syntax_timeout_secs", self.syntax_timeout_secs),
            ("build_timeout_secs", self.build_timeout_secs),
            ("test_timeout_secs", self.test_timeout_secs),
            ("lint_timeout_secs", self.lint_timeout_secs),
            ("format_timeout_secs", self.format_timeout_secs),
        ] {
            if value == Some(0) {
                anyhow::bail!("[verification] {name} must be positive");
            }
        }
        match (self.test_policy.unwrap_or_default(), &self.external_oracle) {
            (TestPolicy::ExternalOracle, Some(oracle)) => oracle.validate()?,
            (TestPolicy::ExternalOracle, None) => anyhow::bail!(
                "[verification] test_policy = \"external-oracle\" requires \
                 [verification.external_oracle]"
            ),
            (_, Some(_)) => anyhow::bail!(
                "[verification.external_oracle] requires \
                 test_policy = \"external-oracle\""
            ),
            (_, None) => {}
        }
        Ok(())
    }
}

/// Test-evidence policy at a coding gate.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum TestPolicy {
    /// Verify the resulting implementation, tests, and project configuration.
    /// Tests are ordinary mutable project artifacts.
    #[default]
    Evolving,
    /// In addition to the resulting suite, run recognized pre-existing test
    /// files against the candidate implementation. Intended only for tasks
    /// that promise backward compatibility.
    BackwardCompatible,
    /// In addition to the resulting suite, overlay separately supplied,
    /// protected acceptance material and run its configured command.
    ExternalOracle,
}

impl TestPolicy {
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Evolving => "evolving",
            Self::BackwardCompatible => "backward-compatible",
            Self::ExternalOracle => "external-oracle",
        }
    }
}

/// Protected files and command for `TestPolicy::ExternalOracle`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExternalOracleConfig {
    /// Directory overlaid onto a private copy of the candidate only at the
    /// acceptance boundary. It may contain tests, manifests, or harness code.
    pub path: PathBuf,
    /// Command executed from the root of that private verification copy.
    pub command: String,
}

impl ExternalOracleConfig {
    fn validate(&self) -> Result<()> {
        anyhow::ensure!(
            !self.path.as_os_str().is_empty(),
            "[verification.external_oracle] path must not be empty"
        );
        anyhow::ensure!(
            !self.command.trim().is_empty(),
            "[verification.external_oracle] command must not be empty"
        );
        Ok(())
    }
}

/// The `[exploration]` search block (PSP-10 system 20). Sequential eager
/// branches only; the hard branch cap is 3 for this release.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct ExplorationConfig {
    /// Branches opened before any expansion trigger (default 1).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub initial_branches: Option<u8>,
    /// Branch identities per forest, children included (hard cap 3).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_branches: Option<u8>,
    /// Prefer a distinct model family on expansion (a prior, never a
    /// certificate).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub distinct_family: Option<bool>,
    /// Cumulative eager-copy file reservation cap.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_workspace_files: Option<u64>,
    /// Cumulative eager-copy byte reservation cap.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_workspace_bytes: Option<u64>,
}

impl ExplorationConfig {
    /// Validate the branch bounds (PSP-10: at most three branches, at
    /// least one).
    pub fn validate(&self) -> Result<()> {
        let initial = self.initial_branches.unwrap_or(1);
        let max = self.max_branches.unwrap_or(3);
        anyhow::ensure!(
            (1..=3).contains(&max),
            "[exploration] max_branches must be between 1 and 3 (got {max})"
        );
        anyhow::ensure!(
            initial >= 1 && initial <= max,
            "[exploration] initial_branches must be between 1 and max_branches"
        );
        Ok(())
    }
}

/// The `[prompts]` block (PSP-10 system 25, Gate AE). The activation floor
/// may only be raised and the margin narrowed; invalid values fail at
/// startup.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct PromptsConfig {
    /// External replacement bundle directories, pinned at session start.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub bundles: Vec<String>,
    /// Minimum paired activation tasks (floor 30; raise-only).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub activation_min_tasks: Option<u32>,
    /// Noninferiority margin epsilon in [0, 0.05].
    #[serde(skip_serializing_if = "Option::is_none")]
    pub noninferiority_margin: Option<f64>,
}

impl PromptsConfig {
    /// The activation bounds after startup validation.
    pub fn activation_bounds(&self) -> Result<perspt_sdk::prompt::ActivationBounds> {
        let bounds = perspt_sdk::prompt::ActivationBounds {
            min_tasks: self.activation_min_tasks.unwrap_or(30),
            noninferiority_margin: self.noninferiority_margin.unwrap_or(0.05),
        };
        bounds
            .validate()
            .map_err(|e| anyhow::anyhow!("[prompts]: {e}"))?;
        Ok(bounds)
    }
}

impl Config {
    /// Parse a `Config` from a TOML string. A partial document is valid.
    pub fn from_toml_str(content: &str) -> Result<Self> {
        let config: Self = toml::from_str(content).context("Failed to parse TOML configuration")?;
        config.validate()?;
        Ok(config)
    }

    /// Load a `Config` from a file path. Returns `Config::default()` when the
    /// file does not exist, so callers can always work with effective values.
    pub fn load_from_path(path: &Path) -> Result<Self> {
        if !path.exists() {
            return Ok(Self::default());
        }
        let content = std::fs::read_to_string(path)
            .with_context(|| format!("Failed to read config file: {}", path.display()))?;
        Self::from_toml_str(&content)
    }

    /// Serialize this config to a TOML string.
    pub fn to_toml_string(&self) -> Result<String> {
        toml::to_string_pretty(self).context("Failed to serialize configuration to TOML")
    }

    /// Return a clone with the API key masked, for display purposes.
    pub fn masked(&self) -> Self {
        let mut clone = self.clone();
        if clone.api_key.is_some() {
            clone.api_key = Some(MASKED_API_KEY.to_string());
        }
        for entry in clone.providers.values_mut() {
            if entry.api_key.is_some() {
                entry.api_key = Some(MASKED_API_KEY.to_string());
            }
        }
        clone
    }

    pub fn validate(&self) -> Result<()> {
        anyhow::ensure!(
            self.ensemble.is_none(),
            "the [ensemble] section was removed by PSP-10: the ensemble is replaced \
             by the bounded search forest. Configure [exploration] instead \
             (initial_branches, max_branches, distinct_family) and delete [ensemble]."
        );
        if let Some(exploration) = &self.exploration {
            exploration.validate()?;
        }
        if let Some(prompts) = &self.prompts {
            prompts.activation_bounds()?;
        }
        if self.models.as_ref().and_then(|m| m.turn_timeout_secs) == Some(0) {
            anyhow::bail!("[models] turn_timeout_secs must be positive");
        }
        if let Some(context) = &self.context {
            context.validate()?;
        }
        if let Some(verification) = &self.verification {
            verification.validate()?;
        }
        let mut server_ids = std::collections::BTreeSet::new();
        for server in &self.external_tools {
            server.validate()?;
            anyhow::ensure!(
                server_ids.insert(server.id.as_str()),
                "duplicate external tool server id {:?}",
                server.id
            );
        }
        Ok(())
    }

    /// Set a single key to a string value, used by `config --set`.
    ///
    /// Returns an error for unknown keys so typos surface immediately.
    pub fn set_value(&mut self, key: &str, value: &str) -> Result<()> {
        let value = value.to_string();
        match key {
            "provider" | "provider_type" | "default_provider" => self.provider = Some(value),
            "model" | "default_model" => self.model = Some(value),
            "api_key" => self.api_key = Some(value),
            "base_url" => self.base_url = Some(value),
            "vertex_project_id" => self.vertex_project_id = Some(value),
            "vertex_location" => self.vertex_location = Some(value),
            "architect_model" => self.architect_model = Some(value),
            "actuator_model" => self.actuator_model = Some(value),
            "verifier_model" => self.verifier_model = Some(value),
            "speculator_model" => self.speculator_model = Some(value),
            "package_manager" | "python_package_manager" => self.package_manager = Some(value),
            other => anyhow::bail!(
                "Unknown configuration key: {other}. Valid keys: provider, model, api_key, \
                 base_url, vertex_project_id, vertex_location, architect_model, actuator_model, \
                 verifier_model, speculator_model, package_manager"
            ),
        }
        Ok(())
    }
}

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

    #[test]
    fn empty_string_parses_to_defaults() {
        let cfg = Config::from_toml_str("").unwrap();
        assert!(cfg.provider.is_none());
        assert!(cfg.model.is_none());
        assert!(cfg.api_key.is_none());
    }

    #[test]
    fn test_evidence_policies_parse_and_evolving_is_the_default() {
        assert_eq!(TestPolicy::default(), TestPolicy::Evolving);
        let cfg = Config::from_toml_str(
            r#"
            [verification]
            test_policy = "external-oracle"

            [verification.external_oracle]
            path = "/trusted/acceptance"
            command = "cargo test --test acceptance"
            "#,
        )
        .unwrap();
        let verification = cfg.verification.unwrap();
        assert_eq!(verification.test_policy, Some(TestPolicy::ExternalOracle));
        assert_eq!(
            verification.external_oracle.unwrap().command,
            "cargo test --test acceptance"
        );
    }

    #[test]
    fn external_oracle_configuration_is_never_silently_ignored() {
        let missing = Config::from_toml_str(
            r#"
            [verification]
            test_policy = "external-oracle"
            "#,
        )
        .unwrap_err();
        assert!(missing.to_string().contains("external_oracle"));

        let inactive = Config::from_toml_str(
            r#"
            [verification]
            test_policy = "evolving"

            [verification.external_oracle]
            path = "/trusted/acceptance"
            command = "cargo test"
            "#,
        )
        .unwrap_err();
        assert!(inactive.to_string().contains("external-oracle"));
    }

    #[test]
    fn package_manager_set_value_and_alias() {
        let mut cfg = Config::default();
        cfg.set_value("package_manager", "poetry").unwrap();
        assert_eq!(cfg.package_manager.as_deref(), Some("poetry"));
        // The python-specific key is accepted as an alias for clarity.
        let mut cfg2 = Config::default();
        cfg2.set_value("python_package_manager", "pdm").unwrap();
        assert_eq!(cfg2.package_manager.as_deref(), Some("pdm"));
    }

    #[test]
    fn aliases_are_accepted() {
        let cfg = Config::from_toml_str(
            r#"
            provider_type = "openai"
            default_model = "phi-4-npu-ov"
            "#,
        )
        .unwrap();
        assert_eq!(cfg.provider.as_deref(), Some("openai"));
        assert_eq!(cfg.model.as_deref(), Some("phi-4-npu-ov"));
    }

    #[test]
    fn missing_file_returns_default() {
        let path = Path::new("/nonexistent/perspt/config.toml");
        let cfg = Config::load_from_path(path).unwrap();
        assert!(cfg.provider.is_none());
    }

    #[test]
    fn masked_hides_api_key() {
        let cfg = Config {
            api_key: Some("super-secret".to_string()),
            ..Default::default()
        };
        assert_eq!(cfg.masked().api_key.as_deref(), Some("***"));
    }

    #[test]
    fn masked_leaves_absent_key_absent() {
        let cfg = Config::default();
        assert!(cfg.masked().api_key.is_none());
    }

    #[test]
    fn set_value_updates_known_keys() {
        let mut cfg = Config::default();
        cfg.set_value("default_model", "phi-4-npu-ov").unwrap();
        assert_eq!(cfg.model.as_deref(), Some("phi-4-npu-ov"));
        cfg.set_value("provider", "openai").unwrap();
        assert_eq!(cfg.provider.as_deref(), Some("openai"));
        cfg.set_value("vertex_project_id", "test-project").unwrap();
        cfg.set_value("vertex_location", "test-location").unwrap();
        assert_eq!(cfg.vertex_project_id.as_deref(), Some("test-project"));
        assert_eq!(cfg.vertex_location.as_deref(), Some("test-location"));
    }

    #[test]
    fn providers_table_parses_with_defaulted_adapter() {
        let cfg = Config::from_toml_str(
            r#"
            [providers.anthropic]
            api_key_env = "ANTHROPIC_API_KEY"

            [providers.local]
            adapter  = "ollama"
            base_url = "http://localhost:11434"

            [models]
            architect = "anthropic::claude-opus-5"
            speculator = "local::qwen2.5-coder"
            "#,
        )
        .unwrap();
        assert_eq!(cfg.providers.len(), 2);
        let anthropic = &cfg.providers["anthropic"];
        assert_eq!(anthropic.adapter_or("anthropic"), "anthropic");
        assert_eq!(anthropic.api_key_env.as_deref(), Some("ANTHROPIC_API_KEY"));
        let local = &cfg.providers["local"];
        assert_eq!(local.adapter_or("local"), "ollama");
        let models = cfg.models.unwrap();
        assert_eq!(
            models.architect.as_deref(),
            Some("anthropic::claude-opus-5")
        );
        assert_eq!(models.adjudicator, None);
    }

    #[test]
    fn masked_hides_provider_table_keys_too() {
        let cfg = Config::from_toml_str(
            r#"
            [providers.openai]
            api_key = "sk-super-secret"
            "#,
        )
        .unwrap();
        assert_eq!(
            cfg.masked().providers["openai"].api_key.as_deref(),
            Some("***")
        );
    }

    #[test]
    fn flat_config_still_parses_without_tables() {
        let cfg = Config::from_toml_str("provider = \"openai\"\n").unwrap();
        assert!(cfg.providers.is_empty());
        assert!(cfg.models.is_none());
    }

    #[test]
    fn set_value_rejects_unknown_key() {
        let mut cfg = Config::default();
        assert!(cfg.set_value("nope", "x").is_err());
    }

    #[test]
    fn round_trip_set_does_not_duplicate() {
        let mut cfg = Config::default();
        cfg.set_value("default_model", "a").unwrap();
        cfg.set_value("default_model", "b").unwrap();
        let serialized = cfg.to_toml_string().unwrap();
        // Exactly one model line after two sets.
        assert_eq!(serialized.matches("model").count(), 1);
        let reparsed = Config::from_toml_str(&serialized).unwrap();
        assert_eq!(reparsed.model.as_deref(), Some("b"));
    }

    #[test]
    fn external_tools_default_to_agent_only() {
        let config = Config::from_toml_str(
            r#"
            [[external_tools]]
            id = "local-search"
            transport = "stdio"
            command = ["search-server", "--stdio"]
            "#,
        )
        .unwrap();
        let server = &config.external_tools[0];
        assert!(server.supports(ExternalToolMode::Agent));
        assert!(!server.supports(ExternalToolMode::Chat));
    }

    #[test]
    fn external_tool_modes_and_local_policy_parse() {
        let config = Config::from_toml_str(
            r#"
            [[external_tools]]
            id = "records"
            transport = "streamable_http"
            url = "https://tools.example.test/mcp"
            modes = ["agent", "chat"]
            headers_from_env = { Authorization = "RECORDS_AUTH" }

            [external_tools.tools.lookup]
            effect = "data_read"
            risk = "low"
            "#,
        )
        .unwrap();
        let server = &config.external_tools[0];
        assert!(server.supports(ExternalToolMode::Agent));
        assert!(server.supports(ExternalToolMode::Chat));
        assert_eq!(server.tools["lookup"].effect, Some(EffectKind::DataRead));
    }

    #[test]
    fn mcp_options_validate() {
        let config = Config::from_toml_str(
            r#"
            [[external_tools]]
            id = "complete"
            transport = "stdio"
            command = ["server"]
            sampling = true
            elicitation = true
            subscriptions = true
            resource_subscriptions = ["file:///workspace/guide.md"]
            tasks = true
            max_sampling_tokens = 2048
            max_task_wait_ms = 45000
            roots = [{ uri = "file:///workspace", name = "Project" }]
            "#,
        )
        .unwrap();
        let server = &config.external_tools[0];
        assert!(server.sampling && server.elicitation && server.subscriptions && server.tasks);
        assert_eq!(server.roots[0].name.as_deref(), Some("Project"));
        assert_eq!(server.max_task_wait_ms, 45_000);
    }

    #[test]
    fn invalid_mcp_config_is_rejected() {
        assert!(Config::from_toml_str(
            r#"
            [[external_tools]]
            id = "legacy"
            transport = "http"
            url = "https://example.test/mcp"
            "#,
        )
        .is_err());
        assert!(Config::from_toml_str(
            r#"
            [[external_tools]]
            id = "bad-root"
            transport = "stdio"
            command = ["server"]
            roots = [{ uri = "https://example.test/not-a-root" }]
            "#,
        )
        .is_err());
        assert!(Config::from_toml_str(
            r#"
            [[external_tools]]
            id = "bad-task-bound"
            transport = "stdio"
            command = ["server"]
            max_task_wait_ms = 0
            "#,
        )
        .is_err());
    }

    #[test]
    fn duplicate_external_server_ids_are_rejected() {
        let invalid = r#"
            [[external_tools]]
            id = "same"
            transport = "stdio"
            command = ["one"]

            [[external_tools]]
            id = "same"
            transport = "stdio"
            command = ["two"]
        "#;
        assert!(Config::from_toml_str(invalid).is_err());
    }
}

#[cfg(test)]
mod psp10_config_tests {
    use super::*;

    #[test]
    fn a_present_ensemble_block_fails_with_a_pointed_migration_error() {
        let error = Config::from_toml_str("[ensemble]\nwidth = 2\n").unwrap_err();
        let message = format!("{error:#}");
        assert!(message.contains("[exploration]"), "{message}");
        assert!(message.contains("PSP-10"), "{message}");
    }

    #[test]
    fn exploration_bounds_are_enforced_at_startup() {
        assert!(Config::from_toml_str("[exploration]\nmax_branches = 4\n").is_err());
        assert!(Config::from_toml_str("[exploration]\ninitial_branches = 0\n").is_err());
        let config =
            Config::from_toml_str("[exploration]\ninitial_branches = 1\nmax_branches = 3\n")
                .unwrap();
        config.exploration.unwrap().validate().unwrap();
    }

    #[test]
    fn prompt_activation_bounds_are_floor_and_range_checked() {
        assert!(Config::from_toml_str("[prompts]\nactivation_min_tasks = 29\n").is_err());
        assert!(Config::from_toml_str("[prompts]\nnoninferiority_margin = 0.06\n").is_err());
        let config = Config::from_toml_str(
            "[prompts]\nactivation_min_tasks = 40\nnoninferiority_margin = 0.01\n",
        )
        .unwrap();
        let bounds = config.prompts.unwrap().activation_bounds().unwrap();
        assert_eq!(bounds.min_tasks, 40);
    }
}