car-server-core 0.55.0

Transport-neutral library for the CAR daemon JSON-RPC dispatcher (used by car-server and tokhn-daemon)
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
//! CAR-managed projects — the non-developer's unit of work.
//!
//! A non-dev doesn't have (or want to pick) a git repo. A **project** is a
//! named, CAR-managed git repository under `~/.car/projects/<slug>/`: created
//! and initialized for them, so the coder's worktree/branch machinery works
//! underneath while the user only ever sees a name. A project has a **kind** —
//! `App` (generic code) or `Agent` (a declarative CAR agent, Stage 2) — which
//! decides what gets seeded and how an approved session is delivered.
//!
//! This is distinct from `car_memgine::project::scaffold_project`, which
//! scaffolds a `<repo>/.car/` *team-metadata* directory; we never call it.

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

/// What a project produces, which selects seeding + the contract style.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ProjectKind {
    /// Generic code: the coder's normal shell/file loop, model-derived
    /// outcome contract, delivered to `main`.
    App,
    /// A declarative CAR agent: seeded with an `agent.json` + `scenarios.json`
    /// the coder fills in; the contract is "all scenarios pass"; approving
    /// registers the agent so it runs in-daemon (Stage 2).
    Agent,
}

impl ProjectKind {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::App => "app",
            Self::Agent => "agent",
        }
    }

    pub fn parse(s: &str) -> Result<Self, String> {
        match s.trim() {
            "app" | "" => Ok(Self::App),
            "agent" => Ok(Self::Agent),
            other => Err(format!(
                "unknown project kind '{other}' (expected app | agent)"
            )),
        }
    }
}

/// A CAR-managed project. The git repo IS `repo_path`; this metadata lives
/// beside it in `project.json` (gitignored).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CoderProject {
    pub slug: String,
    pub display_name: String,
    pub kind: ProjectKind,
    pub repo_path: PathBuf,
    pub created_at: u64,
    /// When present, an Agent-project build replaces this registered agent
    /// instead of deriving a new id from the project slug.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub existing_agent_id: Option<String>,
    /// Builder input staged with the project until the generated spec is
    /// approved and registered. The registered spec remains authoritative.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub builder_draft: Option<car_registry::declarative::AgentBuilderDraft>,
}

fn now_secs() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

/// `projects` under the CAR state root (`~/.car/projects` unless `CAR_HOME`
/// moves the root) — managed project repos. `CAR_PROJECTS_DIR` still overrides
/// both for tests and embedders (mirroring `CAR_CODER_STATE_DIR`).
pub fn projects_root() -> Result<PathBuf, String> {
    if let Some(dir) = std::env::var_os("CAR_PROJECTS_DIR") {
        return Ok(PathBuf::from(dir));
    }
    let root = car_home::root()
        .ok_or("cannot resolve home directory (CAR_HOME/HOME/USERPROFILE unset)")?;
    Ok(root.join("projects"))
}

/// Hard cap on a slugified id. Registration (`car-registry`'s supervisor
/// `validate_id`) requires every agent id to also be a legal car-peers
/// peer name, whose own hard cap is 128 chars (`is_valid_peer_name`) —
/// "two validators with two answers" is the exact drift that doc comment
/// records happening once before. `slugify()` derives ids from free-text
/// descriptions, so it caps well under that ceiling. Long names that
/// would exceed the cap keep a 64-bit digest suffix of the full slug so
/// distinct long names stay distinct with collision-resistant odds
/// (car#1492).
const SLUG_MAX_LEN: usize = 64;

/// Hex chars appended to an over-cap slug (sha256 of the full slug):
/// 16 hex chars = 64 bits of digest, so long names that share the
/// truncated prefix stay distinct with collision-resistant odds (a
/// birthday collision needs ~2^32 same-prefix names). The round-1
/// value of 6 (24 bits) collided on a real pair — "a" × 60 +
/// "-candidate-665" and "-candidate-880" both slugified to "a" × 57 +
/// "-066649", so the second request silently loaded the first one's
/// project (car#1492).
const SLUG_SUFFIX_HEX_LEN: usize = 16;

