harn-vm 0.8.26

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
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
//! Typed effect records carried on `HandoffArtifact` envelopes.
//!
//! `EffectRecord` is the leaf payload that names a single side-effect a
//! spawned child agent may exercise (e.g. `Net write to https://api.example`,
//! `Fs read of /workspace/src`). The set sits on each handoff so the
//! dispatcher (E5.4) and the OpenTrustGraph receipt chain (E5.5) can prove
//! the child never escaped its parent's effect grant.
//!
//! Computation at spawn time walks the child's entrypoint module via the
//! same capability analysis `harn graph --json` uses (issue HARN-#1758),
//! plus a recursive AST walker that lifts harness sub-handle method calls
//! (`harness.net.get(...)`, `harness.fs.write_file(...)`, ...) into the
//! same effect shape. The two extraction paths feed one canonicalization
//! step so downstream consumers see a single deduped, deterministically
//! ordered list.

use std::collections::{BTreeMap, BTreeSet};

use serde::{Deserialize, Serialize};

use harn_ir::{CallClassification, Capability, LiteralValue, NodeSemantics};
use harn_parser::{Node, SNode};

use super::CapabilityPolicy;

/// Discriminator for the kind of effect captured. Matches the
/// classification used by the OpenTrustGraph receipt format (E5.5).
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Ord, PartialOrd, Hash)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum EffectKind {
    /// Reads or writes against the host's stdio streams.
    Stdio,
    /// Filesystem access (read, write, list, delete, ...).
    Fs,
    /// Network access (HTTP, SSE, WebSocket).
    Net,
    /// LLM model calls — captures the provider and model when statically
    /// known so the receipt chain can name the inference dependency.
    Llm {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        provider: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        model: Option<String>,
    },
    /// Pipeline-declared tool dispatched through the agent loop.
    Tool { name: String },
    /// Bridged host capability call (`host_call(capability.operation, ...)`).
    Hostcall { name: String },
    /// Targeted delegation to a named persona / sub-agent identity.
    Persona { id: String },
    /// Spawn / sub-agent / worker dispatch primitives.
    Spawn,
}

/// What kind of interaction the effect represents. Mirrors the
/// `read | write | mutate | observe` taxonomy the receipt schema uses.
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, Ord, PartialOrd, Hash)]
#[serde(rename_all = "snake_case")]
pub enum EffectScope {
    /// Pure read: no observable state change for other actors.
    Read,
    /// Write that creates or replaces state owned by this effect.
    Write,
    /// Mutation of state that may already be observed by other actors.
    Mutate,
    /// Side-channel observation (stdio sink, telemetry emission, ...).
    Observe,
}

/// Single typed effect carried on a `HandoffArtifact.effects` entry.
///
/// `resource` is an opaque, statically-known target identifier (path,
/// URL, tool id, persona id). The dispatcher (E5.4) is free to enforce
/// ⊆ against the resource string; when no resource can be derived the
/// field stays `None`.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Ord, PartialOrd, Hash)]
pub struct EffectRecord {
    pub kind: EffectKind,
    pub scope: EffectScope,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resource: Option<String>,
}

impl EffectRecord {
    pub fn new(kind: EffectKind, scope: EffectScope) -> Self {
        Self {
            kind,
            scope,
            resource: None,
        }
    }

    pub fn with_resource(mut self, resource: impl Into<String>) -> Self {
        let resource = resource.into();
        self.resource = if resource.is_empty() {
            None
        } else {
            Some(resource)
        };
        self
    }
}

