car-ffi-common 0.34.0

Shared logic for FFI bindings (NAPI, PyO3) — JSON wrappers for verify, multi-agent, scheduler
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
//! JSON wrappers for car-verify functions.

use car_ir::{ActionProposal, ToolSchema};
use serde_json::Value;
use std::collections::{HashMap, HashSet};

/// Verify a proposal from JSON inputs. Returns result JSON.
///
/// When `tool_schemas_json` is supplied (a JSON array of `ToolSchema`
/// objects, e.g. `[{"name":"echo","parameters":{...}}]`), each
/// `tool_call`'s parameters are validated against the matching
/// schema — catching type mismatches and missing required fields, not
/// just unknown tools (car-releases#56). `tool_names` remains
/// supported for existence-only checks when no schemas are at hand;
/// `tool_schemas_json` takes precedence when both are passed.
pub fn verify(
    proposal_json: &str,
    initial_state_json: Option<&str>,
    tool_names: Option<Vec<String>>,
    max_actions: usize,
    tool_schemas_json: Option<&str>,
) -> Result<String, String> {
    let proposal: ActionProposal =
        serde_json::from_str(proposal_json).map_err(|e| format!("invalid proposal JSON: {}", e))?;
    let initial_state: Option<HashMap<String, Value>> = initial_state_json
        .map(serde_json::from_str)
        .transpose()
        .map_err(|e| format!("invalid state JSON: {}", e))?;

    let result = if let Some(schemas_json) = tool_schemas_json {
        let schemas: Vec<ToolSchema> = serde_json::from_str(schemas_json)
            .map_err(|e| format!("invalid tool schemas JSON: {}", e))?;
        let map: HashMap<String, ToolSchema> =
            schemas.into_iter().map(|s| (s.name.clone(), s)).collect();
        car_verify::verify_with_schemas(&proposal, initial_state.as_ref(), Some(&map), max_actions)
    } else {
        let tools: Option<HashSet<String>> = tool_names.map(|v| v.into_iter().collect());
        car_verify::verify(
            &proposal,
            initial_state.as_ref(),
            tools.as_ref(),
            max_actions,
        )
    };

    serde_json::to_string(&serde_json::json!({
        "valid": result.valid,
        "issues": result.issues.iter().map(|i| serde_json::json!({
            "action_id": i.action_id,
            "severity": i.severity,
            "message": i.message,
        })).collect::<Vec<_>>(),
        "simulated_state": result.simulated_state,
        "execution_levels": result.execution_levels,
        "conflicts": result.conflicts,
        // Evidence bundle: the verifier's declared scope — checks run,
        // assumptions, untested regions, residual risks, coverage
        // confidence (survey "Code as Agent Harness" §5.2.2).
        "evidence": result.evidence,
    }))
    .map_err(|e| e.to_string())
}

/// Simulate a proposal from JSON inputs. Returns state JSON.
pub fn simulate(proposal_json: &str, initial_state_json: Option<&str>) -> Result<String, String> {
    let proposal: ActionProposal =
        serde_json::from_str(proposal_json).map_err(|e| format!("invalid proposal JSON: {}", e))?;
    let initial_state: Option<HashMap<String, Value>> = initial_state_json
        .map(serde_json::from_str)
        .transpose()
        .map_err(|e| format!("invalid state JSON: {}", e))?;

    let state = car_verify::simulate(&proposal, initial_state.as_ref());
    serde_json::to_string(&state).map_err(|e| e.to_string())
}

/// Optimize a proposal from JSON. Returns optimized proposal JSON.
pub fn optimize(proposal_json: &str) -> Result<String, String> {
    let proposal: ActionProposal =
        serde_json::from_str(proposal_json).map_err(|e| format!("invalid proposal JSON: {}", e))?;
    let optimized = car_verify::optimize(&proposal);
    serde_json::to_string(&optimized).map_err(|e| e.to_string())
}

