car-registry 0.38.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
//! `manifest.toml` integration for the supervisor
//! (Parslee-ai/car#182).
//!
//! Phase 2 moved the manifest types + canonicalization + ed25519
//! signing into the dedicated `car-bundle` crate. This module now
//! re-exports the public surface and holds the supervisor-side
//! helpers — loading from a directory, projecting to the
//! supervisor's flat [`AgentSpec`], and verifying signatures when
//! present.

use std::collections::HashSet;
use std::path::{Path, PathBuf};

pub use car_bundle::{
    AgentIdentity, AgentManifest, BundleError, CapabilityDeclarations, ExternalProcessTransport,
    LifecyclePolicy, PublisherInfo, RestartPolicy as BundleRestartPolicy, RuntimeRequirements,
    TransportSpec,
};

use crate::supervisor::{AgentSpec, RestartPolicy, SupervisorError};

/// Convert from the bundle crate's RestartPolicy (which lives in
/// `car-bundle` so it can stay standalone) to the supervisor's
/// in-memory enum. They have the same variants by design; this
/// function exists to make the boundary explicit and to catch
/// any future divergence at compile time.
fn map_restart_policy(p: BundleRestartPolicy) -> RestartPolicy {
    match p {
        BundleRestartPolicy::Never => RestartPolicy::Never,
        BundleRestartPolicy::OnFailure => RestartPolicy::OnFailure,
        BundleRestartPolicy::Always => RestartPolicy::Always,
    }
}

fn unmap_restart_policy(p: RestartPolicy) -> BundleRestartPolicy {
    match p {
        RestartPolicy::Never => BundleRestartPolicy::Never,
        RestartPolicy::OnFailure => BundleRestartPolicy::OnFailure,
        RestartPolicy::Always => BundleRestartPolicy::Always,
    }
}

/// Build an [`AgentManifest`] from a legacy [`AgentSpec`].
pub fn from_legacy_spec(spec: &AgentSpec) -> AgentManifest {
    AgentManifest {
        agent: AgentIdentity {
            id: spec.id.clone(),
            name: spec.name.clone(),
            namespace: None,
            version: None,
            description: None,
            license: None,
            homepage: None,
        },
        publisher: None,
        runtime: None,
        lifecycle: None,
        transport: TransportSpec::ExternalProcess(ExternalProcessTransport {
            command: Some(spec.command.clone()),
            interpreter: None,
            binary_url: None,
            sha256: None,
            health_url: None,
            args: spec.args.clone(),
            cwd: spec.cwd.clone(),
            env: spec.env.clone(),
            restart: unmap_restart_policy(spec.restart),
            max_restarts: spec.max_restarts,
            backoff_secs: spec.backoff_secs,
            auto_start: spec.auto_start,
            token: spec.token.clone(),
            capabilities: spec.capabilities.clone(),
        }),
        capabilities: None,
    }
}

