harn-vm 0.8.8

Async bytecode virtual machine for the Harn programming language
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
use std::cell::RefCell;
use std::collections::{BTreeMap, BTreeSet};

use serde::{Deserialize, Serialize};

use super::{current_mutation_session, new_id, now_rfc3339, ArtifactRecord, RunRecord};

const HANDOFF_TYPE: &str = "handoff_artifact";
const HANDOFF_ARTIFACT_KIND: &str = "handoff";
const RUN_RECEIPT_LINK_KIND: &str = "run_receipt";
const DEFAULT_HANDOFF_KIND: &str = "handoff";

thread_local! {
    static HANDOFF_ROUTES: RefCell<Vec<HandoffRouteConfig>> = const { RefCell::new(Vec::new()) };
}

#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(default)]
pub struct HandoffTargetRecord {
    pub kind: String,
    pub id: Option<String>,
    pub label: Option<String>,
    pub uri: Option<String>,
}

impl HandoffTargetRecord {
    pub fn normalize(mut self) -> Self {
        self.kind = normalize_target_kind(&self.kind);
        if self
            .id
            .as_deref()
            .is_some_and(|value| value.trim().is_empty())
        {
            self.id = None;
        }
        if self
            .label
            .as_deref()
            .is_some_and(|value| value.trim().is_empty())
        {
            self.label = None;
        }
        if self
            .uri
            .as_deref()
            .is_some_and(|value| value.trim().is_empty())
        {
            self.uri = None;
        }
        self
    }

    pub fn display_name(&self) -> String {
        self.label
            .clone()
            .or_else(|| self.id.clone())
            .unwrap_or_else(|| "unknown".to_string())
    }
}

#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct HandoffRouteTargetConfig {
    pub id: Option<String>,
    pub target: String,
    pub when: Option<String>,
    pub transport: Option<String>,
    pub allow_cleartext: Option<bool>,
    pub metadata: BTreeMap<String, serde_json::Value>,
}

impl HandoffRouteTargetConfig {
    pub fn normalize(mut self) -> Self {
        if self
            .id
            .as_deref()
            .is_some_and(|value| value.trim().is_empty())
        {
            self.id = None;
        }
        self.target = self.target.trim().to_string();
        self.when = self
            .when
            .map(|value| value.trim().to_string())
            .filter(|value| !value.is_empty());
        self.transport = self
            .transport
            .map(|value| value.trim().to_string())
            .filter(|value| !value.is_empty());
        self
    }
}

#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct HandoffRouteConfig {
    pub id: Option<String>,
    pub kind: String,
    pub from: String,
    #[serde(alias = "routes")]
    pub route: Vec<HandoffRouteTargetConfig>,
    pub metadata: BTreeMap<String, serde_json::Value>,
}

impl HandoffRouteConfig {
    pub fn normalize(mut self) -> Self {
        if self
            .id
            .as_deref()
            .is_some_and(|value| value.trim().is_empty())
        {
            self.id = None;
        }
        self.kind = normalize_handoff_kind(&self.kind);
        self.from = self.from.trim().to_string();
        self.route = self
            .route
            .into_iter()
            .map(HandoffRouteTargetConfig::normalize)
            .collect();
        self
    }
}

#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct HandoffRouteDecisionRecord {
    pub route_id: Option<String>,
    pub route_index: Option<u64>,
    pub target_index: Option<u64>,
    pub handoff_id: Option<String>,
    pub handoff_kind: String,
    pub source_persona: String,
    pub target: String,
    pub target_persona_or_human: HandoffTargetRecord,
    pub matched_when: String,
    pub selected_at: String,
    pub dispatch_kind: String,
    pub dispatch_status: Option<String>,
    pub dispatch_receipt: Option<serde_json::Value>,
    pub metadata: BTreeMap<String, serde_json::Value>,
}