/// Check a proposal for transactional conflicts against the current shared
/// state (survey §4.3/§5.2.4). `versions_json` is a JSON object mapping
/// state key → current version (from `StateStore::versions`);
/// `state_json` (optional) maps key → current value for value-level
/// assumption checks. Returns the `TransactionReport` JSON:
/// `{ consistent, conflicts: [{ kind, key, actions, explanation,
/// resolution }] }`.
pub fn transaction_check(
    proposal_json: &str,
    versions_json: Option<&str>,
    state_json: Option<&str>,
) -> Result<String, String> {
    let proposal: ActionProposal = crate::from_json("proposal", proposal_json)?;
    let versions: HashMap<String, u64> =
        crate::from_json_opt("versions", versions_json)?.unwrap_or_default();
    let state: Option<HashMap<String, Value>> = crate::from_json_opt("state", state_json)?;
    let report = car_verify::check_transaction(&proposal, &versions, state.as_ref());
    crate::to_json(&report)
}

/// Like [`transaction_check`], but augments each action's write set with the keys
/// a verified Code World Model predicts it writes (Code World Models Slice 3b —
/// pre-flight conflict detection). `predictions_json` is a JSON object mapping an
/// `action_id` → array of predicted write keys (the caller produced them by
/// running the generated model). Predicted writes are unioned into the action's
/// declared write set before the same conflict analysis runs, so a tool that
/// writes a key it didn't declare is caught *before* execution. Returns the same
/// `TransactionReport` JSON as `transaction_check`.
pub fn transaction_check_with_predictions(
    proposal_json: &str,
    versions_json: Option<&str>,
    state_json: Option<&str>,
    predictions_json: &str,
) -> Result<String, String> {
    let proposal: ActionProposal = crate::from_json("proposal", proposal_json)?;
    let versions: HashMap<String, u64> =
        crate::from_json_opt("versions", versions_json)?.unwrap_or_default();
    let state: Option<HashMap<String, Value>> = crate::from_json_opt("state", state_json)?;
    let predicted: HashMap<String, Vec<String>> =
        crate::from_json("predictions", predictions_json)?;
    let report = car_verify::check_transaction_with_predictions(
        &proposal,
        &versions,
        state.as_ref(),
        &predicted,
    );
    crate::to_json(&report)
}

/// Static information-flow + tool-sequence safety check over a plan
/// (arXiv 2601.08012; `docs/proposals/verifiable-tool-safety.md`). `labels_json`
/// is a JSON object mapping `tool_name` → `ToolLabels`
/// (`{ capability?, confidentiality, trust, sink, declassifier }`, all
/// defaulting to public/trusted/non-sink). `policy_json` (optional) is a
/// `FlowPolicy` (`{ min_confidential, forbidden_sequences: [[before, after]] }`).
/// Returns the `FlowReport` JSON `{ safe, violations: [{ kind, actions, key?,
/// explanation, mitigation }] }` — flagging sensitive data reaching an
/// exfiltration/untrusted sink and forbidden tool orderings, statically, before
/// execution. Tools absent from `labels_json` are unconstrained, so an empty map
/// is trivially safe.
pub fn check_information_flow(
    proposal_json: &str,
    labels_json: &str,
    policy_json: Option<&str>,
) -> Result<String, String> {
    let proposal: ActionProposal = crate::from_json("proposal", proposal_json)?;
    let labels: HashMap<String, car_verify::ToolLabels> = crate::from_json("labels", labels_json)?;
    let policy: car_verify::FlowPolicy =
        crate::from_json_opt("policy", policy_json)?.unwrap_or_default();
    let report = car_verify::check_information_flow(&proposal, &labels, &policy);
    crate::to_json(&report)
}

