hex/src/capture_host/annotate_read.rs
Dax 2ac5e4b582
annotate: agent tools for captures (labs) (#2220)
* Annotate: agent tools that read a capture from the CLI

Adds Labs › Agent tools for captures (off by default, every OS, Annotate
group, labs.annotate_agent_tools) behind four new `hex annotate` commands
that run in the CLI process rather than over the control socket, so they
work with Hex closed and only read files and decode the bundle's video:

- `inspect [<capture>] [--marks] [--json]` prints summary.md, one line per
  mark (or No marks), scrawl.json pretty, or the marks as JSON.
- `zoom [<capture>] (--at <M:SS|secs|phrase> | --mark <n|id> [--frame N])
  [--span secs] [--frames N] [--full]` writes a dense sheet around a moment
  or a mark into <bundle>/zoom/ and prints its path, each cell's time, and
  what was said; a mark prints the mark's line first.
- `frames [<capture>] --from <M:SS|secs> --to <M:SS|secs> [--fps 4]` writes
  one PNG per frame and prints each path.
- `skill` prints the new skills/hex-annotate guide, installed with
  `npx skills add anomalyco/hex --skill hex-annotate`.

They reuse the engine's own primitives (zoom, agent_context, handoff,
sketch) and capture_host::library's bundle resolution, and leave everything
outside <bundle>/zoom/ alone. While the lab is off they refuse naming
`hex labs on annotate-agent-tools`; a build without the capture engine
answers unsupported like the other annotate commands.

Also adds the settings key to the registry, translations for the card, the
skill docs, docs/cli.md, the capture and labs feature maps, the maps'
checks and proof limits, and the four labs goldens the new card moves.

* Annotate agent tools: review fixes

- frames loads the bundle, clamps --to to its durationMs, and refuses a range
  over 240 frames with `invalid` (the count is (to - from) * fps / 1000 + 1),
  so one call can't write a whole recording; the cap is in the skill and both
  docs, and checked_range is tested at the cap, the clamp, and a start past
  the end.
- The hex-annotate skill no longer claims an Install action, says only
  inspect/zoom/frames take a bundle (skill takes none), shows a --mark run
  printing the mark line first with real curly-quoted Said lines, says frames
  falls back to frames/ keyframes without a video, and states the 240 cap.
- The Labs row takes the same Annotate policy lock as Copy a capture as one
  file.
- The capture() doc comment says the four agent reads run in the CLI process
  on every OS.
- crates/router parse_clock_ms multiplies and adds with checked arithmetic, so
  absurd minutes read as no time instead of overflowing; tested.

* Annotate agent tools: Annotate lock and clock bounds

- An organization's DisableAnnotate lock now covers the agent tools lab:
  labs_lock maps it to Lock::Annotate, switches(Lock::Annotate) includes its
  switch, and the gate reads off under the lock through a policy-parameterized
  annotate_agent_tools_under (the same shape as voice_prompt_under). The new
  policy test proves the managed card, setting_lock, the gate under a forced
  lock, enforce turning it off, and keep_saved leaving the saved switch alone.
- parse_clock_ms refuses NaN, infinities, negatives, and values at or past
  u64's range in both the M:SS and bare-seconds branches (seconds_ms), with
  the new 0:1e300, 1e300, 0:NaN, inf, and 0:-1 cases.
- docs/cli.md and the capture map note that frames extracts with ffmpeg from
  PATH when one is installed, as the engine already does.

* Annotate agent tools: count frames as the engine's decoder does

`frames` capped a range by (to - from) * fps / 1000 + 1, but the engine's
own decoder steps inclusively by max(1000 / fps, 1) ms, which asks for more
frames when fps doesn't divide 1000: 240 fps steps 4 ms, so 999 ms is 250
frames, not 240, and the cap let it through.

`checked_range` now counts frame_count's larger of the two formulas, so the
240-frame cap holds whichever decoder runs. The test adds 0-999 ms at
240 fps (refused: 250 frames) and 0-959 ms at 240 fps (allowed: exactly 240
frames, 231 at the rate), and the capture map states both counts.
2026-11-21 13:59:43 -05:00

