claw-vcs 0.1.1

Claw VCS: intent-native, agent-native version control.
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
use clap::Args;

use std::collections::HashSet;
use std::path::PathBuf;

use claw_core::id::{ChangeId, ObjectId};
use claw_core::object::Object;
use claw_core::types::{
    Capsule, CapsulePublic, ChangeStatus, Evidence, Intent, IntentStatus, Policy, Revision,
};
use claw_crypto::capsule::{append_capsule_signature, build_capsule, build_capsule_for_recipients};
use claw_crypto::recipient::RecipientPublicKey;
use claw_policy::{evaluator::evaluate_policy, PolicyContext};
use claw_store::ClawStore;

use super::agent::{ensure_registered_signing_agent, keypair_for_agent, AgentRegistration};
use crate::config::{find_repo_root, load_or_default_config};

#[derive(Args)]
pub struct ShipArgs {
    /// Intent ID to ship
    #[arg(short, long)]
    intent: String,
    /// Revision ref to ship
    #[arg(short, long, default_value = "heads/main")]
    revision_ref: String,
    /// Agent ID
    #[arg(short, long, default_value = "claw")]
    agent: String,
    /// Capsule evidence item in the form `name=status[:duration_ms]`.
    #[arg(long = "evidence")]
    evidence: Vec<String>,
    /// Command that produced the supplied evidence
    #[arg(long = "evidence-command")]
    evidence_command: Option<String>,
    /// Runner identity that produced the supplied evidence
    #[arg(long = "runner")]
    runner_identity: Option<String>,
    /// Environment/toolchain digest for freshness-gated evidence
    #[arg(long = "environment-digest")]
    environment_digest: Option<String>,
    /// Log digest for freshness-gated evidence
    #[arg(long = "log-digest")]
    log_digest: Option<String>,
    /// Artifact digest for freshness-gated evidence
    #[arg(long = "artifact-digest")]
    artifact_digest: Option<String>,
    /// Evidence expiration window in milliseconds
    #[arg(long = "evidence-expires-in-ms")]
    evidence_expires_in_ms: Option<u64>,
    /// File containing private capsule metadata to encrypt
    #[arg(long = "private-file")]
    private_file: Option<PathBuf>,
    /// Recipient envelope in the form recipient-id:key-id:hex-x25519-public-key
    #[arg(long = "recipient-key")]
    recipient_keys: Vec<String>,
    /// Add an additional registered agent signature to the capsule
    #[arg(long = "co-sign")]
    co_sign: Vec<String>,
}

fn parse_evidence(items: &[String]) -> anyhow::Result<Vec<Evidence>> {
    let mut out = Vec::with_capacity(items.len());

    for raw in items {
        let (name, status_and_duration) = if let Some(parts) = raw.split_once('=') {
            parts
        } else if let Some(parts) = raw.split_once(':') {
            parts
        } else {
            anyhow::bail!(
                "invalid --evidence '{}'; expected name=status[:duration_ms]",
                raw
            );
        };

        if name.trim().is_empty() {
            anyhow::bail!("invalid --evidence '{}'; name cannot be empty", raw);
        }

        let (status, duration_ms) =
            if let Some((status, duration)) = status_and_duration.split_once(':') {
                let parsed = duration.parse::<u64>().map_err(|_| {
                    anyhow::anyhow!(
                        "invalid --evidence '{}'; duration_ms must be an unsigned integer",
                        raw
                    )
                })?;
                (status, parsed)
            } else {
                (status_and_duration, 0)
            };

        if status.trim().is_empty() {
            anyhow::bail!("invalid --evidence '{}'; status cannot be empty", raw);
        }

        out.push(Evidence {
            name: name.trim().to_string(),
            status: status.trim().to_string(),
            duration_ms,
            artifact_refs: vec![],
            summary: None,
            revision_id: None,
            command: None,
            exit_code: None,
            started_at_ms: None,
            ended_at_ms: None,
            environment_digest: None,
            runner_identity: None,
            log_digest: None,
            artifact_digest: None,
            expires_at_ms: None,
            trust_domain: None,
            signature: None,
        });
    }

    Ok(out)
}