/// Map an information-flow `FlowReport` to an enforcement decision (Slice 2 of
/// `docs/proposals/verifiable-tool-safety.md`). `report_json` is the output of
/// `check_information_flow`; `gate_policy_json` (optional) is a `FlowGatePolicy`
/// (`{ on_sensitive_to_sink, on_forbidden_sequence }`, each `allow` |
/// `require_approval` | `block`; defaults block exfiltration and escalate
/// forbidden orderings). Returns the `FlowGateDecision` JSON `{ action, blocked,
/// needs_approval, reason }` — turning the advisory check into a gate that
/// blocks clear hazards and escalates ambiguous ones to HITL.
pub fn gate_information_flow(
    report_json: &str,
    gate_policy_json: Option<&str>,
) -> Result<String, String> {
    let report: car_verify::FlowReport = crate::from_json("report", report_json)?;
    let policy: car_verify::FlowGatePolicy =
        crate::from_json_opt("gate policy", gate_policy_json)?.unwrap_or_default();
    let decision = car_verify::gate_flow(&report, &policy);
    crate::to_json(&decision)
}

/// Enforce a `FlowGateDecision` against the durable approval ledger (verifiable
/// tool safety, Slice 3 — the HITL bridge). `decision_json` is the output of
/// `gate_information_flow`; `approvals_json` (optional) is a JSON array of prior
/// `ApprovalRecord`s (`{ fingerprint, required_tier, decision, reviewer, reason,
/// evidence?, decided_at }`) — the human-in-the-loop history. A `require_approval`
/// hazard a human previously **approved** (by `flow_fingerprint`) is allowed,
/// one **rejected** is blocked, an unseen one becomes pending. Returns the
/// `FlowEnforcement` JSON `{ allow, blocked, pending: [{ fingerprint, violation
/// }], reason }`. Stateless: the ledger is rebuilt from `approvals_json` each
/// call (the daemon owns the live ledger).
pub fn enforce_information_flow(
    decision_json: &str,
    approvals_json: Option<&str>,
) -> Result<String, String> {
    let decision: car_verify::FlowGateDecision = crate::from_json("decision", decision_json)?;
    let mut ledger = car_policy::permission::ApprovalLedger::new();
    if let Some(aj) = approvals_json {
        let records: Vec<car_policy::permission::ApprovalRecord> =
            crate::from_json("approvals", aj)?;
        for r in records {
            ledger
                .record(r)
                .map_err(|e| format!("record approval: {e}"))?;
        }
    }
    let enforcement = car_policy::enforce_flow(&decision, &ledger);
    crate::to_json(&enforcement)
}

/// Check equivalence of two proposals from JSON.
pub fn equivalent(p1_json: &str, p2_json: &str) -> Result<bool, String> {
    let p1: ActionProposal =
        serde_json::from_str(p1_json).map_err(|e| format!("invalid proposal1 JSON: {}", e))?;
    let p2: ActionProposal =
        serde_json::from_str(p2_json).map_err(|e| format!("invalid proposal2 JSON: {}", e))?;
    Ok(car_verify::equivalent(&p1, &p2, None))
}

/// Analyze a schedule of multi-agent read-generate-write operations for the four
/// concurrency anomalies of arXiv 2606.17182 and classify the achieved
/// consistency level (`docs/proposals/concurrency-anomalies.md`). `ops_json` is a
/// JSON array of `AgentOp` (`{ id, agent?, read_set?, write_set?, tools_read?,
/// tools_written?, depends_on?, read_at?, commit_at? }`; omitted fields default).
/// Returns the `ConcurrencyReport` JSON `{ level: "l0".."l4", serializable,
/// anomalies: [{ anomaly, key, ops, explanation }] }` — `level` set by the most
/// severe anomaly present (causal-cascade → l0 … none → l4 serializable).
pub fn analyze_concurrency(ops_json: &str) -> Result<String, String> {
    let ops: Vec<car_verify::AgentOp> = crate::from_json("ops", ops_json)?;
    let report = car_verify::analyze_concurrency(&ops);
    crate::to_json(&report)
}