411 lines
16 KiB
Rust
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//! `hex annotate inspect|zoom|frames`: reading a capture bundle for a coding
//! agent, in the CLI process rather than the running Hex. These only read
//! files and decode the bundle's video, so they work with Hex closed and on
//! every OS; Labs › Agent tools for captures gates them.
use scrawl_capture::model::parse_clock_ms;
use scrawl_capture::{agent_context, handoff, sketch, zoom};
use crate::control::ControlError;
use super::library;
/// `hex annotate inspect`: the agent summary, the marks, or the manifest.
pub(crate) fn inspect(capture: &str, marks: bool, json: bool) -> Result<String, ControlError> {
let dir = library::resolve(capture)?;
let bundle = library::load(&dir).ok_or_else(|| library::unreadable(&dir))?;
if marks {
let entries = agent_context::mark_entries(&bundle);
if json {
let list: Vec<_> = entries.iter().map(agent_context::MarkEntry::json).collect();
return pretty(&serde_json::Value::Array(list));
}
if entries.is_empty() {
return Ok("No marks\n".into());
}
let mut out = String::new();
for entry in &entries {
out.push_str(&entry.line());
out.push('\n');
}
return Ok(out);
}
if json {
// The manifest as written, not a re-serialization of what loads.
let path = dir.join("scrawl.json");
let text = std::fs::read_to_string(&path).map_err(|error| {
ControlError::new(
"not-found",
format!("couldn't read {}: {error}", path.display()),
)
})?;
let manifest: serde_json::Value = serde_json::from_str(&text).map_err(|error| {
ControlError::new(
"not-found",
format!("{} isn't valid JSON: {error}", path.display()),
)
})?;
return pretty(&manifest);
}
let mut out = sketch::summary_markdown(&bundle, &dir);
if !out.ends_with('\n') {
out.push('\n');
}
Ok(out)
}
/// `hex annotate zoom`: a dense sheet of frames around a moment or a mark,
/// with the bundle's ink drawn in.
pub(crate) fn zoom(
capture: &str,
at: Option<&str>,
mark: Option<&str>,
keyframe: Option<usize>,
span_seconds: f64,
count: usize,
full: bool,
) -> Result<String, ControlError> {
if !span_seconds.is_finite() || span_seconds <= 0.0 {
return Err(ControlError::new("invalid", "--span must be positive"));
}
let dir = library::resolve(capture)?;
let bundle = library::load(&dir).ok_or_else(|| library::unreadable(&dir))?;
let (focus, line) = match mark {
Some(query) => {
let entry = agent_context::find_mark(&bundle, query, keyframe)
.map_err(|message| ControlError::new("not-found", message))?;
let line = entry.line();
(zoom::Focus::Mark(entry), Some(line))
}
None => (
zoom::Focus::At(at.ok_or_else(|| ControlError::new("invalid", "pass --at or --mark"))?),
None,
),
};
let span_ms = (span_seconds * 1_000.0) as u64;
let sheet = zoom::zoom(&dir, &bundle, focus, span_ms, count, !full)
.map_err(|error| ControlError::new("failed", format!("{error:#}")))?;
Ok(zoom_text(line.as_deref(), &sheet))
}
/// What `hex annotate zoom` prints: the mark it zoomed into, the sheet's
/// path, each cell's time, and what was said over the window.
fn zoom_text(mark: Option<&str>, sheet: &zoom::ZoomSheet) -> String {
let mut out = String::new();
if let Some(line) = mark {
out.push_str(line);
out.push('\n');
}
out.push_str(&sheet.path.display().to_string());
out.push('\n');
let cells: Vec<String> = sheet
.cells
.iter()
.map(|(index, t)| format!("#{index} {}", zoom::clock(*t)))
.collect();
out.push_str(&format!(
"{} → {}, {} frames: {}",
zoom::clock(sheet.from_ms),
zoom::clock(sheet.to_ms),
sheet.cells.len(),
cells.join(", ")
));
out.push('\n');
if !sheet.said.is_empty() {
out.push_str(&format!("Said: “{}”\n", sheet.said));
}
out
}
/// The most PNGs one `hex annotate frames` writes: a dense look at a range,
/// not a frame-by-frame dump of the whole recording.
const MAX_FRAMES: u64 = 240;
/// `hex annotate frames`: one PNG per frame across a time range.
pub(crate) fn frames(
capture: &str,
from: &str,
to: &str,
fps: u32,
) -> Result<String, ControlError> {
let from_ms = clock_arg("--from", from)?;
let to_ms = clock_arg("--to", to)?;
if to_ms < from_ms {
return Err(ControlError::new(
"invalid",
"the range ends before it starts",
));
}
if !(1..=240).contains(&fps) {
return Err(ControlError::new(
"invalid",
"FPS must be between 1 and 240",
));
}
let dir = library::resolve(capture)?;
let bundle = library::load(&dir).ok_or_else(|| library::unreadable(&dir))?;
let (from_ms, to_ms) = checked_range(from_ms, to_ms, fps, bundle.duration_ms)?;
let paths = handoff::extract_frames_range(&dir, from_ms, to_ms, fps)
.map_err(|error| ControlError::new("failed", format!("{error:#}")))?;
let mut out = String::new();
for path in paths {
out.push_str(&path.display().to_string());
out.push('\n');
}
Ok(out)
}
/// The range `frames` extracts: `to_ms` clamped to the recording's length, so
/// a range past the end never asks the decoder for frames that never existed,
/// and at most [`MAX_FRAMES`] PNGs, counted the way whichever decoder runs
/// counts them, so one call can't write a whole recording frame by frame.
fn checked_range(
from_ms: u64,
to_ms: u64,
fps: u32,
duration_ms: u64,
) -> Result<(u64, u64), ControlError> {
let to_ms = to_ms.min(duration_ms);
if to_ms < from_ms {
return Err(ControlError::new(
"invalid",
"the range ends before it starts",
));
}
if frame_count(from_ms, to_ms, fps) > MAX_FRAMES {
return Err(ControlError::new(
"invalid",
format!("a range writes at most {MAX_FRAMES} frames; narrow it or use a lower --fps"),
));
}
Ok((from_ms, to_ms))
}
/// How many PNGs a range asks for, as the larger of the two counts its
/// decoders produce: `ffmpeg` samples at the rate, and the engine's own
/// decoder steps inclusively by `max(1000 / fps, 1)` ms, which asks for more
/// frames when `fps` doesn't divide 1000 (240 fps steps 4 ms, so 999 ms is
/// 250 frames, not 240). The cap must hold for whichever one runs.
fn frame_count(from_ms: u64, to_ms: u64, fps: u32) -> u64 {
let span = to_ms.saturating_sub(from_ms);
let at_rate = span.saturating_mul(u64::from(fps)) / 1_000 + 1;
let step_ms = (1_000 / u64::from(fps.max(1))).max(1);
let at_decoder_step = span / step_ms + 1;
at_rate.max(at_decoder_step)
}
/// A `--from` or `--to` time: `M:SS`, seconds, or `SS.mmm`.
fn clock_arg(name: &str, value: &str) -> Result<u64, ControlError> {
parse_clock_ms(value)
.ok_or_else(|| ControlError::new("invalid", format!("invalid {name} time: {value}")))
}
fn pretty(value: &serde_json::Value) -> Result<String, ControlError> {
let mut text = serde_json::to_string_pretty(value)
.map_err(|error| ControlError::new("internal", format!("couldn't print JSON: {error}")))?;
text.push('\n');
Ok(text)
}
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use super::*;
/// A bundle on disk with two marks, a transcript, and one keyframe.
fn bundle(root: &std::path::Path) -> PathBuf {
let dir = root.join("1792933491953.scrawl");
std::fs::create_dir_all(&dir).unwrap();
let frame = r#"{"x":0,"y":0,"width":1,"height":1,"scale":2}"#;
let manifest = format!(
r#"{{"version":1,"id":"a","createdAtMs":1792933491953,"durationMs":4000,
"target":{{"mode":"window","app":"Brave","displayId":1,"frame":{frame}}},
"transcript":{{"source":"parakeet","text":"make it blue","segments":[],
"words":[{{"text":"make","t0":0,"t1":200}},{{"text":"it","t0":300,"t1":500}},
{{"text":"blue","t0":600,"t1":900}}]}},
"strokes":[],
"marks":[{{"id":"m1","strokes":[],"t0":1000,"t1":1500,
"boxNorm":[0.1,0.1,0.4,0.4],"shape":"circle","description":"marked"}},
{{"id":"m2","strokes":[],"t0":2500,"t1":3000,
"boxNorm":[0.5,0.5,0.8,0.8],"shape":"circle","description":"marked"}}],
"events":[],
"keyframes":[{{"index":1,"t":1200,"reason":"speech","file":"frames/frame-01.png",
"event":"","markId":"m1"}}],
"contactSheet":"contact-sheet.png"}}"#
);
std::fs::write(dir.join("scrawl.json"), manifest).unwrap();
dir
}
fn temp_root(name: &str) -> PathBuf {
let root = std::env::temp_dir().join(format!(
"hex-annotate-read-{name}-{}",
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
std::fs::create_dir_all(&root).unwrap();
root
}
#[test]
fn marks_print_one_line_each_and_json_is_a_list() {
let root = temp_root("marks");
let dir = bundle(&root);
let path = dir.to_str().unwrap();
let lines = inspect(path, true, false).unwrap();
let lines: Vec<&str> = lines.lines().collect();
assert_eq!(lines.len(), 2, "{lines:?}");
assert!(lines[0].starts_with("#1 ✎ 0:01"), "{}", lines[0]);
assert!(lines[0].ends_with("· m1"), "{}", lines[0]);
assert!(lines[1].ends_with("· m2"), "{}", lines[1]);
let json: serde_json::Value =
serde_json::from_str(&inspect(path, true, true).unwrap()).unwrap();
assert_eq!(json.as_array().unwrap().len(), 2);
assert_eq!(json[1]["id"], "m2");
let _ = std::fs::remove_dir_all(root);
}
#[test]
fn a_bundle_without_marks_says_so_and_manifest_json_is_pretty() {
let root = temp_root("no-marks");
let plain = root.join("1792933491954.scrawl");
std::fs::create_dir_all(&plain).unwrap();
std::fs::write(
plain.join("scrawl.json"),
r#"{"version":1,"id":"b","createdAtMs":1,"durationMs":1000,
"target":{"mode":"display","displayId":0,
"frame":{"x":0,"y":0,"width":1,"height":1,"scale":1}},
"transcript":{"source":"hex","text":"","segments":[],"words":[]},
"strokes":[],"marks":[],"events":[],"keyframes":[],
"contactSheet":"c.png","note":"hello"}"#,
)
.unwrap();
let path = plain.to_str().unwrap();
assert_eq!(inspect(path, true, false).unwrap(), "No marks\n");
let manifest = inspect(path, false, true).unwrap();
assert!(
manifest.contains("\n \"note\": \"hello\",\n"),
"{manifest}"
);
let _ = std::fs::remove_dir_all(root);
}
#[test]
fn the_summary_is_summary_markdown_and_unknown_captures_are_not_found() {
let root = temp_root("summary");
let dir = bundle(&root);
let summary = inspect(dir.to_str().unwrap(), false, false).unwrap();
assert!(summary.ends_with('\n'), "{summary:?}");
assert!(summary.contains("Brave"), "{summary}");
let error = inspect("no-such-capture", false, false).unwrap_err();
assert_eq!(error.code, "not-found");
let _ = std::fs::remove_dir_all(root);
}
#[test]
fn zoom_needs_a_moment_and_a_positive_span() {
let root = temp_root("zoom-args");
let dir = bundle(&root);
let path = dir.to_str().unwrap();
let error = zoom(path, None, None, None, 2.0, 12, false).unwrap_err();
assert_eq!(error.message, "pass --at or --mark");
let error = zoom(path, Some("0:01"), None, None, 0.0, 12, false).unwrap_err();
assert_eq!(error.message, "--span must be positive");
let error = zoom(path, None, Some("9"), None, 2.0, 12, false).unwrap_err();
assert_eq!(error.code, "not-found");
// The bundle has no video to decode, so the sheet fails with why.
let error = zoom(path, Some("0:01"), None, None, 2.0, 12, false).unwrap_err();
assert_eq!(error.message, "The bundle has no video to zoom into");
let _ = std::fs::remove_dir_all(root);
}
/// The lines an agent reads: a mark first when one was asked for, then the
/// sheet's path, each cell's time, and what was said over the window.
#[test]
fn a_sheet_reads_as_its_mark_cells_and_what_was_said() {
let sheet = zoom::ZoomSheet {
path: PathBuf::from("/captures/1792.scrawl/zoom/zoom-9500-11500.png"),
cells: vec![(1, 9_500), (2, 9_681), (3, 9_863)],
from_ms: 9_500,
to_ms: 11_500,
said: "but the width changes".into(),
};
let text = zoom_text(Some("#2 ✎② 0:09 circled · m2"), &sheet);
assert!(text.ends_with('\n'));
let lines: Vec<&str> = text.lines().collect();
assert_eq!(
lines,
vec![
"#2 ✎② 0:09 circled · m2",
&sheet.path.display().to_string(),
"0:09.500 → 0:11.500, 3 frames: #1 0:09.500, #2 0:09.681, #3 0:09.863",
"Said: “but the width changes”",
]
);
let quiet = zoom::ZoomSheet {
said: String::new(),
..sheet
};
let text = zoom_text(None, &quiet);
assert_eq!(text.lines().count(), 2, "{text:?}");
assert!(!text.contains("Said:"), "{text:?}");
}
#[test]
fn frames_reads_both_times_before_the_bundle() {
let error = frames("latest", "0:05", "0:02", 4).unwrap_err();
assert_eq!(error.message, "the range ends before it starts");
let error = frames("latest", "0:01", "0:02", 0).unwrap_err();
assert_eq!(error.message, "FPS must be between 1 and 240");
let error = frames("latest", "soon", "0:02", 4).unwrap_err();
assert_eq!(error.message, "invalid --from time: soon");
}
/// The range is clamped to the recording's length, and one call writes at
/// most 240 PNGs, so a long or hostile range is refused before any video
/// is decoded.
#[test]
fn a_range_is_clamped_to_the_recording_and_capped_at_240_frames() {
assert_eq!(checked_range(0, 9_000, 4, 4_000).unwrap(), (0, 4_000));
assert_eq!(checked_range(0, 59_750, 4, 60_000).unwrap(), (0, 59_750));
let error = checked_range(0, 60_000, 4, 60_000).unwrap_err();
assert_eq!(error.code, "invalid");
assert!(
error.message.contains("at most 240 frames"),
"{}",
error.message
);
// The engine's own decoder steps by max(1000 / fps, 1) ms, so at 240
// fps it asks for 250 frames over 999 ms even though the rate says
// 240; the cap counts the larger formula and refuses.
assert_eq!(frame_count(0, 999, 240), 250);
let error = checked_range(0, 999, 240, 60_000).unwrap_err();
assert_eq!(error.code, "invalid");
assert!(
error.message.contains("at most 240 frames"),
"{}",
error.message
);
// Just within the cap under both formulas: 959 ms is 240 frames
// stepping 4 ms and 231 at the rate.
assert_eq!(frame_count(0, 959, 240), 240);
assert_eq!(checked_range(0, 959, 240, 60_000).unwrap(), (0, 959));
// A range that starts past the end is refused, not clamped to nothing.
let error = checked_range(8_000, 9_000, 4, 4_000).unwrap_err();
assert_eq!(error.message, "the range ends before it starts");
// The cap reaches `frames` before it resolves or decodes a video.
let root = temp_root("frames-cap");
let dir = bundle(&root);
let error = frames(dir.to_str().unwrap(), "0:00", "0:04", 240).unwrap_err();
assert_eq!(error.code, "invalid");
assert!(
error.message.contains("at most 240 frames"),
"{}",
error.message
);
let _ = std::fs::remove_dir_all(root);
}
}