harn-vm 0.10.41

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
//! Tests for `AgentEvent::from_host_payload` — typed host-emit deserialization.
//!
//! These pin the accept/reject boundary and the per-field defaults that the
//! retired hand-written `build_agent_event` match applied, so the serde path
//! stays behavior-identical.

use super::*;
use serde_json::json;

#[test]
fn from_host_deserializes_generic_variant() {
    let event = AgentEvent::from_host_payload(
        "s1",
        "iteration_start",
        &json!({ "iteration": 3, "provider": "openai", "model": "gpt" }),
    )
    .expect("iteration_start");
    match event {
        AgentEvent::IterationStart {
            session_id,
            iteration,
            provider,
            model,
        } => {
            assert_eq!(session_id, "s1");
            assert_eq!(iteration, 3);
            assert_eq!(provider, "openai");
            assert_eq!(model, "gpt");
        }
        other => panic!("expected IterationStart, got {other:?}"),
    }
}

#[test]
fn from_host_tool_call_defaults_status_and_audit() {
    // No `status` in the payload -> Pending; audit comes from the (absent)
    // ambient mutation session -> None, never from the payload.
    let event = AgentEvent::from_host_payload(
        "s1",
        "tool_call",
        &json!({ "tool_call_id": "t1", "tool_name": "read_file", "audit": {"bogus": true} }),
    )
    .expect("tool_call");
    match event {
        AgentEvent::ToolCall {
            status,
            raw_input,
            audit,
            ..
        } => {
            assert_eq!(status, ToolCallStatus::Pending);
            assert_eq!(raw_input, serde_json::Value::Null);
            assert!(audit.is_none());
        }
        other => panic!("expected ToolCall, got {other:?}"),
    }
}

#[test]
fn from_host_tool_call_update_defaults_status_and_maps_executor_alias() {
    let event = AgentEvent::from_host_payload(
        "s1",
        "tool_call_update",
        &json!({
            "tool_call_id": "t1",
            "tool_name": "read_file",
            "mutation_status": "unknown",
            "executor": "harn",
        }),
    )
    .expect("tool_call_update");
    match event {
        AgentEvent::ToolCallUpdate {
            status, executor, ..
        } => {
            assert_eq!(status, ToolCallStatus::InProgress);
            assert_eq!(executor, Some(ToolExecutor::HarnBuiltin));
        }
        other => panic!("expected ToolCallUpdate, got {other:?}"),
    }
}

#[test]
fn from_host_tool_call_update_preserves_structured_executor() {
    let event = AgentEvent::from_host_payload(
        "s1",
        "tool_call_update",
        &json!({
            "tool_call_id": "t1",
            "tool_name": "linear_create",
            "status": "completed",
            "mutation_status": "unknown",
            "executor": { "kind": "mcp_server", "server_name": "linear" },
        }),
    )
    .expect("tool_call_update");
    match event {
        AgentEvent::ToolCallUpdate { executor, .. } => {
            assert_eq!(
                executor,
                Some(ToolExecutor::McpServer {
                    server_name: "linear".to_string()
                })
            );
        }
        other => panic!("expected ToolCallUpdate, got {other:?}"),
    }
}

#[test]
fn from_host_tool_call_update_preserves_structured_mutation_status() {
    for (wire, expected) in [
        ("applied", ToolMutationStatus::Applied),
        ("not_applied", ToolMutationStatus::NotApplied),
        ("unknown", ToolMutationStatus::Unknown),
    ] {
        let event = AgentEvent::from_host_payload(
            "s1",
            "tool_call_update",
            &json!({
                "tool_call_id": "t1",
                "tool_name": "edit",
                "status": "completed",
                "mutation_status": wire,
            }),
        )
        .expect("typed mutation status");
        assert!(matches!(
            event,
            AgentEvent::ToolCallUpdate {
                mutation_status: status,
                ..
            } if status == expected
        ));
    }
}

#[test]
fn from_host_tool_call_update_rejects_unknown_mutation_status() {
    let error = AgentEvent::from_host_payload(
        "s1",
        "tool_call_update",
        &json!({
            "tool_call_id": "t1",
            "tool_name": "edit",
            "status": "completed",
            "mutation_status": "maybe",
        }),
    )
    .expect_err("unknown mutation status rejected");
    assert!(format!("{error:?}").contains("unknown variant `maybe`"));
}