/// Compute the effect set for a child agent's entrypoint module.
///
/// Parses `source`, walks the resulting AST via the same `harn_ir`
/// capability analyzer that backs `harn graph --json`, and also lifts
/// harness sub-handle method calls (`harness.net.get(...)`, etc.) into
/// the same effect shape. The result is deterministically ordered and
/// deduplicated.
///
/// When `ceiling` is provided, the result is clamped to it: an effect
/// is dropped if the ceiling's `capabilities` map is non-empty and does
/// not allow the matching capability/op, or if the effect's
/// `side_effect_level` exceeds the ceiling's `side_effect_level`. Empty
/// ceilings are treated as "no constraint" — the same convention the
/// rest of the policy machinery uses.
pub fn compute_handoff_effects(
    source: &str,
    ceiling: Option<&CapabilityPolicy>,
) -> Vec<EffectRecord> {
    let Ok(program) = harn_parser::parse_source(source) else {
        return Vec::new();
    };
    let mut collected: BTreeSet<EffectRecord> = BTreeSet::new();

    // Builtin / host-call effects via the existing IR analyzer — same
    // surface `harn graph --json` reads.
    let report = harn_ir::analyze_program(&program);
    for handler in &report.handlers {
        for node in &handler.nodes {
            let NodeSemantics::Call(call) = &node.semantics else {
                continue;
            };
            for effect in effects_from_call(call) {
                collected.insert(effect);
            }
        }
    }

    // Harness sub-handle method calls aren't builtin invocations, so the
    // IR doesn't see them. Walk the AST directly to lift them into the
    // same shape — keeps producer-side analysis consistent with what the
    // dispatcher will need to enforce.
    for node in &program {
        walk_for_harness_effects(node, &mut collected);
    }

    let mut effects: Vec<EffectRecord> = collected.into_iter().collect();
    if let Some(ceiling) = ceiling {
        effects.retain(|effect| effect_allowed_by_ceiling(effect, ceiling));
    }
    effects
}

fn effects_from_call(call: &harn_ir::CallSemantics) -> Vec<EffectRecord> {
    // Primary extraction: name-based builtin recognition. This path
    // carries the richest information (resource from literal args,
    // provider/model on LLM calls) and is the authoritative shape.
    if let Some(effect) = builtin_effect(&call.name) {
        return vec![annotate_with_resource(effect, call)];
    }
    if call.name == "host_call" {
        if let Some(operation) = call.literal_args.first().and_then(literal_as_str) {
            return vec![EffectRecord::new(
                EffectKind::Hostcall {
                    name: operation.to_string(),
                },
                hostcall_scope(operation),
            )];
        }
    }
    // Fallback: pipeline-declared tools and other capabilities the
    // builtin recognizer doesn't know about (custom tool_call dispatch,
    // user-defined capability classifications). Only consulted when the
    // primary extraction returns nothing — same call shouldn't produce
    // two records with different `resource` fields just because two
    // extraction paths happen to match.
    if let CallClassification::Capabilities(capability_effects) = &call.classification {
        return capability_effects
            .iter()
            .filter_map(capability_effect_to_record)
            .collect();
    }
    Vec::new()
}

fn builtin_effect(name: &str) -> Option<EffectRecord> {
    match name {
        // stdio
        "print" | "println" | "eprint" | "eprintln" | "write_stdout" | "write_stderr" => {
            Some(EffectRecord::new(EffectKind::Stdio, EffectScope::Observe))
        }
        "read_stdin" => Some(EffectRecord::new(EffectKind::Stdio, EffectScope::Read)),

        // fs reads
        "read_file" | "read_file_bytes" | "read_file_result" | "read_lines" | "list_dir"
        | "walk_dir" | "glob" | "file_exists" | "stat" => {
            Some(EffectRecord::new(EffectKind::Fs, EffectScope::Read))
        }

        // fs writes
        "write_file" | "write_file_bytes" | "append_file" | "mkdir" | "copy_file" | "move_file" => {
            Some(EffectRecord::new(EffectKind::Fs, EffectScope::Write))
        }
        "delete_file" => Some(EffectRecord::new(EffectKind::Fs, EffectScope::Mutate)),
        "apply_edit" => Some(EffectRecord::new(EffectKind::Fs, EffectScope::Mutate)),

        // network — mirrors `is_network_call` in harn-ir; the EffectKind
        // is identical for every transport because the dispatcher (E5.4)
        // enforces the ⊆ relation at the `Net` granularity, not per-verb.
        "http_get"
        | "http_post"
        | "http_put"
        | "http_patch"
        | "http_delete"
        | "http_request"
        | "http_download"
        | "http_session"
        | "http_session_request"
        | "http_session_close"
        | "http_stream_open"
        | "http_stream_read"
        | "http_stream_close"
        | "sse_connect"
        | "sse_receive"
        | "sse_close"
        | "sse_server_response"
        | "sse_server_send"
        | "sse_server_heartbeat"
        | "sse_server_flush"
        | "sse_server_close"
        | "sse_server_cancel"
        | "websocket_connect"
        | "websocket_accept"
        | "websocket_send"
        | "websocket_receive"
        | "websocket_close"
        | "websocket_route"
        | "websocket_server"
        | "websocket_server_close" => Some(EffectRecord::new(EffectKind::Net, EffectScope::Write)),

        // llm
        "llm_call"
        | "llm_call_safe"
        | "llm_stream_call"
        | "llm_call_structured"
        | "llm_call_structured_safe"
        | "llm_call_structured_result"
        | "llm_completion"
        | "agent_llm_turn"
        | "agent_turn"
        | "agent_loop" => Some(EffectRecord::new(
            EffectKind::Llm {
                provider: None,
                model: None,
            },
            EffectScope::Write,
        )),

        // spawn / worker dispatch
        "spawn_agent"
        | "send_input"
        | "resume_agent"
        | "wait_agent"
        | "close_agent"
        | "worker_trigger"
        | "__host_sub_agent_run"
        | "__host_worker_spawn"
        | "__host_worker_send_input"
        | "__host_worker_resume"
        | "__host_worker_trigger"
        | "__host_worker_wait"
        | "__host_worker_close" => Some(EffectRecord::new(EffectKind::Spawn, EffectScope::Write)),

        // pipeline-declared tools dispatched through tool_call
        "tool_call" | "host_tool_call" => Some(EffectRecord::new(
            EffectKind::Tool {
                name: String::new(),
            },
            EffectScope::Write,
        )),

        _ => None,
    }
}

