car-registry 0.55.0

File-based agent registry + lifecycle supervisor for Common Agent Runtime.
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
//! Declarative agents — in-daemon agents that need no external process.
//!
//! A [`DeclarativeAgentSpec`](crate::declarative::DeclarativeAgentSpec) is pure data: an identity (system prompt), a
//! tool **allowlist** (names of tools the daemon already exposes), an optional
//! deny list, a standing goal, an optional deterministic completion goal, an
//! optional structured cadence request, and scenarios (test cases). The daemon runs it with a generic model→tool loop — there is no command to spawn, so a
//! non-developer never installs Node/Python/anything.
//!
//! This is a **parallel registry** to [`crate::supervisor`], deliberately NOT
//! an extension of `supervisor::AgentSpec`: that type's whole security model is
//! the absolute-executable-path validation in `Supervisor::upsert` (the
//! 2026-05 audit's control). A declarative agent has no command, so it must
//! never travel through that path. `agents.list` read-merges declarative
//! entries (tagged `kind:"declarative"`) for the unified host view.

use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};

/// A test case for a declarative agent: run it on `input`, the output must
/// contain `expect` (a stable substring — not an exact match, so the contract
/// tolerates benign model variation).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Scenario {
    pub input: String,
    pub expect: String,
}

/// Deterministic completion contract for a declarative agent invocation.
/// The daemon runs `check` in the same scratch worktree after each agent pass
/// and re-drives until it exits 0 or `max_iterations` is exhausted.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
pub struct DeclarativeGoal {
    pub check: String,
    #[serde(default = "default_goal_iterations")]
    pub max_iterations: u32,
}

fn default_goal_iterations() -> u32 {
    8
}

/// Scheduler-compatible trigger kinds that a declarative agent can request.
/// The serialized spellings match `car_scheduler::TaskTrigger` for the shared
/// variants, without making the registry depend on the scheduler (which already
/// depends on the registry).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum AgentCadenceTrigger {
    Cron,
    Interval,
    Manual,
}

/// The user's requested recurring cadence, preserved on the declarative spec.
/// Activation into a durable scheduler task is a separate operation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
pub struct AgentCadence {
    pub trigger: AgentCadenceTrigger,
    /// Cron expression for `cron`, interval string for `interval`, and empty for
    /// `manual`.
    pub schedule: String,
    #[serde(default)]
    pub timezone: Option<String>,
    /// The exact trimmed phrase the user supplied.
    pub phrase: String,
}

/// Who owns the agent's conversation context across a multi-turn run.
///
/// The daemon already bounds the assistant and coder loops to the model's
/// context window; a declarative agent had no such bound and no way to ask for
/// one. This is that switch, per agent, named for who does the work rather than
/// for a mechanism the spec author cannot see.
///
/// Deserialization is deliberately TOLERANT (see the hand-written impl below):
/// an unrecognized value warns and falls back to [`ContextPolicy::Car`] rather
/// than failing the parse. A strict impl would be a foot-gun here — the
/// authoring guide teaches hand-editing `declagents.json`, and `DeclRegistry`
/// treats an unparseable file as an empty registry that the next `upsert`
/// writes back, so one mistyped policy would delete every agent on the box.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum ContextPolicy {
    /// CAR manages it: before each model call the running history is compacted
    /// to fit the model's context window, exactly as the assistant and coder
    /// loops do (oldest middle turns dropped on a turn boundary, the system
    /// prompt and the original task pinned, a `[history compacted:` notice left
    /// behind). The default, so an agent that never thinks about context still
    /// gets a bounded one.
    #[default]
    Car,
    /// The agent author manages it. CAR never compacts this agent's history —
    /// the spec owns whatever summarizing, truncation or externalization it
    /// wants. Choose it deliberately: nothing else bounds the transcript.
    #[serde(rename = "self")]
    SelfManaged,
}

impl ContextPolicy {
    /// Whether CAR compacts this agent's history.
    ///
    /// Exhaustive on purpose (repo rule): a `matches!` here would make every
    /// future variant silently self-managed — i.e. would turn "we added a
    /// policy" into "we switched compaction off for it", which is the failure
    /// mode with no symptom until a run overflows.
    pub fn is_car_managed(self) -> bool {
        match self {
            ContextPolicy::Car => true,
            ContextPolicy::SelfManaged => false,
        }
    }

    /// The on-disk / on-the-wire spelling.
    pub fn as_str(self) -> &'static str {
        match self {
            ContextPolicy::Car => "car",
            ContextPolicy::SelfManaged => "self",
        }
    }
}