/// Project an [`AgentManifest`] back to the supervisor's
/// in-memory [`AgentSpec`]. Phase 2: same projection rules as
/// phase 1; pure_data + health_url-only manifests still can't be
/// projected (the supervisor doesn't spawn them).
pub fn to_agent_spec(manifest: &AgentManifest) -> Result<AgentSpec, SupervisorError> {
    match &manifest.transport {
        TransportSpec::PureData => Err(SupervisorError::Other(format!(
            "agent `{}` is a pure_data bundle; supervisor cannot spawn it. \
             Pure-data agents are loaded by the runtime in a later phase.",
            manifest.agent.id
        ))),
        TransportSpec::ExternalProcess(t) => {
            // Signature note (#182 phase 5): this returns a fresh AgentSpec and
            // never mutates `manifest`. The signed source manifest is verified
            // upstream (at registry_install fetch + warn-only at upsert); the
            // spec we produce here resolves `interpreter` to an absolute path,
            // and `persist()` writes a publisher-STRIPPED runtime mirror of the
            // spec — intentionally NOT re-verifiable. A future strict-signature
            // phase must verify the fetched signed manifest, never the on-disk
            // resolved mirror (whose command differs from the signed bytes).
            //
            // Resolve the command. A manifest sets EITHER an absolute
            // `command` OR a bare `interpreter` name resolved against
            // the consumer's $PATH at install time (#182 phase 5) —
            // never both. The `interpreter` path is the only opt-in to
            // PATH resolution; a bare `command` still requires an
            // absolute path (validated downstream by `validate_command`
            // at upsert). `resolve_interpreter` runs that same gate, so
            // a PATH-injection or /tmp-parked interpreter is rejected.
            let has_command = t.command.as_deref().is_some_and(|c| !c.is_empty());
            let interpreter = t.interpreter.as_deref().filter(|s| !s.is_empty());
            let command = match (has_command, interpreter) {
                (true, Some(_)) => {
                    return Err(SupervisorError::Other(format!(
                        "agent `{}` sets both `command` and `interpreter`; \
                         set either `command` (absolute) or `interpreter` \
                         (PATH-resolved), not both",
                        manifest.agent.id
                    )));
                }
                (false, Some(name)) => crate::supervisor::resolve_interpreter(name)?
                    .to_string_lossy()
                    .into_owned(),
                (true, None) => t.command.clone().expect("has_command implies Some"),
                (false, None) => {
                    return Err(SupervisorError::Other(format!(
                        "agent `{}` has transport.kind=external_process but no \
                         `command` or `interpreter`; health_url-only entries \
                         are tracked but not spawned by the supervisor in this \
                         phase.",
                        manifest.agent.id
                    )));
                }
            };
            Ok(AgentSpec {
                id: manifest.agent.id.clone(),
                name: manifest.agent.name.clone(),
                command,
                args: t.args.clone(),
                cwd: t.cwd.clone(),
                env: t.env.clone(),
                restart: map_restart_policy(t.restart),
                max_restarts: t.max_restarts,
                backoff_secs: t.backoff_secs,
                auto_start: t.auto_start,
                token: t.token.clone(),
                capabilities: t.capabilities.clone(),
            })
        }
    }
}

/// Read every `<dir>/<id>/manifest.toml` under `dir`. Skips
/// malformed files with a `tracing::warn!`. Optionally verifies
/// signatures when present — verification failures log a warning
/// but do NOT remove the manifest from the returned list in phase
/// 2 (warn-but-not-reject keeps existing setups working while
/// operators sign their agents; phase 3 makes verification
/// strict).
pub fn load_manifest_dir(dir: &Path) -> Result<Vec<AgentManifest>, SupervisorError> {
    if !dir.exists() {
        return Ok(Vec::new());
    }
    let mut out = Vec::new();
    for entry in std::fs::read_dir(dir)? {
        let entry = entry?;
        let path = entry.path();
        if !path.is_dir() {
            continue;
        }
        let manifest_path = path.join("manifest.toml");
        if !manifest_path.is_file() {
            continue;
        }
        let text = match std::fs::read_to_string(&manifest_path) {
            Ok(t) => t,
            Err(e) => {
                tracing::warn!(
                    manifest = %manifest_path.display(),
                    error = %e,
                    "skipping unreadable manifest.toml"
                );
                continue;
            }
        };
        let m = match AgentManifest::from_toml_str(&text) {
            Ok(m) => m,
            Err(e) => {
                tracing::warn!(
                    manifest = %manifest_path.display(),
                    error = %e,
                    "skipping malformed manifest.toml"
                );
                continue;
            }
        };
        if m.publisher.is_some() {
            if let Err(e) = car_bundle::verify_signature(&m) {
                tracing::warn!(
                    manifest = %manifest_path.display(),
                    agent_id = %m.agent.id,
                    error = %e,
                    "manifest signature did not verify (phase 2 warn-only; \
                     phase 3 will reject)"
                );
            }
        }
        out.push(m);
    }
    out.sort_by(|a, b| a.agent.id.cmp(&b.agent.id));
    Ok(out)
}