fn annotate_with_resource(mut effect: EffectRecord, call: &harn_ir::CallSemantics) -> EffectRecord {
    // Effect resources are best-effort: first literal arg (path / url /
    // tool name) when statically derivable. Unknown literals stay
    // unannotated rather than guessed.
    match &mut effect.kind {
        EffectKind::Llm { provider, model } => {
            for arg in &call.literal_args {
                if let LiteralValue::Dict(entries) = arg {
                    if let Some(value) = entries.get("provider").and_then(literal_as_str) {
                        *provider = Some(value.to_string());
                    }
                    if let Some(value) = entries.get("model").and_then(literal_as_str) {
                        *model = Some(value.to_string());
                    }
                }
            }
        }
        EffectKind::Tool { name } => {
            if let Some(value) = call.literal_args.first().and_then(literal_as_str) {
                *name = value.to_string();
            }
        }
        _ => {
            if let Some(value) = call.literal_args.first().and_then(literal_as_str) {
                effect.resource = Some(value.to_string());
            }
        }
    }
    effect
}

fn capability_effect_to_record(effect: &harn_ir::CapabilityEffect) -> Option<EffectRecord> {
    let (kind, scope) = match effect.capability {
        Capability::WorkspaceMutation => (EffectKind::Fs, EffectScope::Mutate),
        Capability::CommandExecution => (
            EffectKind::Hostcall {
                name: format!("process.{}", effect.operation),
            },
            EffectScope::Write,
        ),
        Capability::NetworkAccess => (EffectKind::Net, EffectScope::Write),
        Capability::ConnectorAccess => (
            EffectKind::Hostcall {
                name: if effect.operation.is_empty() {
                    "connector.call".to_string()
                } else {
                    format!("connector.{}", effect.operation)
                },
            },
            EffectScope::Write,
        ),
        Capability::ModelCall => (
            EffectKind::Llm {
                provider: None,
                model: None,
            },
            EffectScope::Write,
        ),
        Capability::WorkerDispatch => (EffectKind::Spawn, EffectScope::Write),
        Capability::HumanApproval => return None,
        Capability::AutonomyPolicy => return None,
    };
    let resource = effect.path.clone();
    Some(EffectRecord {
        kind,
        scope,
        resource,
    })
}

fn hostcall_scope(operation: &str) -> EffectScope {
    match operation {
        op if op.starts_with("workspace.read") || op.starts_with("workspace.list") => {
            EffectScope::Read
        }
        op if op.starts_with("workspace.write") || op == "workspace.apply_edit" => {
            EffectScope::Mutate
        }
        op if op.starts_with("process.") => EffectScope::Write,
        _ => EffectScope::Write,
    }
}

fn literal_as_str(value: &LiteralValue) -> Option<&str> {
    match value {
        LiteralValue::String(value) | LiteralValue::Identifier(value) => Some(value.as_str()),
        _ => None,
    }
}

fn walk_for_harness_effects(node: &SNode, out: &mut BTreeSet<EffectRecord>) {
    if let Some(effect) = harness_method_effect(node) {
        out.insert(effect);
    }
    for child in child_nodes(node) {
        walk_for_harness_effects(child, out);
    }
}

