openhawk-verify 0.1.0

Agent claim verification engine — wraps claimcheck for OpenHawk sessions
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
// hawk-verify: ClaimCheck bridge
//
// claimcheck: https://github.com/ojuschugh1/claimcheck
//
// claimcheck <transcript.jsonl> --json --project-dir <path>
//
// JSON output:
// {
//   "truth_score": "67%",
//   "summary": { "total": 4, "pass": 2, "fail": 1, "unverifiable": 1 },
//   "claims": [
//     { "claim_type": "File", "raw_text": "created src/auth.ts", "result": "PASS", "reason": null },
//     { "claim_type": "Package", "raw_text": "installed jsonwebtoken", "result": "FAIL",
//       "reason": "package not found in any lockfile" }
//   ]
// }
//
// Fallback: when claimcheck is not installed, the engine checks session_actions
// in SQLite (the original behaviour).

use std::path::Path;
use std::process::Command;

use rusqlite::{params, Connection};
use serde::{Deserialize, Serialize};
use thiserror::Error;

// ── Error ─────────────────────────────────────────────────────────────────────

#[derive(Debug, Error)]
pub enum VerifyError {
    #[error("database error: {0}")]
    Database(String),
    #[error("serialization error: {0}")]
    Serialization(String),
    #[error("claimcheck error: {0}")]
    ClaimCheck(String),
}

impl From<rusqlite::Error> for VerifyError {
    fn from(e: rusqlite::Error) -> Self {
        VerifyError::Database(e.to_string())
    }
}

impl From<serde_json::Error> for VerifyError {
    fn from(e: serde_json::Error) -> Self {
        VerifyError::Serialization(e.to_string())
    }
}

// ── claimcheck binary bridge ──────────────────────────────────────────────────

/// Returns true if the `claimcheck` binary is on PATH.
pub fn claimcheck_available() -> bool {
    Command::new("claimcheck").arg("--help").output().is_ok()
}

/// Raw JSON output from `claimcheck --json`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClaimCheckReport {
    pub truth_score: String,
    pub summary: ClaimCheckSummary,
    pub claims: Vec<ClaimCheckClaim>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClaimCheckSummary {
    pub total: u32,
    pub pass: u32,
    pub fail: u32,
    pub unverifiable: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClaimCheckClaim {
    pub claim_type: String,
    pub raw_text: String,
    pub result: String, // "PASS", "FAIL", "UNVERIFIABLE"
    pub reason: Option<String>,
}

/// Run `claimcheck <transcript_path> --json --project-dir <project_dir>`.
/// Optionally pass `--baseline <ref>` and `--retest`.
pub fn run_claimcheck(
    transcript_path: &Path,
    project_dir: &Path,
    baseline: Option<&str>,
    retest: bool,
    test_cmd: Option<&str>,
) -> Result<ClaimCheckReport, VerifyError> {
    let mut cmd = Command::new("claimcheck");
    cmd.arg(transcript_path)
        .arg("--json")
        .arg("--project-dir")
        .arg(project_dir);

    if let Some(b) = baseline {
        cmd.arg("--baseline").arg(b);
    }
    if retest {
        cmd.arg("--retest");
        if let Some(tc) = test_cmd {
            cmd.arg("--test-cmd").arg(tc);
        }
    }

    let output = cmd.output().map_err(|e| VerifyError::ClaimCheck(e.to_string()))?;

    // claimcheck exits 0 even when claims fail — parse stdout regardless
    let stdout = String::from_utf8_lossy(&output.stdout);
    if stdout.trim().is_empty() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(VerifyError::ClaimCheck(format!(
            "claimcheck produced no output. stderr: {stderr}"
        )));
    }

    serde_json::from_str(&stdout).map_err(|e| {
        VerifyError::ClaimCheck(format!("failed to parse claimcheck JSON: {e}\noutput: {stdout}"))
    })
}

// ── Domain types (shared between claimcheck bridge and fallback engine) ───────

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentClaim {
    pub action_type: String,
    pub resource: String,
    pub claimed_at: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionAction {
    pub step_number: i64,
    pub timestamp: String,
    pub action_type: String,
    pub agent_pid: i64,
    pub payload: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionEvidence {
    pub session_id: String,
    pub actions: Vec<SessionAction>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "verdict", content = "reason")]
pub enum ClaimVerdict {
    Pass,
    Fail,
    Inconclusive { reason: String },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClaimResult {
    pub claim: AgentClaim,
    pub verdict: ClaimVerdict,
    pub discrepancies: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum VerificationStatus {
    Verified,
    Unverified,
    Inconclusive,
}

impl std::fmt::Display for VerificationStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            VerificationStatus::Verified => write!(f, "Verified"),
            VerificationStatus::Unverified => write!(f, "Unverified"),
            VerificationStatus::Inconclusive => write!(f, "Inconclusive"),
        }
    }
}

