tambo 0.6.4

Install and prove the whole AI knowledge-tool kit
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
use std::{
    collections::BTreeMap,
    fs,
    path::{Path, PathBuf},
};

use anyhow::{bail, Context, Result};
use serde::{Deserialize, Serialize};

pub const SCHEMA_VERSION: u32 = 1;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Profile {
    Kg,
    Retrieval,
    CodeIntel,
    Crew,
    Everything,
}

impl Profile {
    /// Every tool a NEW plan for this profile selects: the built-ins, then the
    /// embedded stack members that declare this profile, in name order.
    pub fn tools(self) -> Vec<ToolName> {
        let mut tools = self.builtin_tools();
        tools.extend(self.members());
        tools
    }

    /// Whether `tools` is a valid selection for this profile: the built-ins
    /// exactly, then any members of this profile in name order. A selection
    /// saved before a member existed stays valid after an upgrade adds one
    /// (wu M1, aegis-1i5h1j); an undeclared, duplicate or out-of-order member
    /// is refused.
    pub fn accepts(self, tools: &[ToolName]) -> bool {
        let builtins = self.builtin_tools();
        let members = self.members();
        let (head, tail) = tools.split_at(tools.len().min(builtins.len()));
        let mut allowed = members.iter();
        head == builtins.as_slice() && tail.iter().all(|t| allowed.any(|m| m == t))
    }

    /// Members declaring this profile, in name order.
    pub fn members(self) -> Vec<ToolName> {
        crate::members::all()
            .iter()
            .filter(|m| m.profiles.contains(&self))
            .map(|m| ToolName::Member(m.name.as_str()))
            .collect()
    }