/// Gate a concurrency report into remediations under a policy (arXiv 2606.17182
/// Slice 2 — `docs/proposals/concurrency-anomalies.md`; the analogue of
/// `gate_information_flow` for concurrency). `report_json` is a
/// `ConcurrencyReport` (the output of [`analyze_concurrency`]); `policy_json`
/// (optional) is a `ConcurrencyGatePolicy` `{ abort_at_or_below,
/// require_approval_at_or_below }` (levels `"l0".."l4"`; defaults abort on l0,
/// approval on l1). Returns the `ConcurrencyGate` JSON `{ safe, level, abort,
/// remediations: [{ anomaly, remediation: { kind, .. }, disposition }] }`.
pub fn gate_concurrency(report_json: &str, policy_json: Option<&str>) -> Result<String, String> {
    let report: car_verify::ConcurrencyReport = crate::from_json("report", report_json)?;
    let policy: car_verify::ConcurrencyGatePolicy = match policy_json {
        Some(p) => crate::from_json("policy", p)?,
        None => car_verify::ConcurrencyGatePolicy::default(),
    };
    let gate = car_verify::gate_concurrency(&report, &policy);
    crate::to_json(&gate)
}

/// Statically verify a workflow graph for structural defects (arXiv 2603.20356
/// "Agentproof" — `docs/proposals/workflow-graph-verification.md`). `graph_json`
/// is a `WorkflowGraph` `{ entry, terminals: [..], stages: [..], edges: [{ from,
/// to, condition? }] }`. Returns the `WorkflowVerifyReport` JSON `{ sound,
/// defects: [{ kind, subject, witness: [..stage path..], explanation }] }` —
/// `kind` is `missing_entry` | `dangling_edge` | `unreachable_stage` | `dead_end`
/// | `no_exit_reachable` | `unreachable_terminal`. Each defect carries a witness
/// path from the entry, the actionable counter-example for a repair loop.
pub fn verify_workflow_graph(graph_json: &str) -> Result<String, String> {
    let graph: car_verify::WorkflowGraph = crate::from_json("graph", graph_json)?;
    let report = car_verify::verify_workflow_graph(&graph);
    crate::to_json(&report)
}

/// Check temporal safety policies over a workflow graph (arXiv 2603.20356
/// "Agentproof" Slice 2 — `docs/proposals/workflow-graph-verification.md`).
/// `graph_json` is a `WorkflowGraph`; `policies_json` is a JSON array of
/// `TemporalPolicy` (currently `{ kind: "precedes", earlier, later, name? }` —
/// `earlier` must be visited before `later` on every path, e.g. a human-gate).
/// Returns the `PolicyReport` JSON `{ compliant, violations: [{ policy, stage,
/// witness: [..path..], explanation }] }`; each violation's witness is a path
/// that reaches the guarded stage without the required predecessor.
pub fn check_workflow_policies(graph_json: &str, policies_json: &str) -> Result<String, String> {
    let graph: car_verify::WorkflowGraph = crate::from_json("graph", graph_json)?;
    let policies: Vec<car_verify::TemporalPolicy> = crate::from_json("policies", policies_json)?;
    let report = car_verify::check_temporal_policies(&graph, &policies);
    crate::to_json(&report)
}

/// Verify a plan's sequential feasibility by symbolic forward simulation (arXiv
/// 2603.14730 "GNNVerifier" — `docs/proposals/plan-precondition-verification.md`;
/// the deterministic, training-free counterpart). `request_json` is a
/// `PlanCheckRequest` `{ initial: [..facts..], steps: [{ id, preconditions?,
/// add_effects?, del_effects? }], goal: [..facts..] }`. Returns the
/// `PlanCheckReport` JSON `{ valid, defects: [{ kind, step?, fact, explanation }],
/// final_state: [..facts..] }` — `kind` is `unmet_precondition` |
/// `goal_not_achieved`. Effects apply even when a precondition fails, so one pass
/// surfaces every defect.
pub fn check_plan(request_json: &str) -> Result<String, String> {
    let req: car_verify::PlanCheckRequest = crate::from_json("request", request_json)?;
    let report = car_verify::check_plan(&req);
    crate::to_json(&report)
}

#[derive(serde::Deserialize)]
struct GoalEvalRequest {
    condition: car_verify::goal::GoalCondition,
    #[serde(default)]
    inputs: car_verify::goal::GoalInputs,
}