impl HandoffRouteDecisionRecord {
    pub fn normalize(mut self) -> Self {
        self.handoff_id = self
            .handoff_id
            .map(|value| value.trim().to_string())
            .filter(|value| !value.is_empty());
        self.handoff_kind = normalize_handoff_kind(&self.handoff_kind);
        self.source_persona = self.source_persona.trim().to_string();
        self.target = self.target.trim().to_string();
        self.target_persona_or_human = self.target_persona_or_human.normalize();
        self.matched_when = self.matched_when.trim().to_string();
        if self.matched_when.is_empty() {
            self.matched_when = "always".to_string();
        }
        self.selected_at = self.selected_at.trim().to_string();
        if self.selected_at.is_empty() {
            self.selected_at = now_rfc3339();
        }
        self.dispatch_kind = normalize_target_kind(&self.dispatch_kind);
        self.dispatch_status = self
            .dispatch_status
            .map(|value| value.trim().to_string())
            .filter(|value| !value.is_empty());
        self
    }
}

#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(default)]
pub struct HandoffEvidenceRefRecord {
    pub artifact_id: Option<String>,
    pub kind: Option<String>,
    pub label: Option<String>,
    pub path: Option<String>,
    pub uri: Option<String>,
}

#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct HandoffBudgetRemainingRecord {
    pub tokens: Option<i64>,
    pub tool_calls: Option<i64>,
    pub dollars: Option<f64>,
}

#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(default)]
pub struct HandoffDeadlineCheckbackRecord {
    pub deadline: Option<String>,
    pub checkback_at: Option<String>,
}

#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(default)]
pub struct HandoffReceiptLinkRecord {
    pub kind: String,
    pub label: Option<String>,
    pub run_id: Option<String>,
    pub artifact_id: Option<String>,
    pub path: Option<String>,
    pub href: Option<String>,
}

impl HandoffReceiptLinkRecord {
    pub fn normalize(mut self) -> Self {
        if self.kind.trim().is_empty() {
            self.kind = RUN_RECEIPT_LINK_KIND.to_string();
        }
        if self
            .label
            .as_deref()
            .is_some_and(|value| value.trim().is_empty())
        {
            self.label = None;
        }
        if self
            .run_id
            .as_deref()
            .is_some_and(|value| value.trim().is_empty())
        {
            self.run_id = None;
        }
        if self
            .artifact_id
            .as_deref()
            .is_some_and(|value| value.trim().is_empty())
        {
            self.artifact_id = None;
        }
        if self
            .path
            .as_deref()
            .is_some_and(|value| value.trim().is_empty())
        {
            self.path = None;
        }
        if self
            .href
            .as_deref()
            .is_some_and(|value| value.trim().is_empty())
        {
            self.href = None;
        }
        self
    }
}

#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct HandoffArtifact {
    #[serde(rename = "_type")]
    pub type_name: String,
    pub kind: String,
    pub id: String,
    pub parent_run_id: Option<String>,
    pub source_persona: String,
    pub target_persona_or_human: HandoffTargetRecord,
    pub task: String,
    pub reason: String,
    pub evidence_refs: Vec<HandoffEvidenceRefRecord>,
    pub files_or_entities_touched: Vec<String>,
    pub open_questions: Vec<String>,
    pub blocked_on: Vec<String>,
    pub requested_capabilities: Vec<String>,
    pub allowed_side_effects: Vec<String>,
    pub budget_remaining: Option<HandoffBudgetRemainingRecord>,
    pub deadline_checkback: Option<HandoffDeadlineCheckbackRecord>,
    pub confidence: Option<f64>,
    pub receipt_links: Vec<HandoffReceiptLinkRecord>,
    pub route_decision: Option<HandoffRouteDecisionRecord>,
    pub created_at: String,
    pub metadata: BTreeMap<String, serde_json::Value>,
}