fn harness_method_effect(node: &SNode) -> Option<EffectRecord> {
    let (object, method) = match &node.node {
        Node::MethodCall { object, method, .. }
        | Node::OptionalMethodCall { object, method, .. } => (object, method),
        _ => return None,
    };
    let (sub_handle, root) = harness_sub_handle(object)?;
    if !is_harness_root(root) {
        return None;
    }
    let (kind, scope) = match (sub_handle.as_str(), method.as_str()) {
        ("stdio", "print" | "println" | "eprint" | "eprintln") => {
            (EffectKind::Stdio, EffectScope::Observe)
        }
        ("stdio", "read_line" | "prompt") => (EffectKind::Stdio, EffectScope::Read),
        ("clock", _) => return None,
        ("env", "set" | "unset") => (
            EffectKind::Hostcall {
                name: "env.set".to_string(),
            },
            EffectScope::Mutate,
        ),
        ("env", _) => (
            EffectKind::Hostcall {
                name: "env.get".to_string(),
            },
            EffectScope::Read,
        ),
        ("random", _) => return None,
        ("fs", "read_file" | "read_text" | "read" | "exists" | "list_dir" | "stat") => {
            (EffectKind::Fs, EffectScope::Read)
        }
        ("fs", "write_file" | "write_text" | "append_file" | "mkdir" | "copy_file") => {
            (EffectKind::Fs, EffectScope::Write)
        }
        ("fs", "delete_file" | "delete" | "remove") => (EffectKind::Fs, EffectScope::Mutate),
        ("fs", _) => (EffectKind::Fs, EffectScope::Read),
        ("net", _) => (EffectKind::Net, EffectScope::Write),
        _ => return None,
    };
    Some(EffectRecord::new(kind, scope))
}

fn harness_sub_handle(node: &SNode) -> Option<(String, &SNode)> {
    match &node.node {
        Node::PropertyAccess { object, property }
        | Node::OptionalPropertyAccess { object, property } => {
            Some((property.clone(), object.as_ref()))
        }
        _ => None,
    }
}

fn is_harness_root(node: &SNode) -> bool {
    matches!(&node.node, Node::Identifier(name) if name == "harness")
}