/// Deterministic goal-condition evaluation (the goal loop's Evaluator half —
/// see `docs/proposals/goal-loop.md`). CAR's answer to `/goal`: decide "am I
/// done?" over runtime **ground truth** rather than a model reading its own
/// transcript. `request_json` is `{ condition, inputs }` where `condition` is a
/// composable `GoalCondition` (`{ kind: "all_of"|"any_of", conditions: [..] }`,
/// or a leaf `{ kind: "tool_receipts_grounded" | "plan_achieved" |
/// "state_consistent" | "state_predicate", key, equals | "command", id,
/// expect_exit | "model_judge", id }`) and `inputs` is the gathered
/// `GoalInputs` `{ receipts_grounded?, plan_achieved?, state_consistent?,
/// state?, command_exits?, model_verdicts? }`. Returns the `GoalVerdict` JSON
/// `{ met, grounded, reason }` — `grounded` is false iff a met verdict relied on
/// a `model_judge` (the "did it verify or vibe-check?" signal `/goal` cannot
/// give). A leaf whose input wasn't gathered fails closed (unmet).
pub fn evaluate_goal(request_json: &str) -> Result<String, String> {
    let req: GoalEvalRequest = crate::from_json("request", request_json)?;
    let verdict = car_verify::goal::evaluate_goal(&req.condition, &req.inputs);
    crate::to_json(&verdict)
}

#[derive(serde::Deserialize)]
struct IntentCheckRequest {
    #[serde(default)]
    intent: car_verify::IntentSpec,
    #[serde(default)]
    actions: Vec<car_verify::IntentAction>,
}

/// Intent-grounded verify-before-commit (arXiv 2601.05755 "VIGIL"): flag actions
/// that drift outside the user's declared intent, blocking commit when the
/// drifting action is influenced by an untrusted tool result (tool-stream
/// injection). `request_json` is `{ intent: { allowed_tools?, allowed_resources?,
/// forbidden_capabilities? }, actions: [{ id, tool?, targets?, capabilities?,
/// depends_on?, untrusted? }] }`. Returns the `IntentReport` JSON `{ safe,
/// commit_blocked: [action_id..], violations: [{ action, kind, detail,
/// tool_influenced, explanation }] }` — `kind` is `tool_out_of_intent` |
/// `target_out_of_intent` | `forbidden_capability`.
pub fn check_intent(request_json: &str) -> Result<String, String> {
    let req: IntentCheckRequest = crate::from_json("request", request_json)?;
    let report = car_verify::check_intent(&req.intent, &req.actions);
    crate::to_json(&report)
}

#[derive(serde::Deserialize)]
struct IntentPlanRequest {
    #[serde(default)]
    intent: car_verify::IntentSpec,
    #[serde(default)]
    actions: Vec<car_ir::Action>,
    /// Tools whose output is attacker-controllable (web/file/remote reads).
    #[serde(default)]
    untrusted_tools: Vec<String>,
    /// Specific action ids the executor marked tainted from tool-result
    /// provenance.
    #[serde(default)]
    untrusted_ids: Vec<String>,
}

/// Intent-grounded verify-before-commit straight from a plan's `car_ir` actions
/// (VIGIL Slice 4 — the IR populater + check in one call). `request_json` is `{
/// intent, actions: [Action], untrusted_tools?: [..], untrusted_ids?: [..] }`. The
/// runtime derives the `IntentAction`s from its own IR — `tool`, `expected_effects`
/// → targets, the executor's dependency edges → `depends_on`,
/// `metadata.capabilities` → capabilities, and `untrusted` from the supplied
/// tool/id provenance — then runs [`check_intent`]. Returns the same
/// `IntentReport` JSON. Saves a caller hand-assembling the check input.
pub fn check_intent_plan(request_json: &str) -> Result<String, String> {
    let req: IntentPlanRequest = crate::from_json("request", request_json)?;
    let untrusted_tools: std::collections::HashSet<String> =
        req.untrusted_tools.into_iter().collect();
    let untrusted_ids: std::collections::HashSet<String> = req.untrusted_ids.into_iter().collect();
    let actions = car_verify::intent_actions_from(&req.actions, &untrusted_tools, &untrusted_ids);
    let report = car_verify::check_intent(&req.intent, &actions);
    crate::to_json(&report)
}