/// Turn a human name into a filename-safe slug: lowercase, runs of
/// non-`[a-z0-9]` collapse to a single `-`, trimmed. Empty → "project".
/// Matches the supervisor's filename-safe id alphabet so a project slug is a
/// legal agent id too (Stage 2 derives agent ids from project slugs).
/// Names longer than [`SLUG_MAX_LEN`] chars are truncated and suffixed
/// with a digest of the full slug, so a long description always yields an
/// id that every CAR surface accepts — including the 128-char peer-name
/// rule registration enforces — and distinct long names stay distinct
/// with collision-resistant odds.
pub fn slugify(name: &str) -> String {
    let mut out = String::new();
    let mut prev_dash = false;
    for c in name.trim().chars() {
        if c.is_ascii_alphanumeric() {
            out.push(c.to_ascii_lowercase());
            prev_dash = false;
        } else if !prev_dash && !out.is_empty() {
            out.push('-');
            prev_dash = true;
        }
    }
    let trimmed = out.trim_matches('-');
    if trimmed.is_empty() {
        return "project".to_string();
    }
    // Short slugs stay byte-identical to the historical form.
    if trimmed.len() <= SLUG_MAX_LEN {
        return trimmed.to_string();
    }
    // The slug is pure ASCII at this point, so byte slicing is
    // char-boundary safe. Budget: prefix + '-' + suffix == SLUG_MAX_LEN.
    let keep = SLUG_MAX_LEN - SLUG_SUFFIX_HEX_LEN - 1;
    let mut capped = trimmed[..keep].trim_end_matches('-').to_string();
    // The digest is of the FULL slug, not the raw name: names that
    // normalize identically (case, punctuation) must keep resolving to
    // the same id, which resolve_or_create_project's idempotency (same
    // slug → same project dir) depends on.
    use sha2::{Digest, Sha256};
    let digest = Sha256::digest(trimmed.as_bytes());
    capped.push('-');
    for byte in &digest[..SLUG_SUFFIX_HEX_LEN / 2] {
        capped.push_str(&format!("{byte:02x}"));
    }
    capped
}

fn project_dir(slug: &str) -> Result<PathBuf, String> {
    Ok(projects_root()?.join(slug))
}

/// Process-wide lock serializing tests that mutate the `CAR_PROJECTS_DIR`
/// global env var (across this module and the rpc tests). Never locked in
/// production — projects_root just reads the var.
#[cfg(test)]
pub(crate) fn projects_env_lock() -> &'static std::sync::Mutex<()> {
    static LOCK: std::sync::OnceLock<std::sync::Mutex<()>> = std::sync::OnceLock::new();
    LOCK.get_or_init(|| std::sync::Mutex::new(()))
}

fn git(dir: &Path, args: &[&str]) -> Result<(), String> {
    let out = std::process::Command::new("git")
        .arg("-C")
        .arg(dir)
        .args(args)
        .output()
        .map_err(|e| format!("git {args:?}: {e}"))?;
    if out.status.success() {
        Ok(())
    } else {
        Err(format!(
            "git {args:?} failed: {}",
            String::from_utf8_lossy(&out.stderr).trim()
        ))
    }
}

/// Resolve a project by name, creating + initializing it if absent. Idempotent:
/// an existing slug loads its `project.json` (the requested `kind` is ignored
/// for an existing project — its persisted kind wins). New projects get a git
/// repo (`git init -b main`), kind-appropriate seed files, an initial commit,
/// and a `project.json`.
pub fn resolve_or_create_project(name: &str, kind: ProjectKind) -> Result<CoderProject, String> {
    resolve_or_create_project_for_agent(name, kind, None, None)
}