fn child_nodes(node: &SNode) -> Vec<&SNode> {
    let mut children: Vec<&SNode> = Vec::new();
    match &node.node {
        Node::AttributedDecl { inner, .. } => children.push(inner.as_ref()),
        Node::Pipeline { body, .. }
        | Node::FnDecl { body, .. }
        | Node::ToolDecl { body, .. }
        | Node::SpawnExpr { body }
        | Node::Retry { body, .. }
        | Node::TryExpr { body }
        | Node::DeferStmt { body }
        | Node::MutexBlock { body }
        | Node::Block(body)
        | Node::OverrideDecl { body, .. } => children.extend(body.iter()),
        Node::ImplBlock { methods, .. } => children.extend(methods.iter()),
        Node::IfElse {
            condition,
            then_body,
            else_body,
        } => {
            children.push(condition.as_ref());
            children.extend(then_body.iter());
            if let Some(else_body) = else_body.as_ref() {
                children.extend(else_body.iter());
            }
        }
        Node::ForIn { iterable, body, .. } => {
            children.push(iterable.as_ref());
            children.extend(body.iter());
        }
        Node::WhileLoop { condition, body } => {
            children.push(condition.as_ref());
            children.extend(body.iter());
        }
        Node::MatchExpr { value, arms } => {
            children.push(value.as_ref());
            for arm in arms {
                if let Some(guard) = arm.guard.as_ref() {
                    children.push(guard.as_ref());
                }
                children.extend(arm.body.iter());
            }
        }
        Node::CostRoute { options, body } => {
            for (_key, value) in options {
                children.push(value);
            }
            children.extend(body.iter());
        }
        Node::ReturnStmt { value } => {
            if let Some(value) = value.as_ref() {
                children.push(value.as_ref());
            }
        }
        Node::ThrowStmt { value } => children.push(value.as_ref()),
        Node::TryCatch {
            body,
            catch_body,
            finally_body,
            ..
        } => {
            children.extend(body.iter());
            children.extend(catch_body.iter());
            if let Some(finally_body) = finally_body.as_ref() {
                children.extend(finally_body.iter());
            }
        }
        Node::SkillDecl { fields, .. } => {
            for (_name, value) in fields {
                children.push(value);
            }
        }
        Node::EvalPackDecl {
            fields,
            body,
            summarize,
            ..
        } => {
            for (_name, value) in fields {
                children.push(value);
            }
            children.extend(body.iter());
            if let Some(summarize) = summarize.as_ref() {
                children.extend(summarize.iter());
            }
        }
        Node::LetBinding { value, .. } | Node::VarBinding { value, .. } => {
            children.push(value.as_ref());
        }
        Node::DeadlineBlock { duration, body } => {
            children.push(duration.as_ref());
            children.extend(body.iter());
        }
        Node::YieldExpr { value } => {
            if let Some(value) = value.as_ref() {
                children.push(value.as_ref());
            }
        }
        Node::EmitExpr { value } => children.push(value.as_ref()),
        Node::GuardStmt {
            condition,
            else_body,
        } => {
            children.push(condition.as_ref());
            children.extend(else_body.iter());
        }
        Node::RequireStmt { condition, message } => {
            children.push(condition.as_ref());
            if let Some(message) = message.as_ref() {
                children.push(message.as_ref());
            }
        }
        Node::HitlExpr { args, .. } => {
            for arg in args {
                children.push(&arg.value);
            }
        }
        Node::Parallel {
            expr,
            body,
            options,
            ..
        } => {
            children.push(expr.as_ref());
            children.extend(body.iter());
            for (_key, value) in options {
                children.push(value);
            }
        }
        Node::SelectExpr {
            cases,
            timeout,
            default_body,
        } => {
            for case in cases {
                children.push(case.channel.as_ref());
                children.extend(case.body.iter());
            }
            if let Some((duration, body)) = timeout.as_ref() {
                children.push(duration.as_ref());
                children.extend(body.iter());
            }
            if let Some(body) = default_body.as_ref() {
                children.extend(body.iter());
            }
        }
        Node::FunctionCall { args, .. } => children.extend(args.iter()),
        Node::MethodCall { object, args, .. } | Node::OptionalMethodCall { object, args, .. } => {
            children.push(object.as_ref());
            children.extend(args.iter());
        }
        Node::PropertyAccess { object, .. } | Node::OptionalPropertyAccess { object, .. } => {
            children.push(object.as_ref());
        }
        Node::SubscriptAccess { object, index }
        | Node::OptionalSubscriptAccess { object, index } => {
            children.push(object.as_ref());
            children.push(index.as_ref());
        }
        Node::SliceAccess { object, start, end } => {
            children.push(object.as_ref());
            if let Some(start) = start.as_ref() {
                children.push(start.as_ref());
            }
            if let Some(end) = end.as_ref() {
                children.push(end.as_ref());
            }
        }
        Node::BinaryOp { left, right, .. } => {
            children.push(left.as_ref());
            children.push(right.as_ref());
        }
        Node::UnaryOp { operand, .. } => children.push(operand.as_ref()),
        Node::Ternary {
            condition,
            true_expr,
            false_expr,
        } => {
            children.push(condition.as_ref());
            children.push(true_expr.as_ref());
            children.push(false_expr.as_ref());
        }
        Node::Assignment { target, value, .. } => {
            children.push(target.as_ref());
            children.push(value.as_ref());
        }
        Node::EnumConstruct { args, .. } => children.extend(args.iter()),
        Node::StructConstruct { fields, .. } => {
            for entry in fields {
                children.push(&entry.key);
                children.push(&entry.value);
            }
        }
        Node::ListLiteral(items) => children.extend(items.iter()),
        Node::DictLiteral(entries) => {
            for entry in entries {
                children.push(&entry.key);
                children.push(&entry.value);
            }
        }
        Node::Spread(inner) => children.push(inner.as_ref()),
        Node::TryOperator { operand } | Node::TryStar { operand } => {
            children.push(operand.as_ref());
        }
        Node::OrPattern(items) => children.extend(items.iter()),
        Node::Closure { body, .. } => children.extend(body.iter()),
        Node::RangeExpr { start, end, .. } => {
            children.push(start.as_ref());
            children.push(end.as_ref());
        }
        _ => {}
    }
    children
}

fn effect_allowed_by_ceiling(effect: &EffectRecord, ceiling: &CapabilityPolicy) -> bool {
    if !ceiling.capabilities.is_empty() {
        let (capability, op) = effect_capability_op(effect);
        let allowed = ceiling
            .capabilities
            .get(capability)
            .is_some_and(|ops| ops.is_empty() || ops.iter().any(|allowed| allowed == op));
        if !allowed {
            return false;
        }
    }
    if let Some(ceiling_level) = ceiling.side_effect_level.as_deref() {
        let requested = side_effect_level_for(effect);
        if requested_exceeds_ceiling(requested, ceiling_level) {
            return false;
        }
    }
    true
}