#[test]
fn from_host_tool_call_update_rejects_unknown_executor() {
    let error = AgentEvent::from_host_payload(
        "s1",
        "tool_call_update",
        &json!({ "tool_call_id": "t1", "tool_name": "x", "executor": "nope" }),
    )
    .expect_err("unknown executor rejected");
    assert!(format!("{error:?}").contains("invalid tool executor"));
}

#[test]
fn from_host_progress_reported_defaults_replace_true() {
    let event = AgentEvent::from_host_payload("s1", "progress_reported", &json!({}))
        .expect("progress_reported");
    match event {
        AgentEvent::ProgressReported {
            replace,
            entries,
            metadata,
            message,
            ..
        } => {
            assert!(replace, "replace defaults to true");
            assert_eq!(entries, json!([]));
            assert_eq!(metadata, json!({}));
            assert!(message.is_none());
        }
        other => panic!("expected ProgressReported, got {other:?}"),
    }
}

#[test]
fn from_host_verdict_deserializes_complete_payload() {
    // The loop always emits a normalized (complete) verdict payload; the
    // typed path deserializes it 1:1.
    let event = AgentEvent::from_host_payload(
        "s1",
        "scope_classifier_verdict",
        &json!({
            "iteration": 1,
            "label": "escalate",
            "original_label": "trivial",
            "confidence": 0.4,
            "confidence_threshold": 0.65,
            "evidence": "e",
            "skip_main_turn": false,
        }),
    )
    .expect("scope_classifier_verdict");
    match event {
        AgentEvent::ScopeClassifierVerdict {
            label,
            confidence,
            confidence_threshold,
            skip_main_turn,
            ..
        } => {
            assert_eq!(label, "escalate");
            assert_eq!(confidence, 0.4);
            assert_eq!(confidence_threshold, 0.65);
            assert!(!skip_main_turn);
        }
        other => panic!("expected ScopeClassifierVerdict, got {other:?}"),
    }
}

#[test]
fn from_host_input_guardrail_deserializes_complete_payload() {
    let event = AgentEvent::from_host_payload(
        "s1",
        "input_guardrail_verdict",
        &json!({
            "iteration": 1,
            "tripwire": true,
            "reason": "policy denied",
            "label": "prompt_injection",
            "confidence": 0.97,
            "confidence_threshold": 0.8,
            "classifier_kind": "custom",
        }),
    )
    .expect("input_guardrail_verdict");
    match event {
        AgentEvent::InputGuardrailVerdict {
            tripwire,
            reason,
            label,
            confidence,
            classifier_kind,
            ..
        } => {
            assert!(tripwire);
            assert_eq!(reason, "policy denied");
            assert_eq!(label, "prompt_injection");
            assert_eq!(confidence, 0.97);
            assert_eq!(classifier_kind.as_deref(), Some("custom"));
        }
        other => panic!("expected InputGuardrailVerdict, got {other:?}"),
    }
}

#[test]
fn from_host_nudge_maps_to_feedback_injected() {
    let event = AgentEvent::from_host_payload(
        "s1",
        "llm_auto_continue",
        &json!({
            "previous_max_tokens": 100,
            "raised_max_tokens": 400,
            "attempt": 1,
            "max_continuations": 3,
        }),
    )
    .expect("llm_auto_continue");
    match event {
        AgentEvent::FeedbackInjected { kind, content, .. } => {
            assert_eq!(kind, "llm_auto_continue");
            assert_eq!(content, "100->400 (attempt 1/3)");
        }
        other => panic!("expected FeedbackInjected, got {other:?}"),
    }
}