/// Full verification report — produced either by claimcheck or the fallback engine.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VerificationReport {
    pub session_id: String,
    pub overall_status: VerificationStatus,
    pub claims: Vec<ClaimResult>,
    /// Set when the real claimcheck binary was used.
    pub truth_score: Option<String>,
    /// Raw claimcheck output when available.
    pub claimcheck_raw: Option<ClaimCheckReport>,
}

// ── VerificationEngine ────────────────────────────────────────────────────────

pub struct VerificationEngine {
    pub db: Connection,
}

impl VerificationEngine {
    pub fn new(db: Connection) -> Self {
        Self { db }
    }

    /// Verify a session using the real claimcheck binary when available.
    ///
    /// `transcript_path` — path to a `.jsonl` or `.md` transcript file exported
    ///   from Claude Code, Cursor, or any supported tool.
    /// `project_dir` — the project root claimcheck should check against.
    /// `baseline` — git ref for the session window (e.g. "HEAD~3", "main").
    /// `retest` — re-run tests to verify test claims.
    pub fn verify_with_claimcheck(
        &self,
        session_id: &str,
        transcript_path: &Path,
        project_dir: &Path,
        baseline: Option<&str>,
        retest: bool,
        test_cmd: Option<&str>,
    ) -> Result<VerificationReport, VerifyError> {
        let cc = run_claimcheck(transcript_path, project_dir, baseline, retest, test_cmd)?;

        // Map claimcheck results into our domain types
        let claims: Vec<ClaimResult> = cc.claims.iter().map(|c| {
            let verdict = match c.result.as_str() {
                "PASS" => ClaimVerdict::Pass,
                "FAIL" => ClaimVerdict::Fail,
                _ => ClaimVerdict::Inconclusive {
                    reason: c.reason.clone().unwrap_or_else(|| "unverifiable".to_string()),
                },
            };
            let discrepancies = if let Some(ref r) = c.reason {
                vec![r.clone()]
            } else {
                vec![]
            };
            ClaimResult {
                claim: AgentClaim {
                    action_type: c.claim_type.clone(),
                    resource: c.raw_text.clone(),
                    claimed_at: String::new(),
                },
                verdict,
                discrepancies,
            }
        }).collect();

        let overall_status = if cc.summary.fail > 0 {
            VerificationStatus::Unverified
        } else if cc.summary.pass > 0 {
            VerificationStatus::Verified
        } else {
            VerificationStatus::Inconclusive
        };

        let report = VerificationReport {
            session_id: session_id.to_string(),
            overall_status,
            claims,
            truth_score: Some(cc.truth_score.clone()),
            claimcheck_raw: Some(cc),
        };

        self.store_report_full(&report)?;
        Ok(report)
    }

    /// Fallback: verify using session_actions in SQLite (no claimcheck binary needed).
    pub fn verify_session(
        &self,
        session_id: &str,
        claims: Vec<AgentClaim>,
    ) -> Result<VerificationReport, VerifyError> {
        let actions = self.load_actions(session_id)?;
        let evidence = SessionEvidence { session_id: session_id.to_string(), actions };

        let mut results = Vec::with_capacity(claims.len());
        for claim in claims {
            let verdict = self.verify_claim(&claim, &evidence);
            let discrepancies = match &verdict {
                ClaimVerdict::Fail => vec![format!(
                    "no recorded {} action for resource '{}'",
                    claim.action_type, claim.resource
                )],
                _ => vec![],
            };
            results.push(ClaimResult { claim, verdict, discrepancies });
        }

        let overall_status = derive_status(&results);
        let report = VerificationReport {
            session_id: session_id.to_string(),
            overall_status,
            claims: results,
            truth_score: None,
            claimcheck_raw: None,
        };

        self.store_report_full(&report)?;
        Ok(report)
    }