fn parse_recipient_public_keys(items: &[String]) -> anyhow::Result<Vec<RecipientPublicKey>> {
    let mut out = Vec::with_capacity(items.len());
    for raw in items {
        let mut parts = raw.splitn(3, ':');
        let recipient_id = parts.next().unwrap_or_default().trim();
        let key_id = parts.next().unwrap_or_default().trim();
        let public_key_hex = parts.next().unwrap_or_default().trim();

        if recipient_id.is_empty() || key_id.is_empty() || public_key_hex.is_empty() {
            anyhow::bail!(
                "invalid --recipient-key '{}'; expected recipient-id:key-id:hex-x25519-public-key",
                raw
            );
        }

        let public_key_bytes = hex::decode(public_key_hex).map_err(|err| {
            anyhow::anyhow!(
                "invalid --recipient-key '{}'; public key must be 32-byte hex ({err})",
                raw
            )
        })?;
        let public_key: [u8; 32] = public_key_bytes.as_slice().try_into().map_err(|_| {
            anyhow::anyhow!(
                "invalid --recipient-key '{}'; public key must be exactly 32 bytes",
                raw
            )
        })?;

        out.push(RecipientPublicKey {
            recipient_id: recipient_id.to_string(),
            key_id: key_id.to_string(),
            public_key,
        });
    }

    Ok(out)
}