#[test]
fn from_host_no_progress_nudge_preserves_injected_text_and_streak() {
    let event = AgentEvent::from_host_payload(
        "s1",
        "no_progress_streak_nudge",
        &json!({
            "iteration": 4,
            "content": "No progress last turn. Emit exactly one well-formed <tool_call> now.",
            "streak": 2,
            "turns_since_progress": 2,
            "has_tools": true,
            "made_tool_calls": false,
        }),
    )
    .expect("no_progress_streak_nudge");
    match event {
        AgentEvent::FeedbackInjected {
            kind,
            content,
            streak,
            ..
        } => {
            assert_eq!(kind, "no_progress_streak_nudge");
            assert_eq!(
                content,
                "No progress last turn. Emit exactly one well-formed <tool_call> now."
            );
            assert_eq!(streak, Some(2));
        }
        other => panic!("expected FeedbackInjected, got {other:?}"),
    }
}

#[test]
fn from_host_no_progress_nudge_without_text_uses_explanatory_fallback() {
    let event = AgentEvent::from_host_payload(
        "s1",
        "no_progress_streak_nudge",
        &json!({
            "iteration": 4,
            "streak": 2,
            "turns_since_progress": 2,
            "has_tools": true,
            "made_tool_calls": false,
        }),
    )
    .expect("no_progress_streak_nudge");
    match event {
        AgentEvent::FeedbackInjected {
            kind,
            content,
            streak,
            ..
        } => {
            assert_eq!(kind, "no_progress_streak_nudge");
            assert_ne!(content, "2");
            assert!(content.contains("No progress was detected"));
            assert_eq!(streak, Some(2));
        }
        other => panic!("expected FeedbackInjected, got {other:?}"),
    }
}

#[test]
fn from_host_judge_decision_preserves_source() {
    let event = AgentEvent::from_host_payload(
        "s1",
        "judge_decision",
        &json!({
            "iteration": 3,
            "verdict": "continue",
            "reasoning": "need verifier output",
            "next_step": "run tests",
            "judge_duration_ms": 0,
            "source": "deterministic",
            "trigger": "verify_completion",
            "reason": "repeated_verification_failures",
            "escalation_recommended": true,
            "escalation_target": "frontier",
            "specific_gaps": [],
            "accepted_evidence": [],
        }),
    )
    .expect("judge_decision");
    match event {
        AgentEvent::JudgeDecision {
            source,
            trigger,
            escalation_recommended,
            escalation_target,
            ..
        } => {
            assert_eq!(source.as_deref(), Some("deterministic"));
            assert_eq!(trigger.as_deref(), Some("verify_completion"));
            assert_eq!(escalation_recommended, Some(true));
            assert_eq!(escalation_target.as_deref(), Some("frontier"));
        }
        other => panic!("expected JudgeDecision, got {other:?}"),
    }
}

#[test]
fn from_host_stance_events_map_to_stance_transition() {
    let event = AgentEvent::from_host_payload(
        "s1",
        "stance_write_access_granted",
        &json!({
            "escape_tool": "grant_write",
            "allowed_tools": ["read_file", "write_file"],
            "consent": "operator",
        }),
    )
    .expect("stance_write_access_granted");
    match event {
        AgentEvent::StanceTransition {
            phase,
            escape_tool,
            allowed_tools,
            consent,
            ..
        } => {
            assert_eq!(phase, "write_access_granted");
            assert_eq!(escape_tool, "grant_write");
            assert_eq!(allowed_tools, vec!["read_file", "write_file"]);
            assert_eq!(consent, "operator");
        }
        other => panic!("expected StanceTransition, got {other:?}"),
    }
}

#[test]
fn from_host_deserializes_budget_events() {
    // Budget termination is a normal host-emitted loop outcome, so both
    // variants must stay inside the explicit host allowlist.
    match AgentEvent::from_host_payload(
        "s1",
        "budget_exhausted",
        &json!({ "kind": "budget", "max_iterations": 12, "iteration": 12, "cost_usd": 0.0, "wall_clock_ms": 0 }),
    )
    .expect("budget_exhausted")
    {
        AgentEvent::BudgetExhausted {
            max_iterations,
            kind,
            ..
        } => {
            assert_eq!(max_iterations, 12);
            assert_eq!(kind.as_deref(), Some("budget"));
        }
        other => panic!("expected BudgetExhausted, got {other:?}"),
    }
    match AgentEvent::from_host_payload(
        "s1",
        "budget_circuit_breaker",
        &json!({ "kind": "consecutive_failures", "consecutive_count": 3, "paused_for_ms": 500 }),
    )
    .expect("budget_circuit_breaker")
    {
        AgentEvent::BudgetCircuitBreaker {
            consecutive_count,
            paused_for_ms,
            ..
        } => {
            assert_eq!(consecutive_count, 3);
            assert_eq!(paused_for_ms, 500);
        }
        other => panic!("expected BudgetCircuitBreaker, got {other:?}"),
    }
}