    /// The built-in tools of this profile, which every plan for it must list.
    pub fn builtin_tools(self) -> Vec<ToolName> {
        match self {
            Self::Kg => vec![ToolName::Quipu, ToolName::Camayoc],
            Self::Retrieval => vec![ToolName::Quipu, ToolName::Camayoc, ToolName::Bobbin],
            Self::CodeIntel => vec![
                ToolName::Quipu,
                ToolName::Camayoc,
                ToolName::Bobbin,
                ToolName::Yupana,
            ],
            Self::Crew => vec![ToolName::Quipu, ToolName::Camayoc, ToolName::Bobbin],
            Self::Everything => vec![
                ToolName::Quipu,
                ToolName::Camayoc,
                ToolName::Bobbin,
                ToolName::Yupana,
                ToolName::DesirePath,
            ],
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum CrewMode {
    Shantytown,
    Creel,
    Both,
    Standalone,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum CrewOwner {
    Shantytown,
    Creel,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum CrewRouting {
    SingleOwner,
    ExplicitHandoff,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CrewSelection {
    pub mode: CrewMode,
    pub durable_owner: Option<CrewOwner>,
    pub burst_owner: Option<CrewOwner>,
    pub routing: Option<CrewRouting>,
    pub policy: CrewPolicy,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CrewPolicy {
    pub identity_source: IdentitySource,
    pub model: Option<String>,
    pub tools: Vec<ToolName>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum IdentitySource {
    Quipu,
}

impl CrewPolicy {
    fn standard() -> Self {
        Self {
            identity_source: IdentitySource::Quipu,
            model: None,
            tools: Profile::Crew.tools(),
        }
    }

    fn validate(&self) -> Result<()> {
        if !Profile::Crew.accepts(&self.tools) {
            bail!("crew policy tools must match the crew profile conventions");
        }
        if self
            .model
            .as_ref()
            .is_some_and(|model| model.trim().is_empty())
        {
            bail!("crew policy model must be omitted or non-empty");
        }
        Ok(())
    }
}

impl CrewSelection {
    pub fn for_mode(mode: CrewMode) -> Self {
        match mode {
            CrewMode::Shantytown => Self {
                mode,
                durable_owner: Some(CrewOwner::Shantytown),
                burst_owner: None,
                routing: Some(CrewRouting::SingleOwner),
                policy: CrewPolicy::standard(),
            },
            CrewMode::Creel => Self {
                mode,
                durable_owner: None,
                burst_owner: Some(CrewOwner::Creel),
                routing: Some(CrewRouting::SingleOwner),
                policy: CrewPolicy::standard(),
            },
            CrewMode::Both => Self {
                mode,
                durable_owner: Some(CrewOwner::Shantytown),
                burst_owner: Some(CrewOwner::Creel),
                routing: Some(CrewRouting::ExplicitHandoff),
                policy: CrewPolicy::standard(),
            },
            CrewMode::Standalone => Self {
                mode,
                durable_owner: None,
                burst_owner: None,
                routing: None,
                policy: CrewPolicy::standard(),
            },
        }
    }

    fn validate(&self) -> Result<()> {
        let mut expected = Self::for_mode(self.mode);
        expected.policy = self.policy.clone();
        if self != &expected {
            bail!(
                "crew {:?} must use the declared ownership/routing contract; expected {:?}",
                self.mode,
                expected
            );
        }
        self.policy.validate()?;
        Ok(())
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum ToolName {
    Quipu,
    Camayoc,
    Bobbin,
    Yupana,
    DesirePath,
    /// A stack member declared as data (`members/<name>.toml`, aegis-1i5h1j).
    /// Only names embedded in this build exist: deserialising any other name
    /// is refused, exactly as an unknown built-in always was.
    Member(&'static str),
}

impl ToolName {
    /// Every built-in tool. `parse` resolves built-in names from this list and
    /// member validation reserves them from it, so a built-in missing here is
    /// unparseable (its tests fail) rather than silently shadowable (malcolm N2).
    pub const BUILTINS: [ToolName; 5] = [
        Self::Quipu,
        Self::Camayoc,
        Self::Bobbin,
        Self::Yupana,
        Self::DesirePath,
    ];

    pub fn as_str(self) -> &'static str {
        match self {
            Self::Quipu => "quipu",
            Self::Camayoc => "camayoc",
            Self::Bobbin => "bobbin",
            Self::Yupana => "yupana",
            Self::DesirePath => "desire-path",
            Self::Member(name) => name,
        }
    }

    /// The tool called `name`: a built-in, or a member embedded in this build.
    pub fn parse(name: &str) -> Option<Self> {
        if let Some(builtin) = Self::BUILTINS.into_iter().find(|t| t.as_str() == name) {
            return Some(builtin);
        }
        Some(Self::Member(crate::members::get(name)?.name.as_str()))
    }
}

impl Serialize for ToolName {
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        s.serialize_str(self.as_str())
    }
}

impl<'de> Deserialize<'de> for ToolName {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        let name = String::deserialize(d)?;
        Self::parse(&name).ok_or_else(|| {
            serde::de::Error::custom(format!(
                "unknown tool '{name}': neither a built-in tool nor a stack member of this \
                 caboodle build (a member removed since the plan was written, or a plan from \
                 a newer caboodle); re-plan or use the caboodle that wrote it"
            ))
        })
    }
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum QuipuFlavor {
    /// The reviewed release feature set, which deliberately excludes the
    /// `lancedb` cargo feature — `vector.backend = "lancedb"` refuses at
    /// startup on a box installed this way.
    #[default]
    Release,
    /// The same reviewed revision built with the `lancedb` feature added.
    /// Only the feature list changes, so this flavor cannot drift to an
    /// unreviewed Quipu.
    Lancedb,
}

impl QuipuFlavor {
    /// The default flavor is omitted from serialized plans so that plans
    /// written before this field existed and plans written today stay
    /// byte-identical.
    fn is_release(&self) -> bool {
        *self == Self::Release
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Plan {
    pub schema_version: u32,
    pub profile: Profile,
    pub tools: Vec<ToolName>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub shares: Vec<PathBuf>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub quipu_db: Option<PathBuf>,
    #[serde(default, skip_serializing_if = "QuipuFlavor::is_release")]
    pub quipu_flavor: QuipuFlavor,
    /// Quipu is owned outside Tambo; prove the executables selected by PATH.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub external_quipu: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stack_config: Option<StackConfig>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub crew: Option<CrewSelection>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub intent: Option<InstallIntent>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub embedding_model: Option<crate::embedding::EmbeddingModel>,
    /// Register Quipu's MCP endpoint with Claude Code through a headersHelper
    /// that reads the token at connect time (aegis-nvw6ye). Opt-in because it
    /// changes the user's Claude configuration.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub quipu_mcp: Option<QuipuMcp>,
    /// Per-host exclusions selected with `--host-profile` (aegis-fv4).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub host_profiles: Vec<HostProfile>,
}

/// A host on which another lane owns part of the plan. Selecting it drops
/// that part for the run and says so; an excluded runtime is never reported
/// as verified (aegis-fv4).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HostProfile {
    pub name: String,
    /// The lane that owns the crew runtimes on this host. When set, the
    /// plan's `[crew]` is excluded on this host.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub crew_excluded_owner: Option<String>,
    /// Plan tools another lane owns on this host, each named with that lane
    /// (aegis-fv4 D3: shuttle has no reviewed macOS delivery yet). Dropped for
    /// the run and reported, never installed or verified by caboodle.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub excluded_tools: Vec<ExcludedTool>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ExcludedTool {
    pub tool: ToolName,
    pub owner: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct QuipuMcp {
    /// The Quipu server (or its `/mcp` endpoint). Never a credential.
    pub url: String,
    /// Absolute path of this host's token FILE, baked in as the helper's
    /// default so Claude Code's own environment needs no QUIPU_AUTH_TOKEN_FILE.
    /// A path, never the token.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub token_file: Option<String>,
}

impl QuipuMcp {
    fn validate(&self) -> Result<()> {
        require_safe_text("quipu_mcp.url", &self.url)?;
        let rest = self
            .url
            .strip_prefix("https://")
            .or_else(|| self.url.strip_prefix("http://"))
            .ok_or_else(|| anyhow::anyhow!("quipu_mcp.url must be an http:// or https:// URL"))?;
        let authority = rest.split('/').next().unwrap_or("");
        if authority.is_empty() || authority.contains('@') || self.url.contains(['?', '#', ' ']) {
            bail!(
                "quipu_mcp.url must be a plain server URL with no credentials, query or fragment"
            );
        }
        if let Some(path) = &self.token_file {
            require_safe_text("quipu_mcp.token_file", path)?;
            if !path.starts_with('/') || path.contains(['\'', '\n', '\r']) {
                bail!(
                    "quipu_mcp.token_file must be an absolute path without quotes or line breaks"
                );
            }
        }
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StackConfig {
    pub quipu: QuipuStackConfig,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct QuipuStackConfig {
    pub owl: QuipuOwlConfig,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct QuipuOwlConfig {
    pub reactive_materialize: bool,
}

impl StackConfig {
    pub fn recommended() -> Self {
        Self {
            quipu: QuipuStackConfig {
                owl: QuipuOwlConfig {
                    reactive_materialize: true,
                },
            },
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct InstallIntent {
    pub intended_use: String,
    #[serde(default)]
    pub crew_members: Vec<CrewMemberTheme>,
    pub anticipated_questions: Vec<QuestionContract>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CrewMemberTheme {
    pub name: String,
    pub theme: String,
    pub domain: String,
    pub role: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct QuestionContract {
    pub question: String,
    pub answer_shape: String,
    pub seed_intent: String,
    pub sparql: String,
    pub expected: String,
    /// Set only on the built-in self-test contract. An explicit flag, not the
    /// marker: a user's own question may legitimately use the same marker (CI's
    /// fixture does), and must never be answered from caboodle's scratch store.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub self_test: bool,
}

/// Marker the built-in self-test question seeds and expects. Same contract CI's
/// quipu round trip uses (adapter.rs), so a fresh box can pass it with no
/// ontology of its own (aegis-ro425e.4).
pub const SELF_TEST_MARKER: &str = "caboodle-verify-roundtrip";

impl QuestionContract {
    /// The question offered when a first-time user presses enter at the
    /// question-count prompt. It proves the store answers a real query; it
    /// says nothing about the user's own domain, and `verify-questions` always
    /// runs it against its own seeded scratch store.
    pub fn self_test() -> Self {
        Self {
            question: "does the knowledge store answer a query about a fact written to it?".to_owned(),
            answer_shape: "one entity label".to_owned(),
            seed_intent: format!(
                "caboodle writes one Verification node named {SELF_TEST_MARKER} into a scratch store"
            ),
            sparql: format!(
                "SELECT ?s ?label WHERE {{ ?s <http://www.w3.org/2000/01/rdf-schema#label> ?label . FILTER(?label = \"{SELF_TEST_MARKER}\") }}"
            ),
            expected: SELF_TEST_MARKER.to_owned(),
            self_test: true,
        }
    }

    /// The explicit flag, or (for plans written before the flag existed) an
    /// exact match on every field of the self-test contract. Never the marker
    /// alone: that made a user question sharing the marker pass vacuously
    /// against the seeded scratch store (caught by CI's negative control).
    pub fn is_self_test(&self) -> bool {
        self.self_test
            || *self
                == Self {
                    self_test: false,
                    ..Self::self_test()
                }
    }
}

impl InstallIntent {
    pub fn read(path: &Path) -> Result<Self> {
        if !path.exists() {
            bail!(
                "no intent file at {}; run `tambo init --guided` to answer the interview instead, or write one (see the \"Using caboodle\" chapter of docs/book)",
                path.display()
            );
        }
        let body =
            fs::read_to_string(path).with_context(|| format!("read intent {}", path.display()))?;
        let intent: Self =
            toml::from_str(&body).with_context(|| format!("parse intent {}", path.display()))?;
        intent.validate()?;
        Ok(intent)
    }

    pub fn validate(&self) -> Result<()> {
        require_safe_text("intended use", &self.intended_use)?;
        if self.anticipated_questions.is_empty() {
            bail!("intent requires at least one anticipated ontology question");
        }
        let mut names = std::collections::BTreeSet::new();
        for member in &self.crew_members {
            for (field, value) in [
                ("crew member name", &member.name),
                ("crew member theme", &member.theme),
                ("crew member domain", &member.domain),
                ("crew member role", &member.role),
            ] {
                require_safe_text(field, value)?;
            }
            if !names.insert(member.name.to_ascii_lowercase()) {
                bail!("duplicate crew member name {:?}", member.name);
            }
        }
        let mut questions = std::collections::BTreeSet::new();
        for contract in &self.anticipated_questions {
            for (field, value) in [
                ("anticipated question", &contract.question),
                ("answer shape", &contract.answer_shape),
                ("seed intent", &contract.seed_intent),
                ("expected answer", &contract.expected),
            ] {
                require_safe_text(field, value)?;
            }
            if !questions.insert(contract.question.to_ascii_lowercase()) {
                bail!("duplicate anticipated question {:?}", contract.question);
            }
            let query = contract.sparql.to_ascii_uppercase();
            if !(query.split_whitespace().any(|word| word == "SELECT")
                || query.split_whitespace().any(|word| word == "ASK"))
            {
                bail!("anticipated question SPARQL must contain SELECT or ASK");
            }
            require_safe_text("anticipated question SPARQL", &contract.sparql)?;
        }
        Ok(())
    }
}

fn require_safe_text(field: &str, value: &str) -> Result<()> {
    if value.trim().is_empty() {
        bail!("{field} must not be empty");
    }
    let lower = value.to_ascii_lowercase();
    for marker in [
        "password=",
        "token=",
        "secret=",
        "authorization:",
        "bearer ",
    ] {
        if lower.contains(marker) {
            bail!("{field} appears to contain a credential ({marker})");
        }
    }
    Ok(())
}

impl Plan {
    /// Remote access is an explicit advanced option. Local embedded plans never
    /// need a server or a client credential.
    pub fn requires_remote_quipu(&self) -> bool {
        self.quipu_mcp.is_some()
            || std::env::var("QUIPU_SERVER").is_ok_and(|url| !url.trim().is_empty())
    }

    pub fn for_profile(profile: Profile) -> Self {
        Self {
            schema_version: SCHEMA_VERSION,
            profile,
            tools: profile.tools(),
            shares: Vec::new(),
            quipu_db: None,
            quipu_flavor: QuipuFlavor::default(),
            external_quipu: false,
            stack_config: Some(StackConfig::recommended()),
            crew: None,
            intent: None,
            embedding_model: None,
            quipu_mcp: None,
            host_profiles: Vec::new(),
        }
    }

    pub fn for_crew(mode: CrewMode) -> Self {
        Self {
            profile: Profile::Crew,
            crew: Some(CrewSelection::for_mode(mode)),
            ..Self::for_profile(Profile::Crew)
        }
    }

    pub fn read(path: &Path) -> Result<Self> {
        if !path.exists() {
            bail!(
                "no plan at {}; run `tambo init --guided` (or `tambo plan`) first",
                path.display()
            );
        }
        let body =
            fs::read_to_string(path).with_context(|| format!("read plan {}", path.display()))?;
        let plan: Self =
            toml::from_str(&body).with_context(|| format!("parse plan {}", path.display()))?;
        plan.validate()?;
        Ok(plan)
    }

    pub fn write(&self, path: &Path) -> Result<()> {
        self.validate()?;
        let body = toml::to_string_pretty(self).context("serialize plan")?;
        fs::write(path, body).with_context(|| format!("write plan {}", path.display()))
    }

    pub fn validate(&self) -> Result<()> {
        if self.schema_version != SCHEMA_VERSION {
            bail!(
                "unsupported plan schema {}; expected {}",
                self.schema_version,
                SCHEMA_VERSION
            );
        }
        if self.external_quipu && self.quipu_flavor != QuipuFlavor::Release {
            bail!("external_quipu cannot request a Tambo build flavor");
        }
        if self.tools.is_empty() {
            bail!("plan selects no tools");
        }
        if !self.profile.accepts(&self.tools) {
            bail!(
                "tools do not match the {:?} profile conventions",
                self.profile
            );
        }
        if !self.shares.is_empty() && self.quipu_db.is_none() {
            bail!("plans with knowledge shares require an explicit --quipu-db");
        }
        if self.shares.iter().any(|path| path.as_os_str().is_empty()) {
            bail!("knowledge share paths must not be empty");
        }
        if let Some(intent) = &self.intent {
            intent.validate()?;
        }
        if let Some(model) = &self.embedding_model {
            model.validate()?;
        }
        if let Some(mcp) = &self.quipu_mcp {
            if !self.tools.contains(&ToolName::Quipu) {
                bail!("[quipu_mcp] requires a profile that installs quipu");
            }
            mcp.validate()?;
        }
        match (self.profile, &self.crew) {
            (Profile::Crew, Some(crew)) => crew.validate()?,
            (Profile::Crew, None) => bail!("crew profile requires a [crew] selection"),
            (Profile::Everything, Some(crew)) => crew.validate()?,
            (_, Some(_)) => bail!("[crew] is only valid with profile = \"crew\" or \"everything\""),
            (_, None) => {}
        }
        let mut names = std::collections::HashSet::new();
        for host in &self.host_profiles {
            if host.name.trim().is_empty() || !names.insert(host.name.as_str()) {
                bail!("host profile names must be non-empty and unique");
            }
            if host
                .crew_excluded_owner
                .as_deref()
                .is_some_and(|owner| owner.trim().is_empty())
            {
                bail!(
                    "host profile {}: crew_excluded_owner must name the owning lane",
                    host.name
                );
            }
            let mut excluded = std::collections::BTreeSet::new();
            for entry in &host.excluded_tools {
                if entry.owner.trim().is_empty() {
                    bail!(
                        "host profile {}: excluded tool {} must name the owning lane",
                        host.name,
                        entry.tool.as_str()
                    );
                }
                // Built-ins are the profile's fixed prefix: excluding one would leave
                // a plan no profile accepts. Only declared stack members qualify.
                if !matches!(entry.tool, ToolName::Member(_))
                    || !self.tools.contains(&entry.tool)
                    || !excluded.insert(entry.tool)
                {
                    bail!(
                        "host profile {}: excluded tool {} must be a selected stack member, listed once",
                        host.name,
                        entry.tool.as_str()
                    );
                }
            }
        }
        Ok(())
    }

    /// Apply a named host profile. Returns the plan to run and the exclusion
    /// lines to print. An unknown name refuses rather than running everything.
    pub fn for_host(mut self, host: Option<&str>) -> Result<(Self, Vec<String>)> {
        let Some(host) = host else {
            return Ok((self, Vec::new()));
        };
        let profile = self
            .host_profiles
            .iter()
            .find(|p| p.name == host)
            .cloned()
            .with_context(|| format!("plan has no host profile named {host}"))?;
        let mut excluded = Vec::new();
        if let Some(owner) = profile.crew_excluded_owner {
            if self.profile == Profile::Crew {
                bail!("host profile {host} excludes crew, but this plan's profile IS crew");
            }
            if self.crew.take().is_some() {
                excluded.push(format!(
                    "crew: EXCLUDED on host profile {host}; owned by {owner}; not installed or verified by caboodle"
                ));
            }
        }
        // The returned plan has already applied this profile's tool exclusions, so
        // it must not carry them into a later validate() of the selected plan.
        if let Some(applied) = self.host_profiles.iter_mut().find(|p| p.name == host) {
            applied.excluded_tools.clear();
        }
        for entry in &profile.excluded_tools {
            if let Some(index) = self.tools.iter().position(|t| *t == entry.tool) {
                self.tools.remove(index);
                excluded.push(format!(
                    "{}: EXCLUDED on host profile {host}; owned by {}; not installed or verified by caboodle",
                    entry.tool.as_str(),
                    entry.owner
                ));
            }
        }
        Ok((self, excluded))
    }
}

#[derive(Debug, Default, Serialize, Deserialize)]
pub struct State {
    pub schema_version: u32,
    pub tools: BTreeMap<String, ToolState>,
    #[serde(default)]
    pub crew: BTreeMap<String, CrewRuntimeState>,
    #[serde(default)]
    pub shares: BTreeMap<String, ShareState>,
    #[serde(default)]
    pub models: BTreeMap<String, ModelArtifactState>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolState {
    pub version: String,
    pub applied: bool,
    pub verified: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CrewRuntimeState {
    pub version: String,
    pub applied: bool,
    pub verified: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelArtifactState {
    pub path: PathBuf,
    pub sha256: String,
    pub provisioned: bool,
    /// True only after verify re-hashed the artifact on disk; a fetch alone
    /// records `provisioned`, never `verified`.
    pub verified: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ShareState {
    pub path: PathBuf,
    pub staging_graph: String,
    pub outcome: String,
    pub promotion_eligible: bool,
    pub blockers: Vec<String>,
}

impl State {
    pub fn read(path: &Path) -> Result<Self> {
        if !path.exists() {
            return Ok(Self {
                schema_version: SCHEMA_VERSION,
                tools: BTreeMap::new(),
                crew: BTreeMap::new(),
                shares: BTreeMap::new(),
                models: BTreeMap::new(),
            });
        }
        let body =
            fs::read_to_string(path).with_context(|| format!("read state {}", path.display()))?;
        let state: Self = serde_json::from_str(&body)
            .with_context(|| format!("parse state {}", path.display()))?;
        if state.schema_version != SCHEMA_VERSION {
            bail!("unsupported state schema {}", state.schema_version);
        }
        Ok(state)
    }

    pub fn write(&self, path: &Path) -> Result<()> {
        let parent = path.parent().unwrap_or_else(|| Path::new("."));
        fs::create_dir_all(parent)
            .with_context(|| format!("create state directory {}", parent.display()))?;
        let mut tmp = tempfile::NamedTempFile::new_in(parent)
            .with_context(|| format!("create temporary state in {}", parent.display()))?;
        serde_json::to_writer_pretty(&mut tmp, self).context("serialize state")?;
        use std::io::Write;
        writeln!(tmp).context("finish state")?;
        tmp.persist(path)
            .map_err(|error| error.error)
            .with_context(|| format!("replace state {}", path.display()))?;
        Ok(())
    }
}

#[cfg(test)]
mod self_test_question_tests {
    use super::QuestionContract;

    #[test]
    fn self_test_is_the_flag_never_the_marker() {
        assert!(QuestionContract::self_test().is_self_test());
        // A user question that shares the marker (CI's fixture does) is NOT the
        // self-test and must be verified against the user's store.
        let mut users_own = QuestionContract::self_test();
        users_own.self_test = false;
        users_own.question = "what depends on the service?".to_owned();
        assert!(!users_own.is_self_test());
        // A plan written before the flag existed: every field equal, flag absent.
        let legacy = QuestionContract {
            self_test: false,
            ..QuestionContract::self_test()
        };
        assert!(legacy.is_self_test());
    }

    #[test]
    fn the_flag_round_trips_and_is_omitted_for_user_questions() {
        let toml = toml::to_string(&QuestionContract::self_test()).unwrap();
        assert!(toml.contains("self_test = true"));
        let mut user = QuestionContract::self_test();
        user.self_test = false;
        user.question = "q".to_owned();
        assert!(!toml::to_string(&user).unwrap().contains("self_test"));
    }
}

#[cfg(test)]
mod host_profile_tests {
    use super::{CrewMode, ExcludedTool, HostProfile, Plan, Profile, ToolName};

    fn plan() -> Plan {
        let mut plan = Plan::for_profile(Profile::Everything);
        plan.crew = Plan::for_crew(CrewMode::Both).crew;
        plan.host_profiles = vec![HostProfile {
            name: "mac".into(),
            crew_excluded_owner: Some("st-peer-autopull".into()),
            excluded_tools: Vec::new(),
        }];
        plan
    }

    #[test]
    fn host_profile_drops_an_excluded_tool_and_names_its_owner() {
        // aegis-fv4 D3: a tool with no reviewed delivery on this host.
        let mut excluding = plan();
        let tool = *excluding
            .tools
            .iter()
            .find(|t| matches!(t, ToolName::Member(_)))
            .expect("the everything profile carries stack members");
        excluding.host_profiles[0].excluded_tools = vec![ExcludedTool {
            tool,
            owner: "its own release lane".into(),
        }];
        excluding.validate().unwrap();
        let (selected, lines) = excluding.clone().for_host(Some("mac")).unwrap();
        assert!(!selected.tools.contains(&tool));
        assert!(lines.iter().any(|l| l.starts_with(tool.as_str())
            && l.contains("EXCLUDED")
            && l.contains("its own release lane")));
        // The selected plan still validates (it is re-checked by the commands).
        selected.validate().unwrap();
        let (unchanged, _) = excluding.for_host(None).unwrap();
        assert!(unchanged.tools.contains(&tool));
    }

    #[test]
    fn excluded_tools_must_be_owned_selected_and_listed_once() {
        let mut ownerless = plan();
        let tool = *ownerless
            .tools
            .iter()
            .find(|t| matches!(t, ToolName::Member(_)))
            .unwrap();
        ownerless.host_profiles[0].excluded_tools = vec![ExcludedTool {
            tool,
            owner: " ".into(),
        }];
        assert!(ownerless.validate().is_err());
        let mut twice = plan();
        let entry = ExcludedTool {
            tool,
            owner: "lane".into(),
        };
        twice.host_profiles[0].excluded_tools = vec![entry.clone(), entry.clone()];
        assert!(twice.validate().is_err());
        let mut unselected = plan();
        unselected.tools.retain(|t| *t != tool);
        unselected.host_profiles[0].excluded_tools = vec![ExcludedTool {
            tool,
            owner: "lane".into(),
        }];
        assert!(unselected.validate().is_err());
        let mut builtin = plan();
        builtin.host_profiles[0].excluded_tools = vec![ExcludedTool {
            tool: ToolName::Bobbin,
            owner: "lane".into(),
        }];
        assert!(builtin.validate().is_err());
    }

    #[test]
    fn host_profile_drops_crew_and_names_the_owner() {
        let (selected, lines) = plan().for_host(Some("mac")).unwrap();
        assert!(selected.crew.is_none());
        assert_eq!(lines.len(), 1);
        assert!(lines[0].contains("EXCLUDED") && lines[0].contains("st-peer-autopull"));
        let (unchanged, none) = plan().for_host(None).unwrap();
        assert!(unchanged.crew.is_some() && none.is_empty());
        assert!(plan().for_host(Some("nonesuch")).is_err());
    }

    #[test]
    fn host_profiles_must_be_named_uniquely_and_own_what_they_exclude() {
        let mut duplicate = plan();
        duplicate
            .host_profiles
            .push(duplicate.host_profiles[0].clone());
        assert!(duplicate.validate().is_err());
        let mut ownerless = plan();
        ownerless.host_profiles[0].crew_excluded_owner = Some(" ".into());
        assert!(ownerless.validate().is_err());
        let mut crew_only = Plan::for_crew(CrewMode::Both);
        crew_only.host_profiles = plan().host_profiles;
        assert!(crew_only.for_host(Some("mac")).is_err());
    }
}