fn effect_capability_op(effect: &EffectRecord) -> (&'static str, &'static str) {
    match (&effect.kind, effect.scope) {
        (EffectKind::Stdio, EffectScope::Read) => ("stdio", "read"),
        (EffectKind::Stdio, _) => ("stdio", "write"),
        (EffectKind::Fs, EffectScope::Read) => ("workspace", "read_text"),
        (EffectKind::Fs, EffectScope::Write) => ("workspace", "write_text"),
        (EffectKind::Fs, EffectScope::Mutate) => ("workspace", "apply_edit"),
        (EffectKind::Fs, EffectScope::Observe) => ("workspace", "exists"),
        (EffectKind::Net, _) => ("network", "http"),
        (EffectKind::Llm { .. }, _) => ("llm", "call"),
        (EffectKind::Tool { .. }, _) => ("host", "tool_call"),
        (EffectKind::Hostcall { .. }, _) => ("connector", "call"),
        (EffectKind::Persona { .. }, _) => ("worker", "dispatch"),
        (EffectKind::Spawn, _) => ("worker", "dispatch"),
    }
}

fn side_effect_level_for(effect: &EffectRecord) -> &'static str {
    match (&effect.kind, effect.scope) {
        (EffectKind::Stdio, _) => "read_only",
        (EffectKind::Fs, EffectScope::Read | EffectScope::Observe) => "read_only",
        (EffectKind::Fs, _) => "workspace_write",
        (EffectKind::Net, _) => "network",
        (EffectKind::Llm { .. }, _) => "network",
        (EffectKind::Tool { .. }, _) => "workspace_write",
        (EffectKind::Hostcall { name }, _) if name.starts_with("process.") => "process_exec",
        (EffectKind::Hostcall { .. }, _) => "read_only",
        (EffectKind::Persona { .. }, _) => "workspace_write",
        (EffectKind::Spawn, _) => "workspace_write",
    }
}

fn requested_exceeds_ceiling(requested: &str, ceiling: &str) -> bool {
    fn rank(value: &str) -> usize {
        match value {
            "none" => 0,
            "read_only" => 1,
            "workspace_write" => 2,
            "process_exec" => 3,
            "network" => 4,
            _ => 5,
        }
    }
    rank(requested) > rank(ceiling)
}