pub fn run(args: ShipArgs) -> anyhow::Result<()> {
    let root = find_repo_root()?;
    let store = ClawStore::open(&root)?;
    let config = load_or_default_config(&root)?;

    // Load intent
    let intent_obj_id = store
        .get_ref(&format!("intents/{}", args.intent))?
        .ok_or_else(|| anyhow::anyhow!("intent not found: {}", args.intent))?;
    let intent_obj = store.load_object(&intent_obj_id)?;
    let mut intent = match intent_obj {
        Object::Intent(i) => i,
        _ => anyhow::bail!("not an intent"),
    };

    // Load revision
    let rev_id = store
        .get_ref(&args.revision_ref)?
        .ok_or_else(|| anyhow::anyhow!("ref not found: {}", args.revision_ref))?;
    let revision_obj = store.load_object(&rev_id)?;
    let revision = match revision_obj {
        Object::Revision(r) => r,
        _ => anyhow::bail!("ref is not a revision: {}", args.revision_ref),
    };

    let now_ms = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)?
        .as_millis() as u64;

    let registered_agent = ensure_registered_signing_agent(&store, &args.agent)?;
    let keypair = keypair_for_agent(&args.agent, &registered_agent)?;
    let mut evidence = parse_evidence(&args.evidence)?;
    enrich_evidence_for_revision(&mut evidence, &rev_id, now_ms, &args);
    let mut signing_agents = vec![registered_agent.clone()];

    let public = CapsulePublic {
        agent_id: registered_agent.agent_id.clone(),
        agent_version: registered_agent.agent_version.clone(),
        toolchain_digest: None,
        env_fingerprint: None,
        evidence,
    };

    let recipients = parse_recipient_public_keys(&args.recipient_keys)?;
    let mut capsule = if let Some(private_file) = args.private_file.as_deref() {
        if recipients.is_empty() {
            anyhow::bail!("--private-file requires at least one --recipient-key");
        }
        let private_data = std::fs::read(private_file)?;
        build_capsule_for_recipients(&rev_id, public, &private_data, &recipients, &keypair)?
    } else {
        if !recipients.is_empty() {
            anyhow::bail!("--recipient-key requires --private-file");
        }
        build_capsule(&rev_id, public, None, None, &keypair)?
    };
    capsule.key_id = Some(registered_agent.public_key.clone());
    for signer in &args.co_sign {
        let cosigner = ensure_registered_signing_agent(&store, signer)?;
        let cosigner_key = keypair_for_agent(signer, &cosigner)?;
        append_capsule_signature(&mut capsule, &cosigner_key)?;
        signing_agents.push(cosigner);
    }

    if config.policy.fail_closed_ship {
        enforce_ship_policies(
            &store,
            &intent,
            &revision,
            &rev_id,
            &capsule,
            &signing_agents,
        )?;
    }

    let capsule_id = store.store_object(&Object::Capsule(capsule))?;

    // Add capsule mapping refs
    store.set_ref(&format!("capsules/{}", rev_id.to_hex()), &capsule_id)?;
    store.set_ref(
        &format!("capsules/by-revision/{}", rev_id.to_hex()),
        &capsule_id,
    )?;
    // Backward-compatible short reverse key.
    store.set_ref(
        &format!("capsules/by-revision/{}", &rev_id.to_hex()[..16]),
        &capsule_id,
    )?;

    let mut finalized_change: Option<ChangeId> = revision.change_id;
    if finalized_change.is_none() && intent.change_ids.len() == 1 {
        if let Ok(single_change) = ChangeId::from_string(&intent.change_ids[0]) {
            finalized_change = Some(single_change);
        }
    }

    if finalized_change.is_none() && intent.change_ids.is_empty() {
        anyhow::bail!(
            "intent {} has no linked changes; create one with `claw change create --intent {}`",
            intent.id,
            intent.id
        );
    }

    if let Some(change_id) = finalized_change {
        let change_ref = format!("changes/{change_id}");
        let Some(change_obj_id) = store.get_ref(&change_ref)? else {
            anyhow::bail!("change not found: {change_id}");
        };
        let change_obj = store.load_object(&change_obj_id)?;
        let Object::Change(mut change) = change_obj else {
            anyhow::bail!("ref {} is not a change", change_ref);
        };
        if change.intent_id != intent.id {
            anyhow::bail!(
                "change {} does not belong to intent {}",
                change.id,
                intent.id
            );
        }
        change.head_revision = Some(rev_id);
        change.status = ChangeStatus::Integrated;
        change.updated_at_ms = now_ms;
        let new_change_id = store.store_object(&Object::Change(change.clone()))?;
        store.set_ref(&change_ref, &new_change_id)?;

        let change_id_string = change.id.to_string();
        if !intent.change_ids.iter().any(|id| id == &change_id_string) {
            intent.change_ids.push(change_id_string);
        }
    }

    // Update intent status coherently with associated changes.
    let mut updated_intent = intent;
    let mut intent_changed = false;

    let all_integrated = if updated_intent.change_ids.is_empty() {
        false
    } else {
        let mut all_integrated = true;
        for change_id in &updated_intent.change_ids {
            let Some(change_obj_id) = store.get_ref(&format!("changes/{change_id}"))? else {
                all_integrated = false;
                break;
            };
            let change_obj = store.load_object(&change_obj_id)?;
            let Object::Change(change) = change_obj else {
                all_integrated = false;
                break;
            };
            if change.intent_id != updated_intent.id {
                all_integrated = false;
                break;
            }
            if change.status != ChangeStatus::Integrated {
                all_integrated = false;
                break;
            }
        }
        all_integrated
    };

    if all_integrated {
        if updated_intent.status != IntentStatus::Done
            && updated_intent.status != IntentStatus::Superseded
        {
            updated_intent.status = IntentStatus::Done;
            intent_changed = true;
        }
    } else if updated_intent.status == IntentStatus::Done {
        updated_intent.status = IntentStatus::Open;
        intent_changed = true;
    }

    if intent_changed {
        updated_intent.updated_at_ms = now_ms;
    }

    let new_intent_id = store.store_object(&Object::Intent(updated_intent.clone()))?;
    store.set_ref(&format!("intents/{}", updated_intent.id), &new_intent_id)?;

    println!("Shipped intent: {}", updated_intent.id);
    println!("  Capsule: {capsule_id}");
    println!("  Revision: {rev_id}");

    Ok(())
}