    pub fn verify_claim(&self, claim: &AgentClaim, evidence: &SessionEvidence) -> ClaimVerdict {
        if evidence.actions.is_empty() {
            return ClaimVerdict::Inconclusive { reason: "no evidence".to_string() };
        }
        let matched = evidence.actions.iter().any(|a| {
            a.action_type == claim.action_type && action_matches_resource(a, &claim.resource)
        });
        if matched { ClaimVerdict::Pass } else { ClaimVerdict::Fail }
    }

    fn load_actions(&self, session_id: &str) -> Result<Vec<SessionAction>, VerifyError> {
        let mut stmt = self.db.prepare(
            "SELECT step_number, timestamp, action_type, agent_pid, payload \
             FROM session_actions WHERE session_id = ?1 ORDER BY step_number ASC",
        )?;
        let rows = stmt.query_map(params![session_id], |row| {
            Ok(SessionAction {
                step_number: row.get(0)?,
                timestamp: row.get(1)?,
                action_type: row.get(2)?,
                agent_pid: row.get(3)?,
                payload: row.get(4)?,
            })
        })?;
        let mut actions = Vec::new();
        for row in rows {
            actions.push(row?);
        }
        Ok(actions)
    }

    fn store_report_full(&self, report: &VerificationReport) -> Result<(), VerifyError> {
        let json = serde_json::to_string(report)?;
        self.db.execute(
            "INSERT INTO verification_reports (session_id, timestamp, overall_status, report_json) \
             VALUES (?1, datetime('now'), ?2, ?3)",
            params![report.session_id, report.overall_status.to_string(), json],
        )?;
        Ok(())
    }
}

fn action_matches_resource(action: &SessionAction, resource: &str) -> bool {
    if let Ok(v) = serde_json::from_str::<serde_json::Value>(&action.payload) {
        for key in &["resource", "path", "url", "command"] {
            if let Some(val) = v.get(key).and_then(|x| x.as_str()) {
                if val == resource {
                    return true;
                }
            }
        }
    }
    false
}