/// Round-trip a typed effect list through the `metadata` map a child
/// spawn-config carries. Pipelines that pre-compute effects can stash
/// them under `effects` and the spawn shim lifts them onto the handoff.
pub fn effects_from_metadata(metadata: &BTreeMap<String, serde_json::Value>) -> Vec<EffectRecord> {
    metadata
        .get("effects")
        .and_then(|value| serde_json::from_value::<Vec<EffectRecord>>(value.clone()).ok())
        .unwrap_or_default()
}

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

    #[test]
    fn harness_net_call_yields_net_effect() {
        let source = r#"fn main(harness: Harness) { harness.net.get("https://example.test") }"#;
        let effects = compute_handoff_effects(source, None);
        assert!(
            effects
                .iter()
                .any(|effect| matches!(effect.kind, EffectKind::Net)
                    && effect.scope == EffectScope::Write),
            "expected Net write effect, got {effects:?}"
        );
    }

    #[test]
    fn http_get_builtin_yields_net_effect_with_resource() {
        let source = r#"fn main() { http_get("https://example.test/api") }"#;
        let effects = compute_handoff_effects(source, None);
        let net = effects
            .iter()
            .find(|effect| matches!(effect.kind, EffectKind::Net))
            .expect("net effect");
        assert_eq!(net.scope, EffectScope::Write);
        assert_eq!(net.resource.as_deref(), Some("https://example.test/api"));
    }

    #[test]
    fn harness_fs_write_yields_fs_write_effect() {
        let source = r#"fn main(harness: Harness) { harness.fs.write_file("/tmp/out", "hi") }"#;
        let effects = compute_handoff_effects(source, None);
        assert!(
            effects
                .iter()
                .any(|effect| matches!(effect.kind, EffectKind::Fs)
                    && effect.scope == EffectScope::Write),
            "expected Fs write effect, got {effects:?}"
        );
    }

    #[test]
    fn llm_call_emits_llm_effect_with_provider_and_model() {
        let source = r#"fn main() {
            llm_call("summarize", { provider: "anthropic", model: "claude-3-5-sonnet" })
        }"#;
        let effects = compute_handoff_effects(source, None);
        let llm = effects
            .iter()
            .find(|effect| matches!(effect.kind, EffectKind::Llm { .. }))
            .expect("llm effect");
        let EffectKind::Llm { provider, model } = &llm.kind else {
            panic!("expected llm kind, got {:?}", llm.kind);
        };
        assert_eq!(provider.as_deref(), Some("anthropic"));
        assert_eq!(model.as_deref(), Some("claude-3-5-sonnet"));
    }

    #[test]
    fn ceiling_drops_disallowed_capabilities() {
        let source = r#"fn main(harness: Harness) {
            harness.net.get("https://example.test")
            harness.fs.read_file("/tmp/in")
        }"#;
        let mut ceiling = CapabilityPolicy::default();
        ceiling
            .capabilities
            .insert("workspace".to_string(), vec!["read_text".to_string()]);
        let effects = compute_handoff_effects(source, Some(&ceiling));
        assert!(
            effects
                .iter()
                .all(|effect| !matches!(effect.kind, EffectKind::Net)),
            "ceiling without `network` should drop Net effect, got {effects:?}"
        );
        assert!(
            effects
                .iter()
                .any(|effect| matches!(effect.kind, EffectKind::Fs)),
            "ceiling with workspace.read_text should keep Fs read, got {effects:?}"
        );
    }

    #[test]
    fn ceiling_side_effect_level_clamps_writes() {
        let source = r#"fn main(harness: Harness) {
            harness.net.get("https://example.test")
            println("hi")
        }"#;
        let ceiling = CapabilityPolicy {
            side_effect_level: Some("read_only".to_string()),
            ..Default::default()
        };
        let effects = compute_handoff_effects(source, Some(&ceiling));
        assert!(
            effects
                .iter()
                .all(|effect| !matches!(effect.kind, EffectKind::Net)),
            "read_only ceiling must drop Net write, got {effects:?}"
        );
        assert!(
            effects
                .iter()
                .any(|effect| matches!(effect.kind, EffectKind::Stdio)),
            "stdio observe should pass read_only ceiling, got {effects:?}"
        );
    }

    #[test]
    fn effect_record_round_trips_through_serde() {
        let effects = vec![
            EffectRecord::new(EffectKind::Net, EffectScope::Write)
                .with_resource("https://api.example/v1"),
            EffectRecord::new(EffectKind::Fs, EffectScope::Read).with_resource("/workspace/src"),
            EffectRecord::new(
                EffectKind::Llm {
                    provider: Some("anthropic".to_string()),
                    model: Some("claude-3-7-sonnet".to_string()),
                },
                EffectScope::Write,
            ),
            EffectRecord::new(
                EffectKind::Tool {
                    name: "search".to_string(),
                },
                EffectScope::Read,
            ),
        ];
        let encoded = serde_json::to_string(&effects).expect("encode");
        let decoded: Vec<EffectRecord> = serde_json::from_str(&encoded).expect("decode");
        assert_eq!(decoded, effects);
    }

    #[test]
    fn empty_source_returns_no_effects() {
        let effects = compute_handoff_effects("fn main() {}", None);
        assert!(effects.is_empty(), "got {effects:?}");
    }

    #[test]
    fn effects_from_metadata_round_trips_typed_payload() {
        let effects = vec![EffectRecord::new(EffectKind::Net, EffectScope::Write)
            .with_resource("https://api.example")];
        let mut metadata: BTreeMap<String, serde_json::Value> = BTreeMap::new();
        metadata.insert(
            "effects".to_string(),
            serde_json::to_value(&effects).expect("encode"),
        );
        assert_eq!(effects_from_metadata(&metadata), effects);
    }

    #[test]
    fn deduplicates_repeated_effects() {
        let source = r#"fn main() {
            http_get("https://example.test")
            http_get("https://example.test")
            http_get("https://example.test")
        }"#;
        let effects = compute_handoff_effects(source, None);
        let net_count = effects
            .iter()
            .filter(|effect| matches!(effect.kind, EffectKind::Net))
            .count();
        assert_eq!(net_count, 1, "expected dedup, got {effects:?}");
    }
}