fn enforce_ship_policies(
    store: &ClawStore,
    intent: &Intent,
    revision: &Revision,
    rev_id: &ObjectId,
    capsule: &Capsule,
    signing_agents: &[AgentRegistration],
) -> anyhow::Result<()> {
    let policies = load_policies_for_intent(store, intent)?;
    if policies.is_empty() {
        return Ok(());
    }

    let (signer_agent_ids, signer_key_ids) = policy_signers(signing_agents);
    let context = PolicyContext {
        revision_id: Some(*rev_id),
        signer_agent_ids,
        signer_key_ids,
        touched_paths: collect_touched_paths(store, revision)?,
        trust_score: derive_capsule_trust_score(capsule),
        now_ms: Some(current_time_ms()),
    };

    for policy in policies {
        evaluate_policy(&policy, revision, capsule, &context).map_err(|err| {
            anyhow::anyhow!(
                "policy '{}' blocked shipping revision {} for intent {}: {}. Add the required evidence/reviewer signatures (for example with --evidence/--co-sign) or set policy.fail_closed_ship = false in .claw/config.toml",
                policy.policy_id,
                rev_id.to_hex(),
                intent.id,
                err
            )
        })?;
    }

    Ok(())
}

fn enrich_evidence_for_revision(
    evidence: &mut [Evidence],
    rev_id: &ObjectId,
    now_ms: u64,
    args: &ShipArgs,
) {
    for item in evidence {
        item.revision_id.get_or_insert(*rev_id);
        item.started_at_ms.get_or_insert(now_ms);
        item.ended_at_ms.get_or_insert(now_ms);
        item.exit_code
            .get_or_insert(if item.status.eq_ignore_ascii_case("pass") {
                0
            } else {
                1
            });
        if item.command.is_none() {
            item.command = args.evidence_command.clone();
        }
        if item.runner_identity.is_none() {
            item.runner_identity = args.runner_identity.clone();
        }
        if item.environment_digest.is_none() {
            item.environment_digest = args.environment_digest.clone();
        }
        if item.log_digest.is_none() {
            item.log_digest = args.log_digest.clone();
        }
        if item.artifact_digest.is_none() {
            item.artifact_digest = args.artifact_digest.clone();
        }
        if item.expires_at_ms.is_none() {
            item.expires_at_ms = args
                .evidence_expires_in_ms
                .map(|ttl| now_ms.saturating_add(ttl));
        }
    }
}

fn current_time_ms() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|duration| duration.as_millis().min(u128::from(u64::MAX)) as u64)
        .unwrap_or_default()
}

fn load_policies_for_intent(store: &ClawStore, intent: &Intent) -> anyhow::Result<Vec<Policy>> {
    if intent.policy_refs.is_empty() {
        return Ok(vec![]);
    }

    let mut policies = Vec::new();
    let mut seen = HashSet::new();
    for policy_ref in &intent.policy_refs {
        let policy = load_policy_ref(store, policy_ref)?;
        if seen.insert(policy.policy_id.clone()) {
            policies.push(policy);
        }
    }

    Ok(policies)
}

fn load_policy_ref(store: &ClawStore, policy_ref: &str) -> anyhow::Result<Policy> {
    let ref_name = if store.get_ref(policy_ref)?.is_some() {
        policy_ref.to_string()
    } else {
        format!("policies/{policy_ref}")
    };

    let policy_obj_id = store
        .get_ref(&ref_name)?
        .ok_or_else(|| anyhow::anyhow!("policy ref not found: {}", ref_name))?;
    let policy_obj = store.load_object(&policy_obj_id)?;
    match policy_obj {
        Object::Policy(policy) => Ok(policy),
        _ => anyhow::bail!("ref does not point to a policy object: {}", ref_name),
    }
}

fn policy_signers(signing_agents: &[AgentRegistration]) -> (Vec<String>, Vec<String>) {
    let mut signer_agent_ids = Vec::new();
    let mut signer_key_ids = Vec::new();
    let mut seen_agents = HashSet::new();
    let mut seen_keys = HashSet::new();

    for agent in signing_agents {
        let agent_id = agent.agent_id.trim();
        if !agent_id.is_empty() {
            let normalized = agent_id.to_ascii_lowercase();
            if seen_agents.insert(normalized) {
                signer_agent_ids.push(agent_id.to_string());
            }
        }

        let key_id = agent.public_key.trim().to_ascii_lowercase();
        if !key_id.is_empty() && seen_keys.insert(key_id.clone()) {
            signer_key_ids.push(key_id);
        }
    }

    signer_agent_ids.sort();
    signer_key_ids.sort();
    (signer_agent_ids, signer_key_ids)
}