impl HandoffArtifact {
    pub fn normalize(mut self) -> Self {
        if self.type_name.is_empty() {
            self.type_name = HANDOFF_TYPE.to_string();
        }
        self.kind = normalize_handoff_kind(&self.kind);
        if self.id.is_empty() {
            self.id = new_id("handoff");
        }
        if self.created_at.is_empty() {
            self.created_at = now_rfc3339();
        }
        if self.parent_run_id.is_none() {
            self.parent_run_id = current_mutation_session().and_then(|session| session.run_id);
        }
        self.source_persona = self.source_persona.trim().to_string();
        self.task = self.task.trim().to_string();
        self.reason = self.reason.trim().to_string();
        self.target_persona_or_human = self.target_persona_or_human.normalize();
        self.files_or_entities_touched = normalize_string_list(self.files_or_entities_touched);
        self.open_questions = normalize_string_list(self.open_questions);
        self.blocked_on = normalize_string_list(self.blocked_on);
        self.requested_capabilities = normalize_string_list(self.requested_capabilities);
        self.allowed_side_effects = normalize_string_list(self.allowed_side_effects);
        self.receipt_links = self
            .receipt_links
            .into_iter()
            .map(HandoffReceiptLinkRecord::normalize)
            .collect();
        self.route_decision = self
            .route_decision
            .map(HandoffRouteDecisionRecord::normalize);
        self.confidence = self.confidence.map(|value| value.clamp(0.0, 1.0));
        self
    }
}

pub fn install_handoff_routes(routes: Vec<HandoffRouteConfig>) {
    HANDOFF_ROUTES.with(|installed| {
        *installed.borrow_mut() = routes
            .into_iter()
            .map(HandoffRouteConfig::normalize)
            .collect();
    });
}

pub fn snapshot_handoff_routes() -> Vec<HandoffRouteConfig> {
    HANDOFF_ROUTES.with(|installed| installed.borrow().clone())
}

fn normalize_string_list(values: Vec<String>) -> Vec<String> {
    let mut seen = BTreeSet::new();
    values
        .into_iter()
        .map(|value| value.trim().to_string())
        .filter(|value| !value.is_empty() && seen.insert(value.clone()))
        .collect()
}

fn normalize_target_kind(kind: &str) -> String {
    match kind.trim() {
        "human" => "human".to_string(),
        "persona" => "persona".to_string(),
        "a2a" | "external_a2a" => "a2a".to_string(),
        "worker" | "queue" => "worker".to_string(),
        _ => "persona".to_string(),
    }
}

fn normalize_handoff_kind(kind: &str) -> String {
    let kind = kind.trim();
    if kind.is_empty() {
        DEFAULT_HANDOFF_KIND.to_string()
    } else {
        kind.to_string()
    }
}

pub fn normalize_handoff_artifact_json(
    value: serde_json::Value,
) -> Result<HandoffArtifact, String> {
    let handoff: HandoffArtifact =
        serde_json::from_value(value).map_err(|error| format!("handoff parse error: {error}"))?;
    let handoff = handoff.normalize();
    if handoff.source_persona.is_empty() {
        return Err("handoff source_persona is required".to_string());
    }
    if handoff.target_persona_or_human.display_name() == "unknown" {
        return Err("handoff target_persona_or_human is required".to_string());
    }
    if handoff.task.is_empty() {
        return Err("handoff task is required".to_string());
    }
    if handoff.reason.is_empty() {
        return Err("handoff reason is required".to_string());
    }
    if let Some(decision) = handoff.route_decision.as_ref() {
        if decision.target_persona_or_human.display_name() == "unknown" {
            return Err("handoff route_decision target is required".to_string());
        }
    }
    Ok(handoff)
}

pub fn handoff_from_json_value(value: &serde_json::Value) -> Option<HandoffArtifact> {
    let object = value.as_object()?;
    if object.get("_type").and_then(|value| value.as_str()) == Some(HANDOFF_TYPE)
        || (object.contains_key("source_persona")
            && object.contains_key("target_persona_or_human")
            && object.contains_key("task"))
    {
        return normalize_handoff_artifact_json(value.clone()).ok();
    }
    if object.get("_type").and_then(|value| value.as_str()) == Some("artifact")
        || object.get("kind").and_then(|value| value.as_str()) == Some(HANDOFF_ARTIFACT_KIND)
    {
        return object
            .get("data")
            .and_then(handoff_from_json_value)
            .or_else(|| normalize_handoff_artifact_json(value.clone()).ok());
    }
    if object.get("_type").and_then(|value| value.as_str()) == Some("agent_state_handoff") {
        return object
            .get("handoff")
            .and_then(handoff_from_json_value)
            .or_else(|| object.get("summary").and_then(handoff_from_json_value));
    }
    None
}