fn derive_status(results: &[ClaimResult]) -> VerificationStatus {
    if results.is_empty() {
        return VerificationStatus::Inconclusive;
    }
    if results.iter().any(|r| r.verdict == ClaimVerdict::Fail) {
        return VerificationStatus::Unverified;
    }
    if results.iter().all(|r| r.verdict == ClaimVerdict::Pass) {
        VerificationStatus::Verified
    } else {
        VerificationStatus::Inconclusive
    }
}

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

    fn in_memory_db() -> Connection {
        let conn = Connection::open_in_memory().unwrap();
        conn.execute_batch(SCHEMA).unwrap();
        conn
    }

    const SCHEMA: &str = "
        CREATE TABLE IF NOT EXISTS sessions (
            id TEXT PRIMARY KEY, started_at TEXT NOT NULL, ended_at TEXT,
            status TEXT NOT NULL DEFAULT 'Active'
        );
        CREATE TABLE IF NOT EXISTS session_actions (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            session_id TEXT NOT NULL REFERENCES sessions(id),
            step_number INTEGER NOT NULL,
            timestamp TEXT NOT NULL,
            action_type TEXT NOT NULL,
            agent_pid INTEGER NOT NULL,
            payload TEXT NOT NULL,
            UNIQUE(session_id, step_number)
        );
        CREATE TABLE IF NOT EXISTS verification_reports (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            session_id TEXT NOT NULL REFERENCES sessions(id),
            timestamp TEXT NOT NULL,
            overall_status TEXT NOT NULL,
            report_json TEXT NOT NULL
        );
    ";

    fn insert_session(conn: &Connection, id: &str) {
        conn.execute(
            "INSERT INTO sessions (id, started_at) VALUES (?1, datetime('now'))",
            params![id],
        ).unwrap();
    }

    fn insert_action(conn: &Connection, session_id: &str, step: i64, action_type: &str, payload: &str) {
        conn.execute(
            "INSERT INTO session_actions \
             (session_id, step_number, timestamp, action_type, agent_pid, payload) \
             VALUES (?1, ?2, datetime('now'), ?3, 1, ?4)",
            params![session_id, step, action_type, payload],
        ).unwrap();
    }

    // ── claimcheck binary availability ────────────────────────────────────────

    #[test]
    fn claimcheck_available_check_does_not_panic() {
        let _ = claimcheck_available();
    }

    #[test]
    fn run_claimcheck_on_nonexistent_transcript_returns_error() {
        if !claimcheck_available() {
            return; // skip when not installed
        }
        let result = run_claimcheck(
            Path::new("/tmp/nonexistent-hawk-transcript.jsonl"),
            Path::new("."),
            None,
            false,
            None,
        );
        assert!(result.is_err());
    }

    #[test]
    fn run_claimcheck_with_real_transcript_when_installed() {
        if !claimcheck_available() {
            return;
        }
        // write a minimal Claude Code JSONL transcript to a temp file
        let dir = tempfile::TempDir::new().unwrap();
        let transcript = dir.path().join("session.jsonl");
        std::fs::write(
            &transcript,
            r#"{"role":"user","content":"Create a file"}
{"role":"assistant","content":"I created /tmp/hawk-test-claimcheck.txt with the content."}
"#,
        ).unwrap();

        let result = run_claimcheck(&transcript, dir.path(), None, false, None);
        // may succeed or fail depending on whether the file exists — just verify it runs
        match result {
            Ok(report) => {
                assert!(!report.truth_score.is_empty());
                // truth_score is either "N/A" or "X%"
            }
            Err(VerifyError::ClaimCheck(_)) => {
                // claimcheck ran but produced unexpected output — acceptable
            }
            Err(e) => panic!("unexpected error: {e}"),
        }
    }

    // ── fallback engine (SQLite-based) ────────────────────────────────────────

    #[test]
    fn inconclusive_when_no_evidence() {
        let engine = VerificationEngine::new(in_memory_db());
        let claim = AgentClaim {
            action_type: "file_write".into(),
            resource: "/tmp/out.txt".into(),
            claimed_at: "2024-01-01T00:00:00Z".into(),
        };
        let evidence = SessionEvidence { session_id: "s1".into(), actions: vec![] };
        assert_eq!(
            engine.verify_claim(&claim, &evidence),
            ClaimVerdict::Inconclusive { reason: "no evidence".into() }
        );
    }

    #[test]
    fn pass_when_matching_action_exists() {
        let engine = VerificationEngine::new(in_memory_db());
        let claim = AgentClaim {
            action_type: "file_write".into(),
            resource: "/tmp/out.txt".into(),
            claimed_at: "2024-01-01T00:00:00Z".into(),
        };
        let evidence = SessionEvidence {
            session_id: "s1".into(),
            actions: vec![SessionAction {
                step_number: 1,
                timestamp: "2024-01-01T00:00:00Z".into(),
                action_type: "file_write".into(),
                agent_pid: 42,
                payload: r#"{"path":"/tmp/out.txt"}"#.into(),
            }],
        };
        assert_eq!(engine.verify_claim(&claim, &evidence), ClaimVerdict::Pass);
    }

    #[test]
    fn fail_when_no_matching_action() {
        let engine = VerificationEngine::new(in_memory_db());
        let claim = AgentClaim {
            action_type: "api_call".into(),
            resource: "https://api.openai.com/v1/chat".into(),
            claimed_at: "2024-01-01T00:00:00Z".into(),
        };
        let evidence = SessionEvidence {
            session_id: "s1".into(),
            actions: vec![SessionAction {
                step_number: 1,
                timestamp: "2024-01-01T00:00:00Z".into(),
                action_type: "file_write".into(),
                agent_pid: 42,
                payload: r#"{"path":"/tmp/out.txt"}"#.into(),
            }],
        };
        assert_eq!(engine.verify_claim(&claim, &evidence), ClaimVerdict::Fail);
    }

    #[test]
    fn verify_session_all_pass_returns_verified() {
        let conn = in_memory_db();
        insert_session(&conn, "sess-pass");
        insert_action(&conn, "sess-pass", 1, "file_write", r#"{"path":"/tmp/result.txt"}"#);
        let engine = VerificationEngine::new(conn);
        let claims = vec![AgentClaim {
            action_type: "file_write".into(),
            resource: "/tmp/result.txt".into(),
            claimed_at: "2024-01-01T00:00:00Z".into(),
        }];
        let report = engine.verify_session("sess-pass", claims).unwrap();
        assert_eq!(report.overall_status, VerificationStatus::Verified);
        assert_eq!(report.claims[0].verdict, ClaimVerdict::Pass);
        assert!(report.truth_score.is_none()); // fallback path
    }

    #[test]
    fn verify_session_any_fail_returns_unverified() {
        let conn = in_memory_db();
        insert_session(&conn, "sess-fail");
        insert_action(&conn, "sess-fail", 1, "file_write", r#"{"path":"/tmp/result.txt"}"#);
        let engine = VerificationEngine::new(conn);
        let claims = vec![
            AgentClaim {
                action_type: "file_write".into(),
                resource: "/tmp/result.txt".into(),
                claimed_at: "2024-01-01T00:00:00Z".into(),
            },
            AgentClaim {
                action_type: "api_call".into(),
                resource: "https://api.openai.com/v1/chat".into(),
                claimed_at: "2024-01-01T00:00:00Z".into(),
            },
        ];
        let report = engine.verify_session("sess-fail", claims).unwrap();
        assert_eq!(report.overall_status, VerificationStatus::Unverified);
    }

    #[test]
    fn verify_session_no_actions_returns_inconclusive() {
        let conn = in_memory_db();
        insert_session(&conn, "sess-inc");
        let engine = VerificationEngine::new(conn);
        let claims = vec![AgentClaim {
            action_type: "file_write".into(),
            resource: "/tmp/out.txt".into(),
            claimed_at: "2024-01-01T00:00:00Z".into(),
        }];
        let report = engine.verify_session("sess-inc", claims).unwrap();
        assert_eq!(report.overall_status, VerificationStatus::Inconclusive);
    }

    #[test]
    fn verify_session_stores_report_in_sqlite() {
        let conn = in_memory_db();
        insert_session(&conn, "sess-store");
        insert_action(&conn, "sess-store", 1, "file_write", r#"{"path":"/tmp/x.txt"}"#);
        let engine = VerificationEngine::new(conn);
        let claims = vec![AgentClaim {
            action_type: "file_write".into(),
            resource: "/tmp/x.txt".into(),
            claimed_at: "2024-01-01T00:00:00Z".into(),
        }];
        engine.verify_session("sess-store", claims).unwrap();
        let count: i64 = engine.db.query_row(
            "SELECT COUNT(*) FROM verification_reports WHERE session_id = 'sess-store'",
            [],
            |row| row.get(0),
        ).unwrap();
        assert_eq!(count, 1);
    }

    #[test]
    fn verify_session_empty_claims_returns_inconclusive() {
        let conn = in_memory_db();
        insert_session(&conn, "sess-empty");
        let engine = VerificationEngine::new(conn);
        let report = engine.verify_session("sess-empty", vec![]).unwrap();
        assert_eq!(report.overall_status, VerificationStatus::Inconclusive);
    }

    #[test]
    fn discrepancies_populated_on_fail() {
        let conn = in_memory_db();
        insert_session(&conn, "sess-disc");
        insert_action(&conn, "sess-disc", 1, "file_write", r#"{"path":"/tmp/other.txt"}"#);
        let engine = VerificationEngine::new(conn);
        let claims = vec![AgentClaim {
            action_type: "file_write".into(),
            resource: "/tmp/missing.txt".into(),
            claimed_at: "2024-01-01T00:00:00Z".into(),
        }];
        let report = engine.verify_session("sess-disc", claims).unwrap();
        assert_eq!(report.claims[0].verdict, ClaimVerdict::Fail);
        assert!(!report.claims[0].discrepancies.is_empty());
    }

    #[test]
    fn api_call_matched_via_url_field() {
        let engine = VerificationEngine::new(in_memory_db());
        let claim = AgentClaim {
            action_type: "api_call".into(),
            resource: "https://api.openai.com/v1/chat".into(),
            claimed_at: "2024-01-01T00:00:00Z".into(),
        };
        let evidence = SessionEvidence {
            session_id: "s1".into(),
            actions: vec![SessionAction {
                step_number: 1,
                timestamp: "2024-01-01T00:00:00Z".into(),
                action_type: "api_call".into(),
                agent_pid: 42,
                payload: r#"{"url":"https://api.openai.com/v1/chat"}"#.into(),
            }],
        };
        assert_eq!(engine.verify_claim(&claim, &evidence), ClaimVerdict::Pass);
    }

    #[test]
    fn command_exec_matched_via_command_field() {
        let engine = VerificationEngine::new(in_memory_db());
        let claim = AgentClaim {
            action_type: "command_exec".into(),
            resource: "python3".into(),
            claimed_at: "2024-01-01T00:00:00Z".into(),
        };
        let evidence = SessionEvidence {
            session_id: "s1".into(),
            actions: vec![SessionAction {
                step_number: 1,
                timestamp: "2024-01-01T00:00:00Z".into(),
                action_type: "command_exec".into(),
                agent_pid: 42,
                payload: r#"{"command":"python3"}"#.into(),
            }],
        };
        assert_eq!(engine.verify_claim(&claim, &evidence), ClaimVerdict::Pass);
    }
}