fn derive_capsule_trust_score(capsule: &Capsule) -> Option<f32> {
    let total = capsule.public_fields.evidence.len();
    if total == 0 {
        return None;
    }

    let passed = capsule
        .public_fields
        .evidence
        .iter()
        .filter(|e| e.status.eq_ignore_ascii_case("pass"))
        .count();

    Some(passed as f32 / total as f32)
}

fn collect_touched_paths(store: &ClawStore, revision: &Revision) -> anyhow::Result<Vec<String>> {
    let mut touched_paths = Vec::new();
    let mut seen = HashSet::new();

    for patch_id in &revision.patches {
        let patch_obj = store.load_object(patch_id)?;
        let patch = match patch_obj {
            Object::Patch(patch) => patch,
            _ => anyhow::bail!(
                "revision patch reference does not point to a patch object: {}",
                patch_id.to_hex()
            ),
        };

        let path = patch.target_path.trim();
        if path.is_empty() {
            continue;
        }
        if seen.insert(path.to_string()) {
            touched_paths.push(path.to_string());
        }
    }

    Ok(touched_paths)
}

#[cfg(test)]
mod tests {
    use super::{
        collect_touched_paths, derive_capsule_trust_score, parse_evidence,
        parse_recipient_public_keys, policy_signers,
    };
    use crate::commands::agent::AgentRegistration;
    use claw_core::object::{Object, TypeTag};
    use claw_core::types::{Capsule, CapsulePublic, Evidence, Patch, Revision};
    use claw_store::ClawStore;

    fn test_store() -> (tempfile::TempDir, ClawStore) {
        let temp = tempfile::tempdir().unwrap();
        let store = ClawStore::init(temp.path()).unwrap();
        (temp, store)
    }

    #[test]
    fn parses_evidence_with_equals_and_optional_duration() {
        let parsed =
            parse_evidence(&["test=pass:1200".to_string(), "lint=pass".to_string()]).unwrap();

        assert_eq!(parsed.len(), 2);
        assert_eq!(parsed[0].name, "test");
        assert_eq!(parsed[0].status, "pass");
        assert_eq!(parsed[0].duration_ms, 1200);
        assert_eq!(parsed[1].name, "lint");
        assert_eq!(parsed[1].status, "pass");
        assert_eq!(parsed[1].duration_ms, 0);
    }

    #[test]
    fn rejects_invalid_evidence_format() {
        assert!(parse_evidence(&["broken".to_string()]).is_err());
        assert!(parse_evidence(&["=pass".to_string()]).is_err());
        assert!(parse_evidence(&["test=".to_string()]).is_err());
        assert!(parse_evidence(&["test=pass:notnum".to_string()]).is_err());
    }

    #[test]
    fn parses_recipient_public_key_envelope_input() {
        let parsed =
            parse_recipient_public_keys(&[format!("security:security-key:{}", "07".repeat(32))])
                .unwrap();

        assert_eq!(parsed.len(), 1);
        assert_eq!(parsed[0].recipient_id, "security");
        assert_eq!(parsed[0].key_id, "security-key");
        assert_eq!(parsed[0].public_key, [7u8; 32]);
        assert!(parse_recipient_public_keys(&["security:missing-key".to_string()]).is_err());
        assert!(
            parse_recipient_public_keys(&[format!("security:key:{}", "07".repeat(31))]).is_err()
        );
    }