pub fn extract_handoff_from_artifact(artifact: &ArtifactRecord) -> Option<HandoffArtifact> {
    if artifact.kind != HANDOFF_ARTIFACT_KIND {
        return None;
    }
    artifact.data.as_ref().and_then(handoff_from_json_value)
}

pub fn extract_handoffs_from_json_value(value: &serde_json::Value) -> Vec<HandoffArtifact> {
    fn collect(value: &serde_json::Value, out: &mut Vec<HandoffArtifact>) {
        if let Some(handoff) = handoff_from_json_value(value) {
            out.push(handoff);
        }
        let Some(object) = value.as_object() else {
            return;
        };
        for key in ["handoffs", "artifacts"] {
            if let Some(items) = object.get(key).and_then(|value| value.as_array()) {
                for item in items {
                    collect(item, out);
                }
            }
        }
        for key in ["run", "result"] {
            if let Some(nested) = object.get(key) {
                collect(nested, out);
            }
        }
    }

    let mut handoffs = Vec::new();
    collect(value, &mut handoffs);
    dedup_handoffs(handoffs)
}

fn dedup_handoffs(handoffs: Vec<HandoffArtifact>) -> Vec<HandoffArtifact> {
    let mut by_id = BTreeMap::new();
    for handoff in handoffs {
        by_id
            .entry(handoff.id.clone())
            .and_modify(|existing: &mut HandoffArtifact| {
                *existing = merge_handoffs(existing.clone(), handoff.clone())
            })
            .or_insert(handoff);
    }
    by_id.into_values().collect()
}

fn merge_receipt_links(
    left: Vec<HandoffReceiptLinkRecord>,
    right: Vec<HandoffReceiptLinkRecord>,
) -> Vec<HandoffReceiptLinkRecord> {
    let mut seen = BTreeSet::new();
    left.into_iter()
        .chain(right)
        .map(HandoffReceiptLinkRecord::normalize)
        .filter(|link| {
            seen.insert((
                link.kind.clone(),
                link.run_id.clone(),
                link.artifact_id.clone(),
                link.path.clone(),
                link.href.clone(),
            ))
        })
        .collect()
}

fn merge_handoffs(mut left: HandoffArtifact, right: HandoffArtifact) -> HandoffArtifact {
    if left.parent_run_id.is_none() {
        left.parent_run_id = right.parent_run_id;
    }
    if left.source_persona.is_empty() {
        left.source_persona = right.source_persona;
    }
    if left.target_persona_or_human.display_name() == "unknown" {
        left.target_persona_or_human = right.target_persona_or_human;
    }
    if left.task.is_empty() {
        left.task = right.task;
    }
    if left.reason.is_empty() {
        left.reason = right.reason;
    }
    if left.evidence_refs.is_empty() {
        left.evidence_refs = right.evidence_refs;
    }
    if left.files_or_entities_touched.is_empty() {
        left.files_or_entities_touched = right.files_or_entities_touched;
    }
    if left.open_questions.is_empty() {
        left.open_questions = right.open_questions;
    }
    if left.blocked_on.is_empty() {
        left.blocked_on = right.blocked_on;
    }
    if left.requested_capabilities.is_empty() {
        left.requested_capabilities = right.requested_capabilities;
    }
    if left.allowed_side_effects.is_empty() {
        left.allowed_side_effects = right.allowed_side_effects;
    }
    if left.budget_remaining.is_none() {
        left.budget_remaining = right.budget_remaining;
    }
    if left.deadline_checkback.is_none() {
        left.deadline_checkback = right.deadline_checkback;
    }
    if left.confidence.is_none() {
        left.confidence = right.confidence;
    }
    if left.route_decision.is_none() {
        left.route_decision = right.route_decision;
    }
    left.receipt_links = merge_receipt_links(left.receipt_links, right.receipt_links);
    for (key, value) in right.metadata {
        left.metadata.entry(key).or_insert(value);
    }
    left
}