/// Map an intent report to an enforcement disposition (VIGIL Slice 2 — the gate).
/// `report_json` is an `IntentReport` (from [`check_intent`]); `gate_policy_json`
/// is an optional `IntentGatePolicy` `{ on_untainted_drift: "allow" |
/// "require_approval" | "block" }` (default `require_approval`). Injections
/// (tool-stream-influenced drift) and forbidden capabilities always block
/// regardless of policy. Returns the `IntentGateDecision` JSON `{ action, blocked,
/// needs_approval, reason }`.
pub fn gate_intent(report_json: &str, gate_policy_json: Option<&str>) -> Result<String, String> {
    let report: car_verify::IntentReport = crate::from_json("report", report_json)?;
    let policy: car_verify::IntentGatePolicy =
        crate::from_json_opt("gate policy", gate_policy_json)?.unwrap_or_default();
    let decision = car_verify::gate_intent(&report, &policy);
    crate::to_json(&decision)
}

/// Enforce an intent gate decision against the durable approval ledger (VIGIL
/// Slice 3 — the HITL bridge). `decision_json` is the output of [`gate_intent`];
/// `approvals_json` is an optional `ApprovalRecord[]` seeding the ledger. An
/// out-of-intent action a human previously approved commits; one they rejected is
/// blocked; a novel one is pending. Hard blocks (injections / forbidden
/// capabilities) are never committable. Returns the `IntentEnforcement` JSON
/// `{ commit, blocked, pending: [{ fingerprint, violation }], reason }`.
pub fn enforce_intent(decision_json: &str, approvals_json: Option<&str>) -> Result<String, String> {
    let decision: car_verify::IntentGateDecision = crate::from_json("decision", decision_json)?;
    let mut ledger = car_policy::permission::ApprovalLedger::new();
    if let Some(aj) = approvals_json {
        let records: Vec<car_policy::permission::ApprovalRecord> =
            crate::from_json("approvals", aj)?;
        for r in records {
            ledger
                .record(r)
                .map_err(|e| format!("record approval: {e}"))?;
        }
    }
    let enforcement = car_policy::enforce_intent(&decision, &ledger);
    crate::to_json(&enforcement)
}

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

    /// The exact wire contract a Node/Python user-agent uses: an `all_of` of a
    /// grounded-receipts check and a command exit-0 check, over gathered inputs.
    #[test]
    fn evaluate_goal_json_round_trip() {
        let req = r#"{
            "condition": {
                "kind": "all_of",
                "conditions": [
                    { "kind": "tool_receipts_grounded" },
                    { "kind": "command", "id": "tests", "expect_exit": 0 }
                ]
            },
            "inputs": {
                "receipts_grounded": true,
                "command_exits": { "tests": 0 }
            }
        }"#;
        let out = evaluate_goal(req).expect("valid request");
        let v: serde_json::Value = serde_json::from_str(&out).unwrap();
        assert_eq!(v["met"], serde_json::json!(true));
        assert_eq!(v["grounded"], serde_json::json!(true));

        // A failing command flips met to false.
        let req_fail = req.replace("\"tests\": 0", "\"tests\": 1");
        let out = evaluate_goal(&req_fail).unwrap();
        let v: serde_json::Value = serde_json::from_str(&out).unwrap();
        assert_eq!(v["met"], serde_json::json!(false));
    }

    /// A model-judge completion is reported ungrounded through the wire.
    #[test]
    fn evaluate_goal_reports_ungrounded_via_wire() {
        let req = r#"{
            "condition": { "kind": "model_judge", "id": "clarity" },
            "inputs": { "model_verdicts": { "clarity": true } }
        }"#;
        let v: serde_json::Value = serde_json::from_str(&evaluate_goal(req).unwrap()).unwrap();
        assert_eq!(v["met"], serde_json::json!(true));
        assert_eq!(v["grounded"], serde_json::json!(false));
    }
}