Skip to main content

harn_vm/orchestration/
merge_captain_audit.rs

1//! Merge Captain transcript oracle and audit (#1013).
2//!
3//! Consumes JSONL transcript artifacts produced by `JsonlEventSink`
4//! (`.harn-runs/<session-id>/event_log.jsonl`) and reports oracle
5//! findings: extra model calls, invalid structured outputs, repeated
6//! reads, bad waits, unsafe attempted actions, skipped verification,
7//! missing approvals, and non-minimal tool usage.
8//!
9//! The oracle works on a stream of `PersistedAgentEvent` envelopes.
10//! It can run with or without a golden fixture: without, it emits
11//! findings derived purely from transcript-internal heuristics
12//! (parse failures, repeated identical tool calls, write tools that
13//! preceded any approval gate). With a golden, it additionally
14//! cross-checks scenario-specific budgets and required state steps.
15//!
16//! The output is both serializable JSON (machine-readable for CI
17//! gates) and a `Display` impl for human-readable reports.
18
19use std::collections::{BTreeMap, BTreeSet};
20use std::fmt;
21use std::fs;
22use std::io::{BufRead, BufReader};
23use std::path::{Path, PathBuf};
24
25use serde::{Deserialize, Serialize};
26
27use crate::agent_events::{AgentEvent, PersistedAgentEvent, ToolCallErrorCategory, ToolCallStatus};
28use crate::value::VmError;
29
30/// Severity of an audit finding. `Error` fails CI gates; `Warn`
31/// surfaces in reports but does not flip `pass` to `false`; `Info`
32/// is observational.
33#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
34#[serde(rename_all = "snake_case")]
35pub enum FindingSeverity {
36    Info,
37    Warn,
38    Error,
39}
40
41impl FindingSeverity {
42    pub fn as_str(self) -> &'static str {
43        match self {
44            Self::Info => "info",
45            Self::Warn => "warn",
46            Self::Error => "error",
47        }
48    }
49}
50
51/// Categories the oracle can raise. Stable wire identifiers — the
52/// `snake_case` form is what CI parsers should match against.
53#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
54#[serde(rename_all = "snake_case")]
55pub enum FindingCategory {
56    /// Model issued more calls than the scenario budget allows.
57    ExtraModelCall,
58    /// A `Plan` event or tool input failed JSON schema validation,
59    /// or a tool dispatch was rejected with `schema_validation`.
60    InvalidStructuredOutput,
61    /// The same `(tool, args)` pair was issued more than the
62    /// configured threshold (default 1) consecutively without a
63    /// state change or feedback in between.
64    RepeatedRead,
65    /// A `wait`/`sleep` / poll-style tool was issued without a
66    /// progress signal between consecutive reads of the same
67    /// resource.
68    BadWait,
69    /// The agent attempted a write/delete/force-push action without
70    /// any prior approval gate (handoff, approval feedback, or
71    /// explicit approval-required plan).
72    UnsafeAttemptedAction,
73    /// The PR state machine reached a "merge" or "approve" step
74    /// without first running a required "verify" step (e.g. checking
75    /// CI status).
76    SkippedVerification,
77    /// A `Plan` event declared `approval_required: true` but no
78    /// approval gate (handoff, approval feedback, or pause) followed.
79    MissingApproval,
80    /// Tool-call count exceeded the golden's `max_tool_calls`.
81    NonMinimalToolUsage,
82    /// A scenario-required state step was never reached.
83    MissingStateStep,
84    /// State steps appeared out of the expected order.
85    StateOutOfOrder,
86    /// Observed state transitions did not match the scenario's exact
87    /// golden sequence.
88    StateSequenceMismatch,
89    /// The transcript ended without a terminal event (IterationEnd,
90    /// BudgetExhausted, LoopStuck, Handoff). Often a truncated log.
91    IncompleteTranscript,
92    /// A tool call listed in the golden's `forbidden_actions` was
93    /// invoked.
94    ForbiddenAction,
95}
96
97impl FindingCategory {
98    pub fn as_str(self) -> &'static str {
99        match self {
100            Self::ExtraModelCall => "extra_model_call",
101            Self::InvalidStructuredOutput => "invalid_structured_output",
102            Self::RepeatedRead => "repeated_read",
103            Self::BadWait => "bad_wait",
104            Self::UnsafeAttemptedAction => "unsafe_attempted_action",
105            Self::SkippedVerification => "skipped_verification",
106            Self::MissingApproval => "missing_approval",
107            Self::NonMinimalToolUsage => "non_minimal_tool_usage",
108            Self::MissingStateStep => "missing_state_step",
109            Self::StateOutOfOrder => "state_out_of_order",
110            Self::StateSequenceMismatch => "state_sequence_mismatch",
111            Self::IncompleteTranscript => "incomplete_transcript",
112            Self::ForbiddenAction => "forbidden_action",
113        }
114    }
115}
116
117/// One oracle finding linked back to the JSONL events that triggered
118/// it, plus the PR state-machine step (when known) and the tool
119/// names involved.
120#[derive(Clone, Debug, Serialize, Deserialize)]
121pub struct AuditFinding {
122    pub category: FindingCategory,
123    pub severity: FindingSeverity,
124    pub message: String,
125    /// Monotonic event indexes from `PersistedAgentEvent.index`.
126    /// Empty when the finding is suite-level (e.g. a missing state
127    /// step that never fired).
128    #[serde(default, skip_serializing_if = "Vec::is_empty")]
129    pub event_indices: Vec<u64>,
130    /// PR state-machine step name if the finding is bound to one.
131    #[serde(default, skip_serializing_if = "Option::is_none")]
132    pub state_step: Option<String>,
133    /// Tool name(s) involved.
134    #[serde(default, skip_serializing_if = "Vec::is_empty")]
135    pub tools: Vec<String>,
136}
137
138/// One observed PR state-machine transition.
139#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
140pub struct StateTransition {
141    /// Step identifier from the golden's `state_steps` (or the
142    /// default heuristic step list).
143    pub step: String,
144    /// Index of the event that triggered the step.
145    pub event_index: u64,
146    /// Why the step fired: tool name, event variant, or "plan".
147    pub triggered_by: String,
148}
149
150/// Tool-name shape match for golden state steps. Either an exact
151/// name, a substring (`*foo*`), prefix (`foo*`), or suffix
152/// (`*foo`). Matched case-insensitively.
153#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Default)]
154#[serde(default)]
155pub struct ToolPattern {
156    /// Exact tool name. Mutually exclusive with `glob`.
157    pub name: Option<String>,
158    /// Glob pattern (`*` wildcards only). Mutually exclusive with
159    /// `name`.
160    pub glob: Option<String>,
161}
162
163impl ToolPattern {
164    pub fn matches(&self, tool: &str) -> bool {
165        let needle = tool.to_lowercase();
166        if let Some(name) = &self.name {
167            return name.eq_ignore_ascii_case(tool);
168        }
169        if let Some(glob) = &self.glob {
170            return glob_match(&glob.to_lowercase(), &needle);
171        }
172        false
173    }
174}
175
176// Golden-fixture tool patterns promise `*`-only wildcards (everything else
177// literal), which is exactly the shared prose matcher's contract.
178use harn_glob::match_prose as glob_match;
179
180/// One state-machine step in the golden fixture.
181#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Default)]
182#[serde(default)]
183pub struct GoldenStateStep {
184    /// Step identifier (e.g. "intake", "verify_ci", "approve",
185    /// "merge"). Used to link findings back.
186    pub step: String,
187    /// Tool patterns that, when invoked, trigger this step.
188    pub tools: Vec<ToolPattern>,
189    /// Plan field names whose presence triggers the step.
190    /// Example: `["review_risk"]` matches a `Plan` event with that
191    /// key in the structured plan.
192    pub plan_fields: Vec<String>,
193    /// Event variant names that trigger this step (e.g.
194    /// `"handoff"`, `"feedback_injected"`).
195    pub events: Vec<String>,
196    /// When `true`, this step is required for the scenario; failure
197    /// to reach it produces a `MissingStateStep` finding.
198    pub required: bool,
199    /// When this step represents an approval gate. Used by the
200    /// `MissingApproval` rule to decide whether a preceding
201    /// `approval_required: true` plan was satisfied.
202    #[serde(default)]
203    pub approval_gate: bool,
204    /// When this step represents a verification step. Used by the
205    /// `SkippedVerification` rule to decide whether a "merge" was
206    /// preceded by a verifier.
207    #[serde(default)]
208    pub verifier: bool,
209    /// When this step represents a terminal "ship" action (merge,
210    /// label-set, deploy). Used by the `SkippedVerification` rule.
211    #[serde(default)]
212    pub merge_action: bool,
213}
214
215/// Golden fixture: the ideal model behavior for a Merge Captain
216/// scenario. Loaded from JSON and shipped under
217/// `examples/personas/merge_captain/goldens/`.
218#[derive(Clone, Debug, Serialize, Deserialize, Default, PartialEq, Eq)]
219#[serde(default)]
220pub struct MergeCaptainGolden {
221    #[serde(rename = "_type")]
222    pub type_name: String,
223    /// Free-form scenario id (e.g. `"green_pr"`,
224    /// `"failing_ci"`).
225    pub scenario: String,
226    pub description: Option<String>,
227    /// Maximum acceptable model-call count.
228    pub max_model_calls: Option<u64>,
229    /// Maximum acceptable tool-call count.
230    pub max_tool_calls: Option<u64>,
231    /// Maximum acceptable repeated-read run length (default 1 — any
232    /// repetition beyond that triggers a finding).
233    pub max_repeat: Option<u32>,
234    /// Tool patterns that must always be preceded by an approval
235    /// gate.
236    pub require_approval_for: Vec<ToolPattern>,
237    /// Tool patterns that may never appear in this scenario.
238    pub forbidden_actions: Vec<ToolPattern>,
239    /// State-machine steps to track. The first matching pattern in
240    /// declaration order wins for any given event.
241    pub state_steps: Vec<GoldenStateStep>,
242    /// Optional exact transition sequence for deterministic fixtures.
243    /// When present, the audit fails unless the observed transition
244    /// step names match this list byte-for-byte and in order.
245    pub expected_state_transitions: Vec<String>,
246}
247
248/// The audit report. `pass` is `false` iff any finding has
249/// severity `Error`.
250#[derive(Clone, Debug, Serialize, Deserialize, Default)]
251pub struct AuditReport {
252    pub scenario: Option<String>,
253    /// Source path of the transcript (when read from disk).
254    pub source_path: Option<String>,
255    /// Distinct session ids observed in the transcript.
256    pub session_ids: Vec<String>,
257    pub event_count: u64,
258    pub model_call_count: u64,
259    pub tool_call_count: u64,
260    pub findings: Vec<AuditFinding>,
261    pub state_transitions: Vec<StateTransition>,
262    pub pass: bool,
263}
264
265impl AuditReport {
266    pub fn error_findings(&self) -> usize {
267        self.findings
268            .iter()
269            .filter(|f| f.severity == FindingSeverity::Error)
270            .count()
271    }
272
273    pub fn warn_findings(&self) -> usize {
274        self.findings
275            .iter()
276            .filter(|f| f.severity == FindingSeverity::Warn)
277            .count()
278    }
279}
280
281impl fmt::Display for AuditReport {
282    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
283        writeln!(
284            f,
285            "{} scenario={} events={} tool_calls={} model_calls={}",
286            if self.pass { "PASS" } else { "FAIL" },
287            self.scenario.as_deref().unwrap_or("<none>"),
288            self.event_count,
289            self.tool_call_count,
290            self.model_call_count
291        )?;
292        if let Some(path) = &self.source_path {
293            writeln!(f, "  transcript: {path}")?;
294        }
295        if !self.state_transitions.is_empty() {
296            writeln!(f, "  state transitions:")?;
297            for t in &self.state_transitions {
298                writeln!(
299                    f,
300                    "    [{}] {} <- {}",
301                    t.event_index, t.step, t.triggered_by
302                )?;
303            }
304        }
305        if self.findings.is_empty() {
306            writeln!(f, "  findings: none")?;
307        } else {
308            writeln!(f, "  findings ({}):", self.findings.len())?;
309            for finding in &self.findings {
310                let step = finding
311                    .state_step
312                    .as_deref()
313                    .map(|s| format!(" step={s}"))
314                    .unwrap_or_default();
315                let tools = if finding.tools.is_empty() {
316                    String::new()
317                } else {
318                    format!(" tools={}", finding.tools.join(","))
319                };
320                let events = if finding.event_indices.is_empty() {
321                    String::new()
322                } else {
323                    format!(
324                        " events=[{}]",
325                        finding
326                            .event_indices
327                            .iter()
328                            .map(u64::to_string)
329                            .collect::<Vec<_>>()
330                            .join(",")
331                    )
332                };
333                writeln!(
334                    f,
335                    "    [{}] {}: {}{}{}{}",
336                    finding.severity.as_str(),
337                    finding.category.as_str(),
338                    finding.message,
339                    step,
340                    tools,
341                    events
342                )?;
343            }
344        }
345        Ok(())
346    }
347}
348
349/// Result of [`load_transcript_jsonl`]. Wraps the deserialized
350/// envelopes plus the source path the caller passed in.
351#[derive(Clone, Debug)]
352pub struct LoadedTranscript {
353    pub source_path: PathBuf,
354    pub events: Vec<PersistedAgentEvent>,
355}
356
357/// Read a JSONL transcript file, accepting either:
358///   - a path to an `event_log.jsonl` (or rotated `-NNNNNN.jsonl`)
359///   - a path to a `.harn-runs/<session-id>/` directory (we'll
360///     read every `event_log*.jsonl` under it and sort by index)
361pub fn load_transcript_jsonl(path: &Path) -> Result<LoadedTranscript, VmError> {
362    let metadata = fs::metadata(path).map_err(|e| {
363        VmError::Runtime(format!("failed to stat transcript {}: {e}", path.display()))
364    })?;
365    let mut events = Vec::new();
366    if metadata.is_dir() {
367        let mut files: Vec<PathBuf> = fs::read_dir(path)
368            .map_err(|e| {
369                VmError::Runtime(format!(
370                    "failed to read transcript directory {}: {e}",
371                    path.display()
372                ))
373            })?
374            .filter_map(|entry| entry.ok())
375            .map(|entry| entry.path())
376            .filter(|p| {
377                p.file_name()
378                    .and_then(|n| n.to_str())
379                    .map(|name| {
380                        name.starts_with("event_log")
381                            && p.extension().and_then(|e| e.to_str()) == Some("jsonl")
382                    })
383                    .unwrap_or(false)
384            })
385            .collect();
386        files.sort();
387        if files.is_empty() {
388            return Err(VmError::Runtime(format!(
389                "no event_log*.jsonl files under {}",
390                path.display()
391            )));
392        }
393        for file in &files {
394            events.extend(read_jsonl_file(file)?);
395        }
396    } else {
397        events.extend(read_jsonl_file(path)?);
398    }
399    // Sort by index so multi-file dirs interleave correctly.
400    events.sort_by_key(|e| e.index);
401    Ok(LoadedTranscript {
402        source_path: path.to_path_buf(),
403        events,
404    })
405}
406
407fn read_jsonl_file(path: &Path) -> Result<Vec<PersistedAgentEvent>, VmError> {
408    let file = fs::File::open(path).map_err(|e| {
409        VmError::Runtime(format!("failed to open transcript {}: {e}", path.display()))
410    })?;
411    let reader = BufReader::new(file);
412    let mut events = Vec::new();
413    for (line_no, line) in reader.lines().enumerate() {
414        let line = line.map_err(|e| {
415            VmError::Runtime(format!(
416                "failed to read line {} of {}: {e}",
417                line_no + 1,
418                path.display()
419            ))
420        })?;
421        let trimmed = line.trim();
422        if trimmed.is_empty() {
423            continue;
424        }
425        let event: PersistedAgentEvent = serde_json::from_str(trimmed).map_err(|e| {
426            VmError::Runtime(format!(
427                "failed to parse line {} of {} as PersistedAgentEvent: {e}",
428                line_no + 1,
429                path.display()
430            ))
431        })?;
432        events.push(event);
433    }
434    Ok(events)
435}
436
437/// Load a Merge Captain golden fixture from JSON.
438pub fn load_merge_captain_golden(path: &Path) -> Result<MergeCaptainGolden, VmError> {
439    let bytes = fs::read(path).map_err(|e| {
440        VmError::Runtime(format!(
441            "failed to read merge_captain golden {}: {e}",
442            path.display()
443        ))
444    })?;
445    let golden: MergeCaptainGolden = serde_json::from_slice(&bytes).map_err(|e| {
446        VmError::Runtime(format!(
447            "failed to parse merge_captain golden {}: {e}",
448            path.display()
449        ))
450    })?;
451    Ok(golden)
452}
453
454/// Default state-step list applied when a golden does not declare
455/// any. Captures the canonical Merge Captain pipeline: intake →
456/// verify_checks → review_threads → decide_risk → approval_gate →
457/// merge_or_handoff.
458fn default_state_steps() -> Vec<GoldenStateStep> {
459    vec![
460        GoldenStateStep {
461            step: "intake".into(),
462            tools: vec![ToolPattern {
463                glob: Some("*pull_request*".into()),
464                ..Default::default()
465            }],
466            plan_fields: vec!["pr_number".into()],
467            events: vec!["plan".into()],
468            ..Default::default()
469        },
470        GoldenStateStep {
471            step: "verify_checks".into(),
472            tools: vec![
473                ToolPattern {
474                    glob: Some("*check*".into()),
475                    ..Default::default()
476                },
477                ToolPattern {
478                    glob: Some("*ci*".into()),
479                    ..Default::default()
480                },
481                ToolPattern {
482                    glob: Some("*workflow_run*".into()),
483                    ..Default::default()
484                },
485            ],
486            verifier: true,
487            ..Default::default()
488        },
489        GoldenStateStep {
490            step: "decide_risk".into(),
491            plan_fields: vec!["review_risk".into()],
492            events: vec!["plan".into()],
493            ..Default::default()
494        },
495        GoldenStateStep {
496            step: "approval_gate".into(),
497            plan_fields: vec!["approval_required".into()],
498            events: vec!["handoff".into(), "feedback_injected".into()],
499            approval_gate: true,
500            ..Default::default()
501        },
502        GoldenStateStep {
503            step: "merge_or_handoff".into(),
504            tools: vec![
505                ToolPattern {
506                    glob: Some("*merge*".into()),
507                    ..Default::default()
508                },
509                ToolPattern {
510                    glob: Some("*label*".into()),
511                    ..Default::default()
512                },
513            ],
514            events: vec!["handoff".into()],
515            merge_action: true,
516            ..Default::default()
517        },
518    ]
519}
520
521/// Heuristic: does this tool name look like a write/mutation
522/// action? Used by the `UnsafeAttemptedAction` rule when no golden
523/// is provided.
524pub(crate) fn is_merge_captain_write_tool(name: &str) -> bool {
525    let lower = name.to_lowercase();
526    lower.contains("merge")
527        || lower.contains("write_file")
528        || lower.contains("create_pull")
529        || lower.contains("_create")
530        || lower.contains("create_")
531        || lower.contains("delete")
532        || lower.contains("force_push")
533        || lower.contains("apply_patch")
534        || lower.contains("set_label")
535        || lower.contains("post_comment")
536        || lower.contains("approve")
537}
538
539/// Heuristic: does this tool name look like a wait/poll?
540fn is_wait_tool(name: &str) -> bool {
541    let lower = name.to_lowercase();
542    lower.contains("sleep") || lower.contains("wait") || lower.contains("poll")
543}
544
545/// Audit a transcript event stream against an optional golden.
546pub fn audit_transcript(
547    events: &[PersistedAgentEvent],
548    golden: Option<&MergeCaptainGolden>,
549) -> AuditReport {
550    let scenario = golden.map(|g| g.scenario.clone());
551    let mut session_ids: Vec<String> = Vec::new();
552    let mut model_calls: u64 = 0;
553    let mut tool_calls: u64 = 0;
554    let mut findings: Vec<AuditFinding> = Vec::new();
555    let mut transitions: Vec<StateTransition> = Vec::new();
556
557    let state_steps_owned: Vec<GoldenStateStep> = match golden {
558        Some(g) if !g.state_steps.is_empty() => g.state_steps.clone(),
559        _ => default_state_steps(),
560    };
561    let max_repeat = golden.and_then(|g| g.max_repeat).unwrap_or(1);
562
563    // Track repeated tool calls: (tool, arg-hash) per session.
564    let mut last_tool_call: BTreeMap<String, (String, String, Vec<u64>)> = BTreeMap::new();
565
566    // Approval state: how many `approval_required: true` plans are
567    // outstanding (waiting for a gate). Decremented when an
568    // approval_gate step fires.
569    let mut pending_approvals: Vec<u64> = Vec::new();
570
571    // Track verifier-fired subjects before any merge_action. Empty-scope
572    // verifier steps are still remembered for fixture steps that have no PR
573    // identity, but scoped tool actions must verify the same repo/PR.
574    let mut verifier_scopes: BTreeSet<String> = BTreeSet::new();
575
576    // Track which steps fired (for required/order checks).
577    let mut steps_seen: Vec<String> = Vec::new();
578
579    let mut last_index: u64 = 0;
580    let mut saw_terminal: bool = false;
581
582    for env in events {
583        last_index = env.index;
584        let event = &env.event;
585        let session = event.session_id().to_string();
586        if !session_ids.contains(&session) {
587            session_ids.push(session.clone());
588        }
589
590        match event {
591            AgentEvent::AgentMessageChunk { .. } | AgentEvent::AgentThoughtChunk { .. } => {
592                // Streamed text doesn't count as a model call by
593                // itself; we count `IterationStart` instead so each model
594                // round-trip is one call regardless of how many
595                // chunk events stream.
596            }
597            AgentEvent::IterationStart { .. } => {
598                model_calls += 1;
599            }
600            AgentEvent::IterationEnd { .. } => {
601                saw_terminal = true;
602            }
603            AgentEvent::BudgetExhausted { .. } => {
604                saw_terminal = true;
605                findings.push(AuditFinding {
606                    category: FindingCategory::ExtraModelCall,
607                    severity: FindingSeverity::Error,
608                    message: "loop hit max_iterations without resolving".into(),
609                    event_indices: vec![env.index],
610                    state_step: None,
611                    tools: vec![],
612                });
613            }
614            AgentEvent::LoopStuck { .. } => {
615                saw_terminal = true;
616                findings.push(AuditFinding {
617                    category: FindingCategory::ExtraModelCall,
618                    severity: FindingSeverity::Error,
619                    message: "loop stuck on consecutive text-only turns".into(),
620                    event_indices: vec![env.index],
621                    state_step: None,
622                    tools: vec![],
623                });
624            }
625            AgentEvent::LoopStuckSignal { payload, .. } => {
626                let terminal = payload
627                    .get("terminal")
628                    .and_then(serde_json::Value::as_bool)
629                    .unwrap_or(true);
630                if terminal {
631                    saw_terminal = true;
632                    findings.push(AuditFinding {
633                        category: FindingCategory::ExtraModelCall,
634                        severity: FindingSeverity::Error,
635                        message: "loop stuck on pipeline no-progress signal".into(),
636                        event_indices: vec![env.index],
637                        state_step: None,
638                        tools: vec![],
639                    });
640                }
641            }
642            AgentEvent::Handoff { .. } => {
643                saw_terminal = true;
644                // Approval-gate step (default) consumes any pending
645                // approval.
646                if !pending_approvals.is_empty() {
647                    pending_approvals.clear();
648                }
649                check_state_transition(
650                    &state_steps_owned,
651                    StepTrigger::Event("handoff"),
652                    env.index,
653                    "handoff",
654                    &mut transitions,
655                    &mut steps_seen,
656                    &mut findings,
657                    &mut pending_approvals,
658                    &mut verifier_scopes,
659                );
660            }
661            AgentEvent::FeedbackInjected { kind, .. } => {
662                if kind.eq_ignore_ascii_case("approval") || kind.eq_ignore_ascii_case("approved") {
663                    pending_approvals.clear();
664                }
665                check_state_transition(
666                    &state_steps_owned,
667                    StepTrigger::Event("feedback_injected"),
668                    env.index,
669                    "feedback_injected",
670                    &mut transitions,
671                    &mut steps_seen,
672                    &mut findings,
673                    &mut pending_approvals,
674                    &mut verifier_scopes,
675                );
676            }
677            AgentEvent::OrchestrationDecision { decision: plan, .. } => {
678                check_plan_transitions(
679                    &state_steps_owned,
680                    plan,
681                    env.index,
682                    &mut transitions,
683                    &mut steps_seen,
684                    &mut findings,
685                    &mut pending_approvals,
686                    &mut verifier_scopes,
687                );
688                if let Some(approval) = plan
689                    .get("approval_required")
690                    .and_then(serde_json::Value::as_bool)
691                {
692                    if approval {
693                        pending_approvals.push(env.index);
694                    }
695                }
696                if !plan.is_object() {
697                    findings.push(AuditFinding {
698                        category: FindingCategory::InvalidStructuredOutput,
699                        severity: FindingSeverity::Error,
700                        message: "Plan event payload was not a JSON object".into(),
701                        event_indices: vec![env.index],
702                        state_step: None,
703                        tools: vec![],
704                    });
705                }
706            }
707            AgentEvent::ToolCall {
708                tool_name,
709                raw_input,
710                status,
711                ..
712            } => {
713                tool_calls += 1;
714                // Repeated-read detection.
715                let arg_hash = crate::canonical_json::to_string(raw_input);
716                match last_tool_call.get_mut(&session) {
717                    Some(entry) if entry.0 == *tool_name && entry.1 == arg_hash => {
718                        entry.2.push(env.index);
719                        if (entry.2.len() as u32) > max_repeat {
720                            let indices = entry.2.clone();
721                            findings.push(AuditFinding {
722                                category: FindingCategory::RepeatedRead,
723                                severity: FindingSeverity::Error,
724                                message: format!(
725                                    "tool `{}` called {} times consecutively with identical args",
726                                    tool_name,
727                                    indices.len()
728                                ),
729                                event_indices: indices,
730                                state_step: None,
731                                tools: vec![tool_name.clone()],
732                            });
733                            // Reset so we don't emit a finding per call.
734                            *entry = (tool_name.clone(), arg_hash.clone(), vec![env.index]);
735                        }
736                    }
737                    _ => {
738                        last_tool_call.insert(
739                            session.clone(),
740                            (tool_name.clone(), arg_hash.clone(), vec![env.index]),
741                        );
742                    }
743                }
744
745                // Bad-wait detection: a wait/sleep/poll without
746                // arguments that indicate progress.
747                if is_wait_tool(tool_name) {
748                    let indicates_progress = raw_input
749                        .as_object()
750                        .map(|obj| {
751                            obj.contains_key("until")
752                                || obj.contains_key("condition")
753                                || obj.contains_key("subscription_id")
754                        })
755                        .unwrap_or(false);
756                    if !indicates_progress {
757                        findings.push(AuditFinding {
758                            category: FindingCategory::BadWait,
759                            severity: FindingSeverity::Warn,
760                            message: format!(
761                                "wait/poll tool `{tool_name}` invoked without progress predicate (until/condition/subscription_id)"
762                            ),
763                            event_indices: vec![env.index],
764                            state_step: None,
765                            tools: vec![tool_name.clone()],
766                        });
767                    }
768                }
769
770                // Unsafe attempted action: check golden's
771                // require_approval_for, falling back to a default
772                // write-tool heuristic.
773                let needs_approval_match = match golden {
774                    Some(g) if !g.require_approval_for.is_empty() => {
775                        g.require_approval_for.iter().any(|p| p.matches(tool_name))
776                    }
777                    _ => is_merge_captain_write_tool(tool_name),
778                };
779                if needs_approval_match
780                    && pending_approvals.is_empty()
781                    && !already_approved(&steps_seen, &state_steps_owned)
782                {
783                    findings.push(AuditFinding {
784                        category: FindingCategory::UnsafeAttemptedAction,
785                        severity: FindingSeverity::Error,
786                        message: format!(
787                            "tool `{tool_name}` requires prior approval gate, but none observed"
788                        ),
789                        event_indices: vec![env.index],
790                        state_step: None,
791                        tools: vec![tool_name.clone()],
792                    });
793                }
794
795                // Forbidden actions.
796                if let Some(g) = golden {
797                    if g.forbidden_actions.iter().any(|p| p.matches(tool_name)) {
798                        findings.push(AuditFinding {
799                            category: FindingCategory::ForbiddenAction,
800                            severity: FindingSeverity::Error,
801                            message: format!(
802                                "tool `{}` is forbidden in scenario `{}`",
803                                tool_name, g.scenario
804                            ),
805                            event_indices: vec![env.index],
806                            state_step: None,
807                            tools: vec![tool_name.clone()],
808                        });
809                    }
810                }
811
812                // Tool-triggered state transitions. Mutating steps use the
813                // repo/PR scope to ensure verification happened for the same
814                // PR, not merely earlier in the sweep.
815                check_state_transition(
816                    &state_steps_owned,
817                    StepTrigger::Tool {
818                        name: tool_name,
819                        scope: transition_scope(raw_input),
820                    },
821                    env.index,
822                    tool_name,
823                    &mut transitions,
824                    &mut steps_seen,
825                    &mut findings,
826                    &mut pending_approvals,
827                    &mut verifier_scopes,
828                );
829                let _ = status;
830            }
831            AgentEvent::ToolCallUpdate {
832                status,
833                error,
834                error_category,
835                tool_name,
836                ..
837            } => {
838                if matches!(status, ToolCallStatus::Failed) {
839                    if let Some(category) = error_category {
840                        if matches!(category, ToolCallErrorCategory::SchemaValidation) {
841                            findings.push(AuditFinding {
842                                category: FindingCategory::InvalidStructuredOutput,
843                                severity: FindingSeverity::Error,
844                                message: format!(
845                                    "tool `{}` failed schema validation: {}",
846                                    tool_name,
847                                    error.clone().unwrap_or_default()
848                                ),
849                                event_indices: vec![env.index],
850                                state_step: None,
851                                tools: vec![tool_name.clone()],
852                            });
853                        }
854                    }
855                }
856            }
857            _ => {
858                // Other events (skill, tool_search, fs_watch, worker
859                // updates) are not part of the oracle today.
860            }
861        }
862    }
863
864    // Suite-level checks.
865    if !pending_approvals.is_empty() {
866        findings.push(AuditFinding {
867            category: FindingCategory::MissingApproval,
868            severity: FindingSeverity::Error,
869            message: format!(
870                "{} plan(s) declared approval_required: true with no following approval gate",
871                pending_approvals.len()
872            ),
873            event_indices: pending_approvals.clone(),
874            state_step: Some("approval_gate".into()),
875            tools: vec![],
876        });
877    }
878
879    if !events.is_empty() && !saw_terminal {
880        findings.push(AuditFinding {
881            category: FindingCategory::IncompleteTranscript,
882            severity: FindingSeverity::Warn,
883            message:
884                "transcript ended without a IterationEnd / Handoff / BudgetExhausted / LoopStuck event"
885                    .into(),
886            event_indices: vec![last_index],
887            state_step: None,
888            tools: vec![],
889        });
890    }
891
892    // Required state steps.
893    for step in &state_steps_owned {
894        if step.required && !steps_seen.iter().any(|s| s == &step.step) {
895            findings.push(AuditFinding {
896                category: FindingCategory::MissingStateStep,
897                severity: FindingSeverity::Error,
898                message: format!("required state step `{}` was never reached", step.step),
899                event_indices: vec![],
900                state_step: Some(step.step.clone()),
901                tools: vec![],
902            });
903        }
904    }
905
906    // Step ordering: each step must appear at most once before any
907    // step later in the golden's declaration order. We flag if we
908    // see step B fire and then step A (where A is declared before B)
909    // fire afterwards.
910    let order: BTreeMap<&str, usize> = state_steps_owned
911        .iter()
912        .enumerate()
913        .map(|(i, s)| (s.step.as_str(), i))
914        .collect();
915    let mut highest: usize = 0;
916    let mut last_step: Option<&str> = None;
917    for step in &steps_seen {
918        if let Some(idx) = order.get(step.as_str()) {
919            if *idx + 1 < highest && last_step != Some(step.as_str()) {
920                findings.push(AuditFinding {
921                    category: FindingCategory::StateOutOfOrder,
922                    severity: FindingSeverity::Warn,
923                    message: format!("state step `{step}` fired after a later step"),
924                    event_indices: vec![],
925                    state_step: Some(step.clone()),
926                    tools: vec![],
927                });
928            }
929            if *idx > highest {
930                highest = *idx;
931            }
932            last_step = Some(step.as_str());
933        }
934    }
935
936    if let Some(g) = golden {
937        if !g.expected_state_transitions.is_empty() {
938            let observed: Vec<String> = transitions
939                .iter()
940                .map(|transition| transition.step.clone())
941                .collect();
942            if observed != g.expected_state_transitions {
943                findings.push(AuditFinding {
944                    category: FindingCategory::StateSequenceMismatch,
945                    severity: FindingSeverity::Error,
946                    message: format!(
947                        "state transitions {:?} did not match expected {:?}",
948                        observed, g.expected_state_transitions
949                    ),
950                    event_indices: vec![],
951                    state_step: None,
952                    tools: vec![],
953                });
954            }
955        }
956    }
957
958    // Tool-budget check.
959    if let Some(g) = golden {
960        if let Some(max) = g.max_tool_calls {
961            if tool_calls > max {
962                findings.push(AuditFinding {
963                    category: FindingCategory::NonMinimalToolUsage,
964                    severity: FindingSeverity::Error,
965                    message: format!("tool calls ({tool_calls}) exceeded scenario budget ({max})"),
966                    event_indices: vec![],
967                    state_step: None,
968                    tools: vec![],
969                });
970            }
971        }
972        if let Some(max) = g.max_model_calls {
973            if model_calls > max {
974                findings.push(AuditFinding {
975                    category: FindingCategory::ExtraModelCall,
976                    severity: FindingSeverity::Error,
977                    message: format!(
978                        "model calls ({model_calls}) exceeded scenario budget ({max})"
979                    ),
980                    event_indices: vec![],
981                    state_step: None,
982                    tools: vec![],
983                });
984            }
985        }
986    }
987
988    let pass = findings
989        .iter()
990        .all(|f| f.severity != FindingSeverity::Error);
991
992    AuditReport {
993        scenario,
994        source_path: None,
995        session_ids,
996        event_count: events.len() as u64,
997        model_call_count: model_calls,
998        tool_call_count: tool_calls,
999        findings,
1000        state_transitions: transitions,
1001        pass,
1002    }
1003}
1004
1005enum StepTrigger<'a> {
1006    Tool {
1007        name: &'a str,
1008        scope: Option<String>,
1009    },
1010    Event(&'a str),
1011}
1012
1013#[allow(clippy::too_many_arguments)]
1014fn check_state_transition(
1015    steps: &[GoldenStateStep],
1016    trigger: StepTrigger,
1017    event_index: u64,
1018    triggered_by: &str,
1019    transitions: &mut Vec<StateTransition>,
1020    steps_seen: &mut Vec<String>,
1021    findings: &mut Vec<AuditFinding>,
1022    pending_approvals: &mut Vec<u64>,
1023    verifier_scopes: &mut BTreeSet<String>,
1024) {
1025    for step in steps {
1026        let matched = match &trigger {
1027            StepTrigger::Tool { name, .. } => step.tools.iter().any(|p| p.matches(name)),
1028            StepTrigger::Event(name) => step.events.iter().any(|e| e.eq_ignore_ascii_case(name)),
1029        };
1030        if !matched {
1031            continue;
1032        }
1033        let scope = match &trigger {
1034            StepTrigger::Tool { scope, .. } => scope.clone(),
1035            StepTrigger::Event(_) => None,
1036        };
1037        record_step(
1038            step,
1039            event_index,
1040            triggered_by,
1041            scope.as_deref(),
1042            transitions,
1043            steps_seen,
1044            findings,
1045            pending_approvals,
1046            verifier_scopes,
1047        );
1048        // Continue: a single event may match multiple steps when
1049        // golden patterns overlap (e.g. "*pull_request*" intake +
1050        // "*merge_pull_request*" merge). Each fires independently;
1051        // dedup happens in `record_step`'s `steps_seen` check.
1052    }
1053}
1054
1055#[allow(clippy::too_many_arguments)]
1056fn check_plan_transitions(
1057    steps: &[GoldenStateStep],
1058    plan: &serde_json::Value,
1059    event_index: u64,
1060    transitions: &mut Vec<StateTransition>,
1061    steps_seen: &mut Vec<String>,
1062    findings: &mut Vec<AuditFinding>,
1063    pending_approvals: &mut Vec<u64>,
1064    verifier_scopes: &mut BTreeSet<String>,
1065) {
1066    let obj = match plan.as_object() {
1067        Some(o) => o,
1068        None => return,
1069    };
1070    for step in steps {
1071        let plan_match = step.plan_fields.iter().any(|field| {
1072            if step.approval_gate && field == "approval_required" {
1073                obj.get(field).and_then(serde_json::Value::as_bool) == Some(true)
1074            } else {
1075                obj.contains_key(field)
1076            }
1077        });
1078        let event_match = step.events.iter().any(|e| e.eq_ignore_ascii_case("plan"));
1079        if !(plan_match || (event_match && step.plan_fields.is_empty())) {
1080            continue;
1081        }
1082        if !plan_match && !event_match {
1083            continue;
1084        }
1085        record_step(
1086            step,
1087            event_index,
1088            "plan",
1089            transition_scope(plan).as_deref(),
1090            transitions,
1091            steps_seen,
1092            findings,
1093            pending_approvals,
1094            verifier_scopes,
1095        );
1096    }
1097}
1098
1099#[allow(clippy::too_many_arguments)]
1100fn record_step(
1101    step: &GoldenStateStep,
1102    event_index: u64,
1103    triggered_by: &str,
1104    scope: Option<&str>,
1105    transitions: &mut Vec<StateTransition>,
1106    steps_seen: &mut Vec<String>,
1107    findings: &mut Vec<AuditFinding>,
1108    pending_approvals: &mut Vec<u64>,
1109    verifier_scopes: &mut BTreeSet<String>,
1110) {
1111    transitions.push(StateTransition {
1112        step: step.step.clone(),
1113        event_index,
1114        triggered_by: triggered_by.to_string(),
1115    });
1116    if !steps_seen.contains(&step.step) {
1117        steps_seen.push(step.step.clone());
1118    }
1119    if step.approval_gate {
1120        pending_approvals.clear();
1121    }
1122    if step.verifier {
1123        verifier_scopes.insert(scope.unwrap_or("*").to_string());
1124    }
1125    let verified = scope
1126        .map(|scope| verifier_scopes.contains(scope) || verifier_scopes.contains("*"))
1127        .unwrap_or_else(|| !verifier_scopes.is_empty());
1128    if step.merge_action && !verified {
1129        findings.push(AuditFinding {
1130            category: FindingCategory::SkippedVerification,
1131            severity: FindingSeverity::Error,
1132            message: format!(
1133                "merge action `{}` reached without a preceding verifier step",
1134                step.step
1135            ),
1136            event_indices: vec![event_index],
1137            state_step: Some(step.step.clone()),
1138            tools: vec![],
1139        });
1140    }
1141}
1142
1143fn transition_scope(value: &serde_json::Value) -> Option<String> {
1144    let repo = value.get("repo").and_then(serde_json::Value::as_str)?;
1145    let pr_number = value
1146        .get("pr_number")
1147        .or_else(|| value.get("number"))
1148        .and_then(serde_json::Value::as_u64)?;
1149    Some(format!("{repo}#{pr_number}"))
1150}
1151
1152fn already_approved(steps_seen: &[String], steps: &[GoldenStateStep]) -> bool {
1153    steps
1154        .iter()
1155        .filter(|s| s.approval_gate)
1156        .any(|s| steps_seen.contains(&s.step))
1157}
1158
1159#[cfg(test)]
1160mod tests {
1161    use super::*;
1162    use crate::agent_events::{AgentEvent, PersistedAgentEvent, ToolCallStatus};
1163    use serde_json::json;
1164
1165    #[path = "structured_output_tests.rs"]
1166    mod structured_output;
1167
1168    fn env(index: u64, event: AgentEvent) -> PersistedAgentEvent {
1169        PersistedAgentEvent {
1170            index,
1171            emitted_at_ms: 0,
1172            frame_depth: None,
1173            event,
1174        }
1175    }
1176
1177    fn iteration_start(index: u64, session: &str, iter: usize) -> PersistedAgentEvent {
1178        env(
1179            index,
1180            AgentEvent::IterationStart {
1181                session_id: session.into(),
1182                iteration: iter,
1183                provider: String::new(),
1184                model: String::new(),
1185            },
1186        )
1187    }
1188
1189    fn iteration_end(index: u64, session: &str, iter: usize) -> PersistedAgentEvent {
1190        env(
1191            index,
1192            AgentEvent::IterationEnd {
1193                session_id: session.into(),
1194                iteration: iter,
1195                iteration_info: serde_json::Value::Null,
1196            },
1197        )
1198    }
1199
1200    fn tool_call(
1201        index: u64,
1202        session: &str,
1203        tool: &str,
1204        args: serde_json::Value,
1205    ) -> PersistedAgentEvent {
1206        env(
1207            index,
1208            AgentEvent::ToolCall {
1209                session_id: session.into(),
1210                tool_call_id: format!("call_{index}"),
1211                tool_name: tool.into(),
1212                kind: None,
1213                status: ToolCallStatus::Pending,
1214                raw_input: args,
1215                parsing: None,
1216                audit: None,
1217            },
1218        )
1219    }
1220
1221    fn plan(index: u64, session: &str, plan: serde_json::Value) -> PersistedAgentEvent {
1222        env(
1223            index,
1224            AgentEvent::OrchestrationDecision {
1225                session_id: session.into(),
1226                decision: plan,
1227            },
1228        )
1229    }
1230
1231    fn handoff(index: u64, session: &str) -> PersistedAgentEvent {
1232        env(
1233            index,
1234            AgentEvent::Handoff {
1235                session_id: session.into(),
1236                artifact_id: format!("artifact_{index}"),
1237                handoff: Box::new(crate::orchestration::HandoffArtifact::default()),
1238            },
1239        )
1240    }
1241
1242    fn loop_stuck_signal(index: u64, session: &str, terminal: bool) -> PersistedAgentEvent {
1243        env(
1244            index,
1245            AgentEvent::LoopStuckSignal {
1246                session_id: session.into(),
1247                payload: json!({"terminal": terminal}),
1248            },
1249        )
1250    }
1251
1252    #[test]
1253    fn pass_minimal_green_pr_default_rules() {
1254        let events = vec![
1255            iteration_start(1, "s", 1),
1256            tool_call(2, "s", "fetch_pull_request", json!({"number": 1})),
1257            tool_call(3, "s", "list_checks", json!({"pr": 1})),
1258            plan(
1259                4,
1260                "s",
1261                json!({
1262                    "review_risk": "low",
1263                    "approval_required": false,
1264                    "pr_number": 1,
1265                }),
1266            ),
1267            iteration_end(5, "s", 1),
1268        ];
1269        let report = audit_transcript(&events, None);
1270        assert!(report.pass, "report: {report}");
1271        assert_eq!(report.tool_call_count, 2);
1272        assert_eq!(report.model_call_count, 1);
1273        assert!(
1274            report.findings.is_empty(),
1275            "findings: {:?}",
1276            report.findings
1277        );
1278    }
1279
1280    #[test]
1281    fn flags_repeated_reads_with_default_threshold() {
1282        let events = vec![
1283            iteration_start(1, "s", 1),
1284            tool_call(2, "s", "list_checks", json!({"pr": 1})),
1285            tool_call(3, "s", "list_checks", json!({"pr": 1})),
1286            tool_call(4, "s", "list_checks", json!({"pr": 1})),
1287            iteration_end(5, "s", 1),
1288        ];
1289        let report = audit_transcript(&events, None);
1290        assert!(!report.pass);
1291        assert!(report
1292            .findings
1293            .iter()
1294            .any(|f| f.category == FindingCategory::RepeatedRead));
1295    }
1296
1297    #[test]
1298    fn flags_unsafe_action_without_approval() {
1299        let events = vec![
1300            iteration_start(1, "s", 1),
1301            tool_call(2, "s", "merge_pull_request", json!({"number": 1})),
1302            iteration_end(3, "s", 1),
1303        ];
1304        let report = audit_transcript(&events, None);
1305        assert!(!report.pass);
1306        assert!(report
1307            .findings
1308            .iter()
1309            .any(|f| f.category == FindingCategory::UnsafeAttemptedAction));
1310    }
1311
1312    #[test]
1313    fn approval_required_false_does_not_open_approval_gate() {
1314        let events = vec![
1315            iteration_start(1, "s", 1),
1316            plan(
1317                2,
1318                "s",
1319                json!({"approval_required": false, "review_risk": "low"}),
1320            ),
1321            tool_call(3, "s", "merge_pull_request", json!({"number": 1})),
1322            iteration_end(4, "s", 1),
1323        ];
1324        let report = audit_transcript(&events, None);
1325        assert!(!report.pass);
1326        assert!(report
1327            .findings
1328            .iter()
1329            .any(|f| f.category == FindingCategory::UnsafeAttemptedAction));
1330    }
1331
1332    #[test]
1333    fn flags_missing_approval_after_required_plan() {
1334        let events = vec![
1335            iteration_start(1, "s", 1),
1336            plan(
1337                2,
1338                "s",
1339                json!({"approval_required": true, "review_risk": "high"}),
1340            ),
1341            iteration_end(3, "s", 1),
1342        ];
1343        let report = audit_transcript(&events, None);
1344        assert!(!report.pass);
1345        assert!(report
1346            .findings
1347            .iter()
1348            .any(|f| f.category == FindingCategory::MissingApproval));
1349    }
1350
1351    #[test]
1352    fn handoff_satisfies_pending_approval() {
1353        let events = vec![
1354            iteration_start(1, "s", 1),
1355            plan(
1356                2,
1357                "s",
1358                json!({"approval_required": true, "review_risk": "high"}),
1359            ),
1360            handoff(3, "s"),
1361        ];
1362        let report = audit_transcript(&events, None);
1363        assert!(
1364            !report
1365                .findings
1366                .iter()
1367                .any(|f| f.category == FindingCategory::MissingApproval),
1368            "findings: {:?}",
1369            report.findings
1370        );
1371    }
1372
1373    #[test]
1374    fn non_terminal_loop_stuck_signal_does_not_complete_transcript() {
1375        let events = vec![iteration_start(1, "s", 1), loop_stuck_signal(2, "s", false)];
1376        let report = audit_transcript(&events, None);
1377        assert!(report
1378            .findings
1379            .iter()
1380            .any(|f| f.category == FindingCategory::IncompleteTranscript));
1381    }
1382
1383    #[test]
1384    fn terminal_loop_stuck_signal_completes_transcript() {
1385        let events = vec![iteration_start(1, "s", 1), loop_stuck_signal(2, "s", true)];
1386        let report = audit_transcript(&events, None);
1387        assert!(
1388            !report
1389                .findings
1390                .iter()
1391                .any(|f| f.category == FindingCategory::IncompleteTranscript),
1392            "findings: {:?}",
1393            report.findings
1394        );
1395    }
1396
1397    #[test]
1398    fn flags_skipped_verification_when_merge_runs_without_verifier() {
1399        let golden = MergeCaptainGolden {
1400            type_name: "merge_captain_golden".into(),
1401            scenario: "test".into(),
1402            state_steps: vec![
1403                GoldenStateStep {
1404                    step: "verify".into(),
1405                    tools: vec![ToolPattern {
1406                        glob: Some("*list_checks*".into()),
1407                        ..Default::default()
1408                    }],
1409                    verifier: true,
1410                    ..Default::default()
1411                },
1412                GoldenStateStep {
1413                    step: "approve".into(),
1414                    events: vec!["feedback_injected".into()],
1415                    approval_gate: true,
1416                    ..Default::default()
1417                },
1418                GoldenStateStep {
1419                    step: "merge".into(),
1420                    tools: vec![ToolPattern {
1421                        glob: Some("*merge*".into()),
1422                        ..Default::default()
1423                    }],
1424                    merge_action: true,
1425                    required: true,
1426                    ..Default::default()
1427                },
1428            ],
1429            ..Default::default()
1430        };
1431        let events = vec![
1432            iteration_start(1, "s", 1),
1433            env(
1434                2,
1435                AgentEvent::FeedbackInjected {
1436                    session_id: "s".into(),
1437                    kind: "approval".into(),
1438                    content: "ok".into(),
1439                    streak: None,
1440                },
1441            ),
1442            tool_call(3, "s", "merge_pull_request", json!({"number": 1})),
1443            iteration_end(4, "s", 1),
1444        ];
1445        let report = audit_transcript(&events, Some(&golden));
1446        assert!(report
1447            .findings
1448            .iter()
1449            .any(|f| f.category == FindingCategory::SkippedVerification));
1450    }
1451
1452    #[test]
1453    fn verifier_scope_must_match_merge_scope() {
1454        let golden = MergeCaptainGolden {
1455            type_name: "merge_captain_golden".into(),
1456            scenario: "test".into(),
1457            state_steps: vec![
1458                GoldenStateStep {
1459                    step: "verify".into(),
1460                    tools: vec![ToolPattern {
1461                        glob: Some("*list_checks*".into()),
1462                        ..Default::default()
1463                    }],
1464                    verifier: true,
1465                    ..Default::default()
1466                },
1467                GoldenStateStep {
1468                    step: "merge".into(),
1469                    tools: vec![ToolPattern {
1470                        glob: Some("*merge*".into()),
1471                        ..Default::default()
1472                    }],
1473                    merge_action: true,
1474                    ..Default::default()
1475                },
1476            ],
1477            ..Default::default()
1478        };
1479        let events = vec![
1480            iteration_start(1, "s", 1),
1481            tool_call(
1482                2,
1483                "s",
1484                "list_checks",
1485                json!({"repo": "burin-labs/harn", "pr_number": 1}),
1486            ),
1487            tool_call(
1488                3,
1489                "s",
1490                "merge_pull_request",
1491                json!({"repo": "burin-labs/harn", "pr_number": 2}),
1492            ),
1493            iteration_end(4, "s", 1),
1494        ];
1495        let report = audit_transcript(&events, Some(&golden));
1496        assert!(report
1497            .findings
1498            .iter()
1499            .any(|f| f.category == FindingCategory::SkippedVerification));
1500    }
1501
1502    #[test]
1503    fn flags_extra_model_calls_against_golden() {
1504        let golden = MergeCaptainGolden {
1505            type_name: "merge_captain_golden".into(),
1506            scenario: "test".into(),
1507            max_model_calls: Some(1),
1508            ..Default::default()
1509        };
1510        let events = vec![
1511            iteration_start(1, "s", 1),
1512            iteration_end(2, "s", 1),
1513            iteration_start(3, "s", 2),
1514            iteration_end(4, "s", 2),
1515        ];
1516        let report = audit_transcript(&events, Some(&golden));
1517        assert!(!report.pass);
1518        assert!(report
1519            .findings
1520            .iter()
1521            .any(|f| f.category == FindingCategory::ExtraModelCall));
1522    }
1523
1524    #[test]
1525    fn flags_non_minimal_tool_usage() {
1526        let golden = MergeCaptainGolden {
1527            type_name: "merge_captain_golden".into(),
1528            scenario: "test".into(),
1529            max_tool_calls: Some(1),
1530            ..Default::default()
1531        };
1532        let events = vec![
1533            iteration_start(1, "s", 1),
1534            tool_call(2, "s", "list_checks", json!({"a": 1})),
1535            tool_call(3, "s", "list_threads", json!({"a": 2})),
1536            iteration_end(4, "s", 1),
1537        ];
1538        let report = audit_transcript(&events, Some(&golden));
1539        assert!(!report.pass);
1540        assert!(report
1541            .findings
1542            .iter()
1543            .any(|f| f.category == FindingCategory::NonMinimalToolUsage));
1544    }
1545
1546    #[test]
1547    fn flags_forbidden_action() {
1548        let golden = MergeCaptainGolden {
1549            type_name: "merge_captain_golden".into(),
1550            scenario: "test".into(),
1551            forbidden_actions: vec![ToolPattern {
1552                glob: Some("*force_push*".into()),
1553                ..Default::default()
1554            }],
1555            ..Default::default()
1556        };
1557        // Approve up front so unsafe-action rule doesn't double-fire.
1558        let events = vec![
1559            iteration_start(1, "s", 1),
1560            env(
1561                2,
1562                AgentEvent::FeedbackInjected {
1563                    session_id: "s".into(),
1564                    kind: "approval".into(),
1565                    content: "ok".into(),
1566                    streak: None,
1567                },
1568            ),
1569            tool_call(3, "s", "force_push", json!({"branch": "main"})),
1570            iteration_end(4, "s", 1),
1571        ];
1572        let report = audit_transcript(&events, Some(&golden));
1573        assert!(!report.pass);
1574        assert!(report
1575            .findings
1576            .iter()
1577            .any(|f| f.category == FindingCategory::ForbiddenAction));
1578    }
1579
1580    #[test]
1581    fn missing_required_state_step() {
1582        let golden = MergeCaptainGolden {
1583            type_name: "merge_captain_golden".into(),
1584            scenario: "test".into(),
1585            state_steps: vec![GoldenStateStep {
1586                step: "verify".into(),
1587                tools: vec![ToolPattern {
1588                    glob: Some("*list_checks*".into()),
1589                    ..Default::default()
1590                }],
1591                required: true,
1592                verifier: true,
1593                ..Default::default()
1594            }],
1595            ..Default::default()
1596        };
1597        let events = vec![iteration_start(1, "s", 1), iteration_end(2, "s", 1)];
1598        let report = audit_transcript(&events, Some(&golden));
1599        assert!(!report.pass);
1600        assert!(report
1601            .findings
1602            .iter()
1603            .any(|f| f.category == FindingCategory::MissingStateStep));
1604    }
1605
1606    #[test]
1607    fn glob_matching_basic_cases() {
1608        let p = ToolPattern {
1609            glob: Some("*merge*".into()),
1610            ..Default::default()
1611        };
1612        assert!(p.matches("gh_merge_pr"));
1613        assert!(p.matches("MERGE"));
1614        assert!(!p.matches("approve"));
1615
1616        let prefix = ToolPattern {
1617            glob: Some("gh_*".into()),
1618            ..Default::default()
1619        };
1620        assert!(prefix.matches("gh_pr_list"));
1621        assert!(!prefix.matches("git_pr_list"));
1622
1623        let suffix = ToolPattern {
1624            glob: Some("*_merge".into()),
1625            ..Default::default()
1626        };
1627        assert!(suffix.matches("force_merge"));
1628        assert!(!suffix.matches("merge_force"));
1629
1630        let exact = ToolPattern {
1631            name: Some("read_file".into()),
1632            ..Default::default()
1633        };
1634        assert!(exact.matches("read_file"));
1635        assert!(!exact.matches("read_files"));
1636    }
1637
1638    #[test]
1639    fn round_trip_report_serialization() {
1640        let events = vec![
1641            iteration_start(1, "s", 1),
1642            tool_call(2, "s", "list_checks", json!({"pr": 1})),
1643            iteration_end(3, "s", 1),
1644        ];
1645        let report = audit_transcript(&events, None);
1646        let json = serde_json::to_string(&report).expect("serialize");
1647        let parsed: AuditReport = serde_json::from_str(&json).expect("deserialize");
1648        assert_eq!(parsed.pass, report.pass);
1649        assert_eq!(parsed.event_count, report.event_count);
1650    }
1651
1652    #[test]
1653    fn loads_jsonl_transcript_from_file() {
1654        use std::io::Write;
1655        let dir = tempfile::tempdir().expect("tempdir");
1656        let path = dir.path().join("event_log.jsonl");
1657        let mut file = fs::File::create(&path).expect("create");
1658        for env in [iteration_start(1, "s", 1), iteration_end(2, "s", 1)] {
1659            let line = serde_json::to_string(&env).expect("ser");
1660            writeln!(file, "{line}").expect("write");
1661        }
1662        drop(file);
1663        let loaded = load_transcript_jsonl(&path).expect("load");
1664        assert_eq!(loaded.events.len(), 2);
1665    }
1666
1667    #[test]
1668    fn loads_jsonl_transcript_from_directory() {
1669        use std::io::Write;
1670        let dir = tempfile::tempdir().expect("tempdir");
1671        let path1 = dir.path().join("event_log.jsonl");
1672        let path2 = dir.path().join("event_log-000001.jsonl");
1673        {
1674            let mut file = fs::File::create(&path1).expect("create");
1675            writeln!(
1676                file,
1677                "{}",
1678                serde_json::to_string(&iteration_start(1, "s", 1)).unwrap()
1679            )
1680            .unwrap();
1681        }
1682        {
1683            let mut file = fs::File::create(&path2).expect("create");
1684            writeln!(
1685                file,
1686                "{}",
1687                serde_json::to_string(&iteration_end(2, "s", 1)).unwrap()
1688            )
1689            .unwrap();
1690        }
1691        let loaded = load_transcript_jsonl(dir.path()).expect("load");
1692        assert_eq!(loaded.events.len(), 2);
1693        assert_eq!(loaded.events[0].index, 1);
1694        assert_eq!(loaded.events[1].index, 2);
1695    }
1696}