pub fn handoff_context_text(handoff: &HandoffArtifact) -> String {
    let mut lines = vec![
        format!("<kind>{}</kind>", handoff.kind),
        format!(
            "<source_persona>{}</source_persona>",
            handoff.source_persona
        ),
        format!(
            "<target kind=\"{}\">{}</target>",
            handoff.target_persona_or_human.kind,
            handoff.target_persona_or_human.display_name()
        ),
        format!("<task>{}</task>", handoff.task),
        format!("<reason>{}</reason>", handoff.reason),
    ];
    append_list_section(
        &mut lines,
        "files_or_entities_touched",
        &handoff.files_or_entities_touched,
    );
    append_list_section(&mut lines, "open_questions", &handoff.open_questions);
    append_list_section(&mut lines, "blocked_on", &handoff.blocked_on);
    append_list_section(
        &mut lines,
        "requested_capabilities",
        &handoff.requested_capabilities,
    );
    append_list_section(
        &mut lines,
        "allowed_side_effects",
        &handoff.allowed_side_effects,
    );
    if !handoff.evidence_refs.is_empty() {
        lines.push("<evidence_refs>".to_string());
        for evidence in &handoff.evidence_refs {
            let mut parts = Vec::new();
            if let Some(label) = evidence.label.as_ref() {
                parts.push(label.clone());
            }
            if let Some(artifact_id) = evidence.artifact_id.as_ref() {
                parts.push(format!("artifact_id={artifact_id}"));
            }
            if let Some(path) = evidence.path.as_ref() {
                parts.push(format!("path={path}"));
            }
            if let Some(uri) = evidence.uri.as_ref() {
                parts.push(format!("uri={uri}"));
            }
            if let Some(kind) = evidence.kind.as_ref() {
                parts.push(format!("kind={kind}"));
            }
            lines.push(format!("- {}", parts.join(" | ")));
        }
        lines.push("</evidence_refs>".to_string());
    }
    if let Some(budget) = handoff.budget_remaining.as_ref() {
        lines.push(format!(
            "<budget_remaining tokens=\"{}\" tool_calls=\"{}\" dollars=\"{}\" />",
            budget
                .tokens
                .map(|value| value.to_string())
                .unwrap_or_default(),
            budget
                .tool_calls
                .map(|value| value.to_string())
                .unwrap_or_default(),
            budget
                .dollars
                .map(|value| format!("{value:.4}"))
                .unwrap_or_default(),
        ));
    }
    if let Some(deadline) = handoff.deadline_checkback.as_ref() {
        lines.push(format!(
            "<deadline_checkback deadline=\"{}\" checkback_at=\"{}\" />",
            deadline.deadline.clone().unwrap_or_default(),
            deadline.checkback_at.clone().unwrap_or_default(),
        ));
    }
    if let Some(confidence) = handoff.confidence {
        lines.push(format!("<confidence>{confidence:.2}</confidence>"));
    }
    if let Some(decision) = handoff.route_decision.as_ref() {
        lines.push(format!(
            "<route_decision target=\"{}\" when=\"{}\" dispatch=\"{}\" selected_at=\"{}\" />",
            decision.target, decision.matched_when, decision.dispatch_kind, decision.selected_at
        ));
    }
    format!("<handoff>\n{}\n</handoff>", lines.join("\n"))
}

fn append_list_section(lines: &mut Vec<String>, label: &str, items: &[String]) {
    if items.is_empty() {
        return;
    }
    lines.push(format!("<{label}>"));
    for item in items {
        lines.push(format!("- {item}"));
    }
    lines.push(format!("</{label}>"));
}

fn handoff_target_label(handoff: &HandoffArtifact) -> String {
    handoff.target_persona_or_human.display_name()
}

fn handoff_metadata(handoff: &HandoffArtifact) -> BTreeMap<String, serde_json::Value> {
    BTreeMap::from([
        ("handoff_id".to_string(), serde_json::json!(handoff.id)),
        ("handoff_kind".to_string(), serde_json::json!(handoff.kind)),
        (
            "target_kind".to_string(),
            serde_json::json!(handoff.target_persona_or_human.kind),
        ),
        (
            "target_label".to_string(),
            serde_json::json!(handoff_target_label(handoff)),
        ),
    ])
}