impl<'de> Deserialize<'de> for ContextPolicy {
    /// Accepts `"car"` and `"self"`; ANYTHING else warns and yields `Car`.
    ///
    /// The strict derive returned `unknown variant`, and one bad character in a
    /// hand-edited `declagents.json` then travelled the whole swallow chain —
    /// [`DeclRegistry::read_all`] maps a parse error to an empty registry, and
    /// the next `upsert` persists that emptiness — so a typo in an optional
    /// field could unregister every agent the user had. A field whose only two
    /// values both mean "keep running" must never be able to do that. The
    /// fallback is the managed default, which is also the safe one: the worst
    /// outcome of guessing wrong is a bounded history for an author who wanted
    /// to bound it themselves, and the warning says so.
    ///
    /// The spec id is not reachable from here (serde hands this impl only the
    /// field's own value), so the warning names the value; the surrounding
    /// spec is one `declagents.json` grep away.
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        // Through `serde_json::Value` rather than `String` so a non-string
        // (`"context": 5`, `null`, an object) takes the same tolerant path
        // instead of the parse error this impl exists to prevent.
        let raw = serde_json::Value::deserialize(deserializer)?;
        match raw.as_str() {
            Some("car") => Ok(ContextPolicy::Car),
            Some("self") => Ok(ContextPolicy::SelfManaged),
            _ => {
                tracing::warn!(
                    value = %raw,
                    "declarative agent spec has an unrecognized `context` policy {raw}; \
                     expected \"car\" or \"self\" — using \"car\" (CAR manages the \
                     history). Fix the value in declagents.json to silence this."
                );
                Ok(ContextPolicy::Car)
            }
        }
    }
}

/// The answers captured by CarHost's guided Agent Builder.
///
/// These stay beside the generated runtime fields so reopening an agent can
/// restore the exact user-authored inputs instead of trying to reverse-engineer
/// them from a model-written identity or standing goal.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct AgentBuilderDraft {
    /// `AgentBuilderTemplate.rawValue` (`custom` for a hand-authored draft).
    #[serde(default)]
    pub template_id: String,
    #[serde(default)]
    pub name: String,
    #[serde(default)]
    pub responsibility: String,
    #[serde(default)]
    pub example: String,
    #[serde(default)]
    pub access: String,
    #[serde(default)]
    pub cadence: String,
    #[serde(default)]
    pub delivery: String,
    #[serde(default)]
    pub privacy: String,
}

/// A declarative, in-daemon agent.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DeclarativeAgentSpec {
    /// Filename-safe id (derived from the project slug).
    pub id: String,
    pub name: String,
    /// System prompt — who the agent is and how it behaves.
    pub identity: String,
    /// Allowlist of tool names the agent may call. The daemon exposes ONLY
    /// these to the model; anything else is invisible. Empty = no tools
    /// (a pure-reasoning agent).
    #[serde(default)]
    pub tools: Vec<String>,
    /// Extra hard denials layered under the allowlist (belt and suspenders).
    #[serde(default)]
    pub denied_tools: Vec<String>,
    /// The agent's persistent objective, prepended to every run.
    #[serde(default)]
    pub standing_goal: String,
    /// Optional deterministic completion contract. This is not shown to the
    /// model as a tool; it is the runtime-owned verifier for each invocation.
    #[serde(default)]
    pub goal: Option<DeclarativeGoal>,
    /// The user's structured cadence request. Existing specs predate this field,
    /// so absence remains valid and means no cadence was requested.
    #[serde(default)]
    pub cadence: Option<AgentCadence>,
    /// Acceptance scenarios — the contract the coder→agent loop drives to green.
    #[serde(default)]
    pub scenarios: Vec<Scenario>,
    /// The seven user-authored Agent Builder answers and selected template.
    /// Legacy and hand-authored specs have no draft and continue to load.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub builder_draft: Option<AgentBuilderDraft>,
    /// The immediately preceding registered version. Upsert always truncates
    /// this to one level, so repeated edits cannot grow an unbounded history.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub previous: Option<Box<DeclarativeAgentSpec>>,
    /// Lifecycle toggle. A disabled agent stays registered but won't run.
    #[serde(default = "default_true")]
    pub enabled: bool,
    /// Who manages the conversation context of a run: CAR (compaction keyed to
    /// the model's context window, the default) or the agent itself.
    ///
    /// `#[serde(default)]` is load-bearing: every spec already written to
    /// `declagents.json` predates this field and must keep loading, with the
    /// same managed behavior a new one gets.
    #[serde(default)]
    pub context: ContextPolicy,
}