/// Write a single manifest.toml atomically. Creates the
/// `<dir>/<id>/` directory if needed.
pub fn write_manifest(
    agents_dir: &Path,
    manifest: &AgentManifest,
) -> Result<PathBuf, SupervisorError> {
    let agent_dir = agents_dir.join(&manifest.agent.id);
    std::fs::create_dir_all(&agent_dir)?;
    let manifest_path = agent_dir.join("manifest.toml");
    let toml_text = manifest
        .to_toml_string()
        .map_err(|e| SupervisorError::Other(format!("serialize manifest: {e}")))?;
    let tmp = agent_dir.join(".manifest.toml.tmp");
    std::fs::write(&tmp, toml_text)?;
    std::fs::rename(&tmp, &manifest_path)?;
    Ok(manifest_path)
}

/// Reap manifest dirs whose ids are not in `keep`. Returns the
/// ids that were removed. Only deletes directories that look like
/// supervised-agent layouts (must contain a `manifest.toml`).
pub fn reap_stale(agents_dir: &Path, keep: &HashSet<String>) -> Vec<String> {
    let Ok(entries) = std::fs::read_dir(agents_dir) else {
        return Vec::new();
    };
    let mut removed = Vec::new();
    for entry in entries.flatten() {
        let p = entry.path();
        if !p.is_dir() {
            continue;
        }
        let Some(name) = p.file_name().and_then(|s| s.to_str()) else {
            continue;
        };
        if keep.contains(name) {
            continue;
        }
        if p.join("manifest.toml").is_file() {
            if let Err(e) = std::fs::remove_dir_all(&p) {
                tracing::warn!(
                    dir = %p.display(),
                    error = %e,
                    "reaping stale manifest dir failed"
                );
                continue;
            }
            removed.push(name.to_string());
        }
    }
    removed
}

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

    fn legacy_spec() -> AgentSpec {
        AgentSpec {
            id: "ui-improver".into(),
            name: "UI Improvement".into(),
            command: "/usr/local/bin/ui-improver".into(),
            args: vec!["--mode".into(), "a2ui".into()],
            cwd: None,
            env: BTreeMap::from([("RUST_LOG".to_string(), "info".to_string())]),
            restart: RestartPolicy::OnFailure,
            max_restarts: 7,
            backoff_secs: 3,
            auto_start: false,
            token: "tok-abc".into(),
            capabilities: Vec::new(),
        }
    }

    #[test]
    fn from_legacy_round_trips_external_process_fields() {
        let spec = legacy_spec();
        let manifest = from_legacy_spec(&spec);
        let round = to_agent_spec(&manifest).unwrap();
        assert_eq!(round.id, spec.id);
        assert_eq!(round.command, spec.command);
        assert_eq!(round.args, spec.args);
        assert_eq!(round.env, spec.env);
        assert_eq!(round.restart, spec.restart);
        assert_eq!(round.max_restarts, spec.max_restarts);
        assert_eq!(round.token, spec.token);
    }

    #[test]
    fn pure_data_manifest_cannot_project_to_agent_spec() {
        let m = AgentManifest {
            agent: AgentIdentity {
                id: "pure-bundle".into(),
                name: "Pure Data".into(),
                namespace: None,
                version: None,
                description: None,
                license: None,
                homepage: None,
            },
            publisher: None,
            runtime: None,
            lifecycle: None,
            transport: TransportSpec::PureData,
            capabilities: None,
        };
        assert!(m.is_pure_data());
        assert!(!m.is_remote_service());
        assert!(to_agent_spec(&m).is_err());
    }

    #[test]
    fn health_url_manifest_cannot_project_to_agent_spec() {
        let m = AgentManifest {
            agent: AgentIdentity {
                id: "remote-svc".into(),
                name: "Remote Service".into(),
                namespace: None,
                version: None,
                description: None,
                license: None,
                homepage: None,
            },
            publisher: None,
            runtime: None,
            lifecycle: None,
            transport: TransportSpec::ExternalProcess(ExternalProcessTransport {
                command: None,
                interpreter: None,
                binary_url: None,
                sha256: None,
                health_url: Some("https://svc.example.com/.well-known/a2a/agent.json".into()),
                args: vec![],
                cwd: None,
                env: BTreeMap::new(),
                restart: BundleRestartPolicy::default(),
                max_restarts: 10,
                backoff_secs: 5,
                auto_start: false,
                token: String::new(),
                capabilities: Vec::new(),
            }),
            capabilities: None,
        };
        assert!(m.is_remote_service());
        assert!(to_agent_spec(&m).is_err());
    }

    #[test]
    fn write_and_load_manifest_round_trip() {
        let dir = tempfile::tempdir().unwrap();
        let m = from_legacy_spec(&legacy_spec());
        let written = write_manifest(dir.path(), &m).unwrap();
        assert!(written.exists());
        let loaded = load_manifest_dir(dir.path()).unwrap();
        assert_eq!(loaded.len(), 1);
        assert_eq!(loaded[0].agent.id, m.agent.id);
        let spec = to_agent_spec(&loaded[0]).unwrap();
        assert_eq!(spec.command, "/usr/local/bin/ui-improver");
        assert_eq!(spec.token, "tok-abc");
    }

    #[test]
    fn load_manifest_dir_skips_malformed_files() {
        let dir = tempfile::tempdir().unwrap();
        let good = from_legacy_spec(&legacy_spec());
        write_manifest(dir.path(), &good).unwrap();
        let bad_dir = dir.path().join("malformed");
        std::fs::create_dir_all(&bad_dir).unwrap();
        std::fs::write(bad_dir.join("manifest.toml"), "this is not valid toml === ").unwrap();
        let loaded = load_manifest_dir(dir.path()).unwrap();
        assert_eq!(loaded.len(), 1);
        assert_eq!(loaded[0].agent.id, "ui-improver");
    }

    #[test]
    fn load_manifest_dir_is_empty_when_path_missing() {
        let dir = tempfile::tempdir().unwrap();
        let missing = dir.path().join("does-not-exist");
        let loaded = load_manifest_dir(&missing).unwrap();
        assert!(loaded.is_empty());
    }

    #[test]
    fn signed_manifest_loads_when_signature_valid() {
        use ed25519_dalek::SigningKey;
        use rand_core::OsRng;

        let dir = tempfile::tempdir().unwrap();
        let mut m = from_legacy_spec(&legacy_spec());
        let key = SigningKey::generate(&mut OsRng);
        car_bundle::sign_manifest(&mut m, &key).unwrap();
        write_manifest(dir.path(), &m).unwrap();
        // Loads + verifies; would warn on failure but the manifest
        // is still returned regardless. The success path leaves the
        // signature intact.
        let loaded = load_manifest_dir(dir.path()).unwrap();
        assert_eq!(loaded.len(), 1);
        assert!(loaded[0].publisher.is_some());
        // The freshly-loaded manifest still verifies.
        car_bundle::verify_signature(&loaded[0]).expect("signature should verify");
    }

    #[test]
    fn signed_but_tampered_manifest_still_loads_in_phase_2_with_warning() {
        use ed25519_dalek::SigningKey;
        use rand_core::OsRng;

        let dir = tempfile::tempdir().unwrap();
        let mut m = from_legacy_spec(&legacy_spec());
        let key = SigningKey::generate(&mut OsRng);
        car_bundle::sign_manifest(&mut m, &key).unwrap();
        // Tamper after signing.
        if let TransportSpec::ExternalProcess(ref mut t) = m.transport {
            t.command = Some("/tmp/tampered".into());
        }
        write_manifest(dir.path(), &m).unwrap();
        // Phase 2 warn-but-not-reject: load still returns the entry
        // even though verify will fail. Phase 3 will reject.
        let loaded = load_manifest_dir(dir.path()).unwrap();
        assert_eq!(loaded.len(), 1);
        // But the signature does NOT verify when checked
        // independently.
        assert!(car_bundle::verify_signature(&loaded[0]).is_err());
    }

    // ---------------------------------------------------------------
    // `interpreter` PATH resolution at install (#182 phase 5)
    // ---------------------------------------------------------------

    /// Build an external_process manifest with the given `command`
    /// and `interpreter` slots — both optional so each test exercises
    /// a specific combination.
    fn interp_manifest(command: Option<&str>, interpreter: Option<&str>) -> AgentManifest {
        AgentManifest {
            agent: AgentIdentity {
                id: "portable-agent".into(),
                name: "Portable Agent".into(),
                namespace: Some("parslee".into()),
                version: Some("0.1.0".into()),
                description: None,
                license: None,
                homepage: None,
            },
            publisher: None,
            runtime: None,
            lifecycle: None,
            transport: TransportSpec::ExternalProcess(ExternalProcessTransport {
                command: command.map(str::to_string),
                interpreter: interpreter.map(str::to_string),
                binary_url: None,
                sha256: None,
                health_url: None,
                args: vec!["agent.js".into()],
                cwd: None,
                env: BTreeMap::new(),
                restart: BundleRestartPolicy::OnFailure,
                max_restarts: 10,
                backoff_secs: 5,
                auto_start: false,
                token: String::new(),
                capabilities: Vec::new(),
            }),
            capabilities: None,
        }
    }

    #[test]
    fn interpreter_node_resolves_to_absolute_path_at_install() {
        // `node` is on PATH in the dev/CI environment. The resolved
        // command must be an absolute path ending in `node` (or
        // `node.exe` on Windows). args/cwd/env are unchanged.
        let m = interp_manifest(None, Some("node"));
        let spec = to_agent_spec(&m).expect("interpreter `node` must resolve when node is on PATH");
        let path = Path::new(&spec.command);
        assert!(
            path.is_absolute(),
            "resolved command must be absolute, got: {}",
            spec.command
        );
        let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("");
        assert_eq!(
            stem, "node",
            "resolved command must be node, got: {}",
            spec.command
        );
        // Non-command fields flow through untouched.
        assert_eq!(spec.args, vec!["agent.js".to_string()]);
    }

    #[test]
    fn interpreter_missing_on_path_errors_clearly() {
        let m = interp_manifest(None, Some("nonexistent-xyz"));
        let err = to_agent_spec(&m).expect_err("missing interpreter must fail");
        assert!(
            err.to_string().contains("interpreter not found on $PATH"),
            "expected PATH-not-found reason, got: {err}"
        );
    }

    #[test]
    fn command_and_interpreter_both_set_is_mutual_exclusion_error() {
        let m = interp_manifest(Some("/usr/local/bin/agent"), Some("node"));
        let err = to_agent_spec(&m).expect_err("command + interpreter must be rejected");
        let msg = err.to_string();
        assert!(
            msg.contains("both") && msg.contains("not both"),
            "expected mutual-exclusion reason, got: {msg}"
        );
    }

    #[test]
    fn neither_command_nor_interpreter_is_missing_command_error() {
        let m = interp_manifest(None, None);
        let err = to_agent_spec(&m).expect_err("neither command nor interpreter must fail");
        assert!(
            err.to_string().contains("command` or `interpreter"),
            "expected missing-command reason, got: {err}"
        );
    }

    #[test]
    fn interpreter_survives_toml_round_trip_then_resolves() {
        // Prove the field survives parse → to_agent_spec: serialize a
        // manifest with `interpreter`, parse it back from TOML text
        // (the manifest.toml → JSON-RPC shape a registry ships), and
        // confirm the parsed manifest still resolves the interpreter.
        let m = interp_manifest(None, Some("node"));
        let toml_text = m.to_toml_string().expect("serialize interpreter manifest");
        assert!(
            toml_text.contains("interpreter = \"node\""),
            "interpreter must serialize into the TOML, got:\n{toml_text}"
        );
        let parsed = AgentManifest::from_toml_str(&toml_text).expect("parse interpreter manifest");
        match &parsed.transport {
            TransportSpec::ExternalProcess(t) => {
                assert_eq!(t.interpreter.as_deref(), Some("node"));
                assert!(t.command.is_none());
            }
            _ => panic!("transport kind drift after round-trip"),
        }
        let spec = to_agent_spec(&parsed).expect("parsed interpreter manifest must resolve");
        assert!(Path::new(&spec.command).is_absolute());
    }
}