    #[test]
    fn derives_capsule_trust_score_from_pass_ratio() {
        let revision_id = claw_core::hash::content_hash(TypeTag::Revision, b"ship");
        let capsule = Capsule {
            revision_id,
            public_fields: CapsulePublic {
                agent_id: "agent".to_string(),
                agent_version: None,
                toolchain_digest: None,
                env_fingerprint: None,
                evidence: vec![
                    Evidence {
                        name: "ci/test".to_string(),
                        status: "PASS".to_string(),
                        duration_ms: 0,
                        artifact_refs: vec![],
                        summary: None,
                        revision_id: None,
                        command: None,
                        exit_code: None,
                        started_at_ms: None,
                        ended_at_ms: None,
                        environment_digest: None,
                        runner_identity: None,
                        log_digest: None,
                        artifact_digest: None,
                        expires_at_ms: None,
                        trust_domain: None,
                        signature: None,
                    },
                    Evidence {
                        name: "lint".to_string(),
                        status: "fail".to_string(),
                        duration_ms: 0,
                        artifact_refs: vec![],
                        summary: None,
                        revision_id: None,
                        command: None,
                        exit_code: None,
                        started_at_ms: None,
                        ended_at_ms: None,
                        environment_digest: None,
                        runner_identity: None,
                        log_digest: None,
                        artifact_digest: None,
                        expires_at_ms: None,
                        trust_domain: None,
                        signature: None,
                    },
                ],
            },
            encrypted_private: None,
            encryption: String::new(),
            key_id: None,
            recipients: vec![],
            signatures: vec![],
        };

        assert_eq!(derive_capsule_trust_score(&capsule), Some(0.5));
    }

    #[test]
    fn policy_signers_deduplicate_agent_ids_and_keys() {
        let signers = vec![
            AgentRegistration {
                schema_version: 2,
                agent_id: "agent-a".to_string(),
                agent_version: None,
                public_key: "ABCDEF".to_string(),
                private_key: None,
                revoked_at_ms: None,
                revocation_reason: None,
                created_at_ms: 1,
                updated_at_ms: 1,
            },
            AgentRegistration {
                schema_version: 2,
                agent_id: "AGENT-A".to_string(),
                agent_version: None,
                public_key: "abcdef".to_string(),
                private_key: None,
                revoked_at_ms: None,
                revocation_reason: None,
                created_at_ms: 1,
                updated_at_ms: 1,
            },
            AgentRegistration {
                schema_version: 2,
                agent_id: "agent-b".to_string(),
                agent_version: None,
                public_key: "1234".to_string(),
                private_key: None,
                revoked_at_ms: None,
                revocation_reason: None,
                created_at_ms: 1,
                updated_at_ms: 1,
            },
        ];

        let (agent_ids, key_ids) = policy_signers(&signers);
        assert_eq!(
            agent_ids,
            vec!["agent-a".to_string(), "agent-b".to_string()]
        );
        assert_eq!(key_ids, vec!["1234".to_string(), "abcdef".to_string()]);
    }

    #[test]
    fn collects_touched_paths_from_revision_patches() {
        let (_tmp, store) = test_store();
        let patch_a_id = store
            .store_object(&Object::Patch(Patch {
                target_path: "src/main.rs".to_string(),
                codec_id: "text".to_string(),
                base_object: None,
                result_object: None,
                ops: vec![],
                codec_payload: None,
            }))
            .unwrap();
        let patch_b_id = store
            .store_object(&Object::Patch(Patch {
                target_path: " src/main.rs ".to_string(),
                codec_id: "text".to_string(),
                base_object: None,
                result_object: None,
                ops: vec![],
                codec_payload: None,
            }))
            .unwrap();
        let patch_c_id = store
            .store_object(&Object::Patch(Patch {
                target_path: "".to_string(),
                codec_id: "text".to_string(),
                base_object: None,
                result_object: None,
                ops: vec![],
                codec_payload: None,
            }))
            .unwrap();

        let revision = Revision {
            change_id: None,
            parents: vec![],
            patches: vec![patch_a_id, patch_b_id, patch_c_id],
            snapshot_base: None,
            tree: None,
            capsule_id: None,
            author: "test".to_string(),
            created_at_ms: 1,
            summary: "ship".to_string(),
            policy_evidence: vec![],
        };

        let touched = collect_touched_paths(&store, &revision).unwrap();
        assert_eq!(touched, vec!["src/main.rs".to_string()]);
    }
}