#[test]
fn from_host_rejects_non_host_and_unknown_event_types() {
    // A real `AgentEvent` variant that is never emitted through the host
    // path stays rejected (parity with the retired match's allowlist).
    AgentEvent::from_host_payload("s1", "worker_update", &json!({}))
        .expect_err("worker_update is not a host-emittable event type");
    AgentEvent::from_host_payload("s1", "totally_made_up", &json!({}))
        .expect_err("unknown event type rejected");
}

// --- Loud-boundary funnel (harn#5142) ------------------------------------

/// A `.harn` boundary reports through the same typed event as the Rust funnel,
/// and `owner` is derived from `kind` here rather than trusted from the
/// payload, so one attribution rule covers both languages.
#[test]
fn from_host_accepts_a_harn_side_boundary_failure_and_derives_the_owner() {
    let event = AgentEvent::from_host_payload(
        "s1",
        "boundary_failure",
        &json!({
            "boundary": "chat_turn_cap",
            "kind": "capped",
            "owner": "agent",
            "detail": "agent_chat_loop stopped at max_turns after 4 turn(s)",
            "dropped_count": 1,
        }),
    )
    .expect("boundary_failure is host-emittable");
    match event {
        AgentEvent::BoundaryFailure {
            session_id,
            boundary,
            kind,
            owner,
            detail,
            dropped_count,
            unreported,
            ..
        } => {
            assert_eq!(session_id, "s1");
            assert_eq!(boundary, crate::boundary::BoundaryId::ChatTurnCap);
            assert_eq!(kind, crate::boundary::BoundaryFailureKind::Capped);
            assert_eq!(
                owner, "policy",
                "a payload-supplied owner must be overruled, not trusted",
            );
            assert!(detail.contains("max_turns"));
            assert_eq!(dropped_count, 1);
            assert!(!unreported);
        }
        other => panic!("expected BoundaryFailure, got {other:?}"),
    }
}

/// The `host_event_ingest` boundary. The `VmError` alone was never enough:
/// every stdlib emit site wraps `agent_emit_event` in `try { }` and discards
/// the result, so a rejected event used to vanish. The funnel emission is not
/// swallowable by a caller's `try`.
#[test]
fn a_rejected_host_event_reports_through_the_funnel() {
    for (event_type, payload) in [
        ("totally_made_up", json!({})),
        ("iteration_start", json!({ "iteration": "not-a-number" })),
    ] {
        let captured = crate::boundary::tests::CapturedEvents::install();
        AgentEvent::from_host_payload("s1", event_type, &payload)
            .expect_err("this payload must be rejected");
        let events = captured.boundary_failures();
        assert_eq!(events.len(), 1, "for {event_type}: got {events:?}");
        match &events[0] {
            AgentEvent::BoundaryFailure {
                session_id,
                boundary,
                kind,
                owner,
                excerpt,
                ..
            } => {
                assert_eq!(session_id, "s1");
                assert_eq!(*boundary, crate::boundary::BoundaryId::HostEventIngest);
                assert_eq!(*kind, crate::boundary::BoundaryFailureKind::Unrecognized);
                assert_eq!(owner, "harness");
                assert!(excerpt.is_some(), "the rejected payload must ride along");
            }
            other => panic!("expected BoundaryFailure, got {other:?}"),
        }
    }
}

#[test]
fn an_accepted_host_event_reports_no_boundary_failure() {
    let captured = crate::boundary::tests::CapturedEvents::install();
    AgentEvent::from_host_payload("s1", "iteration_start", &json!({ "iteration": 1 }))
        .expect("accepted");
    assert!(captured.boundary_failures().is_empty());
}