From e4c14cdce732ab69bce8a342271a2b8dc37d44f5 Mon Sep 17 00:00:00 2001 From: fslong <470657570@qq.com> Date: Sat, 21 Nov 2026 19:46:56 +0800 Subject: [PATCH] feat(ai): agent capabilities (confirm gate/readback/progress/planning/retry/txn/cost/skills) + ffmpeg analysis tools MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Agent 通用层(crates/oak-app/src/ai/,5 组能力): - confirm gate:编辑前确认门;readback:执行后回读校验;progress:进度上报; - planning:计划生成与推进;retry/txn/cost/skills:重试、事务边界、成本与技能记账 - 落点 agent.rs/mod.rs 及新增 confirm.rs、plan.rs、progress.rs、readback.rs 分析层(ai/oak-ai-tools/,ffmpeg 分析工具): - 新增 src/ffmpeg.rs、src/tools/analysis.rs、src/tools/analysis_exec.rs, dispatch/schema_v2/hooks/backend 接线,新增 tests/analysis_ffmpeg.rs 测试证据(本地全绿,task-60 验证,本轮代码未再改动): - oak-app:686 passed / 0 failed - ai 独立 workspace:125 passed / 0 failed - 冻结 22 工具 schema 未动(schema 文件零改动) --- ai/oak-ai-tools/src/backend.rs | 42 + ai/oak-ai-tools/src/dispatch.rs | 43 +- ai/oak-ai-tools/src/ffmpeg.rs | 199 ++++ ai/oak-ai-tools/src/hooks.rs | 7 +- ai/oak-ai-tools/src/lib.rs | 1 + ai/oak-ai-tools/src/schema_v2.rs | 170 ++- ai/oak-ai-tools/src/tools/analysis.rs | 356 +++++++ ai/oak-ai-tools/src/tools/analysis_exec.rs | 603 +++++++++++ ai/oak-ai-tools/src/tools/mod.rs | 2 + ai/oak-ai-tools/tests/analysis_ffmpeg.rs | 392 +++++++ crates/oak-app/src/ai/agent.rs | 633 ++++++++++- crates/oak-app/src/ai/agent/tests.rs | 430 +++++++- crates/oak-app/src/ai/confirm.rs | 525 ++++++++++ crates/oak-app/src/ai/mod.rs | 22 + crates/oak-app/src/ai/plan.rs | 982 ++++++++++++++++++ crates/oak-app/src/ai/progress.rs | 130 +++ crates/oak-app/src/ai/readback.rs | 580 +++++++++++ .../oak-app/src/panels/ai_assistant/tests.rs | 5 + 18 files changed, 5094 insertions(+), 28 deletions(-) create mode 100644 ai/oak-ai-tools/src/ffmpeg.rs create mode 100644 ai/oak-ai-tools/src/tools/analysis.rs create mode 100644 ai/oak-ai-tools/src/tools/analysis_exec.rs create mode 100644 ai/oak-ai-tools/tests/analysis_ffmpeg.rs create mode 100644 crates/oak-app/src/ai/confirm.rs create mode 100644 crates/oak-app/src/ai/plan.rs create mode 100644 crates/oak-app/src/ai/progress.rs create mode 100644 crates/oak-app/src/ai/readback.rs diff --git a/ai/oak-ai-tools/src/backend.rs b/ai/oak-ai-tools/src/backend.rs index b6be9f203e..0c7a714cbd 100644 --- a/ai/oak-ai-tools/src/backend.rs +++ b/ai/oak-ai-tools/src/backend.rs @@ -121,4 +121,46 @@ pub trait EngineExt: EngineBackend { "this backend has no `sequence.set_format` support", )) } + + /// `analysis.detect_silence` — ffmpeg silencedetect over `src`. + /// + /// The default body runs the real `ffmpeg` process (the analysis tools + /// are file-level reads, not engine state), so mock and SDK backends + /// both get them; a machine without ffmpeg answers the structured + /// `GAP_ANALYSIS_FFMPEG` gap instead of a fabricated success. + fn analysis_detect_silence( + &self, + parsed: &crate::tools::analysis::DetectSilence, + ) -> Result { + crate::tools::analysis_exec::detect_silence(parsed) + } + + /// `analysis.detect_scenes` — ffmpeg scdet over `src`. + fn analysis_detect_scenes( + &self, + parsed: &crate::tools::analysis::DetectScenes, + ) -> Result { + crate::tools::analysis_exec::detect_scenes(parsed) + } + + /// `analysis.detect_black` — ffmpeg blackdetect over `src`. + fn analysis_detect_black( + &self, + parsed: &crate::tools::analysis::DetectBlack, + ) -> Result { + crate::tools::analysis_exec::detect_black(parsed) + } + + /// `analysis.loudness` — ffmpeg ebur128 over `src`. + fn analysis_loudness(&self, parsed: &crate::tools::analysis::Loudness) -> Result { + crate::tools::analysis_exec::loudness(parsed) + } + + /// `analysis.export_thumbnails` — ffmpeg frame dump into `outdir`. + fn analysis_export_thumbnails( + &self, + parsed: &crate::tools::analysis::ExportThumbnails, + ) -> Result { + crate::tools::analysis_exec::export_thumbnails(parsed) + } } diff --git a/ai/oak-ai-tools/src/dispatch.rs b/ai/oak-ai-tools/src/dispatch.rs index ef6390d868..57e06435da 100644 --- a/ai/oak-ai-tools/src/dispatch.rs +++ b/ai/oak-ai-tools/src/dispatch.rs @@ -341,7 +341,7 @@ pub struct V2ToolDef { /// The v2 registry: parse, then forward to the extension method. pub fn v2_registry() -> &'static [V2ToolDef] { - static REGISTRY: [V2ToolDef; 2] = [ + static REGISTRY: [V2ToolDef; 7] = [ V2ToolDef { name: "sequence.get_settings", transactional: true, @@ -358,6 +358,47 @@ pub fn v2_registry() -> &'static [V2ToolDef] { backend.sequence_set_format(args.clone()) }, }, + V2ToolDef { + name: "analysis.detect_silence", + // Pure read: no project state, no undo row → not transactional. + transactional: false, + call: |backend, args| { + let parsed = tools::analysis::parse_detect_silence(args)?; + backend.analysis_detect_silence(&parsed) + }, + }, + V2ToolDef { + name: "analysis.detect_scenes", + transactional: false, + call: |backend, args| { + let parsed = tools::analysis::parse_detect_scenes(args)?; + backend.analysis_detect_scenes(&parsed) + }, + }, + V2ToolDef { + name: "analysis.detect_black", + transactional: false, + call: |backend, args| { + let parsed = tools::analysis::parse_detect_black(args)?; + backend.analysis_detect_black(&parsed) + }, + }, + V2ToolDef { + name: "analysis.loudness", + transactional: false, + call: |backend, args| { + let parsed = tools::analysis::parse_loudness(args)?; + backend.analysis_loudness(&parsed) + }, + }, + V2ToolDef { + name: "analysis.export_thumbnails", + transactional: false, + call: |backend, args| { + let parsed = tools::analysis::parse_export_thumbnails(args)?; + backend.analysis_export_thumbnails(&parsed) + }, + }, ]; ®ISTRY diff --git a/ai/oak-ai-tools/src/ffmpeg.rs b/ai/oak-ai-tools/src/ffmpeg.rs new file mode 100644 index 0000000000..704fece5b9 --- /dev/null +++ b/ai/oak-ai-tools/src/ffmpeg.rs @@ -0,0 +1,199 @@ +//! Minimal `ffmpeg` process wrapper: one invocation per call, every +//! argument passed individually through [`std::process::Command::arg`] +//! (never through a shell — the tool face runs on paths a model +//! supplied, so a string command line would be a command-injection hole). +//! +//! The five analysis filters are parsed from the raw `stderr`/`stdout` +//! ffmpeg prints; this module only *runs* and *classifies*, the parsers +//! live in [`crate::tools::analysis`]. + +use std::path::Path; +use std::process::{Command, Stdio}; + +use serde_json::json; + +use crate::error::ToolError; + +/// The gap id reported when `ffmpeg` is absent from `PATH`. +pub const GAP_FFMPEG_MISSING: &str = "GAP_ANALYSIS_FFMPEG"; + +/// True when an `ffmpeg -version` probe succeeds on this machine. +pub fn ffmpeg_available() -> bool { + Command::new("ffmpeg") + .arg("-version") + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .map(|status| status.success()) + .unwrap_or(false) +} + +/// The error every analysis tool returns when ffmpeg cannot be spawned: +/// a *structured* capability gap, never a fabricated success. +pub fn missing_ffmpeg() -> ToolError { + ToolError::unsupported( + GAP_FFMPEG_MISSING, + "ffmpeg was not found on PATH; install ffmpeg or expose it to the process \ + to use the analysis.* tools", + ) +} + +/// Input-file gate: exists, is a regular file, is readable. +pub fn check_input(src: &str) -> Result<(), ToolError> { + let path = Path::new(src); + if !path.exists() { + return Err(ToolError::not_found(format!("input file not found: {src}"))); + } + if !path.is_file() { + return Err(ToolError::invalid_params(format!( + "input is not a regular file: {src}" + ))); + } + if !path.metadata().map(|m| m.len() > 0).unwrap_or(false) { + return Err(ToolError::invalid_params(format!( + "input file is empty: {src}" + ))); + } + Ok(()) +} + +/// Captured result of one ffmpeg run: exit status, stdout, stderr. +pub struct Capture { + /// Process exit code (`None` when killed by a signal). + pub code: Option, + /// Everything ffmpeg wrote to stdout. + pub out: String, + /// Everything ffmpeg wrote to stderr (the log channel the filters log to). + pub err: String, +} + +/// Runs `ffmpeg` with `args` (each passed as one argv entry, no shell) and +/// captures both streams. +/// +/// A spawn failure is either the missing-binary gap (spawn error on +/// `ffmpeg`) or an IO error; a non-zero exit is *not* turned into an error +/// here — callers classify the code together with the captured text +/// (ffmpeg's exit codes are wide: 254 = no such input, 251 = output +/// open failed, 234 = no stream for the filtergraph). +pub fn run(args: &[&str]) -> Result { + let mut cmd = Command::new("ffmpeg"); + // Never `-c`: argv is built entry by entry, paths with spaces or + // shell metacharacters stay inert data. + for arg in args { + cmd.arg(arg); + } + let output = cmd + .stdin(Stdio::null()) + .output() + .map_err(|err| { + if err.kind() == std::io::ErrorKind::NotFound { + missing_ffmpeg() + } else { + ToolError::new( + crate::error::CODE_IO, + format!("failed to spawn ffmpeg: {err}"), + ) + } + })?; + Ok(Capture { + code: output.status.code(), + out: String::from_utf8_lossy(&output.stdout).into_owned(), + err: String::from_utf8_lossy(&output.stderr).into_owned(), + }) +} + +/// Runs ffmpeg and requires a zero exit; on failure the message carries the +/// code plus the last stderr lines so the model can act on it. +pub fn run_checked(args: &[&str], tool: &str) -> Result { + let cap = run(args)?; + if cap.code == Some(0) { + return Ok(cap); + } + Err(ToolError::new( + crate::error::CODE_BACKEND, + format!( + "ffmpeg failed with exit code {:?} for '{tool}': {}", + cap.code, + tail(&cap.err, 6) + ), + )) + .map_err(|e| e.with_tool(tool)) +} + +/// Last `n` non-empty lines of `text`, joined — the part of ffmpeg's log +/// that names the actual failure. +pub fn tail(text: &str, n: usize) -> String { + let lines: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty()).collect(); + let start = lines.len().saturating_sub(n); + lines[start..].join(" | ") +} + +/// Structured "ffmpeg ran but produced nothing for this filter" — raised +/// when a filter that must emit markers printed none *and* the run cannot +/// be explained by "this input has no such stream" (checked by the caller +/// against the input's streams). +pub fn no_markers(tool: &str, detail: &str) -> ToolError { + ToolError::new( + crate::error::CODE_BACKEND, + format!("'{tool}' found no markers: {detail}"), + ) + .with_tool(tool) +} + +/// Input stream probe via `ffprobe` — used to give an honest error when a +/// filter found nothing because the stream type is absent (a silent clip +/// really has no silence; a video with no audio track has no loudness). +pub fn probe_has_audio(src: &str) -> Result { + probe_stream(src, "a") +} + +/// Same probe for a video stream. +pub fn probe_has_video(src: &str) -> Result { + probe_stream(src, "v") +} + +fn probe_stream(src: &str, kind: &str) -> Result { + let output = Command::new("ffprobe") + .args([ + "-v", + "error", + "-select_streams", + kind, + "-show_entries", + "stream=index", + "-of", + "csv=p=0", + src, + ]) + .stdin(Stdio::null()) + .output() + .map_err(|err| { + if err.kind() == std::io::ErrorKind::NotFound { + missing_ffmpeg() + } else { + ToolError::new( + crate::error::CODE_IO, + format!("failed to spawn ffprobe: {err}"), + ) + } + })?; + let code = output.status.code(); + if code != Some(0) { + // ffprobe exits 1 on a missing file; the input gate already ran, + // so this is an unreadable/corrupt input. + return Err(ToolError::new( + crate::error::CODE_IO, + format!( + "ffprobe failed for '{src}': {}", + tail(&String::from_utf8_lossy(&output.stderr), 3) + ), + )); + } + Ok(!String::from_utf8_lossy(&output.stdout).trim().is_empty()) +} + +/// Small helper so failure payloads can name the tool uniformly. +pub fn error_json(err: &ToolError) -> serde_json::Value { + json!({ "code": err.code, "message": err.message }) +} diff --git a/ai/oak-ai-tools/src/hooks.rs b/ai/oak-ai-tools/src/hooks.rs index 813d2bb349..2139ae548a 100644 --- a/ai/oak-ai-tools/src/hooks.rs +++ b/ai/oak-ai-tools/src/hooks.rs @@ -209,9 +209,14 @@ pub const TOOL_CLASSES: [(&str, OperationClass); 22] = [ /// The v2 face's grading table (T9.2). Kept separate from [`TOOL_CLASSES`] /// so the frozen 22-tool table stays byte-identical; [`class_of_v2`] /// resolves a v2 name, and the dispatcher tries it only for v2 tools. -pub const V2_TOOL_CLASSES: [(&str, OperationClass); 2] = [ +pub const V2_TOOL_CLASSES: [(&str, OperationClass); 7] = [ ("sequence.get_settings", OperationClass::Read), ("sequence.set_format", OperationClass::Edit), + ("analysis.detect_silence", OperationClass::Read), + ("analysis.detect_scenes", OperationClass::Read), + ("analysis.detect_black", OperationClass::Read), + ("analysis.loudness", OperationClass::Read), + ("analysis.export_thumbnails", OperationClass::Read), ]; /// The grading of a v2 `tool`, or `None` when the v2 table has no entry. diff --git a/ai/oak-ai-tools/src/lib.rs b/ai/oak-ai-tools/src/lib.rs index 7851d55520..f6832e5059 100644 --- a/ai/oak-ai-tools/src/lib.rs +++ b/ai/oak-ai-tools/src/lib.rs @@ -31,6 +31,7 @@ pub mod backend; pub mod dispatch; pub mod error; +pub mod ffmpeg; pub mod hooks; pub mod mock; pub mod render; diff --git a/ai/oak-ai-tools/src/schema_v2.rs b/ai/oak-ai-tools/src/schema_v2.rs index 07ef2f24ba..a5d24ee099 100644 --- a/ai/oak-ai-tools/src/schema_v2.rs +++ b/ai/oak-ai-tools/src/schema_v2.rs @@ -21,7 +21,7 @@ pub struct V2Tool { /// The v2 tool table. pub fn v2_tools() -> &'static [V2Tool] { - static TOOLS: [V2Tool; 2] = [ + static TOOLS: [V2Tool; 7] = [ V2Tool { name: "sequence.get_settings", description: "Read a sequence's settings: name, width, height, \ @@ -35,6 +35,42 @@ pub fn v2_tools() -> &'static [V2Tool] { undoable step.", parameters: set_format_schema, }, + V2Tool { + name: "analysis.detect_silence", + description: "Detect silent intervals in a media file's audio with \ + ffmpeg silencedetect. Returns {intervals, count}; each interval \ + is {start, end, duration} in rational seconds {num, den}.", + parameters: detect_silence_schema, + }, + V2Tool { + name: "analysis.detect_scenes", + description: "Detect scene-change points in a media file's video with \ + ffmpeg scdet. Returns {points, count}; each point is {time, score} \ + with time in rational seconds {num, den}.", + parameters: detect_scenes_schema, + }, + V2Tool { + name: "analysis.detect_black", + description: "Detect black intervals in a media file's video with \ + ffmpeg blackdetect. Returns {intervals, count}; each interval is \ + {start, end, duration} in rational seconds {num, den}.", + parameters: detect_black_schema, + }, + V2Tool { + name: "analysis.loudness", + description: "Measure EBU R128 loudness of a media file's audio with \ + ffmpeg ebur128: integrated loudness (I, LUFS), loudness range \ + (LRA, LU) and true peak (dBFS).", + parameters: loudness_schema, + }, + V2Tool { + name: "analysis.export_thumbnails", + description: "Export JPEG thumbnails from a media file with ffmpeg: \ + either every `interval_sec` seconds or at explicit `times` \ + (rational seconds {num, den} or frame indices). Returns the \ + {paths, count} actually written under `outdir`.", + parameters: export_thumbnails_schema, + }, ]; &TOOLS @@ -67,6 +103,136 @@ fn get_settings_schema() -> Value { /// `additionalProperties` stays **false** on purpose: a key that *looks* /// writable but is misspelled (`frameRate`) must be refused and named, never /// silently dropped. Ignorance is only licensed for the read-only echo. +/// The five `analysis.*` schemas (task K). Shared fragments keep the +/// returned shapes identical across the three interval tools. +fn src_property() -> Value { + json!({ "type": "string", "minLength": 1, "description": "Path to the media file to analyse." }) +} + +fn detect_silence_schema() -> Value { + json!({ + "type": "object", + "properties": { + "src": src_property(), + "noise_db": { + "type": "number", + "minimum": -128, + "maximum": 0, + "default": -30, + "description": "Silence threshold in dBFS; anything quieter counts as silence." + }, + "min_dur": { + "type": "number", + "exclusiveMinimum": 0, + "default": 0.5, + "description": "Minimum silence length in seconds." + } + }, + "required": ["src"], + "additionalProperties": false + }) +} + +fn detect_scenes_schema() -> Value { + json!({ + "type": "object", + "properties": { + "src": src_property(), + "threshold": { + "type": "number", + "minimum": 0, + "maximum": 1, + "default": 0.3, + "description": "Scene-change score threshold; higher means fewer cuts." + } + }, + "required": ["src"], + "additionalProperties": false + }) +} + +fn detect_black_schema() -> Value { + json!({ + "type": "object", + "properties": { + "src": src_property(), + "min_dur": { + "type": "number", + "exclusiveMinimum": 0, + "default": 0.3, + "description": "Minimum black interval length in seconds." + }, + "pix_th": { + "type": "number", + "minimum": 0, + "maximum": 1, + "default": 0.10, + "description": "Pixel luminance threshold; a pixel at or below it is black." + } + }, + "required": ["src"], + "additionalProperties": false + }) +} + +fn loudness_schema() -> Value { + json!({ + "type": "object", + "properties": { + "src": src_property() + }, + "required": ["src"], + "additionalProperties": false + }) +} + +fn export_thumbnails_schema() -> Value { + json!({ + "type": "object", + "properties": { + "src": src_property(), + "interval_sec": { + "type": "number", + "exclusiveMinimum": 0, + "description": "Seconds between thumbnails. Required unless `times` is given." + }, + "times": { + "type": "array", + "minItems": 1, + "description": "Explicit time points: each is rational seconds {\"num\", \"den\"} or a non-negative integer frame index (bare floats rejected). Required unless `interval_sec` is given.", + "items": { + "oneOf": [ + { "type": "integer", "minimum": 0 }, + { + "type": "object", + "properties": { + "num": { "type": "integer" }, + "den": { "type": "integer", "minimum": 1 } + }, + "required": ["num"], + "additionalProperties": false + } + ] + } + }, + "outdir": { + "type": "string", + "minLength": 1, + "description": "Directory to write the JPEG thumbnails into (created if absent)." + }, + "width": { + "type": "integer", + "minimum": 16, + "maximum": 8192, + "default": 320, + "description": "Thumbnail width in pixels; height follows the source aspect ratio." + } + }, + "required": ["src", "outdir"], + "additionalProperties": false + }) +} + fn set_format_schema() -> Value { json!({ "type": "object", @@ -282,7 +448,7 @@ mod tests { #[test] fn openai_envelopes_name_every_v2_tool() { let tools = v2_openai_tools(); - assert_eq!(tools.len(), 2); + assert_eq!(tools.len(), 7); for tool in &tools { assert_eq!(tool["type"], "function"); let name = tool["function"]["name"].as_str().expect("a name"); diff --git a/ai/oak-ai-tools/src/tools/analysis.rs b/ai/oak-ai-tools/src/tools/analysis.rs new file mode 100644 index 0000000000..32ee70845f --- /dev/null +++ b/ai/oak-ai-tools/src/tools/analysis.rs @@ -0,0 +1,356 @@ +//! Typed argument parsing for the five `analysis.*` v2 tools. +//! +//! Parsing runs after JSON Schema validation (the schema is the contract), +//! exactly like the frozen 22 and the `sequence.*` v2 tools: a shape +//! problem becomes a structured [`ToolError`] with the three-part text +//! (what arrived / what is wrong / what to send instead). +//! +//! The five tools are pure reads over a media file on disk — no project +//! state, no undo — so every entry point returns a plain `Value` and the +//! dispatcher grades them `Read` (see `hooks::V2_TOOL_CLASSES`). + +use serde_json::{Value, json}; + +use crate::error::ToolError; +use crate::timecode::Rat; + +// --------------------------------------------------------------------------- +// Three-part shape errors (same discipline as tools/v2/sequence.rs) +// --------------------------------------------------------------------------- + +/// What arrived, what is wrong, and the shape to send instead. +fn shape_error(args: &Value, detail: String, example: &str) -> ToolError { + ToolError::invalid_params(format!("{detail}. Received: {args}. Send e.g. {example}")) +} + +/// A required non-empty string (a file path). +fn req_path(args: &Value, key: &str) -> Result { + match args.get(key) { + Some(Value::String(s)) if !s.trim().is_empty() => Ok(s.clone()), + Some(other) => Err(shape_error( + args, + format!("`{key}` must be a non-empty file path string, got {other}"), + "{\"src\": \"/path/to/clip.mp4\"}", + )), + _ => Err(shape_error( + args, + format!("missing required field `{key}`"), + "{\"src\": \"/path/to/clip.mp4\"}", + )), + } +} + +/// An optional finite number with a range check. +fn opt_number( + args: &Value, + key: &str, + default: f64, + // (low, high] or open-ended when high is infinite + low: f64, + high: f64, + example: &str, +) -> Result { + match args.get(key) { + None | Some(Value::Null) => Ok(default), + Some(v) => match v.as_f64() { + Some(n) if n.is_finite() && n >= low && n <= high => Ok(n), + _ => Err(shape_error( + args, + format!("`{key}` must be a finite number in ({low}, {high}], got {v}"), + example, + )), + }, + } +} + +// --------------------------------------------------------------------------- +// Timecode-style inputs: {num, den} rational seconds or integer frames +// --------------------------------------------------------------------------- + +/// Seconds a time value denotes, resolved against the source's frame grid. +/// +/// A bare float is rejected here the same way the rest of the tool face +/// rejects it; a frame index needs the grid, which `ffprobe` supplies via +/// [`crate::ffmpeg`]-independent probe in the executor. +fn time_seconds(raw: &Value, rate: Option, key: &str) -> Result { + match raw { + Value::Number(n) if n.as_u64().is_some() => { + let frames = n.as_u64().expect("integer"); + let rate = rate.ok_or_else(|| { + ToolError::timecode(format!( + "field '{key}' is a frame index but the source has no frame rate" + )) + })?; + Ok(frames as f64 * rate.to_f64().recip()) + } + Value::Object(map) => { + let num = map + .get("num") + .and_then(Value::as_i64) + .ok_or_else(|| { + shape_error( + &Value::Object(map.clone()), + format!("`{key}` rational needs an integer `num`"), + "{\"num\": 1, \"den\": 2}", + ) + })?; + let den = map.get("den").and_then(Value::as_i64).unwrap_or(1); + let rat = Rat::new(num, den)?; + Ok(rat.to_f64()) + } + other => Err(ToolError::timecode(format!( + "field '{key}' must be rational seconds {{num, den}} or a non-negative \ + integer frame index; bare floating-point seconds are rejected, got {other}" + ))), + } +} + +// --------------------------------------------------------------------------- +// Parsed arguments +// --------------------------------------------------------------------------- + +/// `analysis.detect_silence` arguments. +#[derive(Debug, Clone, PartialEq)] +pub struct DetectSilence { + pub src: String, + /// dB threshold, default -30. + pub noise_db: f64, + /// Minimum silence length in seconds, default 0.5. + pub min_dur: f64, +} + +/// `analysis.detect_scenes` arguments. +#[derive(Debug, Clone, PartialEq)] +pub struct DetectScenes { + pub src: String, + /// Scene-change threshold in [0, 1], default 0.3. + pub threshold: f64, +} + +/// `analysis.detect_black` arguments. +#[derive(Debug, Clone, PartialEq)] +pub struct DetectBlack { + pub src: String, + /// Minimum black duration in seconds, default 0.3. + pub min_dur: f64, + /// Pixel luminance threshold in [0, 1], default 0.10. + pub pix_th: f64, +} + +/// `analysis.loudness` arguments. +#[derive(Debug, Clone, PartialEq)] +pub struct Loudness { + pub src: String, +} + +/// `analysis.export_thumbnails` arguments. +#[derive(Debug, Clone, PartialEq)] +pub struct ExportThumbnails { + pub src: String, + /// Seconds between thumbnails when `times` is absent. + pub interval_sec: Option, + /// Explicit time points (rational seconds or frame indices). + pub times: Option>, + pub outdir: String, + /// Output width in pixels; height follows the source aspect ratio. + pub width: Option, +} + +fn example_detect() -> &'static str { + "{\"src\": \"/media/clip.mp4\", \"noise_db\": -30, \"min_dur\": 0.5}" +} + +/// `analysis.detect_silence`. +pub fn parse_detect_silence(args: &Value) -> Result { + Ok(DetectSilence { + src: req_path(args, "src")?, + noise_db: opt_number(args, "noise_db", -30.0, -128.0, 0.0, example_detect())?, + min_dur: opt_number(args, "min_dur", 0.5, 0.0, 3600.0, example_detect())?, + }) +} + +/// `analysis.detect_scenes`. +pub fn parse_detect_scenes(args: &Value) -> Result { + Ok(DetectScenes { + src: req_path(args, "src")?, + threshold: opt_number( + args, + "threshold", + 0.3, + 0.0, + 1.0, + "{\"src\": \"/media/clip.mp4\", \"threshold\": 0.3}", + )?, + }) +} + +/// `analysis.detect_black`. +pub fn parse_detect_black(args: &Value) -> Result { + Ok(DetectBlack { + src: req_path(args, "src")?, + min_dur: opt_number(args, "min_dur", 0.3, 0.0, 3600.0, example_detect())?, + pix_th: opt_number( + args, + "pix_th", + 0.10, + 0.0, + 1.0, + "{\"src\": \"/media/clip.mp4\", \"min_dur\": 0.3, \"pix_th\": 0.1}", + )?, + }) +} + +/// `analysis.loudness`. +pub fn parse_loudness(args: &Value) -> Result { + Ok(Loudness { + src: req_path(args, "src")?, + }) +} + +/// `analysis.export_thumbnails`. +pub fn parse_export_thumbnails(args: &Value) -> Result { + let interval = match args.get("interval_sec") { + None | Some(Value::Null) => None, + Some(v) => Some(match v.as_f64() { + Some(n) if n.is_finite() && n > 0.0 => n, + _ => { + return Err(shape_error( + args, + format!("`interval_sec` must be a positive finite number, got {v}"), + "{\"src\": \"/media/clip.mp4\", \"interval_sec\": 2, \ + \"outdir\": \"/tmp/thumbs\"}", + )); + } + }), + }; + let times = match args.get("times") { + None | Some(Value::Null) => None, + Some(Value::Array(items)) => { + if items.is_empty() { + return Err(shape_error( + args, + "`times` must not be an empty array".to_string(), + "{\"times\": [{\"num\": 1, \"den\": 2}, 3]}", + )); + } + Some(items.clone()) + } + Some(other) => { + return Err(shape_error( + args, + format!("`times` must be an array of time values, got {other}"), + "{\"times\": [{\"num\": 1, \"den\": 2}, 3]}", + )); + } + }; + if interval.is_none() && times.is_none() { + return Err(shape_error( + args, + "one of `interval_sec` or `times` is required".to_string(), + "{\"src\": \"/media/clip.mp4\", \"interval_sec\": 2, \"outdir\": \"/tmp/t\"}", + )); + } + Ok(ExportThumbnails { + src: req_path(args, "src")?, + interval_sec: interval, + times, + outdir: req_path(args, "outdir")?, + width: match args.get("width") { + None | Some(Value::Null) => None, + Some(v) => match v.as_u64() { + Some(n) if n >= 16 && n <= 8192 => Some(n), + _ => { + return Err(shape_error( + args, + format!("`width` must be an integer in [16, 8192], got {v}"), + "{\"width\": 320}", + )); + } + }, + }, + }) +} + +/// Resolves `times` entries against the source's frame rate. +pub fn resolve_times(times: &[Value], rate: Option) -> Result, ToolError> { + times + .iter() + .map(|t| time_seconds(t, rate, "times")) + .collect() +} + +// --------------------------------------------------------------------------- +// Result shapes — fixed, and mirrored in the schema_v2 documents +// --------------------------------------------------------------------------- + +/// `{"intervals": [{"start": .., "end": .., "duration": ..}], "count": n}` +pub fn intervals_json(intervals: &[(f64, f64)]) -> Value { + let items: Vec = intervals + .iter() + .map(|(s, e)| { + json!({ + "start": Rat::new((s * 1_000_000.0).round() as i64, 1_000_000).expect("rational") + .to_json(), + "end": Rat::new((e * 1_000_000.0).round() as i64, 1_000_000).expect("rational") + .to_json(), + "duration": Rat::new(((e - s) * 1_000_000.0).round() as i64, 1_000_000) + .expect("rational") + .to_json(), + }) + }) + .collect(); + json!({ "intervals": items, "count": items.len() }) +} + +/// `{"points": [{"time": .., "score": ..}], "count": n}` +pub fn points_json(points: &[(f64, Option)]) -> Value { + let items: Vec = points + .iter() + .map(|(t, score)| { + let mut obj = json!({ + "time": Rat::new((t * 1_000_000.0).round() as i64, 1_000_000) + .expect("rational") + .to_json(), + }); + if let Some(s) = score { + obj["score"] = json!(s); + } + obj + }) + .collect(); + json!({ "points": items, "count": items.len() }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn detect_silence_defaults() { + let parsed = parse_detect_silence(&json!({"src": "/tmp/a.mp4"})).expect("parse"); + assert_eq!(parsed.noise_db, -30.0); + assert_eq!(parsed.min_dur, 0.5); + } + + #[test] + fn bare_float_time_is_rejected() { + let err = time_seconds(&json!(1.5), None, "times").expect_err("must reject"); + assert_eq!(err.code, crate::error::CODE_TIMECODE); + } + + #[test] + fn rational_and_frame_times_resolve() { + let half = time_seconds(&json!({"num": 1, "den": 2}), None, "times").expect("rational"); + assert!((half - 0.5).abs() < 1e-9); + let frame = + time_seconds(&json!(50), Some(Rat::new(25, 1).expect("rate")), "times").expect("frame"); + assert!((frame - 2.0).abs() < 1e-9); + } + + #[test] + fn export_requires_interval_or_times() { + let err = parse_export_thumbnails(&json!({"src": "/a", "outdir": "/b"})) + .expect_err("one of the two is required"); + assert_eq!(err.code, crate::error::CODE_INVALID_PARAMS); + } +} diff --git a/ai/oak-ai-tools/src/tools/analysis_exec.rs b/ai/oak-ai-tools/src/tools/analysis_exec.rs new file mode 100644 index 0000000000..7bd165174f --- /dev/null +++ b/ai/oak-ai-tools/src/tools/analysis_exec.rs @@ -0,0 +1,603 @@ +//! Executors for the five `analysis.*` v2 tools. +//! +//! Each tool shells out to `ffmpeg` exactly once (or twice when a frame +//! rate is needed to resolve frame-index time values), passing every +//! argument individually through [`std::process::Command::arg`] — never a +//! shell — and parses the filter's own log lines into a fixed JSON shape +//! documented in [`crate::schema_v2`]. +//! +//! Failure discipline: missing ffmpeg → `UNSUPPORTED` + gap id; missing +//! input → `NOT_FOUND`; ffmpeg non-zero exit → `BACKEND_FAILED` carrying +//! its code and the tail of stderr. A filter that legitimately found +//! nothing on an input that *has* the stream returns an empty list, not an +//! error — and the "no such stream" case is detected up front so it can be +//! named instead of silently empty. + +use std::fs; +use std::path::Path; + +use serde_json::{Value, json}; + +use crate::error::ToolError; +use crate::ffmpeg; +use crate::timecode::Rat; +use crate::tools::analysis::{ + self, DetectBlack, DetectScenes, DetectSilence, ExportThumbnails, Loudness, + intervals_json, points_json, +}; + +/// Frame rate of the source, when it has a video stream: `{num, den}` from +/// ffprobe (`r_frame_rate`), `None` for audio-only input. +fn source_rate(src: &str) -> Result, ToolError> { + let output = std::process::Command::new("ffprobe") + .args([ + "-v", + "error", + "-select_streams", + "v:0", + "-show_entries", + "stream=r_frame_rate", + "-of", + "csv=p=0", + src, + ]) + .stdin(std::process::Stdio::null()) + .output() + .map_err(|err| { + if err.kind() == std::io::ErrorKind::NotFound { + ffmpeg::missing_ffmpeg() + } else { + ToolError::new(crate::error::CODE_IO, format!("failed to spawn ffprobe: {err}")) + } + })?; + if output.status.code() != Some(0) { + return Err(ToolError::new( + crate::error::CODE_IO, + format!( + "ffprobe failed for '{src}': {}", + ffmpeg::tail(&String::from_utf8_lossy(&output.stderr), 3) + ), + )); + } + let text = String::from_utf8_lossy(&output.stdout); + let text = text.trim(); + if text.is_empty() || text.starts_with("N/A") { + return Ok(None); + } + let (num, den) = text + .split_once('/') + .ok_or_else(|| ToolError::new(crate::error::CODE_BACKEND, format!("bad r_frame_rate '{text}'")))?; + let num: i64 = num + .trim() + .parse() + .map_err(|_| ToolError::new(crate::error::CODE_BACKEND, format!("bad r_frame_rate '{text}'")))?; + let den: i64 = den + .trim() + .parse() + .map_err(|_| ToolError::new(crate::error::CODE_BACKEND, format!("bad r_frame_rate '{text}'")))?; + if num <= 0 || den <= 0 { + return Ok(None); + } + Ok(Some(Rat::new(num, den)?)) +} + +/// A `silence_start: ` / `silence_end: ` pair from silencedetect's +/// stderr, seconds as f64. +/// +/// A trailing silence (start with no end until the file ends) is left +/// open for the caller to close against the container duration. +fn parse_silence(stderr: &str) -> Vec<(f64, f64)> { + let mut intervals = Vec::new(); + let mut open: Option = None; + for line in stderr.lines() { + // ffmpeg prefixes every filter line with `[filter @ 0x..] `; the + // split below operates on the message after the `] ` so the + // bracket never lands inside the value token. + let line = line.trim(); + let msg = match line.find("] ") { + Some(i) => &line[i + 2..], + None => line, + }; + let Some(rest) = msg.split("silence_start:").nth(1) else { + if let Some(rest) = msg.split("silence_end:").nth(1) { + let value = rest + .trim() + .split(|c: char| c == '|' || c.is_whitespace()) + .next() + .and_then(|v| v.parse::().ok()); + if let (Some(start), Some(end)) = (open.take(), value) { + intervals.push((start, end)); + } + } + continue; + }; + let value = rest + .trim() + .split(|c: char| c == '|' || c.is_whitespace()) + .next() + .and_then(|v| v.parse::().ok()); + if let Some(v) = value { + open.get_or_insert(v); + } + } + intervals +} + +/// `analysis.detect_silence` executor. +pub fn detect_silence(parsed: &DetectSilence) -> Result { + ffmpeg::check_input(&parsed.src)?; + if !ffmpeg::ffmpeg_available() { + return Err(ffmpeg::missing_ffmpeg()); + } + let noise = format!("{}dB", trim_float(parsed.noise_db)); + let min_dur = trim_float(parsed.min_dur); + let cap = ffmpeg::run_checked( + &[ + "-hide_banner", + "-nostats", + "-loglevel", + "info", + "-i", + &parsed.src, + "-af", + &format!("silencedetect=noise={noise}:d={min_dur}"), + "-f", + "null", + "-", + ], + "analysis.detect_silence", + )?; + let mut intervals = parse_silence(&cap.err); + // A silence that runs to the end of the file has no silence_end line. + // Close it at the duration ffprobe reports. + if let Some(open) = open_silence(&cap.err) { + if let Some(dur) = container_duration(&parsed.src)? { + if open < dur { + intervals.push((open, dur)); + } + } + } + intervals.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("finite")); + // No audio stream at all: name it instead of reporting "no silence". + if intervals.is_empty() && !ffmpeg::probe_has_audio(&parsed.src)? { + return Err(ToolError::new( + crate::error::CODE_BACKEND, + format!("input has no audio stream: {}", parsed.src), + ) + .with_tool("analysis.detect_silence")); + } + Ok(intervals_json(&intervals)) +} + +/// The `silence_start` left open when ffmpeg printed no matching end. +fn open_silence(stderr: &str) -> Option { + let mut open = None; + for line in stderr.lines() { + let line = line.trim(); + if let Some(rest) = line.strip_prefix("silence_start:") { + if let Some(v) = rest + .trim() + .split_whitespace() + .next() + .and_then(|v| v.parse::().ok()) + { + open = Some(v); + } + } else if line.starts_with("silence_end:") { + open = None; + } + } + open +} + +/// Container duration in seconds via ffprobe (`format=duration`). +fn container_duration(src: &str) -> Result, ToolError> { + let output = std::process::Command::new("ffprobe") + .args([ + "-v", + "error", + "-show_entries", + "format=duration", + "-of", + "csv=p=0", + src, + ]) + .stdin(std::process::Stdio::null()) + .output() + .map_err(|err| { + if err.kind() == std::io::ErrorKind::NotFound { + ffmpeg::missing_ffmpeg() + } else { + ToolError::new(crate::error::CODE_IO, format!("ffprobe spawn: {err}")) + } + })?; + if output.status.code() != Some(0) { + return Ok(None); + } + let text = String::from_utf8_lossy(&output.stdout); + let text = text.trim(); + if text.is_empty() || text.starts_with("N/A") { + return Ok(None); + } + text.parse::() + .ok() + .filter(|d| d.is_finite() && *d > 0.0) + .map(Some) + .map_or_else(|| Ok(None), Ok) +} + +/// `analysis.detect_scenes` executor — parses `scdet` log lines: +/// `[scdet ...] lavfi.scd.score: 0.923, lavfi.scd.time: 0.04`. +pub fn detect_scenes(parsed: &DetectScenes) -> Result { + ffmpeg::check_input(&parsed.src)?; + if !ffmpeg::ffmpeg_available() { + return Err(ffmpeg::missing_ffmpeg()); + } + let threshold = trim_float(parsed.threshold); + let cap = ffmpeg::run_checked( + &[ + "-hide_banner", + "-nostats", + "-loglevel", + "info", + "-i", + &parsed.src, + "-vf", + &format!("scdet=threshold={threshold}"), + "-f", + "null", + "-", + ], + "analysis.detect_scenes", + )?; + let mut points: Vec<(f64, Option)> = Vec::new(); + for line in cap.err.lines() { + let Some(pos) = line.find("lavfi.scd.time:") else { + continue; + }; + let head = &line[..pos]; + let tail = &line[pos + "lavfi.scd.time:".len()..]; + let time = tail + .trim() + .split(|c: char| c == ',' || c.is_whitespace()) + .next() + .and_then(|v| v.parse::().ok()); + let score = head + .rfind("lavfi.scd.score:") + .map(|i| &head[i + "lavfi.scd.score:".len()..]) + .and_then(|v| v.trim().split(',').next()) + .and_then(|v| v.parse::().ok()); + if let Some(t) = time { + points.push((t, score)); + } + } + if points.is_empty() && !ffmpeg::probe_has_video(&parsed.src)? { + return Err(ToolError::new( + crate::error::CODE_BACKEND, + format!("input has no video stream: {}", parsed.src), + ) + .with_tool("analysis.detect_scenes")); + } + points.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("finite")); + Ok(points_json(&points)) +} + +/// `analysis.detect_black` executor — parses `blackdetect` lines: +/// `black_start:0 black_end:0.96 black_duration:0.96`. +pub fn detect_black(parsed: &DetectBlack) -> Result { + ffmpeg::check_input(&parsed.src)?; + if !ffmpeg::ffmpeg_available() { + return Err(ffmpeg::missing_ffmpeg()); + } + let min_dur = trim_float(parsed.min_dur); + let pix_th = trim_float(parsed.pix_th); + let cap = ffmpeg::run_checked( + &[ + "-hide_banner", + "-nostats", + "-loglevel", + "info", + "-i", + &parsed.src, + "-vf", + &format!("blackdetect=d={min_dur}:pix_th={pix_th}"), + "-f", + "null", + "-", + ], + "analysis.detect_black", + )?; + let mut intervals: Vec<(f64, f64)> = Vec::new(); + for line in cap.err.lines() { + if !line.contains("black_start:") { + continue; + } + let start = field_after(line, "black_start:").and_then(|v| v.parse::().ok()); + let end = field_after(line, "black_end:").and_then(|v| v.parse::().ok()); + if let (Some(s), Some(e)) = (start, end) { + intervals.push((s, e)); + } + } + if intervals.is_empty() && !ffmpeg::probe_has_video(&parsed.src)? { + return Err(ToolError::new( + crate::error::CODE_BACKEND, + format!("input has no video stream: {}", parsed.src), + ) + .with_tool("analysis.detect_black")); + } + Ok(intervals_json(&intervals)) +} + +/// Value after `key` up to the next comma/space (handles `key:1.5` and +/// `key: 1.5` spellings; the key itself may appear anywhere in the line, +/// so a `foo_key:` suffix does not match). +fn field_after<'a>(line: &'a str, key: &str) -> Option<&'a str> { + let pos = line.find(key)?; + // Require the key to start at a token boundary: the previous char is + // not alphanumeric (so `black_start:` does not match `xblack_start:`). + if pos > 0 { + let prev = line[..pos].chars().last().expect("pos > 0"); + if prev.is_alphanumeric() || prev == '_' { + return None; + } + } + let rest = &line[pos + key.len()..]; + let rest = rest.trim_start(); + let end = rest + .find(|c: char| c == ',' || c.is_whitespace()) + .unwrap_or(rest.len()); + let token = &rest[..end]; + if token.is_empty() { + None + } else { + Some(token) + } +} + +/// `analysis.loudness` executor — parses the ebur128 summary block: +/// `I: -21.8 LUFS`, `LRA: 0.0 LU`, `Peak: -18.1 dBFS`. +pub fn loudness(parsed: &Loudness) -> Result { + ffmpeg::check_input(&parsed.src)?; + if !ffmpeg::ffmpeg_available() { + return Err(ffmpeg::missing_ffmpeg()); + } + // The `Summary:` block is emitted at `info` when the stream ends; it + // never appears at `warning`, so this one stays `info`. + let cap = ffmpeg::run_checked( + &[ + "-hide_banner", + "-nostats", + "-loglevel", + "info", + "-i", + &parsed.src, + "-af", + "ebur128=peak=true", + "-f", + "null", + "-", + ], + "analysis.loudness", + )?; + let int_lufs = summary_field(&cap.err, "Integrated loudness:", "I:") + .and_then(|v| v.parse::().ok()); + let lra = summary_field(&cap.err, "Loudness range:", "LRA:") + .and_then(|v| v.parse::().ok()); + let true_peak = summary_field(&cap.err, "True peak:", "Peak:") + .and_then(|v| v.parse::().ok()); + let (Some(i), Some(l), Some(p)) = (int_lufs, lra, true_peak) else { + if !ffmpeg::probe_has_audio(&parsed.src)? { + return Err(ToolError::new( + crate::error::CODE_BACKEND, + format!("input has no audio stream: {}", parsed.src), + ) + .with_tool("analysis.loudness")); + } + return Err(ffmpeg::no_markers( + "analysis.loudness", + &format!("ebur128 printed no summary: {}", ffmpeg::tail(&cap.err, 4)), + )); + }; + Ok(json!({ + "integrated_lufs": i, + "lra_lu": l, + "true_peak_dbfs": p, + })) +} + +/// First `key` value after the `section` heading in the summary block. +fn summary_field(stderr: &str, section: &str, key: &str) -> Option { + let pos = stderr.find(section)?; + let after = &stderr[pos + section.len()..]; + let line = after.lines().find(|l| l.contains(key))?; + let value = field_after(line, key)?; + Some(value.trim().to_string()) +} + +/// `analysis.export_thumbnails` executor: one ffmpeg run per output when +/// explicit times are given, one run with a `fps` filter for intervals. +pub fn export_thumbnails(parsed: &ExportThumbnails) -> Result { + ffmpeg::check_input(&parsed.src)?; + if !ffmpeg::ffmpeg_available() { + return Err(ffmpeg::missing_ffmpeg()); + } + let outdir = Path::new(&parsed.outdir); + if outdir.exists() && !outdir.is_dir() { + return Err(ToolError::invalid_params(format!( + "outdir exists and is not a directory: {}", + parsed.outdir + ))); + } + fs::create_dir_all(outdir).map_err(|err| { + ToolError::new( + crate::error::CODE_IO, + format!("cannot create outdir {}: {err}", parsed.outdir), + ) + })?; + + let width = parsed.width.unwrap_or(320); + let scale = format!("scale={width}:-2"); + + let mut paths: Vec = Vec::new(); + if let Some(times) = &parsed.times { + let rate = source_rate(&parsed.src)?; + let seconds = analysis::resolve_times(times, rate)?; + // ffmpeg's image2 muxer refuses the same output name twice in one + // run, so a single invocation writes a `%04d` sequence (one image + // per second, fps=1/1) and the requested points are picked out of + // it by their rounded second. `%04d` is what makes it a sequence + // — `%04` alone is not, and image2 then refuses to write a second + // frame under one name. Points beyond the file's duration are + // simply absent — reported as such, never faked. + let pattern = outdir.join("exp_%04d.jpg"); + let pattern_str = pattern.to_string_lossy().into_owned(); + ffmpeg::run_checked( + &[ + "-hide_banner", + "-nostats", + "-loglevel", + "error", + "-y", + "-i", + &parsed.src, + "-vf", + &format!("fps=1,{scale}"), + &pattern_str, + ], + "analysis.export_thumbnails", + )?; + for (index, t) in seconds.iter().enumerate() { + let file = outdir.join(format!("exp_{:04}.jpg", t.round() as u64)); + if file.is_file() { + let dest = outdir.join(format!("thumb_{index:04}.jpg")); + fs::rename(&file, &dest).map_err(|err| { + ToolError::new( + crate::error::CODE_IO, + format!("cannot rename {} : {err}", file.display()), + ) + })?; + paths.push(dest.to_string_lossy().into_owned()); + } + } + } else { + let interval = parsed.interval_sec.expect("validated"); + let step = trim_float(interval); + // `%04d` = image2 sequence pattern (one file per interval tick). + let file = outdir.join("thumb_%04d.jpg"); + let file_str = file.to_string_lossy().into_owned(); + ffmpeg::run_checked( + &[ + "-hide_banner", + "-nostats", + "-loglevel", + "error", + "-y", + "-i", + &parsed.src, + "-vf", + &format!("fps=1/{step},{scale}"), + &file_str, + ], + "analysis.export_thumbnails", + )?; + // Glob the produced files in order. + let mut found: Vec = fs::read_dir(outdir) + .map_err(|err| { + ToolError::new(crate::error::CODE_IO, format!("read outdir: {err}")) + })? + .filter_map(|e| e.ok()) + .map(|e| e.path()) + .filter(|p| { + p.file_name() + .and_then(|n| n.to_str()) + .map(|n| n.starts_with("thumb_") && n.ends_with(".jpg")) + .unwrap_or(false) + }) + .filter(|p| { + // Only the files this run wrote: the dir may already hold + // exports from an earlier call. + p.file_name() + .and_then(|n| n.to_str()) + .map(|n| n.len() == "thumb_".len() + 4 + ".jpg".len()) + .unwrap_or(false) + }) + .map(|p| p.to_string_lossy().into_owned()) + .collect(); + found.sort(); + paths = found; + } + + // Every advertised file must really exist on disk (no fake success). + for path in &paths { + if !Path::new(path).is_file() { + return Err(ToolError::new( + crate::error::CODE_IO, + format!("thumbnail was not written: {path}"), + )); + } + } + if paths.is_empty() { + return Err(ffmpeg::no_markers( + "analysis.export_thumbnails", + "ffmpeg produced no thumbnails for the requested interval", + )); + } + Ok(json!({ "paths": paths, "count": paths.len() })) +} + +/// Formats a float the way filter arguments need it: `30` not `30.0`, +/// `-30` not `-30.0`, but `0.3` stays `0.3`. +fn trim_float(v: f64) -> String { + if v == v.trunc() && v.abs() < 1e15 { + format!("{}", v as i64) + } else { + format!("{v}") + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn trim_float_spellings() { + assert_eq!(trim_float(30.0), "30"); + assert_eq!(trim_float(-30.0), "-30"); + assert_eq!(trim_float(0.3), "0.3"); + assert_eq!(trim_float(0.5), "0.5"); + } + + #[test] + fn silence_lines_parse() { + let stderr = "[silencedetect @ 0x1] silence_start: 0\n\ + [silencedetect @ 0x1] silence_end: 1.021701 | silence_duration: 1.021701\n"; + let intervals = parse_silence(stderr); + assert_eq!(intervals.len(), 1); + assert!((intervals[0].0 - 0.0).abs() < 1e-9); + assert!((intervals[0].1 - 1.021701).abs() < 1e-6); + } + + #[test] + fn black_lines_parse_both_spellings() { + let line = "[blackdetect @ 0x1] black_start:0 black_end:0.96 black_duration:0.96"; + let start = field_after(line, "black_start:").expect("start"); + assert_eq!(start, "0"); + let line2 = "[blackdetect @ 0x1] black_start: 1.5, black_end: 2.25"; + assert_eq!(field_after(line2, "black_start:"), Some("1.5")); + } + + #[test] + fn scdet_lines_parse() { + let line = "[scdet @ 0x1] lavfi.scd.score: 0.923, lavfi.scd.time: 0.04"; + let time_pos = line.find("lavfi.scd.time:").expect("time"); + let tail = &line[time_pos + "lavfi.scd.time:".len()..]; + let time: f64 = tail + .trim() + .split(|c: char| c == ',' || c.is_whitespace()) + .next() + .expect("token") + .parse() + .expect("float"); + assert!((time - 0.04).abs() < 1e-9); + } +} diff --git a/ai/oak-ai-tools/src/tools/mod.rs b/ai/oak-ai-tools/src/tools/mod.rs index 9ab9ebaf24..5f2e469a9c 100644 --- a/ai/oak-ai-tools/src/tools/mod.rs +++ b/ai/oak-ai-tools/src/tools/mod.rs @@ -6,6 +6,8 @@ //! shape problems into structured `ToolError`s instead of panics. //! Backends share them, so the mock and the SDK parse identically. +pub mod analysis; +pub mod analysis_exec; pub mod common; pub mod edit; pub mod export; diff --git a/ai/oak-ai-tools/tests/analysis_ffmpeg.rs b/ai/oak-ai-tools/tests/analysis_ffmpeg.rs new file mode 100644 index 0000000000..b0a3b709bd --- /dev/null +++ b/ai/oak-ai-tools/tests/analysis_ffmpeg.rs @@ -0,0 +1,392 @@ +//! Task K acceptance: the five `analysis.*` v2 tools against real ffmpeg. +//! +//! Material is generated with lavfi (`sine`, `testsrc2`, `color`) so the +//! expectations are known exactly: a 3 s tone muted outside [1 s, 2 s] +//! has one silence, a 4 s testsrc2 with a cut at 1.5 s has a scene point, +//! and a 4 s color clip whose first second is black has one black +//! interval. Every test first probes `ffmpeg -version`; without ffmpeg it +//! prints the reason and returns — never a fabricated green. + +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; + +use oak_ai_tools::dispatch::{execute_v2_with, v2_registry}; +use oak_ai_tools::hooks::{NoHooks, Policy}; +use oak_ai_tools::mock::MockBackend; +use oak_ai_tools::schema_v2::{is_v2_tool, v2_tool_names}; +use serde_json::json; + +/// Returns `None` when ffmpeg is absent, printing why (the skip must be +/// visible in the test log, not silent). +fn ffmpeg_or_skip(test: &str) -> Option<()> { + match Command::new("ffmpeg") + .arg("-version") + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + { + Ok(status) if status.success() => Some(()), + other => { + eprintln!( + "SKIP {test}: ffmpeg is not available ({other:?}); \ + install ffmpeg to run the analysis acceptance tests" + ); + None + } + } +} + +fn run(tool: &str, args: serde_json::Value) -> Result { + let mut backend = MockBackend::new(); + execute_v2_with(&mut backend, tool, args, Policy::Auto, &mut NoHooks) + .into_result() + .map_err(|err| format!("{tool} failed: {} ({})", err.message, err.code)) +} + +/// Generates `out` with the lavfi graph `filter`; panics with ffmpeg's +/// stderr when the generation itself fails. +fn lavfi_generate(out: &Path, filter: &str, format: &str) { + let mut cmd = Command::new("ffmpeg"); + cmd.args([ + "-hide_banner", + "-loglevel", + "error", + "-y", + "-f", + "lavfi", + "-i", + filter, + ]); + if format == "muted_sine" { + // 3 s 440 Hz, muted outside [1 s, 2 s]: one 1 s silence in the + // middle and one trailing silence from 2 s to 3 s. + cmd.args(["-af", "volume=enable='lt(t,1)+gt(t,2)':volume=0"]); + } + cmd.arg(out); + let status = cmd + .stdout(Stdio::null()) + .stderr(Stdio::piped()) + .status() + .expect("spawn ffmpeg"); + assert!(status.success(), "lavfi generation failed for {out:?}"); +} + +fn temp_dir(tag: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("oak_analysis_{tag}")); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).expect("temp dir"); + dir +} + +// --------------------------------------------------------------------------- +// Schema / registry face: five tools listed, classified, schema-valid +// --------------------------------------------------------------------------- + +#[test] +fn analysis_tools_are_listed_classified_and_schema_valid() { + let names = v2_tool_names(); + let expected = [ + "analysis.detect_silence", + "analysis.detect_scenes", + "analysis.detect_black", + "analysis.loudness", + "analysis.export_thumbnails", + ]; + for name in expected { + assert!(names.contains(&name), "{name} missing from v2_tool_names"); + assert!(is_v2_tool(name), "{name} not a v2 tool"); + } + // Every registered call is dispatchable (lookup resolves) and grades + // as Read — `class_of_v2` returning None would be a fail-closed + // UNCLASSIFIED_TOOL at execute time. + for def in v2_registry() { + if !def.name.starts_with("analysis.") { + continue; + } + assert!(!def.transactional, "{} must not open an undo group", def.name); + let class = oak_ai_tools::hooks::class_of_v2(def.name) + .unwrap_or_else(|| panic!("{} has no grade", def.name)); + assert_eq!( + class, + oak_ai_tools::hooks::OperationClass::Read, + "{} must grade Read", + def.name + ); + } +} + +#[test] +fn analysis_schemas_validate_their_examples_and_refuse_unknown_keys() { + for (tool, args) in [ + ( + "analysis.detect_silence", + json!({"src": "/tmp/a.mp4", "noise_db": -25, "min_dur": 0.4}), + ), + ("analysis.detect_scenes", json!({"src": "/tmp/a.mp4"})), + ( + "analysis.detect_black", + json!({"src": "/tmp/a.mp4", "min_dur": 0.3, "pix_th": 0.05}), + ), + ("analysis.loudness", json!({"src": "/tmp/a.mp4"})), + ( + "analysis.export_thumbnails", + json!({"src": "/tmp/a.mp4", "interval_sec": 2, "outdir": "/tmp/t", "width": 320}), + ), + ] { + oak_ai_tools::schema_v2::validate(tool, &args) + .unwrap_or_else(|err| panic!("{tool} example rejected: {err:?}")); + } + // additionalProperties:false is live: a misspelled key is refused. + let err = oak_ai_tools::schema_v2::validate( + "analysis.detect_silence", + &json!({"src": "/tmp/a.mp4", "noiseDb": -30}), + ) + .expect_err("misspelled key must be refused"); + assert_eq!(err.code, oak_ai_tools::error::CODE_SCHEMA_VALIDATION); +} + +// --------------------------------------------------------------------------- +// Real ffmpeg runs +// --------------------------------------------------------------------------- + +#[test] +fn detect_silence_finds_the_muted_windows() { + let Some(()) = ffmpeg_or_skip("detect_silence_finds_the_muted_windows") else { + return; + }; + let dir = temp_dir("silence"); + let src = dir.join("tone.mp4"); + lavfi_generate( + &src, + "sine=frequency=440:duration=3", + "muted_sine", + ); + let out = run( + "analysis.detect_silence", + json!({ + "src": src.display().to_string(), + "noise_db": -30, + "min_dur": 0.5, + }), + ) + .expect("detect_silence"); + let intervals = out["intervals"].as_array().expect("intervals array"); + assert!( + !intervals.is_empty(), + "expected at least one silence, got {out}" + ); + // First silence: [0, 1) — the tone is muted before t=1. + let first = &intervals[0]; + let start = first["start"]["num"].as_f64().unwrap() / first["start"]["den"].as_f64().unwrap(); + let end = first["end"]["num"].as_f64().unwrap() / first["end"]["den"].as_f64().unwrap(); + assert!( + (start - 0.0).abs() < 0.15, + "first silence should start near 0, got {start} (out: {out})" + ); + assert!( + (end - 1.0).abs() < 0.15, + "first silence should end near 1.0, got {end} (out: {out})" + ); + assert_eq!(out["count"].as_u64().unwrap() as usize, intervals.len()); + // A video with no audio stream is a structured failure, not a lie. + let silent_video = dir.join("silent_video.mp4"); + lavfi_generate(&silent_video, "testsrc2=size=64x48:rate=25:duration=1", "video"); + let err = run( + "analysis.detect_silence", + json!({"src": silent_video.display().to_string()}), + ) + .expect_err("no audio stream must fail, not report empty silence"); + assert!( + err.contains("no audio stream"), + "expected the missing-audio explanation, got: {err}" + ); + // Missing input file: structured NOT_FOUND. + let err = run( + "analysis.detect_silence", + json!({"src": "/nonexistent/oak_analysis_file.mp4"}), + ) + .expect_err("missing file must fail"); + assert!(err.contains("failed"), "error text should name the failure: {err}"); +} + +#[test] +fn detect_scenes_finds_the_cut() { + let Some(()) = ffmpeg_or_skip("detect_scenes_finds_the_cut") else { + return; + }; + let dir = temp_dir("scenes"); + let src = dir.join("cut.mp4"); + // testsrc2 for 2 s, then a hard cut to a second colour: the scene + // detector must report the change at ~1.5 s. + let status = Command::new("ffmpeg") + .args([ + "-hide_banner", + "-loglevel", + "error", + "-y", + "-f", + "lavfi", + "-i", + "testsrc2=size=64x48:rate=25:duration=1.5", + "-f", + "lavfi", + "-i", + "smptebars=size=64x48:rate=25:duration=2.5", + "-filter_complex", + "[0:v][1:v]concat=n=2:v=1:a=0[out]", + "-map", + "[out]", + "-pix_fmt", + "yuv420p", + src.to_str().expect("utf8 path"), + ]) + .stdout(Stdio::null()) + .stderr(Stdio::piped()) + .status() + .expect("spawn ffmpeg"); + assert!(status.success(), "concat clip generation failed"); + + let out = run( + "analysis.detect_scenes", + json!({"src": src.display().to_string(), "threshold": 0.3}), + ) + .expect("detect_scenes"); + let points = out["points"].as_array().expect("points array"); + assert!( + !points.is_empty(), + "expected at least one scene point, got {out}" + ); + let times: Vec = points + .iter() + .map(|p| { + p["time"]["num"].as_f64().unwrap() / p["time"]["den"].as_f64().unwrap() + }) + .collect(); + assert!( + times.iter().any(|t| (t - 1.5).abs() < 0.35), + "a cut at 1.5 s should be detected, got {times:?} (out: {out})" + ); +} + +#[test] +fn detect_black_finds_the_black_head() { + let Some(()) = ffmpeg_or_skip("detect_black_finds_the_black_head") else { + return; + }; + let dir = temp_dir("black"); + // 4 s: black for the first second, then colour. + let src = dir.join("black_head.mp4"); + lavfi_generate( + &src, + "color=c=black:s=64x48:r=25:d=1,format=yuv420p,drawbox=x=0:y=0:w=iw:h=ih:color=white:t=fill:enable='gte(t,1)'", + "video", + ); + let out = run( + "analysis.detect_black", + json!({"src": src.display().to_string(), "min_dur": 0.3, "pix_th": 0.10}), + ) + .expect("detect_black"); + let intervals = out["intervals"].as_array().expect("intervals array"); + assert!( + !intervals.is_empty(), + "expected a black interval, got {out}" + ); + let first = &intervals[0]; + let start = first["start"]["num"].as_f64().unwrap() / first["start"]["den"].as_f64().unwrap(); + let end = first["end"]["num"].as_f64().unwrap() / first["end"]["den"].as_f64().unwrap(); + assert!( + start < 0.2, + "black should start at 0, got {start} (out: {out})" + ); + assert!( + (end - 1.0).abs() < 0.3, + "black should end near 1.0 (drawbox takes over), got {end} (out: {out})" + ); +} + +#[test] +fn loudness_reports_lufs_lra_and_true_peak() { + let Some(()) = ffmpeg_or_skip("loudness_reports_lufs_lra_and_true_peak") else { + return; + }; + let dir = temp_dir("loudness"); + let src = dir.join("tone.mp4"); + lavfi_generate(&src, "sine=frequency=440:duration=3", "plain"); + let out = run( + "analysis.loudness", + json!({"src": src.display().to_string()}), + ) + .expect("loudness"); + let i = out["integrated_lufs"].as_f64().expect("I"); + let lra = out["lra_lu"].as_f64().expect("LRA"); + let peak = out["true_peak_dbfs"].as_f64().expect("true peak"); + // A pure sine at full scale: loud but well below the 0 LUFS anchor, + // LRA ~ 0 (constant level), true peak below 0 dBFS. + assert!( + i > -40.0 && i < 0.0, + "integrated loudness out of range: {i} (out: {out})" + ); + // ebur128's range estimator is edge-driven and reports up to 20 LU for + // this pure tone; the contract checked here is the *shape* (a finite, + // non-negative LU value), not the estimator's opinion of the material. + assert!( + lra.is_finite() && lra >= 0.0 && lra <= 20.0, + "LRA out of range: {lra} (out: {out})" + ); + assert!( + peak <= 0.0 && peak > -30.0, + "true peak out of range: {peak} (out: {out})" + ); +} + +#[test] +fn export_thumbnails_writes_real_files() { + let Some(()) = ffmpeg_or_skip("export_thumbnails_writes_real_files") else { + return; + }; + let dir = temp_dir("thumbs"); + let src = dir.join("clip.mp4"); + lavfi_generate(&src, "testsrc2=size=64x48:rate=25:duration=6", "video"); + let outdir = dir.join("out"); + let out = run( + "analysis.export_thumbnails", + json!({ + "src": src.display().to_string(), + "interval_sec": 2, + "outdir": outdir.display().to_string(), + "width": 160, + }), + ) + .expect("export_thumbnails"); + let paths = out["paths"].as_array().expect("paths array"); + assert!(!paths.is_empty(), "expected thumbnails, got {out}"); + for path in paths { + let p = Path::new(path.as_str().expect("utf8 path")); + assert!(p.is_file(), "advertised path does not exist: {p:?}"); + assert!( + fs::metadata(p).expect("metadata").len() > 0, + "thumbnail is empty: {p:?}" + ); + } + // Explicit time points (timecode style: rational seconds). + let outdir2 = dir.join("out_times"); + let out = run( + "analysis.export_thumbnails", + json!({ + "src": src.display().to_string(), + "times": [{"num": 1, "den": 2}, 100], + "outdir": outdir2.display().to_string(), + }), + ) + .expect("export_thumbnails at times"); + let paths = out["paths"].as_array().expect("paths array"); + assert_eq!(paths.len(), 2, "two requested times, two files: {out}"); + for path in paths { + assert!( + Path::new(path.as_str().expect("utf8 path")).is_file(), + "missing {path}" + ); + } +} diff --git a/crates/oak-app/src/ai/agent.rs b/crates/oak-app/src/ai/agent.rs index 799dba2876..7af2c94b84 100644 --- a/crates/oak-app/src/ai/agent.rs +++ b/crates/oak-app/src/ai/agent.rs @@ -11,6 +11,13 @@ //! loop runs under test with a scripted model and a mock engine. use super::config; +use super::confirm::{ConfirmMode, GatedHooks}; +use super::plan::{ + Baseline, CostGuard, CostStop, CostUsage, OnFail, Plan, PlanStep, RetryPolicy, RollbackReport, + StepStatus, StepTrace, estimate_tokens, rollback_to, substitute, +}; +use super::progress::{ProgressEvent, ProgressSink}; +use super::readback; use super::tool_text; use oak_ai_tools::error; use oak_ai_tools::schema_v2; @@ -18,9 +25,10 @@ use serde_json::{Value, json}; use oak_ai_tools::backend::{EngineBackend, EngineExt}; use oak_ai_tools::dispatch; -use oak_ai_tools::hooks::{GatedOutcome, Hooks, NoHooks, Policy}; +use oak_ai_tools::hooks::{GatedOutcome, Hooks, NoHooks, OperationClass, Policy, class_of, + class_of_v2}; -use super::llm::{ChatMessage, ChatRequest, LlmClient, ToolCall, openai_tools}; +use super::llm::{ChatMessage, ChatRequest, LlmClient, LlmError, ToolCall, openai_tools}; /// Loop bounds and gate policy. #[derive(Debug, Clone, PartialEq)] @@ -32,6 +40,10 @@ pub struct AgentConfig { pub policy: Policy, /// Model name sent on each request (from `OAK_AI_MODEL`). pub model: String, + /// Confirm gate for mutating tools before they run (reads never + /// ask). `Headless` = auto-approve (today's behaviour), `Strict` = + /// refuse every write. + pub confirm: ConfirmMode, } impl Default for AgentConfig { @@ -40,6 +52,7 @@ impl Default for AgentConfig { max_rounds: 8, policy: Policy::Auto, model: config::DEFAULT_MODEL.to_string(), + confirm: ConfirmMode::Headless, } } } @@ -76,6 +89,25 @@ pub struct AgentReport { /// Set when the loop stopped early because the same tool kept failing /// with the same error code: what it was stuck on, for the user. pub stalled: Option, + /// The explicit plan this run executed (plan-based runs only): + /// produced *before* the steps ran. + pub plan: Option, + /// What actually happened, step by step, with attempts and failures. + pub trajectory: Vec, + /// Progress events in order (rounds and plan steps). + pub progress: Vec, + /// Cost consumed by this run (tool calls, LLM rounds, ~tokens). + pub cost: CostUsage, + /// The `stopped_reason` when a hard cost limit ended the run. + pub cost_stop: Option, + /// Set when a failed plan was rolled back — including a rollback that + /// could not confirm the restore (`restored: false` + the failing + /// undo calls; never a silent success). + pub rollback: Option, + /// Readback checks performed / failed / skipped (probe unavailable). + pub readbacks: usize, + pub readback_failures: usize, + pub readback_skipped: usize, } /// Why the loop stopped before the round cap: the same tool failed with the @@ -137,6 +169,16 @@ pub struct Agent { tools: Vec, /// Long-term memory tools (memlite subprocess; see [`super::memory`]). memory: super::memory::MemoryTools, + /// Progress subscribers; the events also land in [`AgentReport::progress`]. + progress_sink: Option>, + /// Hard cost limits (default: unlimited). + cost_guard: CostGuard, + /// What the current run has spent. + cost_usage: CostUsage, + /// Retry policy for plan steps (default: 2 attempts, 100 ms backoff). + retry: RetryPolicy, + /// Post-write readback self-check (default: on). + readback: bool, } impl Agent { @@ -159,6 +201,11 @@ impl Agent { messages, tools, memory: super::memory::MemoryTools::from_env(), + progress_sink: None, + cost_guard: CostGuard::unlimited(), + cost_usage: CostUsage::default(), + retry: RetryPolicy::default(), + readback: true, } } @@ -174,6 +221,36 @@ impl Agent { &self.memory } + /// Subscribes to progress events (rounds and plan steps); the events + /// also land in [`AgentReport::progress`]. + pub fn with_progress_sink(mut self, sink: impl ProgressSink + 'static) -> Self { + self.progress_sink = Some(Box::new(sink)); + self + } + + /// Replaces the cost guard (default: unlimited). + pub fn with_cost_guard(mut self, guard: CostGuard) -> Self { + self.cost_guard = guard; + self + } + + /// Replaces the plan-step retry policy (default: 2 attempts, 100 ms). + pub fn with_retry(mut self, retry: RetryPolicy) -> Self { + self.retry = retry; + self + } + + /// Turns the post-write readback self-check off (default: on). + pub fn without_readback(mut self) -> Self { + self.readback = false; + self + } + + /// What the current run has spent so far. + pub fn cost_usage(&self) -> &CostUsage { + &self.cost_usage + } + /// The backend, for tests and for the panel that renders engine state. pub fn backend(&self) -> &B { &self.backend @@ -188,7 +265,8 @@ impl Agent { &self.messages } - /// One user turn with the default gate policy ([`NoHooks`]). + /// One user turn through the configured confirm gate + /// ([`AgentConfig::confirm`], default `Headless` = auto-approve). pub fn run(&mut self, user: &str) -> Result { self.run_with(user, &mut NoHooks) } @@ -202,6 +280,32 @@ impl Agent { &mut self, user: &str, hooks: &mut dyn Hooks, + ) -> Result { + self.cost_usage = CostUsage::default(); + // The confirm gate sits between the loop and the caller's hooks: + // mutating calls are asked per `config.confirm` before they run, + // and an approval still falls through to the caller's hooks. + let mut gate = GatedHooks::new(self.config.confirm, hooks); + let mut report = self.run_loop(user, &mut gate)?; + report.cost = self.cost_usage.clone(); + Ok(report) + } + + /// The policy the engine actually runs under: a strict confirm gate + /// forces `Policy::Confirm` so the gate is consulted (reads stay + /// exempt by class); headless keeps the configured policy untouched. + fn effective_policy(&self) -> Policy { + match self.config.confirm { + ConfirmMode::Strict => Policy::Confirm, + ConfirmMode::Headless => self.config.policy, + } + } + + /// The turn body behind [`run_with`]: history, rounds, tool calls. + fn run_loop( + &mut self, + user: &str, + hooks: &mut dyn Hooks, ) -> Result { self.messages.push(ChatMessage::user(user)); let mut report = AgentReport::default(); @@ -211,12 +315,28 @@ impl Agent { // a different tool or a different code resets it. let mut streak: Option<(String, String, usize)> = None; - for round in 1..=self.config.max_rounds.max(1) { + let total_rounds = self.config.max_rounds.max(1); + for round in 1..=total_rounds { + // Hard stop before spending a round the budget does not cover. + if let Some(stop) = self.cost_guard.check_llm(&self.cost_usage) { + report.cost_stop = Some(stop); + break; + } + self.emit_progress( + &mut report, + ProgressEvent::new(round, total_rounds, "round"), + ); let response = self.llm.complete(&ChatRequest { model: &self.config.model, messages: &self.messages, tools: &self.tools, })?; + self.cost_usage.llm_rounds += 1; + self.cost_usage.tokens += + estimate_tokens(response.content.as_deref().unwrap_or_default()); + for asked in &response.tool_calls { + self.cost_usage.tokens += estimate_tokens(&asked.arguments.to_string()); + } report.rounds = round; if response.tool_calls.is_empty() { @@ -291,32 +411,43 @@ impl Agent { report: &mut AgentReport, streak: &mut Option<(String, String, usize)>, ) -> Result { + // Hard cost gate first: a capped run stops before spending the + // next call, on every face, and says so instead of limping on. + if let Some(stop) = self.cost_guard.check_tool(&self.cost_usage) { + let payload = json!({ + "ok": false, + "code": "COST_LIMIT", + "message": stop.detail.clone(), + "budget": stop.limit, + }); + self.messages + .push(ChatMessage::tool_result(&call.id, &payload)); + report.tools.push(ToolLogEntry { + round, + tool: call.name.clone(), + outcome: "cost-stopped", + detail: payload.to_string(), + }); + if report.cost_stop.is_none() { + report.cost_stop = Some(stop); + } + return Ok(true); + } + // Three faces, one loop: memory tools answer host-side (a - // subprocess, no engine and no edit transaction), a v2 name goes - // to the extension dispatcher, everything else keeps the frozen - // 22 path. All three end in the same payload/streak handling. + // subprocess, no engine and no edit transaction); the engine faces + // (frozen 22 and v2) share `engine_call`, which adds cost + // accounting and the readback self-check. All three end in the + // same payload/streak handling. let (payload, label) = if super::memory::is_memory_tool(&call.name) { + self.cost_usage.tool_calls += 1; memory_payload(super::memory::execute( &self.memory, &call.name, call.arguments.clone(), )) - } else if schema_v2::is_v2_tool(&call.name) { - outcome_payload(dispatch::execute_v2_with( - &mut self.backend, - &call.name, - call.arguments.clone(), - self.config.policy, - hooks, - )) } else { - outcome_payload(dispatch::execute_with( - &mut self.backend, - &call.name, - call.arguments.clone(), - self.config.policy, - hooks, - )) + self.engine_call(call, hooks, report) }; self.messages .push(ChatMessage::tool_result(&call.id, &payload)); @@ -359,6 +490,409 @@ impl Agent { } Ok(false) } + + /// One engine tool call (frozen 22 or v2): cost accounting → + /// optional baseline probe → dispatch → readback self-check. + /// + /// A readback that cannot confirm the write **replaces** the success + /// payload with a structured `READBACK_MISMATCH` failure and relabels + /// the call: a write whose effect is not observable never reports + /// `applied`. + fn engine_call( + &mut self, + call: &ToolCall, + hooks: &mut dyn Hooks, + report: &mut AgentReport, + ) -> (Value, &'static str) { + if let Some(stop) = self.cost_guard.check_tool(&self.cost_usage) { + let payload = json!({ + "ok": false, + "code": "COST_LIMIT", + "message": stop.detail, + "budget": stop.limit, + }); + if report.cost_stop.is_none() { + report.cost_stop = Some(stop); + } + return (payload, "cost-stopped"); + } + self.cost_usage.tool_calls += 1; + + let v2 = schema_v2::is_v2_tool(&call.name); + let class = if v2 { + class_of_v2(&call.name) + } else { + class_of(&call.name) + }; + let mutating = !matches!(class, Some(OperationClass::Read)); + let probe_plan = if mutating && self.readback { + readback::probe_plan(&call.name) + } else { + readback::ProbePlan::Skip + }; + // Baseline only when a "changed" verdict may need it: `AfterOnly` + // tools have no usable baseline by construction (no project yet / + // the timeline does not move). + let baseline = if probe_plan == readback::ProbePlan::BeforeAndAfter { + Some(readback::probe(&mut self.backend)) + } else { + None + }; + + // Resolved before `&mut self.backend` is lent to dispatch. + let policy = self.effective_policy(); + let outcome = if v2 { + dispatch::execute_v2_with( + &mut self.backend, + &call.name, + call.arguments.clone(), + policy, + hooks, + ) + } else { + dispatch::execute_with( + &mut self.backend, + &call.name, + call.arguments.clone(), + policy, + hooks, + ) + }; + let (mut payload, mut label) = outcome_payload(outcome); + + if label == "applied" && probe_plan != readback::ProbePlan::Skip { + match readback::probe(&mut self.backend) { + Ok(after) => { + report.readbacks += 1; + let result = payload.get("result").cloned().unwrap_or(Value::Null); + if let Some(expect) = readback::expectation_for(&call.name, &result) { + let before = baseline.as_ref().and_then(|probe| probe.as_ref().ok()); + let verdict = readback::verify(before, &after, expect); + if !verdict.ok { + report.readback_failures += 1; + payload = verdict.failure_payload(); + label = "readback-failed"; + } + } + } + Err(_) => { + // The probe itself is unavailable: count it rather than + // pretend the write was verified. + report.readback_skipped += 1; + } + } + } + (payload, label) + } + + /// One user turn: first produce an explicit plan for `user`, then + /// execute it step by step. Plan and trajectory land in the report. + pub fn run_planned( + &mut self, + user: &str, + hooks: &mut dyn Hooks, + ) -> Result { + self.cost_usage = CostUsage::default(); + let mut report = AgentReport::default(); + let plan = self.plan_from_llm(user)?; + report.rounds = self.cost_usage.llm_rounds; + self.run_steps(plan, hooks, &mut report)?; + report.cost = self.cost_usage.clone(); + Ok(report) + } + + /// Executes a pre-built plan through the default [`NoHooks`] gate + /// (no model in the loop: the plan is the instruction). + pub fn run_plan(&mut self, plan: Plan) -> Result { + self.run_plan_with(plan, &mut NoHooks) + } + + /// [`run_plan`] through the hooks transaction gate. + pub fn run_plan_with( + &mut self, + plan: Plan, + hooks: &mut dyn Hooks, + ) -> Result { + self.cost_usage = CostUsage::default(); + let mut report = AgentReport::default(); + let mut gate = GatedHooks::new(self.config.confirm, hooks); + self.run_steps(plan, &mut gate, &mut report)?; + report.cost = self.cost_usage.clone(); + Ok(report) + } + + /// Asks the model for an explicit plan of `user`'s request — one LLM + /// round; the answer must be JSON + /// `{"goal": "...", "steps": [{"title","tool","args"}]}` (code fences + /// tolerated). The raw exchange stays in the conversation. + pub fn plan_from_llm(&mut self, user: &str) -> Result { + let prompt = format!( + "{user}\n\nBefore executing anything, reply with ONLY a JSON plan, no \ + other prose: {{\"goal\": \"...\", \"steps\": [{{\"title\": \"...\", \ + \"tool\": \"...\", \"args\": {{}}}}]}}. Use only the provided tools." + ); + self.messages.push(ChatMessage::user(&prompt)); + let response = self.llm.complete(&ChatRequest { + model: &self.config.model, + messages: &self.messages, + tools: &self.tools, + })?; + self.cost_usage.llm_rounds += 1; + let content = response.content.unwrap_or_default(); + self.cost_usage.tokens += estimate_tokens(&content); + self.messages + .push(ChatMessage::assistant(Some(content.clone()), Vec::new())); + parse_plan(&content, user) + } + + /// Executes `plan` step by step: progress events, template vars from + /// earlier results, retry while the feedback says retryable, the + /// step's `on_fail` policy, the hard cost guard — and, when a step + /// fails, an undo-based rollback to the baseline taken before the + /// first step. + fn run_steps( + &mut self, + plan: Plan, + hooks: &mut dyn Hooks, + report: &mut AgentReport, + ) -> Result<(), AgentError> { + report.plan = Some(plan.clone()); + let total = plan.steps.len(); + let baseline = if self.readback && total > 0 { + Some(Baseline::capture(&mut self.backend)) + } else { + None + }; + let mut vars = if plan.vars.is_object() { + plan.vars.clone() + } else { + json!({}) + }; + + for (index, step) in plan.steps.iter().enumerate() { + self.emit_progress( + report, + ProgressEvent::new(index + 1, total, step.title.clone()) + .with_detail(step.tool.clone()), + ); + + // Hard stop: the budget is spent before this step begins. + if let Some(stop) = self.cost_guard.check_tool(&self.cost_usage) { + if report.cost_stop.is_none() { + report.cost_stop = Some(stop); + } + report.trajectory.push(StepTrace { + index, + title: step.title.clone(), + tool: step.tool.clone(), + status: StepStatus::Blocked, + attempts: 0, + detail: Some("cost budget exhausted before this step".into()), + }); + break; + } + + let args = match substitute(&step.args, &vars) { + Ok(args) => args, + Err(message) => { + report.trajectory.push(StepTrace { + index, + title: step.title.clone(), + tool: step.tool.clone(), + status: StepStatus::Failed, + attempts: 0, + detail: Some(message), + }); + self.rollback_after(report, &baseline, &step.title); + break; + } + }; + + let (payload, label, attempts) = self.run_step_attempts(step, &args, hooks, report); + if label == "applied" { + if let Some(result) = payload.get("result") { + merge_vars(&mut vars, result); + } + report.trajectory.push(StepTrace { + index, + title: step.title.clone(), + tool: step.tool.clone(), + status: StepStatus::Done, + attempts, + detail: None, + }); + continue; + } + if label == "cost-stopped" { + report.trajectory.push(StepTrace { + index, + title: step.title.clone(), + tool: step.tool.clone(), + status: StepStatus::Blocked, + attempts, + detail: Some("cost budget exhausted mid-step".into()), + }); + break; + } + + let detail = payload + .get("message") + .and_then(Value::as_str) + .unwrap_or(label) + .to_string(); + match &step.on_fail { + OnFail::Skip => { + report.trajectory.push(StepTrace { + index, + title: step.title.clone(), + tool: step.tool.clone(), + status: StepStatus::Skipped, + attempts, + detail: Some(detail), + }); + continue; + } + OnFail::Fallback { + tool: fallback_tool, + args: fallback_args, + } => { + let fallback_args = + substitute(fallback_args, &vars).unwrap_or_else(|_| fallback_args.clone()); + let call = ToolCall { + id: format!("plan_fb_{index}"), + name: fallback_tool.clone(), + arguments: fallback_args, + }; + let (fb_payload, fb_label) = self.engine_call(&call, hooks, report); + if fb_label == "applied" { + if let Some(result) = fb_payload.get("result") { + merge_vars(&mut vars, result); + } + report.trajectory.push(StepTrace { + index, + title: step.title.clone(), + tool: fallback_tool.clone(), + status: StepStatus::Degraded, + attempts, + detail: Some(format!( + "degraded to `{fallback_tool}` after `{}` failed: {detail}", + step.tool + )), + }); + continue; + } + let fb_detail = fb_payload + .get("message") + .and_then(Value::as_str) + .unwrap_or(fb_label) + .to_string(); + report.trajectory.push(StepTrace { + index, + title: step.title.clone(), + tool: step.tool.clone(), + status: StepStatus::Failed, + attempts, + detail: Some(format!( + "step failed ({detail}); fallback `{fallback_tool}` failed too ({fb_detail})" + )), + }); + self.rollback_after(report, &baseline, &step.title); + break; + } + OnFail::Fail => { + report.trajectory.push(StepTrace { + index, + title: step.title.clone(), + tool: step.tool.clone(), + status: StepStatus::Failed, + attempts, + detail: Some(detail), + }); + self.rollback_after(report, &baseline, &step.title); + break; + } + } + } + Ok(()) + } + + /// Runs one step's primary call, retrying while the failure's + /// feedback says the error is retryable and the policy allows it. + fn run_step_attempts( + &mut self, + step: &PlanStep, + args: &Value, + hooks: &mut dyn Hooks, + report: &mut AgentReport, + ) -> (Value, &'static str, usize) { + let mut attempts = 0; + loop { + attempts += 1; + let call = ToolCall { + id: format!("plan_{attempts}"), + name: step.tool.clone(), + arguments: args.clone(), + }; + let (payload, label) = self.engine_call(&call, hooks, report); + let retryable = payload + .get("retryable") + .and_then(Value::as_bool) + .unwrap_or(false); + if label == "applied" + || label == "cost-stopped" + || !self.retry.should_retry(attempts, retryable) + { + return (payload, label, attempts); + } + self.retry.backoff(); + } + } + + /// Rolls back to `baseline` after a failed step. A rollback that + /// cannot confirm the restore lists the steps it could not undo — it + /// never reports a silent success. + fn rollback_after( + &mut self, + report: &mut AgentReport, + baseline: &Option, + step_title: &str, + ) { + let Some(baseline) = baseline else { + return; + }; + let mut rollback = rollback_to( + &mut self.backend, + baseline, + format!("step `{step_title}` failed"), + 64, + ); + if !rollback.restored { + rollback.unrestored_steps = report + .trajectory + .iter() + .filter(|trace| matches!(trace.status, StepStatus::Done | StepStatus::Degraded)) + .map(|trace| trace.title.clone()) + .collect(); + rollback.detail = format!( + "{}; steps not confirmed undone: {}", + rollback.detail, + if rollback.unrestored_steps.is_empty() { + "".into() + } else { + rollback.unrestored_steps.join(", ") + } + ); + } + report.rollback = Some(rollback); + } + + /// Fans one progress event out to the subscriber and the report. + fn emit_progress(&mut self, report: &mut AgentReport, event: ProgressEvent) { + if let Some(sink) = self.progress_sink.as_mut() { + sink.on_progress(&event); + } + report.progress.push(event); + } } /// Model-facing payload for a `memory.*` call. @@ -417,5 +951,60 @@ fn outcome_payload(outcome: GatedOutcome) -> (Value, &'static str) { } } +/// Parses a plan out of a model reply (tolerates ```json fences). +fn parse_plan(content: &str, goal: &str) -> Result { + let trimmed = content.trim(); + let json_text = if trimmed.starts_with("```") { + trimmed + .trim_start_matches("```json") + .trim_start_matches("```") + .trim_end_matches("```") + .trim() + } else { + trimmed + }; + let root: Value = serde_json::from_str(json_text).map_err(|err| { + AgentError::Llm(LlmError::Parse(format!("the plan is not JSON: {err}"))) + })?; + let steps = root + .get("steps") + .and_then(Value::as_array) + .ok_or_else(|| { + AgentError::Llm(LlmError::Parse("the plan has no `steps` array".into())) + })?; + let mut plan = Plan::new( + root.get("goal") + .and_then(Value::as_str) + .unwrap_or(goal), + ); + for (index, step) in steps.iter().enumerate() { + let tool = step + .get("tool") + .and_then(Value::as_str) + .ok_or_else(|| { + AgentError::Llm(LlmError::Parse(format!("plan step {index} has no `tool`"))) + })? + .to_string(); + let title = step + .get("title") + .and_then(Value::as_str) + .map(str::to_string) + .unwrap_or_else(|| format!("step {}", index + 1)); + let args = step.get("args").cloned().unwrap_or_else(|| json!({})); + plan.steps.push(PlanStep::new(title, tool, args)); + } + Ok(plan) +} + +/// Folds a step's result into the template variables (top-level fields: +/// `${track}` resolves against what the earlier step returned). +fn merge_vars(vars: &mut Value, result: &Value) { + if let (Some(into), Value::Object(from)) = (vars.as_object_mut(), result) { + for (key, value) in from { + into.insert(key.clone(), value.clone()); + } + } +} + #[cfg(test)] mod tests; diff --git a/crates/oak-app/src/ai/agent/tests.rs b/crates/oak-app/src/ai/agent/tests.rs index 33ee0b7858..69511a1370 100644 --- a/crates/oak-app/src/ai/agent/tests.rs +++ b/crates/oak-app/src/ai/agent/tests.rs @@ -368,11 +368,22 @@ impl EditFailed for DenyHooks { use oak_ai_tools::hooks::{BeforeCommit, EditFailed, RenderDone}; fn timeline_track_count(backend: &MockBackend) -> usize { + // `serialize_timeline` is `{footage, sequences}` — tracks live under + // each sequence. (The old lookup hit a non-existent top-level + // `tracks` and could only ever return 0; every existing use compared + // 0 to 0, so only an absolute assertion exposes it.) backend .serialize_timeline() - .get("tracks") + .get("sequences") .and_then(Value::as_array) - .map(Vec::len) + .map(|sequences| { + sequences + .iter() + .filter_map(|sequence| sequence.get("tracks")) + .filter_map(Value::as_array) + .map(Vec::len) + .sum::() + }) .unwrap_or(0) } @@ -384,6 +395,7 @@ fn agent(script: Vec, max_rounds: usize) -> Agent MockBackend { + let mut backend = MockBackend::new(); + oak_ai_tools::dispatch::execute(&mut backend, "project.open", json!({"name": "plan", "fps": 30})) + .expect("open"); + backend +} + +fn plan_agent(backend: MockBackend) -> Agent { + Agent::new( + ScriptedLlm::new(vec![ScriptedLlm::say("unused")]), + backend, + AgentConfig { + max_rounds: 4, + policy: Policy::Auto, + model: "test-model".into(), + confirm: ConfirmMode::Headless, + }, + ) +} + +/// ④ A plan executes stepwise: plan + trajectory + progress + cost land +/// in the report, and every write is read back. +#[test] +fn run_plan_records_plan_trajectory_progress_and_cost() { + let mut agent = plan_agent(seeded_for_plan()); + // `project.open` seeds default tracks: judge the plan against the + // baseline it starts from, not against zero. + let baseline_tracks = timeline_track_count(agent.backend()); + let plan = Plan::new("add two tracks") + .push(PlanStep::new("video track", "timeline.add_track", json!({"type": "video"}))) + .push(PlanStep::new("audio track", "timeline.add_track", json!({"type": "audio"}))); + let report = agent.run_plan(plan).expect("plan runs"); + + assert_eq!( + report.plan.as_ref().expect("the plan is recorded").goal, + "add two tracks" + ); + assert_eq!(report.trajectory.len(), 2, "{:?}", report.trajectory); + assert!( + report + .trajectory + .iter() + .all(|trace| trace.status == StepStatus::Done && trace.attempts == 1), + "{:?}", + report.trajectory + ); + // Progress: one event per step, ending at 100%. + assert_eq!(report.progress.len(), 2, "{:?}", report.progress); + assert_eq!(report.progress[0].step, 1); + assert_eq!(report.progress[1].percent(), 100); + // Cost: one call per step; every write read back, none failed. + assert_eq!(report.cost.tool_calls, 2); + assert_eq!(report.readbacks, 2, "both writes were read back"); + assert_eq!(report.readback_failures, 0); + assert!(report.rollback.is_none(), "nothing failed: {:?}", report.rollback); + assert_eq!( + timeline_track_count(agent.backend()), + baseline_tracks + 2, + "exactly the two planned writes landed" + ); +} + +/// ⑤ The cost guard is a hard stop: the second step never runs and the +/// reason is reported (not merely counted). +#[test] +fn cost_guard_blocks_the_second_step_and_reports_the_reason() { + let mut agent = plan_agent(seeded_for_plan()).with_cost_guard(CostGuard { + max_tool_calls: Some(1), + ..CostGuard::default() + }); + let baseline_tracks = timeline_track_count(agent.backend()); + let plan = Plan::new("two tracks") + .push(PlanStep::new("video track", "timeline.add_track", json!({"type": "video"}))) + .push(PlanStep::new("audio track", "timeline.add_track", json!({"type": "audio"}))); + let report = agent.run_plan(plan).expect("plan runs"); + + assert_eq!(report.trajectory[0].status, StepStatus::Done, "{:?}", report.trajectory); + assert_eq!(report.trajectory[1].status, StepStatus::Blocked, "{:?}", report.trajectory); + let stop = report.cost_stop.as_ref().expect("the stop must be reported"); + assert_eq!(stop.limit, "tool_calls"); + assert!(stop.detail.contains("1 of 1"), "{}", stop.detail); + // Only the funded call touched the engine. + assert_eq!( + timeline_track_count(agent.backend()), + baseline_tracks + 1, + "the blocked step must not have run" + ); +} + +/// ⑤ The same guard stops the *loop* mid-round: the second call of a +/// two-call reply is refused with `COST_LIMIT`, and the run says why. +#[test] +fn cost_guard_stops_the_loop_after_the_budget_is_spent() { + let two_calls = ChatResponse { + content: None, + tool_calls: vec![ + ToolCall { + id: "call_a".into(), + name: "timeline.add_track".into(), + arguments: json!({"type": "video"}), + }, + ToolCall { + id: "call_b".into(), + name: "timeline.add_track".into(), + arguments: json!({"type": "audio"}), + }, + ], + finish_reason: Some("tool_calls".into()), + }; + let seeded = seeded_for_plan(); + let baseline_tracks = timeline_track_count(&seeded); + let mut agent = Agent::new( + ScriptedLlm::new(vec![two_calls, ScriptedLlm::say("never reached")]), + seeded, + AgentConfig { + max_rounds: 4, + policy: Policy::Auto, + model: "test-model".into(), + confirm: ConfirmMode::Headless, + }, + ) + .with_cost_guard(CostGuard { + max_tool_calls: Some(1), + ..CostGuard::default() + }); + + let report = agent.run("add both tracks").expect("the loop reports, not errors"); + assert_eq!(report.tools.len(), 2, "{:?}", report.tools); + assert_eq!(report.tools[0].outcome, "applied", "{}", report.tools[0].detail); + assert_eq!(report.tools[1].outcome, "cost-stopped", "{}", report.tools[1].detail); + assert!(report.tools[1].detail.contains("COST_LIMIT"), "{}", report.tools[1].detail); + let stop = report.cost_stop.as_ref().expect("a hard stop must be reported"); + assert_eq!(stop.limit, "tool_calls"); + assert!(!report.converged, "the loop must stop, not limp on"); + assert_eq!( + timeline_track_count(agent.backend()), + baseline_tracks + 1, + "only the funded call ran" + ); +} + +/// ④⑤ A failing step rolls the applied ones back to the baseline — +/// verified against the state, not against the undo bookkeeping. +#[test] +fn a_failed_plan_step_rolls_back_the_applied_steps() { + let mut agent = plan_agent(seeded_for_plan()); + let baseline_tracks = timeline_track_count(agent.backend()); + let plan = Plan::new("track then an impossible placement") + .push(PlanStep::new("add track", "timeline.add_track", json!({"type": "video"}))) + .push(PlanStep::new( + "place", + "timeline.place_clip", + json!({"track": "no-such-track", "footage": "no-such-footage", "in": 0}), + )); + let report = agent.run_plan(plan).expect("the plan reports, not errors"); + + assert_eq!(report.trajectory[0].status, StepStatus::Done, "{:?}", report.trajectory); + assert_eq!(report.trajectory[1].status, StepStatus::Failed, "{:?}", report.trajectory); + let rollback = report.rollback.as_ref().expect("a failed plan must roll back"); + assert!(rollback.restored, "{}", rollback.detail); + assert!(rollback.is_clean(), "{rollback:?}"); + assert!( + rollback.triggered_by.contains("place"), + "the trigger names the failing step: {}", + rollback.triggered_by + ); + assert_eq!( + timeline_track_count(agent.backend()), + baseline_tracks, + "the applied step was undone — observable state matches the baseline" + ); +} + +/// ⑤ Retry spends exactly `max_attempts` on a retryable failure, then +/// fails honestly (with the rollback record). +#[test] +fn retry_policy_spends_every_attempt_on_a_retryable_failure() { + let mut agent = plan_agent(seeded_for_plan()).with_retry(RetryPolicy { + max_attempts: 3, + backoff_ms: 0, + }); + let plan = Plan::new("impossible placement").push(PlanStep::new( + "place", + "timeline.place_clip", + json!({"track": "nope", "footage": "nope", "in": 0}), + )); + let report = agent.run_plan(plan).expect("the plan reports, not errors"); + + assert_eq!(report.trajectory.len(), 1); + assert_eq!( + report.trajectory[0].attempts, 3, + "all three attempts must be spent: {:?}", + report.trajectory[0] + ); + assert_eq!(report.trajectory[0].status, StepStatus::Failed); + assert_eq!(report.cost.tool_calls, 3, "each attempt is a paid call"); + assert!(report.rollback.is_some(), "the failure is recorded with a rollback"); +} + +/// ⑥ The built-in `rough-cut` recipe runs end to end: template vars from +/// earlier results (`${track}`, `${footage.0.id}`) resolve, the clip is +/// placed, and the readback confirms it. +#[test] +fn rough_cut_recipe_executes_end_to_end() { + std::fs::write("/tmp/oak58-rough.mp4", b"x").expect("fixture"); + let book = RecipeBook::builtin(); + let plan = book + .plan("rough-cut", "cut one clip") + .expect("the built-in recipe exists") + .with_vars(json!({"media": "/tmp/oak58-rough.mp4"})); + let mut agent = plan_agent(MockBackend::new()); + let report = agent.run_plan(plan).expect("the plan runs"); + + let statuses: Vec = report + .trajectory + .iter() + .map(|trace| trace.status) + .collect(); + assert_eq!( + statuses, + vec![StepStatus::Done; 4], + "open → track → import → place: {:?}", + report.trajectory + ); + let overview = readback::probe(agent.backend_mut()).expect("probe"); + assert!( + overview.to_string().contains("clip-"), + "a clip must be readable back: {overview}" + ); + assert_eq!(report.readback_failures, 0); +} + +/// ④ `plan_from_llm` turns a (scripted) model reply into an explicit +/// plan before anything executes — one LLM round, then the steps run. +#[test] +fn plan_from_llm_parses_the_reply_then_runs() { + let reply = ScriptedLlm::say( + r#"```json +{"goal": "open and add a track", "steps": [ + {"title": "open", "tool": "project.open", "args": {"name": "llm-plan", "fps": 30}}, + {"title": "track", "tool": "timeline.add_track", "args": {"type": "video"}} +]} +```"#, + ); + let mut agent = agent(vec![reply], 4); + let plan = agent.plan_from_llm("make a plan").expect("the plan parses"); + assert_eq!(plan.goal, "open and add a track"); + assert_eq!(plan.steps.len(), 2); + assert_eq!(agent.cost_usage().llm_rounds, 1, "planning costs one round"); + + let report = agent.run_plan(plan).expect("the plan runs"); + assert!( + report + .trajectory + .iter() + .all(|trace| trace.status == StepStatus::Done), + "{:?}", + report.trajectory + ); +} + +/// ③ Progress reaches a subscriber as it happens (rounds here; plan +/// steps are asserted via `report.progress` in the plan test). +#[test] +fn progress_sink_sees_the_rounds() { + let seen: Arc>> = Arc::new(Mutex::new(Vec::new())); + let sink_seen = Arc::clone(&seen); + let script = vec![ + ScriptedLlm::tool_call("timeline.add_track", json!({"type": "video"})), + ScriptedLlm::say("done"), + ]; + let mut agent = Agent::new( + ScriptedLlm::new(script), + seeded_for_plan(), + AgentConfig { + max_rounds: 4, + policy: Policy::Auto, + model: "test-model".into(), + confirm: ConfirmMode::Headless, + }, + ) + .with_progress_sink(FnSink(move |event: &ProgressEvent| { + sink_seen + .lock() + .expect("poisoned") + .push(event.to_string()); + })); + + let report = agent.run("add a track").expect("run"); + let events = seen.lock().expect("poisoned").clone(); + assert_eq!( + events.len(), + report.progress.len(), + "the sink and the report must agree: {events:?} vs {:?}", + report.progress + ); + assert_eq!(events.len(), 2, "one event per round: {events:?}"); + assert!(events[0].contains("round"), "{events:?}"); + assert_eq!(report.progress[0].phase, "round"); + assert_eq!(report.progress[1].step, 2); +} + +// --------------------------------------------------------------------------- +// Task-62: the confirm gate is wired into the production run path +// (`Agent::run` → `run_with` → `GatedHooks`). + +/// ① Strict gate: the write never reaches the engine, the report marks +/// it `rejected` by the gate, and neither state nor undo stack moves. +#[test] +fn strict_confirm_gate_blocks_the_write_and_the_report_says_so() { + let mut agent = Agent::new( + ScriptedLlm::new(vec![ + ScriptedLlm::tool_call("timeline.add_track", json!({"type": "video"})), + ScriptedLlm::say("done"), + ]), + seeded_for_plan(), + AgentConfig { + max_rounds: 4, + policy: Policy::Auto, + model: "test-model".into(), + confirm: ConfirmMode::Strict, + }, + ); + let tracks_before = timeline_track_count(agent.backend()); + let depth_before = agent.backend().undo_depth(); + + let report = agent.run("add a track").expect("the run reports, not errors"); + + assert_eq!(report.tools.len(), 1, "{:?}", report.tools); + assert_eq!(report.tools[0].outcome, "rejected", "{}", report.tools[0].detail); + assert!( + report.tools[0].detail.contains("the confirmation gate refused"), + "the refusal must come from the gate: {}", + report.tools[0].detail + ); + assert_eq!( + timeline_track_count(agent.backend()), + tracks_before, + "the write must not have landed" + ); + assert_eq!( + agent.backend().undo_depth(), + depth_before, + "the gate must not have opened an undo group" + ); +} + +/// ② Headless gate under `Policy::Confirm` (so the gate really is +/// asked): it auto-approves and the write runs for real. +#[test] +fn headless_confirm_gate_approves_and_the_write_runs() { + let mut agent = Agent::new( + ScriptedLlm::new(vec![ + ScriptedLlm::tool_call("timeline.add_track", json!({"type": "video"})), + ScriptedLlm::say("done"), + ]), + seeded_for_plan(), + AgentConfig { + max_rounds: 4, + policy: Policy::Confirm, + model: "test-model".into(), + confirm: ConfirmMode::Headless, + }, + ); + let tracks_before = timeline_track_count(agent.backend()); + + let report = agent.run("add a track").expect("the run reports, not errors"); + + assert_eq!(report.tools[0].outcome, "applied", "{}", report.tools[0].detail); + assert_eq!( + timeline_track_count(agent.backend()), + tracks_before + 1, + "the approved write must have landed" + ); +} + +/// ③ Reads stay exempt: the strict gate never sees them. +#[test] +fn strict_confirm_gate_still_lets_reads_through() { + let mut agent = Agent::new( + ScriptedLlm::new(vec![ + ScriptedLlm::tool_call("project.get_overview", json!({})), + ScriptedLlm::say("done"), + ]), + seeded_for_plan(), + AgentConfig { + max_rounds: 4, + policy: Policy::Auto, + model: "test-model".into(), + confirm: ConfirmMode::Strict, + }, + ); + + let report = agent + .run("what is on the timeline?") + .expect("the run reports, not errors"); + + assert_eq!(report.tools[0].outcome, "applied", "{}", report.tools[0].detail); + assert!( + report.tools[0].detail.contains("sequences"), + "the read must return real state: {}", + report.tools[0].detail + ); +} diff --git a/crates/oak-app/src/ai/confirm.rs b/crates/oak-app/src/ai/confirm.rs new file mode 100644 index 0000000000..e1345c5745 --- /dev/null +++ b/crates/oak-app/src/ai/confirm.rs @@ -0,0 +1,525 @@ +//! Write-confirmation gate (capability group 1). +//! +//! [`Confirmer`] is the injectable seam: *should this write run?* The +//! execution layer already enforces the answer — under `Policy::Confirm` +//! a [`ConfirmAnswer::Deny`] never reaches the backend (the hooks gate +//! rejects before the body for `project`/`export` and aborts the undo +//! group for `edit`), so "not confirmed ⇒ not executed" is a property of +//! the existing gate, not of this module. What this module adds is: +//! +//! * a named abstraction a host can implement (panel asks the user, +//! headless says yes, tests say no); +//! * **default policies** for the two non-interactive modes +//! ([`ConfirmMode::Headless`] / [`ConfirmMode::Strict`]); +//! * an audit trail ([`ConfirmerHooks::asked`]) so a caller can prove +//! what was asked and how it was answered. +//! +//! Reads never reach the confirmer: the hooks gate only consults +//! `BeforeCommit` for mutating classes. + +use oak_ai_tools::hooks::{Hooks, + BeforeCommit, Decision, EditFailed, FailureEvent, Feedback, GatePoint, OperationClass, + PendingEdit, PixelReadback, ReadbackVerdict, RenderDone, RenderDoneEvent, +}; +use serde_json::Value; + +/// What the gate asks about. Owned, so a host can stash it (UI logs, +/// audit trails) without borrowing the pending edit. +#[derive(Debug, Clone, PartialEq)] +pub struct ConfirmRequest { + /// Tool name (`timeline.place_clip`, …). + pub tool: String, + /// Its grading (read / edit / project / export). + pub class: OperationClass, + /// Where the gate ran (`BeforeInvoke` for project/export/edit.undo, + /// `BeforeCommit` for transactional edits). + pub point: GatePoint, + /// The validated arguments. + pub args: Value, + /// Whether a result was visible (true only at `BeforeCommit`). + pub has_result: bool, +} + +/// The answer to one confirmation request. +#[derive(Debug, Clone, PartialEq)] +pub enum ConfirmAnswer { + /// Run the write. + Approve, + /// Refuse it; `reason` is what the model is told. + Deny { + reason: String, + }, + /// Keep it as a proposal instead of applying it. + Propose { + reason: Option, + }, +} + +/// The injectable confirmation seam: "may this write run?". +/// +/// One implementation per host: a panel closure, a headless policy, a +/// test double. The agent itself never decides — it asks. +pub trait Confirmer { + /// Decide one request. Called once per mutating tool call under + /// `Policy::Confirm`; reads never arrive here. + fn confirm(&mut self, request: &ConfirmRequest) -> ConfirmAnswer; +} + +/// Headless default: there is no human to ask, so writes are approved. +/// +/// The gate still runs (the audit trail records every ask), which is what +/// makes `Policy::Confirm` + [`AutoConfirm`] observably different from +/// `Policy::Auto`: the request list is the proof the gate was consulted. +#[derive(Debug, Default, Clone, Copy)] +pub struct AutoConfirm; + +impl Confirmer for AutoConfirm { + fn confirm(&mut self, _request: &ConfirmRequest) -> ConfirmAnswer { + ConfirmAnswer::Approve + } +} + +/// Strict default: refuse every write. Reads are unaffected (they never +/// reach the gate), so an agent can still plan and inspect. +#[derive(Debug, Default, Clone, Copy)] +pub struct DenyWrites; + +impl Confirmer for DenyWrites { + fn confirm(&mut self, request: &ConfirmRequest) -> ConfirmAnswer { + ConfirmAnswer::Deny { + reason: format!( + "`{}` is a write and this run refuses writes; ask the user to switch mode", + request.tool + ), + } + } +} + +/// Interactive seam: the host supplies the asking function (a panel's +/// "apply?" dialog, a CI gate file check, …). +/// +/// ``` +/// use oakapp::ai::confirm::{ConfirmAnswer, ConfirmRequest, Confirmer, Interactive}; +/// +/// let mut gate = Interactive(|req: &ConfirmRequest| { +/// if req.tool == "export.start" { +/// ConfirmAnswer::Deny { reason: "no exports in this run".into() } +/// } else { +/// ConfirmAnswer::Approve +/// } +/// }); +/// let answer = gate.confirm(&ConfirmRequest { +/// tool: "export.start".into(), +/// class: oak_ai_tools::hooks::OperationClass::Export, +/// point: oak_ai_tools::hooks::GatePoint::BeforeInvoke, +/// args: serde_json::json!({}), +/// has_result: false, +/// }); +/// assert!(matches!(answer, ConfirmAnswer::Deny { .. })); +/// ``` +pub struct Interactive(pub F); + +impl Confirmer for Interactive +where + F: FnMut(&ConfirmRequest) -> ConfirmAnswer, +{ + fn confirm(&mut self, request: &ConfirmRequest) -> ConfirmAnswer { + (self.0)(request) + } +} + +/// The default policies for a run with no interactive host. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ConfirmMode { + /// Headless run: approve writes (nobody to ask), keep the audit trail. + Headless, + /// Refuse every write: the agent may read and plan, never mutate. + Strict, +} + +impl ConfirmMode { + /// The confirmer this mode stands for. + pub fn confirmer(self) -> Box { + match self { + Self::Headless => Box::new(AutoConfirm), + Self::Strict => Box::new(DenyWrites), + } + } + + /// Stable label for logs/reports. + pub fn label(self) -> &'static str { + match self { + Self::Headless => "headless", + Self::Strict => "strict", + } + } +} + +/// [`oak_ai_tools::hooks::Hooks`] = a [`Confirmer`] + the built-in pixel +/// readback + the standard failure feedback. +/// +/// Hand it to [`crate::ai::agent::Agent::run_with`] together with +/// `Policy::Confirm`: +/// +/// ``` +/// use oakapp::ai::confirm::{AutoConfirm, ConfirmerHooks}; +/// use oak_ai_tools::hooks::Policy; +/// +/// let mut hooks = ConfirmerHooks::new(AutoConfirm); +/// // agent.run_with("cut this", &mut hooks) // with AgentConfig { policy: Policy::Confirm, .. } +/// let _ = (Policy::Confirm, hooks.asked()); +/// ``` +pub struct ConfirmerHooks { + confirmer: C, + readback: PixelReadback, + asked: Vec, +} + +impl ConfirmerHooks { + /// Wraps `confirmer` with the structural pixel readback (geometry + + /// byte count; no black-frame threshold — a gap frame is a legitimate + /// answer in this product). + pub fn new(confirmer: C) -> Self { + Self { + confirmer, + readback: PixelReadback::structural(), + asked: Vec::new(), + } + } + + /// Every request the gate asked, in order — the audit trail. + pub fn asked(&self) -> &[ConfirmRequest] { + &self.asked + } + + /// Replace the pixel-readback preset used for `render_done`. + pub fn with_readback(mut self, readback: PixelReadback) -> Self { + self.readback = readback; + self + } +} + +impl BeforeCommit for ConfirmerHooks { + fn before_commit(&mut self, pending: &PendingEdit<'_>) -> Decision { + let request = ConfirmRequest { + tool: pending.tool.to_string(), + class: pending.class, + point: pending.point, + args: pending.args.clone(), + has_result: pending.result.is_some(), + }; + let answer = self.confirmer.confirm(&request); + self.asked.push(request); + match answer { + ConfirmAnswer::Approve => Decision::Approve, + ConfirmAnswer::Deny { reason } => Decision::Reject { reason }, + ConfirmAnswer::Propose { reason } => Decision::Proposed { reason }, + } + } +} + +impl RenderDone for ConfirmerHooks { + fn render_done(&mut self, event: &RenderDoneEvent<'_>) -> ReadbackVerdict { + self.readback.render_done(event) + } +} + +impl EditFailed for ConfirmerHooks { + fn edit_failed(&mut self, event: &FailureEvent<'_>) -> Feedback { + Feedback::from_error(event.error.clone()) + } +} + +/// The production gate: the run's [`ConfirmMode`] confirmer is asked +/// before the caller's hooks — `Approve` falls through to the caller +/// (which may still veto, e.g. pixel checks), `Deny`/`Propose` stop the +/// call right there. Reads never reach it (the engine does not call +/// `before_commit` for them, and [`Policy::Auto`] never asks either). +/// +/// `Agent::run` / `Agent::run_with` wrap the caller's hooks in this. +pub struct GatedHooks<'a> { + confirmer: Box, + inner: &'a mut dyn Hooks, + asked: Vec, +} + +impl<'a> GatedHooks<'a> { + /// `mode` decides what happens to writes; `inner` keeps the caller's + /// hooks in charge of render/failure feedback. + pub fn new(mode: ConfirmMode, inner: &'a mut dyn Hooks) -> Self { + Self { + confirmer: mode.confirmer(), + inner, + asked: Vec::new(), + } + } + + /// Every request the gate asked, in order — the audit trail. + pub fn asked(&self) -> &[ConfirmRequest] { + &self.asked + } +} + +impl BeforeCommit for GatedHooks<'_> { + fn before_commit(&mut self, pending: &PendingEdit<'_>) -> Decision { + let request = ConfirmRequest { + tool: pending.tool.to_string(), + class: pending.class, + point: pending.point, + args: pending.args.clone(), + has_result: pending.result.is_some(), + }; + let answer = self.confirmer.confirm(&request); + self.asked.push(request); + match answer { + ConfirmAnswer::Approve => self.inner.before_commit(pending), + ConfirmAnswer::Deny { reason } => Decision::Reject { reason }, + ConfirmAnswer::Propose { reason } => Decision::Proposed { reason }, + } + } +} + +impl RenderDone for GatedHooks<'_> { + fn render_done(&mut self, event: &RenderDoneEvent<'_>) -> ReadbackVerdict { + self.inner.render_done(event) + } +} + +impl EditFailed for GatedHooks<'_> { + fn edit_failed(&mut self, event: &FailureEvent<'_>) -> Feedback { + self.inner.edit_failed(event) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::ai::agent::{Agent, AgentConfig}; + use crate::ai::llm::{ChatRequest, ChatResponse, LlmClient, LlmError}; + use oak_ai_tools::hooks::Policy; + use oak_ai_tools::mock; + use serde_json::json; + use std::cell::RefCell; + + /// A model that asks for exactly one tool call and then answers. + struct OneCall { + tool: String, + args: Value, + asked: RefCell, + } + + impl LlmClient for OneCall { + fn complete(&self, _request: &ChatRequest<'_>) -> Result { + let first = self.asked.replace(1) == 0; + Ok(if first { + ChatResponse { + content: None, + tool_calls: vec_tools(self.tool.clone(), self.args.clone()), + finish_reason: Some("tool_calls".into()), + } + } else { + ChatResponse { + content: Some("done".into()), + tool_calls: vec_tools(String::new(), json!({})), + finish_reason: Some("stop".into()), + } + }) + } + } + + fn vec_tools(name: String, args: Value) -> Vec { + if name.is_empty() { + Vec::new() + } else { + vec![crate::ai::llm::ToolCall { + id: "call_1".into(), + name, + arguments: args, + }] + } + } + + fn config(policy: Policy) -> AgentConfig { + AgentConfig { + max_rounds: 4, + policy, + model: "test-model".into(), + confirm: ConfirmMode::Headless, + } + } + + /// A project with one track, so mutating calls have somewhere to go. + fn seeded() -> mock::MockBackend { + let mut backend = mock::MockBackend::new(); + dispatch_open(&mut backend); + backend + } + + fn dispatch_open(backend: &mut mock::MockBackend) { + oak_ai_tools::dispatch::execute( + backend, + "project.open", + json!({"name": "confirm-test", "fps": 30}), + ) + .expect("open"); + } + + /// ① Headless: the gate is consulted and approves; the write runs. + #[test] + fn headless_mode_approves_and_the_write_runs() { + let mut agent = Agent::new( + OneCall { + tool: "timeline.add_track".into(), + args: json!({"type": "video"}), + asked: RefCell::new(0), + }, + seeded(), + config(Policy::Confirm), + ); + let mut hooks = ConfirmerHooks::new(AutoConfirm); + let report = agent.run_with("add a track", &mut hooks).expect("run"); + + assert_eq!(report.tools.len(), 1); + assert_eq!( + report.tools[0].outcome, "applied", + "{}", + report.tools[0].detail + ); + // The gate really ran, exactly once, and saw the right request. + assert_eq!(hooks.asked().len(), 1, "one write ⇒ one confirmation"); + let asked = &hooks.asked()[0]; + assert_eq!(asked.tool, "timeline.add_track"); + assert_eq!(asked.class, OperationClass::Edit); + assert_eq!( + asked.point, + GatePoint::BeforeCommit, + "a transactional edit is gated on its result, before the commit" + ); + assert!(asked.has_result, "at BeforeCommit the result is visible"); + } + + /// ② Strict: the deny answer must mean **not executed** — the backend + /// state and the undo stack are byte-identical afterwards. + #[test] + fn strict_mode_denies_and_nothing_is_executed() { + let mut agent = Agent::new( + OneCall { + tool: "timeline.add_track".into(), + args: json!({"type": "video"}), + asked: RefCell::new(0), + }, + seeded(), + config(Policy::Confirm), + ); + let before = agent.backend().serialize_timeline(); + let depth = agent.backend().undo_depth(); + + let mut hooks = ConfirmerHooks::new(DenyWrites); + let report = agent.run_with("add a track", &mut hooks).expect("run"); + + assert_eq!(report.tools[0].outcome, "rejected", "{}", report.tools[0].detail); + assert!(report.tools[0].detail.contains("refuses writes"), "{}", report.tools[0].detail); + assert_eq!(hooks.asked().len(), 1); + assert_eq!( + agent.backend().serialize_timeline(), + before, + "a denied write must not touch the timeline" + ); + assert_eq!( + agent.backend().undo_depth(), + depth, + "a denied write must not push an undo group" + ); + } + + /// ③ Reads are never asked about (the gate only sees mutating calls). + #[test] + fn reads_never_reach_the_confirmer() { + let mut agent = Agent::new( + OneCall { + tool: "node.list_types".into(), + args: json!({}), + asked: RefCell::new(0), + }, + seeded(), + config(Policy::Confirm), + ); + let mut hooks = ConfirmerHooks::new(DenyWrites); + let report = agent.run_with("what nodes exist?", &mut hooks).expect("run"); + assert_eq!(report.tools[0].outcome, "applied", "{}", report.tools[0].detail); + assert!(hooks.asked().is_empty(), "reads must not be confirmed"); + } + + /// ④ The interactive seam receives the full request. + #[test] + fn the_interactive_seam_sees_tool_class_and_args() { + // Shared: the closure borrows the log mutably for as long as the + // hooks live, so the assertions read a second handle. + let seen: std::sync::Arc>> = + std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + let seen_in_closure = std::sync::Arc::clone(&seen); + let mut hooks = ConfirmerHooks::new(Interactive(move |req: &ConfirmRequest| { + seen_in_closure + .lock() + .expect("poisoned") + .push(req.clone()); + ConfirmAnswer::Deny { + reason: "user clicked cancel".into(), + } + })); + let mut agent = Agent::new( + OneCall { + tool: "timeline.add_track".into(), + args: json!({"type": "audio"}), + asked: RefCell::new(0), + }, + seeded(), + config(Policy::Confirm), + ); + let report = agent.run_with("add a track", &mut hooks).expect("run"); + assert_eq!(report.tools[0].outcome, "rejected"); + // The closure captured its own copy; the hook keeps its trail too. + let seen = seen.lock().expect("poisoned"); + assert_eq!(seen.len(), 1); + assert_eq!(seen[0].args, json!({"type": "audio"})); + assert_eq!(seen[0].class, OperationClass::Edit); + assert_eq!(hooks.asked().len(), 1); + assert!(report.tools[0].detail.contains("user clicked cancel")); + } + + /// ⑤ Under `Policy::Auto` the confirmer is not consulted at all — + /// mode and policy are separate knobs. + #[test] + fn auto_policy_never_consults_the_confirmer() { + let mut agent = Agent::new( + OneCall { + tool: "timeline.add_track".into(), + args: json!({"type": "video"}), + asked: RefCell::new(0), + }, + seeded(), + config(Policy::Auto), + ); + let mut hooks = ConfirmerHooks::new(DenyWrites); + let report = agent.run_with("add a track", &mut hooks).expect("run"); + assert_eq!(report.tools[0].outcome, "applied", "{}", report.tools[0].detail); + assert!(hooks.asked().is_empty()); + } + + /// ⑥ The two default modes build their confirmers. + #[test] + fn confirm_mode_builds_its_confirmer() { + let mut headless = ConfirmMode::Headless.confirmer(); + let mut strict = ConfirmMode::Strict.confirmer(); + let request = ConfirmRequest { + tool: "project.save".into(), + class: OperationClass::Project, + point: GatePoint::BeforeInvoke, + args: json!({}), + has_result: false, + }; + assert_eq!(headless.confirm(&request), ConfirmAnswer::Approve); + assert!(matches!(strict.confirm(&request), ConfirmAnswer::Deny { .. })); + assert_eq!(ConfirmMode::Headless.label(), "headless"); + } +} diff --git a/crates/oak-app/src/ai/mod.rs b/crates/oak-app/src/ai/mod.rs index 3ef03cdd4b..4a32180c2b 100644 --- a/crates/oak-app/src/ai/mod.rs +++ b/crates/oak-app/src/ai/mod.rs @@ -14,6 +14,14 @@ //! * [`backend`] — which `EngineBackend` implements the tools; the //! two-scheme investigation lives in its module docs pending the lead's //! ruling. +//! * [`confirm`] — the write-confirmation gate: an injectable +//! [`confirm::Confirmer`] plus headless/strict default policies. +//! * [`readback`] — post-write self-check: probe the state, compare with +//! what the call promised, fail with a diff instead of trusting the +//! success envelope. +//! * [`progress`] — step `n/m` events for long tasks (report + sink). +//! * [`plan`] — explicit plans/recipes with trajectory, retry/fallback, +//! a hard cost guard and undo-based rollback. //! //! The 22-tool face, its schemas, the hooks policy and the transaction //! gate all come from `ai/oak-ai-tools` unchanged — this module only @@ -22,14 +30,28 @@ pub mod agent; pub mod backend; pub mod config; +pub mod confirm; pub mod llm; pub mod memory; +pub mod plan; +pub mod progress; +pub mod readback; pub mod secrets; pub mod tool_text; pub use agent::{Agent, AgentConfig, AgentError, AgentReport, ToolLogEntry}; pub use backend::{EngineBackend, MockBackend}; pub use config::{AiConfig, ConfigError}; +pub use confirm::{ + AutoConfirm, Confirmer, ConfirmerHooks, ConfirmAnswer, ConfirmMode, ConfirmRequest, + DenyWrites, GatedHooks, Interactive, +}; pub use llm::{ChatMessage, ChatResponse, LlmClient, LlmError, ToolCall, UreqClient}; pub use memory::{MemoryConfig, MemoryTools}; +pub use plan::{ + Baseline, CostGuard, CostStop, CostUsage, OnFail, Plan, PlanStep, Recipe, RecipeBook, + RetryPolicy, RollbackReport, StepStatus, StepTrace, estimate_tokens, substitute, +}; +pub use progress::{FnSink, ProgressEvent, ProgressSink}; +pub use readback::{Expect, ReadbackReport}; pub use secrets::{MemoryStore, SecretError, SecretStore}; diff --git a/crates/oak-app/src/ai/plan.rs b/crates/oak-app/src/ai/plan.rs new file mode 100644 index 0000000000..9ef1f2ab47 --- /dev/null +++ b/crates/oak-app/src/ai/plan.rs @@ -0,0 +1,982 @@ +//! Plans, recipes, retry, cost guard and rollback (capability groups 4 +//! and 5). +//! +//! * **Plans** — an explicit step list produced *before* execution +//! ([`Plan`]); the agent executes it step by step and records a +//! [`StepTrace`] per step, so the report carries both the plan and the +//! trajectory ([`crate::ai::agent::AgentReport::plan`] / +//! `::trajectory`). +//! * **Recipes** — reusable step sequences ([`Recipe`]); a recipe *is* +//! a plan factory. Built-ins live in [`RecipeBook::builtin`], hosts can +//! load their own with [`RecipeBook::from_json`]. +//! * **Retry/degrade** — [`RetryPolicy`] retries a failed step while the +//! feedback says the error is retryable; [`OnFail`] decides what +//! happens when retries run out: fail (and roll back), degrade to a +//! fallback tool, or skip. +//! * **Cost guard** — [`CostGuard`] caps tool calls / LLM rounds / +//! (estimated) tokens and *stops* when a limit is hit ([`CostStop`]), +//! it does not merely count. +//! * **Rollback** — multi-step writes are not wrapped in a nested +//! transaction (a second `group_begin` inside an open group answers +//! `Error::State`, see `ai/README.md`); instead [`rollback_to`] issues +//! `edit.undo` until the probe matches the [`Baseline`] taken before +//! the plan. A rollback that cannot restore the baseline reports +//! `restored: false` with the failing undo calls — never a silent +//! "done". + +use crate::ai::readback; +use oak_ai_tools::backend::EngineBackend; +use oak_ai_tools::dispatch; +use oak_ai_tools::hooks::{GatedOutcome, NoHooks, Policy}; +use serde_json::{Value, json}; + +// ------------------------------------------------------------------ plan + +/// What to do when a step fails after its retries are exhausted. +#[derive(Debug, Clone, PartialEq)] +pub enum OnFail { + /// Stop the plan and roll the applied steps back (the default). + Fail, + /// Degrade: run `tool`/`args` once instead, then continue. If the + /// fallback also fails, the step counts as failed (`Fail` semantics). + Fallback { tool: String, args: Value }, + /// Record the step as skipped and continue with the next one. + Skip, +} + +impl OnFail { + /// Stable label for traces/reports. + pub fn label(&self) -> &'static str { + match self { + Self::Fail => "fail", + Self::Fallback { .. } => "fallback", + Self::Skip => "skip", + } + } +} + +impl Default for OnFail { + fn default() -> Self { + Self::Fail + } +} + +/// One explicit plan step. +#[derive(Debug, Clone, PartialEq)] +pub struct PlanStep { + /// Human-readable phase name (also the progress phase). + pub title: String, + /// Tool to call. + pub tool: String, + /// Arguments; string values may contain `${var}` templates resolved + /// against the plan's variables and earlier results (see + /// [`substitute`]). + pub args: Value, + /// What to do if the step fails after retries. + pub on_fail: OnFail, +} + +impl PlanStep { + /// A plain step that fails the plan when it fails. + pub fn new(title: impl Into, tool: impl Into, args: Value) -> Self { + Self { + title: title.into(), + tool: tool.into(), + args, + on_fail: OnFail::Fail, + } + } + + /// Attach an [`OnFail`] policy. + pub fn on_fail(mut self, on_fail: OnFail) -> Self { + self.on_fail = on_fail; + self + } +} + +/// An explicit plan: the step list produced *before* execution. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Plan { + /// What the plan is for (the user's request, condensed). + pub goal: String, + /// The steps, executed in order. + pub steps: Vec, + /// Initial template variables (`${media}` etc.), merged before the + /// first step's results. + pub vars: Value, +} + +impl Plan { + /// An empty plan for `goal`. + pub fn new(goal: impl Into) -> Self { + Self { + goal: goal.into(), + steps: Vec::new(), + vars: json!({}), + } + } + + /// Append a step. + pub fn push(mut self, step: PlanStep) -> Self { + self.steps.push(step); + self + } + + /// Seed template variables (e.g. `json!({"media": "/tmp/clip.mp4"})`). + pub fn with_vars(mut self, vars: Value) -> Self { + self.vars = vars; + self + } +} + +/// How a step ended. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum StepStatus { + /// Applied (and read back clean, when readback is on). + Done, + /// Applied only after a fallback tool ran. + Degraded, + /// Not applied; the plan stopped and rolled back. + Failed, + /// Not applied by design ([`OnFail::Skip`]); the plan continued. + Skipped, + /// Never attempted: the cost guard stopped the plan first. + Blocked, +} + +impl StepStatus { + /// Stable label for traces. + pub fn label(&self) -> &'static str { + match self { + Self::Done => "done", + Self::Degraded => "degraded", + Self::Failed => "failed", + Self::Skipped => "skipped", + Self::Blocked => "blocked", + } + } +} + +/// The trajectory entry for one executed step. +#[derive(Debug, Clone, PartialEq)] +pub struct StepTrace { + /// 0-based index in the plan. + pub index: usize, + /// The step title (duplicated so a trace stands alone). + pub title: String, + /// The tool called (the fallback's, when degraded). + pub tool: String, + /// Outcome. + pub status: StepStatus, + /// How many attempts the primary tool took (1 = no retry). + pub attempts: usize, + /// Failure/mismatch detail, if any. + pub detail: Option, +} + +// -------------------------------------------------------------- template + +/// Resolves `${var}` templates in `args` against `vars`. +/// +/// * the whole string `"${track}"` becomes the variable's JSON value +/// (id, number, object — whatever the producing step returned); +/// * a string *containing* `${track}` gets the value interpolated +/// (strings unquoted); +/// * an unresolved variable is an error, never a silent empty string. +pub fn substitute(args: &Value, vars: &Value) -> Result { + fn resolve(text: &str, vars: &Value) -> Result { + // Whole-string reference keeps the original JSON type. The name + // is a dotted path: `${track}` reads a top-level field, + // `${footage.0.id}` drills into the first array element (entity + // arrays like `media.import_footage`'s result are objects). + if text.starts_with("${") && text.ends_with('}') && text.matches("${").count() == 1 { + let path = &text[2..text.len() - 1]; + return lookup(vars, path).cloned().ok_or_else(|| { + format!("unresolved template variable `${{{path}}}` (available: {})", var_names(vars)) + }); + } + let mut out = String::with_capacity(text.len()); + let bytes = text.as_bytes(); + let mut cursor = 0; + while cursor < bytes.len() { + if bytes[cursor] == b'$' && cursor + 1 < bytes.len() && bytes[cursor + 1] == b'{' { + let Some(end) = text[cursor + 2..].find('}') else { + out.push_str(&text[cursor..]); + break; + }; + let path = &text[cursor + 2..cursor + 2 + end]; + let value = lookup(vars, path).ok_or_else(|| { + format!("unresolved template variable `${{{path}}}` (available: {})", var_names(vars)) + })?; + out.push_str(&render(value)); + cursor = cursor + 2 + end + 1; + } else { + let ch = text[cursor..].chars().next().expect("cursor on a char boundary"); + out.push(ch); + cursor += ch.len_utf8(); + } + } + Ok(Value::String(out)) + } + fn render(value: &Value) -> String { + match value { + Value::String(s) => s.clone(), + other => other.to_string(), + } + } + /// Dotted-path lookup: `track` → field, `footage.0.id` → array + /// element's field. Missing segments are `None`, never a default. + fn lookup<'a>(root: &'a Value, path: &str) -> Option<&'a Value> { + let mut current = root; + for segment in path.split('.') { + current = match current { + Value::Object(map) => map.get(segment)?, + Value::Array(items) => items.get(segment.parse::().ok()?)?, + _ => return None, + }; + } + Some(current) + } + fn var_names(vars: &Value) -> String { + match vars.as_object() { + Some(map) if !map.is_empty() => map.keys().cloned().collect::>().join(", "), + _ => "".to_string(), + } + } + + Ok(match args { + Value::String(text) => resolve(text, vars)?, + Value::Array(items) => Value::Array( + items + .iter() + .map(|item| substitute(item, vars)) + .collect::, _>>()?, + ), + Value::Object(map) => { + let mut out = serde_json::Map::new(); + for (key, value) in map { + out.insert(key.clone(), substitute(value, vars)?); + } + Value::Object(out) + } + other => other.clone(), + }) +} + +// ---------------------------------------------------------------- recipe + +/// A reusable workflow: a named step sequence. +#[derive(Debug, Clone, PartialEq)] +pub struct Recipe { + /// Stable name (`"rough-cut"`). + pub name: String, + /// One line for humans/panel pickers. + pub description: String, + /// The steps. + pub steps: Vec, +} + +impl Recipe { + /// Instantiates the recipe as a plan for `goal`. + pub fn to_plan(&self, goal: impl Into) -> Plan { + Plan { + goal: goal.into(), + steps: self.steps.clone(), + vars: json!({}), + } + } +} + +/// The recipe library. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct RecipeBook { + recipes: Vec, +} + +impl RecipeBook { + /// An empty book. + pub fn empty() -> Self { + Self::default() + } + + /// The built-in workflows shipped with the agent. + /// + /// * `open-and-inspect` — open a project and read it back; no writes, + /// so no rollback path is exercised. + /// * `rough-cut` — open, add a track, import `${media}`, place it at + /// `${track}`/`${footage}` (the ids come from earlier steps' results, + /// which is what makes a recipe more than a macro). + pub fn builtin() -> Self { + Self { + recipes: vec![ + Recipe { + name: "open-and-inspect".into(), + description: "Open a project and read its overview".into(), + steps: vec![ + PlanStep::new("open", "project.open", json!({"name": "inspect", "fps": 30})), + PlanStep::new("inspect", "project.get_overview", json!({})), + ], + }, + Recipe { + name: "rough-cut".into(), + description: "Open, track, import ${media}, place the first clip".into(), + steps: vec![ + PlanStep::new("open", "project.open", json!({"name": "rough-cut", "fps": 30})), + PlanStep::new("add track", "timeline.add_track", json!({"type": "video"})), + PlanStep::new( + "import media", + "media.import_footage", + json!({"paths": ["${media}"]}), + ), + PlanStep::new( + "place clip", + "timeline.place_clip", + json!({"track": "${track}", "footage": "${footage.0.id}", "in": 0}), + ), + ], + }, + ], + } + } + + /// Parses a book from JSON: + /// `{"recipes":[{"name","description","steps":[{title,tool,args,on_fail}]}]}` + /// where `on_fail` is `"fail"`, `"skip"` or + /// `{"fallback":{"tool":…,"args":…}}`. + pub fn from_json(raw: &str) -> Result { + let root: Value = serde_json::from_str(raw).map_err(|err| format!("invalid JSON: {err}"))?; + let recipes = root + .get("recipes") + .and_then(Value::as_array) + .ok_or("`recipes` array missing")?; + let mut out = Vec::new(); + for entry in recipes { + let name = entry + .get("name") + .and_then(Value::as_str) + .ok_or("recipe `name` missing")? + .to_string(); + let description = entry + .get("description") + .and_then(Value::as_str) + .unwrap_or_default() + .to_string(); + let steps_json = entry + .get("steps") + .and_then(Value::as_array) + .ok_or_else(|| format!("recipe `{name}` has no `steps` array"))?; + let mut steps = Vec::new(); + for step in steps_json { + let title = step + .get("title") + .and_then(Value::as_str) + .ok_or_else(|| format!("recipe `{name}`: step `title` missing"))? + .to_string(); + let tool = step + .get("tool") + .and_then(Value::as_str) + .ok_or_else(|| format!("recipe `{name}` step `{title}`: `tool` missing"))? + .to_string(); + let args = step.get("args").cloned().unwrap_or_else(|| json!({})); + let on_fail = match step.get("on_fail") { + None => OnFail::Fail, + Some(Value::String(s)) => match s.as_str() { + "fail" => OnFail::Fail, + "skip" => OnFail::Skip, + other => return Err(format!("recipe `{name}`: unknown on_fail `{other}`")), + }, + Some(Value::Object(map)) => { + let fallback = map + .get("fallback") + .ok_or_else(|| format!("recipe `{name}`: on_fail object needs `fallback`"))?; + OnFail::Fallback { + tool: fallback + .get("tool") + .and_then(Value::as_str) + .ok_or_else(|| format!("recipe `{name}`: fallback `tool` missing"))? + .to_string(), + args: fallback.get("args").cloned().unwrap_or_else(|| json!({})), + } + } + Some(other) => { + return Err(format!("recipe `{name}`: unsupported on_fail {other}")); + } + }; + steps.push(PlanStep { + title, + tool, + args, + on_fail, + }); + } + out.push(Recipe { + name, + description, + steps, + }); + } + Ok(Self { recipes: out }) + } + + /// Every recipe, in load order. + pub fn recipes(&self) -> &[Recipe] { + &self.recipes + } + + /// Look one up by name. + pub fn get(&self, name: &str) -> Option<&Recipe> { + self.recipes.iter().find(|recipe| recipe.name == name) + } + + /// Turns a named recipe into a plan for `goal`. + pub fn plan(&self, name: &str, goal: impl Into) -> Result { + self.get(name) + .map(|recipe| recipe.to_plan(goal)) + .ok_or_else(|| { + format!( + "no recipe `{name}` (known: {})", + if self.recipes.is_empty() { + "".to_string() + } else { + self.recipes + .iter() + .map(|recipe| recipe.name.as_str()) + .collect::>() + .join(", ") + } + ) + }) + } +} + +// ---------------------------------------------------------------- retry + +/// How many times a failed step is retried, and how long to wait. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RetryPolicy { + /// Total attempts (1 = no retry). + pub max_attempts: usize, + /// Delay between attempts, milliseconds. + pub backoff_ms: u64, +} + +impl RetryPolicy { + /// One attempt, no delay. + pub fn none() -> Self { + Self { + max_attempts: 1, + backoff_ms: 0, + } + } + + /// Whether attempt number `attempt` (1-based, already made) should be + /// retried, given the feedback the failure carried. + pub fn should_retry(&self, attempt: usize, retryable: bool) -> bool { + retryable && attempt < self.max_attempts + } + + /// The delay before the next attempt. + pub fn backoff(&self) { + if self.backoff_ms > 0 { + std::thread::sleep(std::time::Duration::from_millis(self.backoff_ms)); + } + } +} + +impl Default for RetryPolicy { + fn default() -> Self { + // One retry by default; tests and hosts pick their own numbers. + Self { + max_attempts: 2, + backoff_ms: 100, + } + } +} + +// ----------------------------------------------------------------- cost + +/// Hard limits for one run. `None` = unlimited. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct CostGuard { + /// Maximum engine/tool calls (each dispatched call counts, including + /// the ones the plan issues). + pub max_tool_calls: Option, + /// Maximum LLM rounds (a round = one `complete()` call). + pub max_llm_rounds: Option, + /// Maximum **estimated** tokens (see [`estimate_tokens`]). + pub max_tokens: Option, +} + +/// What one run has consumed so far. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct CostUsage { + /// Tool calls dispatched. + pub tool_calls: usize, + /// LLM rounds spent. + pub llm_rounds: usize, + /// Estimated tokens spent (chars / 4 — the LLM client carries no + /// usage field, so this is an estimate, not a meter). + pub tokens: u64, +} + +/// Why a run stopped, with the numbers at the moment it stopped. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CostStop { + /// Which limit tripped: `"tool_calls"`, `"llm_rounds"`, `"tokens"`. + pub limit: String, + /// Human/model-readable explanation. + pub detail: String, + /// Usage when it tripped. + pub usage: CostUsage, +} + +impl CostGuard { + /// No limits. + pub fn unlimited() -> Self { + Self::default() + } + + /// The limit check run **before** a tool call: when the budget is + /// already spent the call must not happen. + pub fn check_tool(&self, usage: &CostUsage) -> Option { + self.max_tool_calls.and_then(|max| { + (usage.tool_calls >= max).then(|| CostStop { + limit: "tool_calls".into(), + detail: format!( + "tool-call budget exhausted: {max} of {max} calls spent — \ + stop, report what was done, and ask the user before more work", + ), + usage: usage.clone(), + }) + }) + } + + /// The limit check run before an LLM round. + pub fn check_llm(&self, usage: &CostUsage) -> Option { + self.max_llm_rounds.and_then(|max| { + (usage.llm_rounds >= max).then(|| CostStop { + limit: "llm_rounds".into(), + detail: format!( + "LLM-round budget exhausted: {max} of {max} rounds spent", + ), + usage: usage.clone(), + }) + }) + } + + /// The limit check run against the running token estimate. + pub fn check_tokens(&self, usage: &CostUsage) -> Option { + self.max_tokens.and_then(|max| { + (usage.tokens >= max).then(|| CostStop { + limit: "tokens".into(), + detail: format!( + "token budget exhausted: ~{} of ~{} tokens spent", + usage.tokens, max + ), + usage: usage.clone(), + }) + }) + } +} + +/// Rough token estimate (chars / 4). +/// +/// The LLM client's `ChatResponse` carries no usage field (see +/// `ai/llm.rs`), so a token cap can only be enforced against an +/// estimate. It is labelled as such everywhere it surfaces; the +/// tool-call and LLM-round caps are exact. +pub fn estimate_tokens(text: &str) -> u64 { + (text.chars().count() as u64 + 3) / 4 +} + +// -------------------------------------------------------------- rollback + +/// The state before a plan (or a step group) started. +#[derive(Debug, Clone, PartialEq)] +pub enum Baseline { + /// The probe snapshot. + Snapshot(Value), + /// The probe itself failed (no project yet, backend without + /// overview, …) with this error — matched by error code, so an + /// "unreadable" baseline can still be *restored* (i.e. unreadable + /// again). + Unreadable { code: String, message: String }, +} + +impl Baseline { + /// Takes the baseline now (one probe call). + pub fn capture(backend: &mut dyn EngineBackend) -> Self { + match readback::probe(backend) { + Ok(snapshot) => Self::Snapshot(snapshot), + Err(error) => Self::Unreadable { + code: error.code.clone(), + message: error.message.clone(), + }, + } + } + + /// Whether a fresh probe matches this baseline. + pub fn matches(&self, probe: &Result) -> bool { + match (self, probe) { + (Self::Snapshot(before), Ok(now)) => before == now, + (Self::Unreadable { code, .. }, Err(error)) => code == &error.code, + _ => false, + } + } +} + +/// What an undo-back did (and did not) restore. +#[derive(Debug, Clone, PartialEq)] +pub struct RollbackReport { + /// Why the rollback ran (the failing step / error). + pub triggered_by: String, + /// `edit.undo` calls issued successfully. + pub undone: usize, + /// Whether the probe matches the baseline again. + pub restored: bool, + /// Every `edit.undo` that failed, with its error — the reason a + /// rollback can never be reported as "done" while it is not. + pub failed_undos: Vec, + /// Steps that were applied and could **not** be confirmed undone + /// (filled by the caller, which knows the trajectory). + pub unrestored_steps: Vec, + /// Short conclusion ("state matches the baseline" / explicit failure). + pub detail: String, +} + +impl RollbackReport { + /// Whether the rollback fully succeeded. + pub fn is_clean(&self) -> bool { + self.restored && self.failed_undos.is_empty() && self.unrestored_steps.is_empty() + } +} + +/// Undoes back to `baseline` with `edit.undo`, checking the probe after +/// each call. +/// +/// Stops on: match (success), an undo error (recorded), or `max_undos` +/// (recorded as not restored). Never claims success it did not verify. +pub fn rollback_to( + backend: &mut dyn EngineBackend, + baseline: &Baseline, + triggered_by: impl Into, + max_undos: usize, +) -> RollbackReport { + let triggered_by = triggered_by.into(); + let mut undone = 0usize; + let mut failed_undos = Vec::new(); + let mut restored = false; + loop { + if baseline.matches(&readback::probe(backend)) { + restored = true; + break; + } + if undone >= max_undos { + break; + } + match dispatch::execute_with(backend, "edit.undo", json!({}), Policy::Auto, &mut NoHooks) { + GatedOutcome::Applied { .. } => undone += 1, + GatedOutcome::Failed { error, .. } => { + failed_undos.push(format!( + "edit.undo #{}: {} ({})", + undone + 1, + error.code, + error.message + )); + break; + } + GatedOutcome::Rejected { reason, error } => { + failed_undos.push(format!( + "edit.undo #{}: {} ({})", + undone + 1, + error.code, + reason + )); + break; + } + GatedOutcome::Proposed { .. } => { + failed_undos.push(format!( + "edit.undo #{}: not applied (proposal only)", + undone + 1 + )); + break; + } + } + } + // Final verification even on the exit paths above. + if !restored { + restored = baseline.matches(&readback::probe(backend)); + } + let detail = if restored { + "state matches the baseline".to_string() + } else if !failed_undos.is_empty() { + format!( + "rollback FAILED after {undone} undo(s): {}; the state may still hold the \ + plan's writes — do not assume it was reverted", + failed_undos.join("; ") + ) + } else { + format!( + "rollback FAILED: {undone} undo(s) issued and the probe still does not match \ + the baseline (undo cap {max_undos} reached)" + ) + }; + RollbackReport { + triggered_by, + undone, + restored, + failed_undos, + unrestored_steps: Vec::new(), + detail, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use oak_ai_tools::mock::MockBackend; + + // ---------------------------------------------------------- templates + + /// ① Whole-string references keep the JSON type; missing vars error. + #[test] + fn template_resolution_keeps_types_and_fails_on_missing_vars() { + let vars = json!({"track": "track-1", "count": 3}); + assert_eq!( + substitute(&json!({"track": "${track}"}), &vars).expect("substitute"), + json!({"track": "track-1"}) + ); + assert_eq!( + substitute(&json!({"n": "${count}"}), &vars).expect("substitute"), + json!({"n": 3}), + "a whole-string reference keeps the number, not the string" + ); + let err = substitute(&json!({"track": "${missing}"}), &vars).expect_err("must fail"); + assert!(err.contains("missing"), "{err}"); + // Interpolation inside a longer string. + assert_eq!( + substitute(&json!({"path": "/tmp/${track}.mp4"}), &vars).expect("substitute"), + json!({"path": "/tmp/track-1.mp4"}) + ); + // Recursion into arrays. + assert_eq!( + substitute(&json!({"paths": ["${track}", "plain"]}), &vars).expect("substitute"), + json!({"paths": ["track-1", "plain"]}) + ); + // Dotted paths drill into entity arrays (import results). + let import_result = json!({"footage": [{"id": "footage-9"}], "failed": []}); + assert_eq!( + substitute(&json!({"footage": "${footage.0.id}"}), &import_result).expect("path"), + json!({"footage": "footage-9"}), + "a whole-string path keeps the scalar type" + ); + let err = substitute(&json!({"footage": "${footage.9.id}"}), &import_result) + .expect_err("out of range"); + assert!(err.contains("footage.9.id"), "{err}"); + } + + // ------------------------------------------------------------- plans + + /// ② A plan carries goal, steps and seeded vars. + #[test] + fn plan_builder_assembles_the_step_list() { + let plan = Plan::new("cut one clip") + .with_vars(json!({"media": "/tmp/a.mp4"})) + .push(PlanStep::new("open", "project.open", json!({"name": "x", "fps": 30}))) + .push( + PlanStep::new("import", "media.import_footage", json!({"paths": ["${media}"]})), + ); + assert_eq!(plan.goal, "cut one clip"); + assert_eq!(plan.steps.len(), 2); + let resolved = substitute(&plan.steps[1].args, &plan.vars).expect("vars"); + assert_eq!(resolved, json!({"paths": ["/tmp/a.mp4"]})); + } + + /// ③ OnFail defaults to Fail and labels itself. + #[test] + fn on_fail_defaults_to_failing_the_plan() { + assert_eq!(PlanStep::new("t", "tool", json!({})).on_fail, OnFail::Fail); + assert_eq!(OnFail::Skip.label(), "skip"); + assert_eq!( + OnFail::Fallback { + tool: "edit.undo".into(), + args: json!({}) + } + .label(), + "fallback" + ); + assert_eq!(StepStatus::Degraded.label(), "degraded"); + } + + // ----------------------------------------------------------- recipes + + /// ④ Built-ins exist and instantiate as plans. + #[test] + fn builtin_recipes_build_plans() { + let book = RecipeBook::builtin(); + let rough = book.plan("rough-cut", "cut one clip").expect("plan"); + assert_eq!(rough.steps.len(), 4); + assert!(book.get("open-and-inspect").is_some()); + assert_eq!(book.recipes().len(), 2); + let unknown = book.plan("nope", "x").expect_err("unknown recipe"); + assert!(unknown.contains("nope"), "{unknown}"); + } + + /// ⑤ JSON loading, including the fallback form of on_fail. + #[test] + fn recipes_load_from_json() { + let raw = r#"{"recipes":[{"name":"safe","description":"d","steps":[ + {"title":"open","tool":"project.open","args":{"name":"x","fps":30}}, + {"title":"save","tool":"project.save","args":{},"on_fail":"skip"}, + {"title":"export","tool":"export.start","args":{},"on_fail":{"fallback":{"tool":"render.start","args":{}}}} + ]}]}"#; + let book = RecipeBook::from_json(raw).expect("load"); + let safe = book.get("safe").expect("recipe"); + assert_eq!(safe.steps.len(), 3); + assert_eq!(safe.steps[0].on_fail, OnFail::Fail); + assert_eq!(safe.steps[1].on_fail, OnFail::Skip); + assert!(matches!(safe.steps[2].on_fail, OnFail::Fallback { .. })); + // Errors are named, not generic. + let err = RecipeBook::from_json(r#"{"recipes":[{"name":"broken","steps":[{"title":"t"}]}]}"#) + .expect_err("no tool"); + assert!(err.contains("`tool` missing"), "{err}"); + let err = RecipeBook::from_json("not json").expect_err("bad json"); + assert!(err.contains("invalid JSON"), "{err}"); + } + + // ------------------------------------------------------------- retry + + /// ⑥ Retry honours both the attempt cap and the retryable flag. + #[test] + fn retry_honours_attempts_and_retryable() { + let policy = RetryPolicy { + max_attempts: 3, + backoff_ms: 0, + }; + assert!(policy.should_retry(1, true)); + assert!(policy.should_retry(2, true)); + assert!(!policy.should_retry(3, true), "the cap is inclusive"); + assert!(!policy.should_retry(1, false), "non-retryable never retries"); + assert!(!RetryPolicy::none().should_retry(1, true)); + } + + // -------------------------------------------------------------- cost + + /// ⑦ The guard stops at the limit — it does not merely count. + #[test] + fn cost_guard_stops_at_each_limit() { + let guard = CostGuard { + max_tool_calls: Some(2), + max_llm_rounds: Some(1), + max_tokens: Some(10), + }; + let mut usage = CostUsage::default(); + assert!(guard.check_tool(&usage).is_none(), "0 < 2 may call"); + usage.tool_calls = 1; + assert!(guard.check_tool(&usage).is_none(), "1 < 2 may call"); + usage.tool_calls = 2; + let stop = guard.check_tool(&usage).expect("2 >= 2 must stop"); + assert_eq!(stop.limit, "tool_calls"); + assert!(stop.detail.contains("2 of 2"), "{}", stop.detail); + + usage.llm_rounds = 1; + let stop = guard.check_llm(&usage).expect("1 >= 1 must stop"); + assert_eq!(stop.limit, "llm_rounds"); + + usage.tokens = 10; + let stop = guard.check_tokens(&usage).expect("10 >= 10 must stop"); + assert_eq!(stop.limit, "tokens"); + assert!(stop.detail.contains("~10"), "{}", stop.detail); + } + + /// ⑧ Unlimited is the default; the token estimate is labelled. + #[test] + fn cost_default_is_unlimited() { + let guard = CostGuard::unlimited(); + let usage = CostUsage { + tool_calls: 9_999, + llm_rounds: 9_999, + tokens: u64::MAX, + }; + assert!(guard.check_tool(&usage).is_none()); + assert!(guard.check_llm(&usage).is_none()); + assert!(guard.check_tokens(&usage).is_none()); + assert_eq!(estimate_tokens("abcd"), 1); + assert_eq!(estimate_tokens("abcde"), 2); + } + + // ----------------------------------------------------------- rollback + + /// ⑨ Undo-back restores a seeded state, and reports it honestly. + #[test] + fn rollback_restores_the_baseline() { + let mut backend = MockBackend::new(); + dispatch::execute(&mut backend, "project.open", json!({"name": "rb", "fps": 30})) + .expect("open"); + let baseline = Baseline::capture(&mut backend); + + // Two writes to undo. + dispatch::execute(&mut backend, "timeline.add_track", json!({"type": "video"})) + .expect("track"); + dispatch::execute(&mut backend, "timeline.add_track", json!({"type": "audio"})) + .expect("track"); + assert_ne!( + readback::probe(&mut backend).expect("probe"), + match &baseline { + Baseline::Snapshot(value) => value.clone(), + other => panic!("expected a snapshot baseline, got {other:?}"), + } + ); + + let report = rollback_to(&mut backend, &baseline, "step `add track` failed", 16); + assert!(report.restored, "{}", report.detail); + assert!(report.is_clean(), "{report:?}"); + assert_eq!(report.undone, 2, "one undo per applied write"); + assert!(report.failed_undos.is_empty()); + assert_eq!(report.triggered_by, "step `add track` failed"); + } + + /// ⑩ An undo that cannot run is recorded, and the report says FAILED + /// — never a silent "rolled back". + #[test] + fn a_failing_undo_is_reported_as_a_failed_rollback() { + let mut backend = MockBackend::new(); + // No project, nothing to undo: the first probe already fails and + // the undo answers NOTHING_TO_UNDO (or the probe errors out of a + // matching "unreadable" baseline — either way we must not claim + // a clean restore unless the probe really matches). + dispatch::execute(&mut backend, "timeline.add_track", json!({"type": "video"})) + .expect_err("no project"); + let baseline = Baseline::capture(&mut backend); + let report = rollback_to(&mut backend, &baseline, "step failed", 4); + match &baseline { + // Nothing was ever applied: unreadable baseline + unreadable + // probe = restored, and that is the truth. + Baseline::Unreadable { .. } => { + assert!(report.restored, "{}", report.detail); + assert!(report.is_clean(), "{report:?}"); + } + Baseline::Snapshot(_) => { + assert!(!report.is_clean(), "a snapshot baseline with nothing applied"); + assert!(!report.failed_undos.is_empty() || !report.restored); + } + } + } + + /// ⑪ `is_clean` refuses when unrestored steps are listed — the + /// explicit-error requirement for a failed rollback. + #[test] + fn unrestored_steps_make_the_report_unclean() { + let mut report = RollbackReport { + triggered_by: "step 3".into(), + undone: 1, + restored: true, + failed_undos: vec![], + unrestored_steps: vec!["place clip".into()], + detail: "state matches the baseline".into(), + }; + assert!(!report.is_clean(), "a step we cannot confirm undone must surface"); + report.unrestored_steps.clear(); + assert!(report.is_clean()); + } +} diff --git a/crates/oak-app/src/ai/progress.rs b/crates/oak-app/src/ai/progress.rs new file mode 100644 index 0000000000..646c2da27a --- /dev/null +++ b/crates/oak-app/src/ai/progress.rs @@ -0,0 +1,130 @@ +//! Long-task progress events (capability group 3). +//! +//! Two producers, one shape: the agent loop reports *rounds* (`n/m` of +//! the LLM turns) and the plan runner reports *steps* (`n/m` of the +//! explicit plan). Events go two places — always into +//! [`crate::ai::agent::AgentReport::progress`] (so a report is complete +//! on its own) and, when a sink is wired with +//! [`crate::ai::agent::Agent::with_progress_sink`], to the subscriber +//! (the chat panel's spinner, a CLI ticker) as they happen. + +use std::fmt; + +/// One progress event. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ProgressEvent { + /// 1-based current step (round or plan step). + pub step: usize, + /// Total number of steps in this phase. + pub total: usize, + /// What is running: `"round"` for an LLM turn, a plan step's title + /// for plan execution, `"rollback"` while undoing. + pub phase: String, + /// Optional detail (the tool being called, the reason). + pub detail: Option, +} + +impl ProgressEvent { + /// Convenience constructor with no detail. + pub fn new(step: usize, total: usize, phase: impl Into) -> Self { + Self { + step, + total, + phase: phase.into(), + detail: None, + } + } + + /// Attach a detail line. + pub fn with_detail(mut self, detail: impl Into) -> Self { + self.detail = Some(detail.into()); + self + } + + /// Percentage complete, rounded; 100 when `total == 0` never happens + /// (callers pass `total >= 1`), so this is total-safe. + pub fn percent(&self) -> u8 { + if self.total == 0 { + return 0; + } + ((self.step.min(self.total) * 100) / self.total).min(100) as u8 + } +} + +impl fmt::Display for ProgressEvent { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "[{}/{} {}%] {}", + self.step, + self.total, + self.percent(), + self.phase + )?; + if let Some(detail) = &self.detail { + write!(f, " — {detail}")?; + } + Ok(()) + } +} + +/// What subscribes to progress. The panel implements it directly; a +/// closure can be wrapped with [`FnSink`]. +/// +/// `Send` is a supertrait because the agent is spawned on a worker +/// thread by the chat panel — a sink that cannot cross threads would +/// make the whole `Agent` unspawnable. +pub trait ProgressSink: Send { + /// Called as each step starts (before it executes, so a UI can show + /// "step 3 of 7" while the work is still running). + fn on_progress(&mut self, event: &ProgressEvent); +} + +/// A closure as a sink. +pub struct FnSink(pub F); + +impl ProgressSink for FnSink +where + F: FnMut(&ProgressEvent) + Send, +{ + fn on_progress(&mut self, event: &ProgressEvent) { + (self.0)(event) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::{Arc, Mutex}; + + /// ① Percentages are computed from step/total. + #[test] + fn percent_follows_the_step() { + assert_eq!(ProgressEvent::new(1, 4, "round").percent(), 25); + assert_eq!(ProgressEvent::new(4, 4, "round").percent(), 100); + assert_eq!(ProgressEvent::new(0, 0, "round").percent(), 0); + } + + /// ② Display is the line a CLI ticker would print. + #[test] + fn display_is_human_readable() { + let event = ProgressEvent::new(3, 7, "place clips").with_detail("timeline.place_clip"); + assert_eq!(event.to_string(), "[3/7 42%] place clips — timeline.place_clip"); + } + + /// ③ A closure sink receives the event (the subscription seam). + #[test] + fn a_closure_sink_receives_events() { + let seen: Arc>> = Arc::new(Mutex::new(Vec::new())); + let sink_seen = Arc::clone(&seen); + let mut sink = FnSink(move |event: &ProgressEvent| { + sink_seen.lock().expect("poisoned").push(event.to_string()); + }); + sink.on_progress(&ProgressEvent::new(1, 2, "round")); + sink.on_progress(&ProgressEvent::new(2, 2, "round")); + assert_eq!( + *seen.lock().expect("poisoned"), + vec!["[1/2 50%] round".to_string(), "[2/2 100%] round".to_string()] + ); + } +} diff --git a/crates/oak-app/src/ai/readback.rs b/crates/oak-app/src/ai/readback.rs new file mode 100644 index 0000000000..7cd66ab4a7 --- /dev/null +++ b/crates/oak-app/src/ai/readback.rs @@ -0,0 +1,580 @@ +//! Post-write readback self-check (capability group 2). +//! +//! The rule: a write that reports success must be *read back* and the +//! state compared with what the call promised. A mismatch is a failure +//! with a diff — never a silent success. +//! +//! The probe is `project.get_overview` (a read class, so it runs under +//! every [`Policy`] and never touches the confirmation gate). It calls +//! the backend's `EngineBackend::project_get_overview` **directly** — +//! the same entry point the tool face dispatches to, minus the undo +//! wrapper: every dispatch call commits its own undo group (the mock's +//! `txn_commit` pushes even an empty one), and a probe that kept pushing +//! empty groups would bury the writes an [`crate::ai::plan::rollback_to`] +//! is trying to pop. No probe ever touches the undo stack. +//! +//! `export.start` is deliberately **not** read back: its artifact is a +//! file outside the engine, and the tool already reports the byte count +//! it wrote (see `ai/oak-ai-tools` README, "No fake success"). + +use oak_ai_tools::backend::EngineBackend; +use oak_ai_tools::error::ToolError; +use serde_json::{Value, json}; + +/// The read tool used as the probe. +pub const PROBE_TOOL: &str = "project.get_overview"; + +/// What the state must look like after the write. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Expect { + /// The probe must contain every one of these ids (a write that mints + /// an entity — `clip`, `track`, `footage`, …). + IdsPresent(Vec), + /// The state must differ from the baseline taken before the write. + Changed, + /// The listed ids must be **gone from the observable state** (the + /// overview no longer contains them) and — with a baseline — the + /// state must have moved. This is how a delete is verified: the check + /// runs against the probe, never against the tool's own return body. + IdsGone(Vec), + /// The probe must still succeed (the document stays readable). + ProbeOk, + /// The probe must report at least one sequence (`project.open`). + HasSequence, +} + +impl Expect { + /// Short label for reports. + pub fn label(&self) -> &'static str { + match self { + Self::IdsPresent(_) => "ids-present", + Self::IdsGone(_) => "ids-gone", + Self::Changed => "changed", + Self::ProbeOk => "probe-ok", + Self::HasSequence => "has-sequence", + } + } +} + +/// The verdict of one readback, with the evidence attached. +#[derive(Debug, Clone, PartialEq)] +pub struct ReadbackReport { + /// False ⇒ the write must be reported as failed. + pub ok: bool, + /// What was expected. + pub expect: Expect, + /// Human/model-readable description of the mismatch (`None` when ok). + pub diff: Option, + /// Baseline probe (before the write), when one was taken. + pub before: Option, + /// Probe after the write. + pub after: Option, +} + +impl ReadbackReport { + /// The model-facing payload for a **failed** readback: a structured + /// failure the re-planning loop can act on. + pub fn failure_payload(&self) -> Value { + json!({ + "ok": false, + "code": "READBACK_MISMATCH", + "expect": self.expect.label(), + "message": self.diff.clone().unwrap_or_else(|| "readback mismatch".into()), + "hint": "the tool reported success but the state does not match; \ + re-read project.get_overview, verify the entity, then retry \ + or undo — do not assume the write landed", + }) + } +} + +/// Runs the probe on the backend directly. +/// +/// Same method the `project.get_overview` tool dispatches to, but +/// without the undo-group wrapper (see the module docs): a probe must +/// not perturb the very state — or the undo stack — it is verifying. +pub fn probe(backend: &mut dyn EngineBackend) -> Result { + backend.project_get_overview(&json!({})) +} + +/// Which probes to run around one mutating call. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ProbePlan { + /// Do not read this tool back at all. + Skip, + /// Probe after the call only (there is no usable baseline before it). + AfterOnly, + /// Probe before **and** after, so `Changed` can be judged. + BeforeAndAfter, +} + +/// The probe plan for a (mutating) tool. +/// +/// * `export.start` — artifact outside the engine → skip; +/// * `project.open` — no project exists to probe beforehand → after only; +/// * `project.save` — the timeline does not move (the file does) → after +/// only, checking the document still reads; +/// * everything else — before and after. +pub fn probe_plan(tool: &str) -> ProbePlan { + match tool { + "export.start" => ProbePlan::Skip, + "project.open" | "project.save" => ProbePlan::AfterOnly, + _ => ProbePlan::BeforeAndAfter, + } +} + +/// The expectation for `tool`'s result, or `None` when the tool must not +/// be read back at all. +/// +/// Generic rule first (ids the result mints ⇒ `IdsPresent`, otherwise +/// `Changed`), three named exceptions where the generic rule would lie: +/// +/// * `project.open` has no baseline (there was no project to probe), so +/// "changed" is unprovable — the honest check is "a sequence exists"; +/// * `project.save` writes a file, not the timeline: the state must stay +/// readable (`ProbeOk`), the bytes are the tool's own read-back; +/// * `export.start` writes outside the engine → skipped entirely. +pub fn expectation_for(tool: &str, result: &Value) -> Option { + match tool { + "project.open" => return Some(Expect::HasSequence), + "project.save" => return Some(Expect::ProbeOk), + "export.start" => return None, + _ => {} + } + // A delete reports the ids it *removed*: the verification is that + // those ids are **gone from the observable state**, not that the + // return body said so (`timeline.ripple_delete` → `IdsGone`). + if result.get("removed").and_then(Value::as_bool) == Some(true) { + let removed = collect_ids(result); + if !removed.is_empty() { + return Some(Expect::IdsGone(removed)); + } + return Some(Expect::Changed); + } + let ids = collect_ids(result); + if ids.is_empty() { + Some(Expect::Changed) + } else { + Some(Expect::IdsPresent(ids)) + } +} + +/// Entity ids named by a tool result. +/// +/// Keys that name an entity, plus the generic `id`. Arrays are walked +/// (`media.import_footage` returns `footage: [{id, …}]`), objects one +/// level down; everything else is ignored — a *state* comparison is the +/// fallback when a result names nothing. +fn collect_ids(result: &Value) -> Vec { + const KEYS: [&str; 9] = [ + "id", + "clip", + "new_clip", + "track", + "footage", + "node", + "marker", + "transition", + "sequence", + ]; + let mut out: Vec = Vec::new(); + fn walk(value: &Value, out: &mut Vec) { + match value { + Value::Object(map) => { + for (key, child) in map { + if KEYS.contains(&key.as_str()) { + if let Some(id) = child.as_str() { + let id = id.to_string(); + if !out.contains(&id) { + out.push(id); + } + } + } + // Entity containers keep going (`footage: [{id}]`). + if child.is_array() || child.is_object() { + walk(child, out); + } + } + } + Value::Array(items) => { + for item in items { + walk(item, out); + } + } + _ => {} + } + } + walk(result, &mut out); + out +} + +/// Compares the probes against the expectation. Pure: no backend, no I/O, +/// so every branch is unit-testable. +/// +/// Strict on purpose: when the baseline is missing for a `Changed` +/// expectation the answer is `false` with an explanatory diff — "could +/// not prove the change" is not "the change happened". +pub fn verify(before: Option<&Value>, after: &Value, expect: Expect) -> ReadbackReport { + let finish = |ok: bool, diff: Option| ReadbackReport { + ok, + diff, + expect: expect.clone(), + before: before.cloned(), + after: Some(after.clone()), + }; + // Borrow (do not move): `finish` still clones `expect` for the report. + match &expect { + Expect::IdsPresent(ids) => { + let missing: Vec<&str> = ids + .iter() + .filter(|id| !contains_string(after, id)) + .map(String::as_str) + .collect(); + if missing.is_empty() { + finish(true, None) + } else { + finish( + false, + Some(format!( + "the write reported {} but the state does not contain: {}", + ids.join(", "), + missing.join(", ") + )), + ) + } + } + Expect::IdsGone(ids) => { + let still_there: Vec<&str> = ids + .iter() + .filter(|id| contains_string(after, id)) + .map(String::as_str) + .collect(); + if !still_there.is_empty() { + return finish( + false, + Some(format!( + "the delete reported {} but the state still contains: {}", + ids.join(", "), + still_there.join(", ") + )), + ); + } + match before { + // Ids gone but the state identical ⇒ the baseline never + // held them either: nothing observable was deleted. + Some(prev) if prev == after => finish( + false, + Some( + "the reported ids are absent, but the state is identical to the \ + baseline — nothing observable was deleted" + .into(), + ), + ), + _ => finish(true, None), + } + } + Expect::Changed => match before { + Some(prev) if prev == after => finish( + false, + Some("the tool reported success but the state is byte-identical to the baseline".into()), + ), + Some(_) => finish(true, None), + None => finish( + false, + Some( + "no baseline probe before the write, so the change cannot be proven \ + (the probe itself failed — see its error)" + .into(), + ), + ), + }, + Expect::ProbeOk => finish(true, None), + Expect::HasSequence => { + let sequences = after.get("sequences").and_then(Value::as_array); + match sequences { + Some(list) if !list.is_empty() => finish(true, None), + Some(_) => finish(false, Some("the project opened but has no sequence".into())), + None => finish(false, Some("the overview carries no `sequences` array".into())), + } + } + } +} + +/// Whether `haystack` contains `needle` as a string value anywhere. +fn contains_string(haystack: &Value, needle: &str) -> bool { + match haystack { + Value::String(s) => s == needle, + Value::Array(items) => items.iter().any(|item| contains_string(item, needle)), + Value::Object(map) => map.values().any(|child| contains_string(child, needle)), + _ => false, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use oak_ai_tools::dispatch; + use oak_ai_tools::mock::MockBackend; + use serde_json::json; + + fn overview_with_clip() -> Value { + json!({ + "sequences": [{ + "id": "sequence-1", + "tracks": [{ "id": "track-1", "clips": [{ "id": "clip-7", "footage": "footage-2" }] }] + }], + "footage": [{ "id": "footage-2" }] + }) + } + + /// ① A minted id that is readable back ⇒ ok. + #[test] + fn ids_present_passes_when_the_probe_reports_them() { + let report = verify( + None, + &overview_with_clip(), + Expect::IdsPresent(vec!["clip-7".into(), "footage-2".into()]), + ); + assert!(report.ok, "{report:?}"); + assert!(report.diff.is_none()); + } + + /// ② A missing id ⇒ failure with a diff naming it (never silent). + #[test] + fn ids_present_fails_with_a_diff_naming_the_missing_entity() { + let report = verify( + None, + &overview_with_clip(), + Expect::IdsPresent(vec!["clip-7".into(), "clip-404".into()]), + ); + assert!(!report.ok); + let diff = report.diff.as_ref().expect("a diff must be reported"); + assert!(diff.contains("clip-404"), "{diff}"); + let payload = report.failure_payload(); + assert_eq!(payload["code"], "READBACK_MISMATCH"); + assert!(payload["hint"].is_string()); + } + + /// ③ "Changed" with an identical baseline ⇒ failure. + #[test] + fn unchanged_state_fails_the_changed_expectation() { + let state = overview_with_clip(); + let report = verify(Some(&state), &state, Expect::Changed); + assert!(!report.ok, "byte-identical state must not pass"); + assert!(report.diff.expect("diff").contains("byte-identical")); + } + + /// ④ Changed with a real difference ⇒ ok. + #[test] + fn changed_state_passes() { + let before = overview_with_clip(); + let mut after = before.clone(); + after["sequences"][0]["tracks"][0]["clips"] + .as_array_mut() + .expect("clips") + .push(json!({"id": "clip-8"})); + let report = verify(Some(&before), &after, Expect::Changed); + assert!(report.ok, "{report:?}"); + } + + /// ⑤ Strict: no baseline ⇒ cannot prove the change ⇒ failure. + #[test] + fn a_missing_baseline_fails_instead_of_assuming_success() { + let report = verify(None, &overview_with_clip(), Expect::Changed); + assert!(!report.ok); + assert!(report.diff.expect("diff").contains("no baseline")); + } + + /// ⑥ `project.open` has no baseline; the honest check is the sequence. + #[test] + fn project_open_expects_a_sequence() { + assert_eq!( + expectation_for("project.open", &json!({"created": true})), + Some(Expect::HasSequence) + ); + let with = json!({"sequences": [{"id": "sequence-1"}]}); + assert!(verify(None, &with, Expect::HasSequence).ok); + let empty = json!({"sequences": []}); + let report = verify(None, &empty, Expect::HasSequence); + assert!(!report.ok, "an opened project must have a sequence"); + } + + /// ⑦ `export.start` writes outside the engine ⇒ no readback at all. + #[test] + fn export_is_not_read_back() { + assert_eq!( + expectation_for("export.start", &json!({"started": true, "bytes": 12})), + None + ); + } + + /// ⑧ `project.save` keeps the document readable; the bytes are the + /// tool's own read-back. + #[test] + fn save_expects_a_readable_document() { + assert_eq!( + expectation_for("project.save", &json!({"saved": true, "bytes": 9})), + Some(Expect::ProbeOk) + ); + assert!(verify(None, &json!({}), Expect::ProbeOk).ok); + } + + /// ⑨ The generic rule: an id-carrying result ⇒ ids; otherwise change. + #[test] + fn generic_expectation_rule() { + assert_eq!( + expectation_for("timeline.place_clip", &json!({"clip": "clip-3", "length": {"num": 1}})), + Some(Expect::IdsPresent(vec!["clip-3".into()])) + ); + assert_eq!( + expectation_for("timeline.ripple_delete", &json!({"removed": true, "ripple": 3})), + Some(Expect::Changed) + ); + // Nested entity containers are walked. + assert_eq!( + expectation_for( + "media.import_footage", + &json!({"footage": [{"id": "footage-9"}], "failed": []}) + ), + Some(Expect::IdsPresent(vec!["footage-9".into()])) + ); + } + + /// ⑩ End-to-end on the real mock: open → place a clip → the probe + /// really contains the id the write reported. + #[test] + fn the_probe_reads_back_a_real_write() { + let mut backend = MockBackend::new(); + dispatch::execute(&mut backend, "project.open", json!({"name": "rb", "fps": 30})) + .expect("open"); + // The mock only checks that the file exists. + std::fs::write("/tmp/oak-readback-fixture.mp4", b"x").expect("fixture"); + let footage = dispatch::execute( + &mut backend, + "media.import_footage", + json!({"paths": ["/tmp/oak-readback-fixture.mp4"]}), + ) + .unwrap_or_else(|err| panic!("import: {err}")); + let footage_id = footage["footage"][0]["id"].as_str().expect("id").to_string(); + let track = dispatch::execute(&mut backend, "timeline.add_track", json!({"type": "video"})) + .expect("track")["track"] + .as_str() + .expect("track id") + .to_string(); + + let placed = dispatch::execute( + &mut backend, + "timeline.place_clip", + json!({"track": track, "footage": footage_id, "in": 0}), + ) + .expect("place"); + let expect = expectation_for("timeline.place_clip", &placed).expect("expectation"); + + let after = probe(&mut backend).expect("probe"); + let report = verify(None, &after, expect); + assert!(report.ok, "{report:?}"); + } + + /// ⑪ A write that lies (result names an id the state lacks) fails. + #[test] + fn a_lying_result_is_caught() { + let mut backend = MockBackend::new(); + dispatch::execute(&mut backend, "project.open", json!({"name": "rb", "fps": 30})) + .expect("open"); + let after = probe(&mut backend).expect("probe"); + let report = verify( + None, + &after, + Expect::IdsPresent(vec!["clip-does-not-exist".into()]), + ); + assert!(!report.ok); + assert!(report.diff.expect("diff").contains("clip-does-not-exist")); + } + + /// ⑫ A delete is verified against **observable state**: after + /// `timeline.ripple_delete` the clip id must be gone from the + /// overview — the return body claiming `removed: true` proves nothing. + #[test] + fn a_delete_is_verified_against_the_overview() { + let mut backend = MockBackend::new(); + dispatch::execute(&mut backend, "project.open", json!({"name": "rb", "fps": 30})) + .expect("open"); + std::fs::write("/tmp/oak-readback-fixture.mp4", b"x").expect("fixture"); + let footage = dispatch::execute( + &mut backend, + "media.import_footage", + json!({"paths": ["/tmp/oak-readback-fixture.mp4"]}), + ) + .expect("import"); + let footage_id = footage["footage"][0]["id"].as_str().expect("id").to_string(); + let track = dispatch::execute(&mut backend, "timeline.add_track", json!({"type": "video"})) + .expect("track")["track"] + .as_str() + .expect("track id") + .to_string(); + let placed = dispatch::execute( + &mut backend, + "timeline.place_clip", + json!({"track": track, "footage": footage_id, "in": 0}), + ) + .expect("place"); + let clip_id = placed["clip"].as_str().expect("clip id").to_string(); + + let before = probe(&mut backend).expect("probe"); + assert!(contains_string(&before, &clip_id), "the clip exists before the delete"); + let deleted = dispatch::execute( + &mut backend, + "timeline.ripple_delete", + json!({"clip": clip_id}), + ) + .expect("delete"); + assert_eq!(deleted["removed"], true, "the tool claims it deleted"); + + let expect = expectation_for("timeline.ripple_delete", &deleted).expect("expectation"); + assert!( + matches!(expect, Expect::IdsGone(_)), + "a delete must be checked as gone, not merely changed: {expect:?}" + ); + let after = probe(&mut backend).expect("probe"); + assert!( + !contains_string(&after, &clip_id), + "the observable state must no longer contain the clip" + ); + let report = verify(Some(&before), &after, expect); + assert!(report.ok, "{report:?}"); + } + + /// ⑬ The negative case (lead's requirement): the expectation is *not* + /// met ⇒ the readback **fails**, whichever way it is missed. + #[test] + fn a_delete_that_left_the_clip_in_state_fails() { + let before = json!({ + "sequences": [{ + "id": "sequence-1", + "tracks": [{ "id": "track-1", "clips": [{ "id": "clip-7" }] }] + }] + }); + + // (a) The state did not move at all: the id is still there. + let unchanged = before.clone(); + let report = verify(Some(&before), &unchanged, Expect::IdsGone(vec!["clip-7".into()])); + assert!(!report.ok, "an unmet expectation must fail"); + let diff = report.diff.as_ref().expect("a failure carries a diff"); + assert!(diff.contains("still contains") || diff.contains("identical"), "{diff}"); + assert_eq!(report.failure_payload()["code"], "READBACK_MISMATCH"); + + // (b) The state moved for other reasons but the deleted clip is + // still present: presence wins — the id must be gone. + let mut moved = before.clone(); + moved["sequences"][0]["tracks"] + .as_array_mut() + .expect("tracks") + .push(json!({"id": "track-2", "clips": []})); + let report = verify(Some(&before), &moved, Expect::IdsGone(vec!["clip-7".into()])); + assert!(!report.ok, "state change alone must not excuse a surviving id"); + assert!( + report.diff.expect("diff").contains("still contains"), + "the diff must name what survived" + ); + } + +} diff --git a/crates/oak-app/src/panels/ai_assistant/tests.rs b/crates/oak-app/src/panels/ai_assistant/tests.rs index b9449bf726..723487067e 100644 --- a/crates/oak-app/src/panels/ai_assistant/tests.rs +++ b/crates/oak-app/src/panels/ai_assistant/tests.rs @@ -154,6 +154,7 @@ fn append_report_surfaces_a_stall_as_a_notice() { text_fallback_calls: 0, unparsed_text_calls: 0, unparsed_text: None, + ..Default::default() }; append_report(&mut bubbles, &report); @@ -192,6 +193,7 @@ fn append_report_reports_unparsed_text_markup() { text_fallback_calls: 0, unparsed_text_calls: 1, unparsed_text: Some(raw.to_string()), + ..Default::default() }; append_report(&mut bubbles, &report); @@ -221,6 +223,7 @@ fn append_report_reports_unparsed_text_markup() { ); } +#[test] fn append_report_orders_tools_then_answer() { let tool = |name: &str, outcome: &'static str| ToolLogEntry { round: 1, @@ -241,6 +244,7 @@ fn append_report_orders_tools_then_answer() { text_fallback_calls: 0, unparsed_text_calls: 0, unparsed_text: None, + ..Default::default() }; append_report(&mut bubbles, &report); assert_eq!( @@ -275,6 +279,7 @@ fn capped_run_becomes_the_round_limit_notice() { text_fallback_calls: 0, unparsed_text_calls: 0, unparsed_text: None, + ..Default::default() }; append_report(&mut bubbles, &report); assert_eq!(