fn default_true() -> bool {
    true
}

impl DeclarativeAgentSpec {
    /// Structural problems that make a spec unusable. Empty = valid.
    pub fn validate(&self) -> Vec<String> {
        let mut issues = Vec::new();
        if !is_filename_safe(&self.id) {
            issues.push(format!(
                "invalid agent id (alphanumeric + -_.): {:?}",
                self.id
            ));
        }
        if self.name.trim().is_empty() {
            issues.push("agent name is empty".into());
        }
        if self.identity.trim().is_empty() {
            issues.push("agent identity (system prompt) is empty".into());
        }
        if let Some(goal) = &self.goal {
            if goal.check.trim().is_empty() {
                issues.push("agent goal.check is empty".into());
            }
            if goal.max_iterations == 0 || goal.max_iterations > 50 {
                issues.push("agent goal.max_iterations must be between 1 and 50".into());
            }
        }
        // Scenarios are the contract the coder→agent loop drives to green; an
        // agent with none was never validated against any example. The builder
        // always writes at least one, so a zero-scenario spec is a hand-edit or
        // a malformed write — reject it at upsert rather than register an
        // unverifiable agent.
        if self.scenarios.is_empty() {
            issues.push("agent must have at least one acceptance scenario".into());
        }
        issues
    }
}

fn is_filename_safe(id: &str) -> bool {
    !id.is_empty()
        && id != "."
        && id != ".."
        && id
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.')
}

/// File-backed registry of declarative agents at `declagents.json` under the
/// CAR state root (`CAR_DECLAGENTS_PATH` overrides for tests/embedders).
/// Atomic write-through — the on-disk JSON is authoritative across restarts,
/// mirroring the supervisor manifest's hygiene.
pub struct DeclRegistry {
    path: PathBuf,
}

impl DeclRegistry {
    /// `declagents.json` under the CAR state root — `$CAR_HOME` when set,
    /// otherwise `~/.car`. `CAR_DECLAGENTS_PATH` is the narrower override and
    /// still wins over both: it names the file outright, so a caller that set
    /// it means that exact path regardless of where the rest of the state
    /// lives.
    pub fn user_default() -> Result<Self, String> {
        if let Some(p) = std::env::var_os("CAR_DECLAGENTS_PATH") {
            return Ok(Self {
                path: PathBuf::from(p),
            });
        }
        let root = car_home::root()
            .ok_or("cannot resolve home directory (CAR_HOME/HOME/USERPROFILE unset)")?;
        Ok(Self {
            path: root.join("declagents.json"),
        })
    }

    pub fn at(path: impl Into<PathBuf>) -> Self {
        Self { path: path.into() }
    }

    /// Exact file this registry reads and writes.
    ///
    /// Location is registry metadata, not part of [`DeclarativeAgentSpec`], so
    /// exposing it cannot leak into persisted `declagents.json` records.
    pub fn path(&self) -> &Path {
        &self.path
    }

    fn read_all(&self) -> Vec<DeclarativeAgentSpec> {
        std::fs::read_to_string(&self.path)
            .ok()
            .and_then(|s| serde_json::from_str(&s).ok())
            .unwrap_or_default()
    }

    fn write_all(&self, specs: &[DeclarativeAgentSpec]) -> Result<(), String> {
        if let Some(parent) = self.path.parent() {
            std::fs::create_dir_all(parent)
                .map_err(|e| format!("create {}: {e}", parent.display()))?;
        }
        let json = serde_json::to_string_pretty(specs).map_err(|e| e.to_string())?;
        // Atomic: write a sibling temp then rename over the target.
        let tmp = self.path.with_extension("json.tmp");
        std::fs::write(&tmp, json).map_err(|e| format!("write {}: {e}", tmp.display()))?;
        std::fs::rename(&tmp, &self.path)
            .map_err(|e| format!("rename into {}: {e}", self.path.display()))
    }

    /// Insert or replace by id. Validates the spec first.
    ///
    /// Replacements retain exactly one prior version in `previous`. Any history
    /// already carried by the existing or incoming value is discarded before
    /// writing, keeping the registry bounded across repeated edits.
    pub fn upsert(&self, mut spec: DeclarativeAgentSpec) -> Result<(), String> {
        let issues = spec.validate();
        if !issues.is_empty() {
            return Err(format!("invalid declarative agent: {}", issues.join("; ")));
        }
        let mut all = self.read_all();
        if let Some(existing) = all.iter_mut().find(|s| s.id == spec.id) {
            let mut previous = existing.clone();
            previous.previous = None;
            spec.previous = Some(Box::new(previous));
            *existing = spec;
        } else {
            spec.previous = None;
            all.push(spec);
        }
        self.write_all(&all)
    }