/// Resolve or create a project while carrying the Agent Builder inputs and an
/// optional existing registered-agent identity through the coder pipeline.
///
/// Existing projects may refresh their staged builder draft, but cannot be
/// rebound to a different registered agent id. That makes retry idempotent
/// without turning a project slug into an overwrite primitive.
pub fn resolve_or_create_project_for_agent(
    name: &str,
    kind: ProjectKind,
    existing_agent_id: Option<String>,
    builder_draft: Option<car_registry::declarative::AgentBuilderDraft>,
) -> Result<CoderProject, String> {
    if kind != ProjectKind::Agent && (existing_agent_id.is_some() || builder_draft.is_some()) {
        return Err("existing_agent_id and builder_draft require an agent project".into());
    }
    let slug = slugify(name);
    let dir = project_dir(&slug)?;
    let meta_path = dir.join("project.json");

    if meta_path.exists() {
        let mut project = load_project(&slug)?;
        if existing_agent_id.is_some() || builder_draft.is_some() {
            if project.kind != ProjectKind::Agent {
                return Err(format!(
                    "project '{}' is kind '{}'; agent edit metadata requires kind 'agent'",
                    project.slug,
                    project.kind.as_str()
                ));
            }
            if let (Some(bound), Some(requested)) = (
                project.existing_agent_id.as_deref(),
                existing_agent_id.as_deref(),
            ) {
                if bound != requested {
                    return Err(format!(
                        "project '{}' is already bound to agent '{}' and cannot be rebound to '{}'",
                        project.slug, bound, requested
                    ));
                }
            }
            if existing_agent_id.is_some() {
                project.existing_agent_id = existing_agent_id;
            }
            if builder_draft.is_some() {
                project.builder_draft = builder_draft;
            }
            persist(&project)?;
        }
        return Ok(project);
    }

    std::fs::create_dir_all(&dir)
        .map_err(|e| format!("create project dir {}: {e}", dir.display()))?;
    git(&dir, &["init", "-q", "-b", "main"])?;

    // `.gitignore` keeps the project-local metadata out of the tracked tree.
    std::fs::write(dir.join(".gitignore"), "project.json\n")
        .map_err(|e| format!("write .gitignore: {e}"))?;

    seed_project(&dir, name, kind)?;

    git(
        &dir,
        &[
            "-c",
            "user.name=car-coder",
            "-c",
            "user.email=coder@parslee.ai",
            "add",
            "-A",
        ],
    )?;
    git(
        &dir,
        &[
            "-c",
            "user.name=car-coder",
            "-c",
            "user.email=coder@parslee.ai",
            "commit",
            "-q",
            "-m",
            "Initialize project",
        ],
    )?;

    let project = CoderProject {
        slug: slug.clone(),
        display_name: name.trim().to_string(),
        kind,
        repo_path: dir.clone(),
        created_at: now_secs(),
        existing_agent_id,
        builder_draft,
    };
    persist(&project)?;
    Ok(project)
}

/// Seed the working tree for a new project. App: a README. Agent: the starter
/// `agent.json` + `scenarios.json` + `.car/identity.md` the coder will fill in
/// (the declarative spec shape lands in Stage 2; this writes neutral stubs).
fn seed_project(dir: &Path, name: &str, kind: ProjectKind) -> Result<(), String> {
    let write = |rel: &str, body: &str| -> Result<(), String> {
        let path = dir.join(rel);
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)
                .map_err(|e| format!("create {}: {e}", parent.display()))?;
        }
        std::fs::write(&path, body).map_err(|e| format!("write {}: {e}", path.display()))
    };
    let display = name.trim();
    write(
        "README.md",
        &format!("# {display}\n\nA CAR-managed project.\n"),
    )?;
    if kind == ProjectKind::Agent {
        // Neutral stubs — Stage 2 replaces these with the DeclarativeAgentSpec
        // shape and the coder loop fills them in.
        write(
            "agent.json",
            "{\n  \"name\": \"\",\n  \"identity\": \"\",\n  \"tools\": [],\n  \"standing_goal\": \"\"\n}\n",
        )?;
        write("scenarios.json", "[]\n")?;
        write(
            ".car/identity.md",
            &format!("# {display}\n\nDescribe what this agent does.\n"),
        )?;
    }
    Ok(())
}

fn persist(project: &CoderProject) -> Result<(), String> {
    let path = project.repo_path.join("project.json");
    let json = serde_json::to_string_pretty(project).map_err(|e| e.to_string())?;
    std::fs::write(&path, json).map_err(|e| format!("write {}: {e}", path.display()))
}

/// Load a project's metadata by slug.
pub fn load_project(slug: &str) -> Result<CoderProject, String> {
    let path = project_dir(slug)?.join("project.json");
    let text = std::fs::read_to_string(&path)
        .map_err(|e| format!("no project '{slug}' ({}): {e}", path.display()))?;
    serde_json::from_str(&text).map_err(|e| format!("parse {}: {e}", path.display()))
}