pub fn handoff_artifact_record(
    handoff: &HandoffArtifact,
    existing: Option<&ArtifactRecord>,
) -> ArtifactRecord {
    let mut metadata = existing
        .map(|artifact| artifact.metadata.clone())
        .unwrap_or_default();
    metadata.extend(handoff_metadata(handoff));
    ArtifactRecord {
        type_name: "artifact".to_string(),
        id: existing
            .map(|artifact| artifact.id.clone())
            .unwrap_or_else(|| format!("artifact_{}", handoff.id)),
        kind: HANDOFF_ARTIFACT_KIND.to_string(),
        title: existing
            .and_then(|artifact| artifact.title.clone())
            .or_else(|| Some(format!("Handoff to {}", handoff_target_label(handoff)))),
        text: Some(handoff_context_text(handoff)),
        data: Some(serde_json::to_value(handoff).unwrap_or(serde_json::Value::Null)),
        source: existing
            .and_then(|artifact| artifact.source.clone())
            .or_else(|| Some(handoff.source_persona.clone())),
        created_at: existing
            .map(|artifact| artifact.created_at.clone())
            .unwrap_or_else(now_rfc3339),
        freshness: existing
            .and_then(|artifact| artifact.freshness.clone())
            .or_else(|| Some("fresh".to_string())),
        priority: existing.and_then(|artifact| artifact.priority).or(Some(85)),
        lineage: existing
            .map(|artifact| artifact.lineage.clone())
            .unwrap_or_default(),
        relevance: handoff.confidence.or(Some(1.0)),
        estimated_tokens: None,
        stage: existing.and_then(|artifact| artifact.stage.clone()),
        metadata,
    }
    .normalize()
}

fn receipt_link_for_run(run: &RunRecord) -> HandoffReceiptLinkRecord {
    HandoffReceiptLinkRecord {
        kind: RUN_RECEIPT_LINK_KIND.to_string(),
        label: run
            .workflow_name
            .clone()
            .or_else(|| Some(run.workflow_id.clone())),
        run_id: Some(run.id.clone()),
        artifact_id: None,
        path: run.persisted_path.clone(),
        href: None,
    }
    .normalize()
}

fn sync_handoff_receipt_links(handoff: &mut HandoffArtifact, run: &RunRecord) {
    if handoff.parent_run_id.is_none() {
        handoff.parent_run_id = Some(run.id.clone());
    }
    handoff.receipt_links = merge_receipt_links(
        std::mem::take(&mut handoff.receipt_links),
        vec![receipt_link_for_run(run)],
    );
}

fn artifact_handoff_id(artifact: &ArtifactRecord) -> Option<String> {
    if artifact.kind != HANDOFF_ARTIFACT_KIND {
        return None;
    }
    artifact
        .metadata
        .get("handoff_id")
        .and_then(|value| value.as_str())
        .map(str::to_string)
        .or_else(|| {
            artifact
                .data
                .as_ref()
                .and_then(|value| value.get("id"))
                .and_then(|value| value.as_str())
                .map(str::to_string)
        })
}

pub fn sync_run_handoffs(run: &mut RunRecord) {
    let mut by_id = BTreeMap::new();
    for handoff in std::mem::take(&mut run.handoffs) {
        by_id.insert(handoff.id.clone(), handoff.normalize());
    }
    for artifact in &run.artifacts {
        if let Some(handoff) = extract_handoff_from_artifact(artifact) {
            by_id
                .entry(handoff.id.clone())
                .and_modify(|existing| {
                    *existing = merge_handoffs(existing.clone(), handoff.clone())
                })
                .or_insert(handoff);
        }
    }

    let mut artifact_index_by_handoff_id = BTreeMap::new();
    for (index, artifact) in run.artifacts.iter().enumerate() {
        if let Some(handoff_id) = artifact_handoff_id(artifact) {
            artifact_index_by_handoff_id.insert(handoff_id, index);
        }
    }

    let mut handoffs = by_id.into_values().collect::<Vec<_>>();
    handoffs.sort_by(|left, right| left.created_at.cmp(&right.created_at));
    for handoff in &mut handoffs {
        sync_handoff_receipt_links(handoff, run);
        if let Some(index) = artifact_index_by_handoff_id.get(&handoff.id).copied() {
            let existing = run.artifacts[index].clone();
            run.artifacts[index] = handoff_artifact_record(handoff, Some(&existing));
        } else {
            run.artifacts.push(handoff_artifact_record(handoff, None));
        }
    }
    run.handoffs = handoffs;
}