    pub fn list(&self) -> Vec<DeclarativeAgentSpec> {
        self.read_all()
    }

    pub fn get(&self, id: &str) -> Option<DeclarativeAgentSpec> {
        self.read_all().into_iter().find(|s| s.id == id)
    }

    pub fn remove(&self, id: &str) -> Result<bool, String> {
        let mut all = self.read_all();
        let before = all.len();
        all.retain(|s| s.id != id);
        let removed = all.len() != before;
        if removed {
            self.write_all(&all)?;
        }
        Ok(removed)
    }

    pub fn set_enabled(&self, id: &str, on: bool) -> Result<(), String> {
        let mut all = self.read_all();
        let spec = all
            .iter_mut()
            .find(|s| s.id == id)
            .ok_or_else(|| format!("no declarative agent '{id}'"))?;
        spec.enabled = on;
        self.write_all(&all)
    }
}

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

    fn spec(id: &str) -> DeclarativeAgentSpec {
        DeclarativeAgentSpec {
            id: id.into(),
            name: "Test".into(),
            identity: "You are a test agent.".into(),
            tools: vec!["read_file".into()],
            denied_tools: vec![],
            standing_goal: "be helpful".into(),
            goal: None,
            cadence: None,
            scenarios: vec![Scenario {
                input: "hi".into(),
                expect: "ok".into(),
            }],
            builder_draft: None,
            previous: None,
            enabled: true,
            context: ContextPolicy::default(),
        }
    }

    fn temp_registry() -> (tempfile::TempDir, DeclRegistry) {
        let dir = tempfile::tempdir().unwrap();
        let reg = DeclRegistry::at(dir.path().join("declagents.json"));
        (dir, reg)
    }

    #[test]
    fn upsert_rejects_spec_with_no_scenarios() {
        let (_d, reg) = temp_registry();
        let mut s = spec("no-scenarios");
        s.scenarios.clear();
        let err = reg
            .upsert(s)
            .expect_err("zero-scenario spec must be rejected");
        assert!(
            err.contains("at least one acceptance scenario"),
            "got: {err}"
        );
    }

    #[test]
    fn upsert_rejects_invalid_goal_contract() {
        let (_d, reg) = temp_registry();
        let mut s = spec("bad-goal");
        s.goal = Some(DeclarativeGoal {
            check: " ".into(),
            max_iterations: 0,
        });
        let err = reg.upsert(s).expect_err("invalid goal must be rejected");
        assert!(err.contains("goal.check"), "{err}");
        assert!(err.contains("goal.max_iterations"), "{err}");
    }

    #[test]
    fn upsert_list_get_remove_round_trip() {
        let (_d, reg) = temp_registry();
        reg.upsert(spec("email-bot")).unwrap();
        reg.upsert(spec("note-taker")).unwrap();
        assert_eq!(reg.list().len(), 2);
        assert_eq!(reg.get("email-bot").unwrap().name, "Test");
        // Upsert replaces, doesn't duplicate.
        let mut updated = spec("email-bot");
        updated.name = "Renamed".into();
        reg.upsert(updated).unwrap();
        assert_eq!(reg.list().len(), 2);
        let current = reg.get("email-bot").unwrap();
        assert_eq!(current.name, "Renamed");
        assert_eq!(current.previous.as_deref().unwrap().name, "Test");
        assert!(current.previous.as_deref().unwrap().previous.is_none());
        assert!(reg.remove("email-bot").unwrap());
        assert!(!reg.remove("email-bot").unwrap());
        assert_eq!(reg.list().len(), 1);
    }

    #[test]
    fn set_enabled_toggles() {
        let (_d, reg) = temp_registry();
        reg.upsert(spec("a")).unwrap();
        reg.set_enabled("a", false).unwrap();
        assert!(!reg.get("a").unwrap().enabled);
        reg.set_enabled("a", true).unwrap();
        assert!(reg.get("a").unwrap().enabled);
        assert!(reg.set_enabled("missing", true).is_err());
    }

    #[test]
    fn invalid_spec_is_rejected() {
        let (_d, reg) = temp_registry();
        let mut bad = spec("../escape");
        assert!(reg.upsert(bad.clone()).is_err());
        bad.id = "ok".into();
        bad.identity = "  ".into();
        assert!(reg.upsert(bad).is_err());
    }

    #[test]
    fn get_preserves_existing_registry_bytes_and_path_is_derived() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("declagents.json");
        let fixture = r#"[
  {
    "id": "existing-agent",
    "name": "Existing",
    "identity": "You preserve old state.",
    "tools": [],
    "standing_goal": "remain compatible",
    "scenarios": [{"input": "ping", "expect": "pong"}],
    "enabled": true
  }
]
"#;
        std::fs::write(&path, fixture).unwrap();
        let reg = DeclRegistry::at(&path);

        assert_eq!(reg.path(), path.as_path());
        assert_eq!(reg.get("existing-agent").unwrap().name, "Existing");
        assert_eq!(
            std::fs::read(&path).unwrap(),
            fixture.as_bytes(),
            "a metadata read must not write registry_path into persisted user state"
        );
    }

    #[test]
    fn persists_across_handles() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("declagents.json");
        DeclRegistry::at(&path).upsert(spec("persist")).unwrap();
        // A fresh handle reads the same on-disk state.
        assert!(DeclRegistry::at(&path).get("persist").is_some());
    }

    #[test]
    fn cadence_round_trips_and_is_optional_for_existing_specs() {
        let mut s = spec("cadence");
        s.cadence = Some(AgentCadence {
            trigger: AgentCadenceTrigger::Cron,
            schedule: "30 8 * * 1-5".into(),
            timezone: Some("America/New_York".into()),
            phrase: "Weekdays at 8:30".into(),
        });
        let json = serde_json::to_value(&s).unwrap();
        assert_eq!(json["cadence"]["trigger"], "cron");
        assert_eq!(json["cadence"]["schedule"], "30 8 * * 1-5");
        assert_eq!(json["cadence"]["timezone"], "America/New_York");
        assert_eq!(json["cadence"]["phrase"], "Weekdays at 8:30");
        assert_eq!(
            serde_json::from_value::<DeclarativeAgentSpec>(json).unwrap(),
            s
        );

        let legacy = serde_json::from_value::<DeclarativeAgentSpec>(serde_json::json!({
            "id": "legacy",
            "name": "Legacy",
            "identity": "You predate cadence.",
            "scenarios": [{"input": "ping", "expect": "pong"}],
        }))
        .unwrap();
        assert_eq!(legacy.cadence, None);
    }

    #[test]
    fn builder_draft_and_previous_round_trip_with_one_level_of_history() {
        let (_d, reg) = temp_registry();
        let mut first = spec("editable");
        first.builder_draft = Some(AgentBuilderDraft {
            template_id: "researchBrief".into(),
            name: "Research Brief".into(),
            responsibility: "Research assigned questions".into(),
            example: "Compare three options".into(),
            access: "Public web".into(),
            cadence: "When assigned".into(),
            delivery: "Save in Work".into(),
            privacy: "Keep supplied files local".into(),
        });
        reg.upsert(first.clone()).unwrap();

        let mut second = first;
        second.standing_goal = "Deliver cited research".into();
        second.builder_draft.as_mut().unwrap().cadence = "Every weekday".into();
        // An incoming chain must not defeat the one-level bound.
        second.previous = Some(Box::new(spec("ignored-history")));
        reg.upsert(second).unwrap();

        let loaded = DeclRegistry::at(reg.path()).get("editable").unwrap();
        assert_eq!(
            loaded.builder_draft.as_ref().unwrap().cadence,
            "Every weekday"
        );
        let previous = loaded.previous.as_deref().unwrap();
        assert_eq!(
            previous.builder_draft.as_ref().unwrap().cadence,
            "When assigned"
        );
        assert!(previous.previous.is_none());

        let json = serde_json::to_string(&loaded).unwrap();
        let round_tripped: DeclarativeAgentSpec = serde_json::from_str(&json).unwrap();
        assert_eq!(round_tripped, loaded);
    }

    #[test]
    fn legacy_spec_defaults_builder_history_to_none() {
        let legacy = serde_json::from_value::<DeclarativeAgentSpec>(serde_json::json!({
            "id": "legacy",
            "name": "Legacy",
            "identity": "You predate editing.",
            "scenarios": [{"input": "ping", "expect": "pong"}]
        }))
        .unwrap();
        assert!(legacy.builder_draft.is_none());
        assert!(legacy.previous.is_none());
    }

    #[test]
    fn context_policy_round_trips_through_the_spec() {
        // The wire/disk spelling is the spec author's spelling: `car` / `self`.
        let mut s = spec("ctx");
        assert_eq!(s.context, ContextPolicy::Car, "default is CAR-managed");
        let json = serde_json::to_value(&s).unwrap();
        assert_eq!(json["context"], "car");
        assert_eq!(
            serde_json::from_value::<DeclarativeAgentSpec>(json).unwrap(),
            s
        );

        s.context = ContextPolicy::SelfManaged;
        let json = serde_json::to_value(&s).unwrap();
        assert_eq!(json["context"], "self");
        assert_eq!(
            serde_json::from_value::<DeclarativeAgentSpec>(json).unwrap(),
            s
        );
    }

    #[test]
    fn a_spec_written_before_the_context_field_still_loads_as_car_managed() {
        // Every agent already on disk predates the field. It must load — with
        // the managed default, not a parse error and not an unmanaged run.
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("declagents.json");
        std::fs::write(
            &path,
            r#"[
  {
    "id": "legacy-agent",
    "name": "Legacy",
    "identity": "You predate the context field.",
    "tools": [],
    "standing_goal": "remain compatible",
    "scenarios": [{"input": "ping", "expect": "pong"}],
    "enabled": true
  }
]
"#,
        )
        .unwrap();

        let loaded = DeclRegistry::at(&path).get("legacy-agent").unwrap();
        assert_eq!(loaded.context, ContextPolicy::Car);
        assert!(loaded.context.is_car_managed());
    }

    #[test]
    fn a_mistyped_context_value_warns_and_defaults_instead_of_failing_the_parse() {
        // The blast radius of strictness here is the whole registry, not one
        // field: `read_all` maps a parse error to an empty Vec and the next
        // `upsert` writes that back. So a typo in a hand-edited spec — which
        // the authoring guide invites — must degrade to the managed default
        // (with a warning), never to "every agent deleted".
        let spec = serde_json::from_value::<DeclarativeAgentSpec>(serde_json::json!({
            "id": "typo",
            "name": "Typo",
            "identity": "x",
            "scenarios": [{"input": "a", "expect": "b"}],
            "context": "mine",
        }))
        .expect("a mistyped context policy must still load");
        assert_eq!(spec.context, ContextPolicy::Car);

        // Non-strings take the same path (`"context": 5` is the same class of
        // hand-edit), and so does a wrong case.
        for bad in [
            serde_json::json!(5),
            serde_json::json!(null),
            serde_json::json!({"who": "me"}),
            serde_json::json!("Self"),
        ] {
            let spec = serde_json::from_value::<DeclarativeAgentSpec>(serde_json::json!({
                "id": "typo",
                "name": "Typo",
                "identity": "x",
                "scenarios": [{"input": "a", "expect": "b"}],
                "context": bad,
            }))
            .expect("a malformed context policy must still load");
            assert_eq!(spec.context, ContextPolicy::Car);
        }
    }

    #[test]
    fn a_mistyped_context_value_cannot_empty_the_registry() {
        // The chain the test above exists to break, end to end: a file holding
        // two agents, one of them hand-edited wrong, must still list two — and
        // an upsert on top of it must not persist an empty registry.
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("declagents.json");
        std::fs::write(
            &path,
            r#"[
  {
    "id": "good-agent",
    "name": "Good",
    "identity": "You are fine.",
    "scenarios": [{"input": "ping", "expect": "pong"}],
    "enabled": true,
    "context": "self"
  },
  {
    "id": "typo-agent",
    "name": "Typo",
    "identity": "You were hand-edited.",
    "scenarios": [{"input": "ping", "expect": "pong"}],
    "enabled": true,
    "context": "mine"
  }
]
"#,
        )
        .unwrap();

        let reg = DeclRegistry::at(&path);
        assert_eq!(reg.list().len(), 2, "a typo must not empty the registry");
        assert_eq!(
            reg.get("typo-agent").unwrap().context,
            ContextPolicy::Car,
            "the mistyped policy falls back to the managed default"
        );
        assert_eq!(
            reg.get("good-agent").unwrap().context,
            ContextPolicy::SelfManaged,
            "a valid neighbour is unaffected"
        );

        reg.upsert(spec("third")).unwrap();
        assert_eq!(
            DeclRegistry::at(&path).list().len(),
            3,
            "upsert after a tolerated typo must not have written an empty registry"
        );
    }
}