/// All managed projects, newest first.
pub fn list_projects() -> Vec<CoderProject> {
    let Ok(root) = projects_root() else {
        return Vec::new();
    };
    let Ok(entries) = std::fs::read_dir(&root) else {
        return Vec::new();
    };
    let mut out: Vec<CoderProject> = entries
        .flatten()
        .filter(|e| e.path().is_dir())
        .filter_map(|e| e.file_name().into_string().ok())
        .filter_map(|slug| load_project(&slug).ok())
        .collect();
    out.sort_by(|a, b| b.created_at.cmp(&a.created_at));
    out
}

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

    /// Point CAR_PROJECTS_DIR at a temp dir for the duration of a closure.
    /// Serialized via a process-wide lock since the env var is global.
    fn with_temp_root<T>(f: impl FnOnce(&Path) -> T) -> T {
        let _guard = super::projects_env_lock()
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let tmp = tempfile::tempdir().unwrap();
        let prev = std::env::var_os("CAR_PROJECTS_DIR");
        unsafe {
            std::env::set_var("CAR_PROJECTS_DIR", tmp.path());
        }
        let out = f(tmp.path());
        unsafe {
            match prev {
                Some(v) => std::env::set_var("CAR_PROJECTS_DIR", v),
                None => std::env::remove_var("CAR_PROJECTS_DIR"),
            }
        }
        out
    }

    fn git_available() -> bool {
        std::process::Command::new("git")
            .arg("--version")
            .output()
            .is_ok()
    }

    #[test]
    fn slugify_is_filename_safe_and_stable() {
        assert_eq!(slugify("My Email Summarizer!"), "my-email-summarizer");
        assert_eq!(slugify("  weird___name  "), "weird-name");
        assert_eq!(slugify("Café ☕ Bot"), "caf-bot");
        assert_eq!(slugify(""), "project");
        assert_eq!(slugify("!!!"), "project");
        assert_eq!(slugify("already-good-123"), "already-good-123");
    }

    #[test]
    fn descriptions_from_1_through_2000_chars_have_bounded_safe_slugs() {
        let source: String = "Agent / WITH spaces_日本語-and.punctuation_0123456789!"
            .chars()
            .cycle()
            .take(2000)
            .collect();
        assert_eq!(source.chars().count(), 2000);

        for length in 1..=2000 {
            let description: String = source.chars().take(length).collect();
            let slug = slugify(&description);
            assert!(
                !slug.is_empty() && slug.len() <= SLUG_MAX_LEN,
                "length {length} produced {} bytes: {slug}",
                slug.len()
            );
            assert!(
                slug.bytes()
                    .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-'),
                "length {length} produced an unsafe slug: {slug}"
            );
            assert!(!slug.starts_with('-'), "length {length}: {slug}");
            assert!(!slug.ends_with('-'), "length {length}: {slug}");
            assert!(!slug.contains("--"), "length {length}: {slug}");
            assert!(
                car_peers::is_valid_peer_name(&slug),
                "length {length} produced an invalid peer name: {slug}"
            );
        }
    }

    /// car#1492: the id slugify() mints must be accepted wherever an agent
    /// id is checked — the 128-char peer-name rule that registration
    /// (car-registry's validate_id) enforces. If these two rules drift
    /// apart again, this is the test that says so.
    #[test]
    fn slugify_caps_long_names_within_peer_name_limit() {
        let long = "research assistant that summarizes every morning brief and files follow-ups "
            .repeat(6);
        assert!(
            long.len() > 300,
            "fixture must actually be long: {}",
            long.len()
        );
        let slug = slugify(&long);
        assert_eq!(
            slug.len(),
            SLUG_MAX_LEN,
            "cap must engage for a 300-char name"
        );
        assert!(car_peers::is_valid_peer_name(&slug));
    }

    /// Truncation alone would make any two long names sharing a prefix
    /// collide; the digest suffix keeps them distinct.
    #[test]
    fn slugify_keeps_distinct_long_names_distinct() {
        let base = "a".repeat(300);
        let left = slugify(&format!("{base} left"));
        let right = slugify(&format!("{base} right"));
        assert_ne!(left, right);
        assert!(car_peers::is_valid_peer_name(&left));
        assert!(car_peers::is_valid_peer_name(&right));
    }

    /// car#1492 round 2: the round-1 6-hex (24-bit) suffix collided on
    /// this exact pair, found by Codex's review — both names slugified
    /// to "a" × 57 + "-066649", so creating the second project silently
    /// loaded the first at resolve_or_create_project. The 16-hex
    /// (64-bit) suffix must keep the pair apart.
    #[test]
    fn slugify_24_bit_collision_pair_stays_distinct() {
        let left = slugify(&format!("{}-candidate-665", "a".repeat(60)));
        let right = slugify(&format!("{}-candidate-880", "a".repeat(60)));
        assert_ne!(left, right);
        assert_eq!(left.len(), SLUG_MAX_LEN);
        assert_eq!(right.len(), SLUG_MAX_LEN);
        assert!(car_peers::is_valid_peer_name(&left));
        assert!(car_peers::is_valid_peer_name(&right));
    }

    /// At the cap the output is byte-identical to the uncapped slug; one
    /// char over, the cap engages and the result stays a legal peer name.
    #[test]
    fn slugify_cap_boundary_is_exact() {
        let at_cap = "x".repeat(SLUG_MAX_LEN);
        assert_eq!(slugify(&at_cap), at_cap);
        let over = "y".repeat(SLUG_MAX_LEN + 1);
        let capped = slugify(&over);
        assert_eq!(capped.len(), SLUG_MAX_LEN);
        assert!(capped.starts_with(&"y".repeat(SLUG_MAX_LEN - SLUG_SUFFIX_HEX_LEN - 1)));
        assert!(car_peers::is_valid_peer_name(&capped));
    }

    /// resolve_or_create_project's idempotency depends on names that
    /// normalize identically resolving to the same slug even past the
    /// cap (the digest is of the full slug, not the raw name).
    #[test]
    fn slugify_truncation_follows_normalization() {
        let lower = slugify(&"Thing One ".repeat(30));
        let upper = slugify(&"THING ONE ".repeat(30));
        assert_eq!(lower, upper);
    }

    #[test]
    fn long_agent_description_gets_a_bounded_unique_slug_without_losing_the_description() {
        if !git_available() {
            return;
        }
        with_temp_root(|root| {
            let stem = "Build an agent that summarizes every support conversation, preserves customer commitments, identifies unresolved follow-up work, and writes focused scenarios. ";
            let mut description = stem.to_string();
            description.push_str(&"x".repeat(400 - description.len()));
            assert_eq!(description.chars().count(), 400);

            let project = resolve_or_create_project(&description, ProjectKind::Agent)
                .expect("create project");
            assert!(
                project.slug.len() <= SLUG_MAX_LEN,
                "bounded slug was {} bytes: {}",
                project.slug.len(),
                project.slug
            );
            assert_eq!(project.repo_path.parent(), Some(root));
            assert_eq!(project.display_name, description);
            assert_eq!(
                project.repo_path.file_name().and_then(|name| name.to_str()),
                Some(project.slug.as_str())
            );

            assert_eq!(project.slug, slugify(&description));
            let repeated = resolve_or_create_project(&description, ProjectKind::Agent).unwrap();
            let equivalent =
                resolve_or_create_project(&description.to_uppercase(), ProjectKind::Agent).unwrap();
            assert_eq!(repeated.repo_path, project.repo_path);
            assert_eq!(equivalent.repo_path, project.repo_path);

            let mut distinct_description = description.clone();
            distinct_description.replace_range(399..400, "y");
            let distinct = resolve_or_create_project(&distinct_description, ProjectKind::Agent)
                .expect("create distinct project");
            assert_ne!(project.slug, distinct.slug);
            assert_eq!(distinct.display_name, distinct_description);
        });
    }

    #[test]
    fn existing_agent_slugs_at_61_through_64_chars_keep_their_identity() {
        if !git_available() {
            return;
        }
        with_temp_root(|_| {
            for length in 61..=64 {
                let description = "a".repeat(length);
                let project = resolve_or_create_project(&description, ProjectKind::Agent).unwrap();
                assert_eq!(project.slug, description);
                let repeated =
                    resolve_or_create_project(&description.to_uppercase(), ProjectKind::Agent)
                        .unwrap();
                assert_eq!(project.repo_path, repeated.repo_path);
            }
        });
    }

    #[test]
    fn create_initializes_git_repo_and_is_idempotent() {
        if !git_available() {
            return;
        }
        with_temp_root(|_root| {
            let p = resolve_or_create_project("My App", ProjectKind::App).unwrap();
            assert_eq!(p.slug, "my-app");
            assert_eq!(p.kind, ProjectKind::App);
            assert!(p.repo_path.join(".git").exists());
            assert!(p.repo_path.join("README.md").exists());
            assert!(p.repo_path.join("project.json").exists());
            // Initial commit exists on main.
            let log = std::process::Command::new("git")
                .arg("-C")
                .arg(&p.repo_path)
                .args(["log", "--oneline"])
                .output()
                .unwrap();
            assert!(log.status.success() && !log.stdout.is_empty());

            // Idempotent: same name → same project, kind preserved even if the
            // caller passes a different kind.
            let again = resolve_or_create_project("My App", ProjectKind::Agent).unwrap();
            assert_eq!(again.slug, p.slug);
            assert_eq!(again.kind, ProjectKind::App, "existing kind wins");
            assert_eq!(again.created_at, p.created_at);
        });
    }

    #[test]
    fn agent_project_persists_builder_draft_and_cannot_rebind_existing_agent() {
        if !git_available() {
            return;
        }
        with_temp_root(|_root| {
            let draft = car_registry::declarative::AgentBuilderDraft {
                template_id: "inboxBrief".into(),
                name: "Inbox Brief".into(),
                responsibility: "Summarize mail".into(),
                example: "Flag replies due today".into(),
                access: "Read connected email".into(),
                cadence: "Weekday mornings".into(),
                delivery: "Save in Work".into(),
                privacy: "Never send automatically".into(),
            };
            let project = resolve_or_create_project_for_agent(
                "Inbox Brief",
                ProjectKind::Agent,
                Some("inbox-agent".into()),
                Some(draft.clone()),
            )
            .unwrap();
            let loaded = load_project(&project.slug).unwrap();
            assert_eq!(loaded.existing_agent_id.as_deref(), Some("inbox-agent"));
            assert_eq!(loaded.builder_draft, Some(draft));

            let error = resolve_or_create_project_for_agent(
                "Inbox Brief",
                ProjectKind::Agent,
                Some("different-agent".into()),
                None,
            )
            .unwrap_err();
            assert!(error.contains("cannot be rebound"), "{error}");
        });
    }

    #[test]
    fn agent_project_seeds_spec_stubs() {
        if !git_available() {
            return;
        }
        with_temp_root(|_root| {
            let p = resolve_or_create_project("Email Bot", ProjectKind::Agent).unwrap();
            assert!(p.repo_path.join("agent.json").exists());
            assert!(p.repo_path.join("scenarios.json").exists());
            assert!(p.repo_path.join(".car/identity.md").exists());
            // project.json is gitignored — not in the tracked tree.
            let tracked = std::process::Command::new("git")
                .arg("-C")
                .arg(&p.repo_path)
                .args(["ls-files"])
                .output()
                .unwrap();
            let files = String::from_utf8_lossy(&tracked.stdout);
            assert!(files.contains("agent.json"));
            assert!(
                !files.contains("project.json"),
                "project.json must be gitignored"
            );
        });
    }

    #[test]
    fn list_returns_created_projects_newest_first() {
        if !git_available() {
            return;
        }
        with_temp_root(|_root| {
            let a = resolve_or_create_project("Alpha", ProjectKind::App).unwrap();
            let b = resolve_or_create_project("Beta", ProjectKind::Agent).unwrap();
            let listed = list_projects();
            assert_eq!(listed.len(), 2);
            let slugs: Vec<&str> = listed.iter().map(|p| p.slug.as_str()).collect();
            assert!(slugs.contains(&a.slug.as_str()));
            assert!(slugs.contains(&b.slug.as_str()));
        });
    }

    #[test]
    fn load_missing_project_errors() {
        with_temp_root(|_root| {
            assert!(load_project("does-not-exist").is_err());
        });
    }

    #[test]
    fn project_kind_round_trips() {
        assert_eq!(ProjectKind::parse("app").unwrap(), ProjectKind::App);
        assert_eq!(ProjectKind::parse("agent").unwrap(), ProjectKind::Agent);
        assert_eq!(ProjectKind::parse("").unwrap(), ProjectKind::App);
        assert!(ProjectKind::parse("widget").is_err());
        assert_eq!(ProjectKind::App.as_str(), "app");
        assert_eq!(ProjectKind::Agent.as_str(), "agent");
    }
}