use crate::program_resume;
use crate::program_status::{self, ProgramStatus};
use crate::transcript_follow::should_use_color;
use anyhow::{bail, Context, Result};
use clap::Subcommand;
use minutes_core::meeting_doc::{
AgendaStatus, AgentAgendaUpdate, AgentSectionWrite, Citation, MeetingDoc, MeetingDocError,
MeetingDocStore, SectionKind, UserDecisionAction, WriteOutcome,
};
use minutes_core::Config;
use std::io::{self, IsTerminal, Read, Write};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, SystemTime};
#[derive(Subcommand, Debug)]
pub enum DocAction {
Init {
#[arg(long)]
session: Option<String>,
#[arg(long)]
title: Option<String>,
#[arg(long = "agenda")]
agenda: Vec<String>,
},
Show {
#[arg(long)]
session: Option<String>,
#[arg(long)]
section: Option<String>,
#[arg(long, default_value = "md", value_parser = ["md", "json"])]
format: String,
},
Note {
text: String,
#[arg(long)]
session: Option<String>,
},
AddAgenda {
text: String,
#[arg(long)]
session: Option<String>,
},
Write {
#[arg(long)]
section: String,
#[arg(long)]
rev: u64,
#[arg(long)]
agent: String,
#[arg(long = "cite", required = true)]
cite: Vec<String>,
#[arg(long)]
text: Option<String>,
#[arg(long)]
ttl: Option<u64>,
#[arg(long)]
session: Option<String>,
},
Agenda {
#[arg(long)]
item: String,
#[arg(long)]
status: String,
#[arg(long)]
rev: u64,
#[arg(long)]
agent: String,
#[arg(long = "cite", required = true)]
cite: Vec<String>,
#[arg(long)]
session: Option<String>,
},
Accept {
#[arg(long)]
section: String,
#[arg(long)]
item: String,
#[arg(long)]
session: Option<String>,
},
Dismiss {
#[arg(long)]
section: String,
#[arg(long)]
item: String,
#[arg(long)]
session: Option<String>,
},
Freeze {
#[arg(long)]
session: Option<String>,
},
Watch {
#[arg(long)]
session: Option<String>,
},
}
pub fn cmd_doc(action: DocAction, config: &Config) -> Result<()> {
let store = MeetingDocStore::default_store();
if let DocAction::Watch { session } = action {
return cmd_doc_watch(session.as_deref(), &store, config);
}
run(action, &store, &mut std::io::stdout())
}
fn parse_citations(specs: &[String]) -> Result<Vec<Citation>> {
specs
.iter()
.map(|spec| Citation::parse_spec(spec).map_err(anyhow::Error::from))
.collect()
}
fn read_content(text: Option<String>) -> Result<String> {
match text {
Some(text) if text != "-" => Ok(text),
_ => {
let mut buf = String::new();
std::io::stdin()
.read_to_string(&mut buf)
.context("reading content from stdin")?;
Ok(buf)
}
}
}
fn active_capture_session() -> Option<String> {
#[cfg(feature = "whisper")]
{
minutes_core::live_transcript::session_status()
.session_id
.filter(|id| !id.trim().is_empty())
}
#[cfg(not(feature = "whisper"))]
{
None
}
}
fn report(outcome: &WriteOutcome, what: &str, out: &mut impl std::io::Write) -> Result<()> {
writeln!(out, "{what} (doc revision {}).", outcome.doc.revision)?;
if outcome.projection_tamper_detected {
eprintln!(
"[minutes] meeting-doc.md had been edited directly; it was rewritten from the record. Edit the doc with `minutes doc` instead."
);
}
Ok(())
}
fn run(action: DocAction, store: &MeetingDocStore, out: &mut impl std::io::Write) -> Result<()> {
match action {
DocAction::Init {
session,
title,
agenda,
} => {
let session = match session.or_else(active_capture_session) {
Some(session) => session,
None => bail!(
"no active capture session; start `minutes live` or `minutes record`, or pass --session"
),
};
let doc = store.init(session, title, &agenda)?;
writeln!(
out,
"Meeting doc created for session {} with {} agenda item(s): {}",
doc.session_id,
doc.agenda.items.len(),
store.projection_path().display()
)?;
}
DocAction::Show {
session,
section,
format,
} => {
let doc = store.load(session.as_deref())?;
match (format.as_str(), section) {
("json", None) => writeln!(out, "{}", serde_json::to_string_pretty(&doc)?)?,
("json", Some(section)) => {
let kind = SectionKind::parse(§ion)?;
let value = serde_json::to_value(&doc)?;
let part = value
.get(kind.as_str())
.cloned()
.unwrap_or(serde_json::Value::Null);
writeln!(out, "{}", serde_json::to_string_pretty(&part)?)?;
}
(_, Some(_)) => bail!("--section needs --format json"),
_ => write!(out, "{}", doc.render_markdown())?,
}
}
DocAction::Note { text, session } => {
let outcome = store.append_user_note(session.as_deref(), &text, None)?;
report(&outcome, "Note added", out)?;
}
DocAction::AddAgenda { text, session } => {
let outcome = store.add_agenda_item(session.as_deref(), &text)?;
report(&outcome, "Agenda item added", out)?;
}
DocAction::Write {
section,
rev,
agent,
cite,
text,
ttl,
session,
} => {
let content = read_content(text)?;
let outcome = store.apply_agent_write(AgentSectionWrite {
session_id: session,
section: SectionKind::parse(§ion)?,
expected_rev: rev,
agent_id: agent,
content,
citations: parse_citations(&cite)?,
ttl_secs: ttl,
})?;
report(&outcome, "Section written", out)?;
}
DocAction::Agenda {
item,
status,
rev,
agent,
cite,
session,
} => {
let outcome = store.apply_agent_agenda_status(AgentAgendaUpdate {
session_id: session,
item_id: item,
status: AgendaStatus::parse(&status)?,
expected_rev: rev,
agent_id: agent,
citations: parse_citations(&cite)?,
})?;
report(&outcome, "Agenda status updated", out)?;
}
DocAction::Accept {
section,
item,
session,
} => decide(store, session, §ion, &item, "accept", out)?,
DocAction::Dismiss {
section,
item,
session,
} => decide(store, session, §ion, &item, "dismiss", out)?,
DocAction::Freeze { session } => {
let outcome = store.freeze(session.as_deref())?;
report(&outcome, "Agent sections frozen", out)?;
}
DocAction::Watch { .. } => {
bail!("`minutes doc watch` runs as an interactive renderer via cmd_doc");
}
}
Ok(())
}
#[derive(Debug, Clone, Copy)]
pub struct WatchOptions {
pub poll_interval: Duration,
pub is_tty: bool,
pub use_color: bool,
}
impl WatchOptions {
pub fn for_cli() -> Self {
let is_tty = io::stdout().is_terminal();
let use_color = should_use_color(
is_tty && io::stderr().is_terminal(),
std::env::var_os("NO_COLOR").is_some(),
std::env::var("TERM").ok().as_deref(),
);
Self {
poll_interval: Duration::from_millis(250),
is_tty,
use_color,
}
}
}
fn is_bidi_control(ch: char) -> bool {
matches!(
ch,
'\u{061C}'
| '\u{200E}'
| '\u{200F}'
| '\u{202A}'..='\u{202E}'
| '\u{2066}'..='\u{2069}'
)
}
pub fn sanitize_terminal_multiline(input: &str) -> String {
let mut out = String::with_capacity(input.len());
for ch in input.chars() {
match ch {
'\n' => out.push('\n'),
'\r' => {}
'\t' => out.push_str(" "),
c if c.is_control() || is_bidi_control(c) => {}
c => out.push(c),
}
}
out
}
pub fn format_agenda_progress(doc: &MeetingDoc) -> Option<String> {
let total = doc.agenda.items.len();
if total == 0 {
return None;
}
let covered = doc
.agenda
.items
.iter()
.filter(|i| i.status == AgendaStatus::Covered)
.count();
let skipped = doc
.agenda
.items
.iter()
.filter(|i| i.status == AgendaStatus::Skipped)
.count();
const BAR_WIDTH: usize = 12;
let filled = (covered * BAR_WIDTH) / total;
let empty = BAR_WIDTH.saturating_sub(filled);
let bar = format!("{}{}", "█".repeat(filled), "░".repeat(empty));
if skipped > 0 {
Some(format!(
"Agenda: {covered}/{total} covered ({skipped} skipped) [{bar}]"
))
} else {
Some(format!("Agenda: {covered}/{total} covered [{bar}]"))
}
}
pub fn render_watch_frame(doc: &MeetingDoc, options: WatchOptions, frame_index: usize) -> String {
let sanitized = sanitize_terminal_multiline(&doc.render_markdown());
let progress = format_agenda_progress(doc);
let mut out = String::with_capacity(sanitized.len() + 192);
if options.is_tty {
out.push_str("\x1b[2J\x1b[H");
} else if frame_index > 0 {
out.push_str("\n---\n");
}
let mut inserted_progress = false;
for line in sanitized.lines() {
if options.use_color {
if line.starts_with("# ") {
out.push_str("\x1b[1;36m");
out.push_str(line);
out.push_str("\x1b[0m\n");
} else if line.starts_with("## ") {
out.push_str("\x1b[1;33m");
out.push_str(line);
out.push_str("\x1b[0m\n");
} else if line.starts_with("> ") {
out.push_str("\x1b[2m");
out.push_str(line);
out.push_str("\x1b[0m\n");
} else if line.starts_with("- [x] ") || line.contains("**[accepted by user]**") {
out.push_str("\x1b[32m");
out.push_str(line);
out.push_str("\x1b[0m\n");
} else {
out.push_str(line);
out.push('\n');
}
} else {
out.push_str(line);
out.push('\n');
}
if !inserted_progress && line.starts_with("> ") {
if let Some(ref strip) = progress {
if options.use_color {
out.push_str("\x1b[36m");
out.push_str(strip);
out.push_str("\x1b[0m\n");
} else {
out.push_str(strip);
out.push('\n');
}
}
inserted_progress = true;
}
}
if options.is_tty {
let state = if doc.frozen { "frozen" } else { "live" };
let footer = format!(
"\nWatching meeting doc · rev {} · {} · Ctrl-C to exit\n",
doc.revision, state
);
if options.use_color {
out.push_str("\x1b[2m");
out.push_str(&footer);
out.push_str("\x1b[0m");
} else {
out.push_str(&footer);
}
}
out
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct FileMetaStamp {
modified: Option<SystemTime>,
len: u64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct DocSnapshotId {
session_id: String,
revision: u64,
frozen: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum NoticeKind {
None,
WaitingForDoc,
SessionMismatch,
ReadError,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WatchDocStatus {
Waiting,
Live,
Frozen,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WatchStep {
Continue { frozen: Option<bool> },
Stop,
}
pub struct DocWatchState {
options: WatchOptions,
last_meta: Option<FileMetaStamp>,
last_snapshot: Option<DocSnapshotId>,
last_notice: NoticeKind,
rendered_frames: usize,
}
impl DocWatchState {
pub fn new(options: WatchOptions) -> Self {
Self {
options,
last_meta: None,
last_snapshot: None,
last_notice: NoticeKind::None,
rendered_frames: 0,
}
}
pub fn step(
&mut self,
store: &MeetingDocStore,
session: Option<&str>,
out: &mut impl Write,
err: &mut impl Write,
) -> Result<WatchStep> {
let store_path = store.store_path();
let meta = match std::fs::metadata(&store_path) {
Ok(m) => FileMetaStamp {
modified: m.modified().ok(),
len: m.len(),
},
Err(e) if e.kind() == io::ErrorKind::NotFound => {
self.last_meta = None;
self.last_snapshot = None;
if self.last_notice != NoticeKind::WaitingForDoc {
let _ = write_notice(
err,
self.options.use_color,
"[minutes] Waiting for active meeting doc... (run `minutes doc init` · Ctrl-C to exit)",
);
self.last_notice = NoticeKind::WaitingForDoc;
}
return Ok(WatchStep::Continue { frozen: None });
}
Err(_) => {
if self.last_notice != NoticeKind::ReadError {
let _ = write_notice(
err,
self.options.use_color,
"[minutes] Unable to inspect meeting doc store; retrying...",
);
self.last_notice = NoticeKind::ReadError;
}
return Ok(WatchStep::Continue {
frozen: self.last_snapshot.as_ref().map(|s| s.frozen),
});
}
};
if self.last_meta.as_ref() == Some(&meta)
&& (self.last_snapshot.is_some() || self.last_notice == NoticeKind::SessionMismatch)
{
return Ok(WatchStep::Continue {
frozen: self.last_snapshot.as_ref().map(|s| s.frozen),
});
}
match store.load(session) {
Ok(doc) => {
self.last_meta = Some(meta);
self.last_notice = NoticeKind::None;
let snapshot = DocSnapshotId {
session_id: doc.session_id.clone(),
revision: doc.revision,
frozen: doc.frozen,
};
if self.last_snapshot.as_ref() == Some(&snapshot) {
return Ok(WatchStep::Continue {
frozen: Some(doc.frozen),
});
}
let frame = render_watch_frame(&doc, self.options, self.rendered_frames);
if let Err(e) = out.write_all(frame.as_bytes()).and_then(|()| out.flush()) {
if e.kind() == io::ErrorKind::BrokenPipe {
return Ok(WatchStep::Stop);
}
return Err(e.into());
}
self.rendered_frames += 1;
self.last_snapshot = Some(snapshot);
Ok(WatchStep::Continue {
frozen: Some(doc.frozen),
})
}
Err(MeetingDocError::NotFound) => {
self.last_meta = None;
self.last_snapshot = None;
if self.last_notice != NoticeKind::WaitingForDoc {
let _ = write_notice(
err,
self.options.use_color,
"[minutes] Waiting for active meeting doc... (run `minutes doc init` · Ctrl-C to exit)",
);
self.last_notice = NoticeKind::WaitingForDoc;
}
Ok(WatchStep::Continue { frozen: None })
}
Err(MeetingDocError::SessionMismatch { .. }) => {
self.last_meta = Some(meta);
self.last_snapshot = None;
if self.last_notice != NoticeKind::SessionMismatch {
let _ = write_notice(
err,
self.options.use_color,
"[minutes] Active meeting doc belongs to a different session; waiting...",
);
self.last_notice = NoticeKind::SessionMismatch;
}
Ok(WatchStep::Continue { frozen: None })
}
Err(_) => {
if self.last_notice != NoticeKind::ReadError {
let _ = write_notice(
err,
self.options.use_color,
"[minutes] Meeting doc is temporarily unreadable; retrying...",
);
self.last_notice = NoticeKind::ReadError;
}
Ok(WatchStep::Continue {
frozen: self.last_snapshot.as_ref().map(|s| s.frozen),
})
}
}
}
}
fn write_notice(err: &mut impl Write, use_color: bool, message: &str) -> io::Result<()> {
if use_color {
writeln!(err, "\x1b[2m{message}\x1b[0m")?;
} else {
writeln!(err, "{message}")?;
}
err.flush()
}
pub fn watch_doc(
store: &MeetingDocStore,
session: Option<&str>,
options: WatchOptions,
stop: &AtomicBool,
out: &mut impl Write,
err: &mut impl Write,
mut on_status_change: impl FnMut(WatchDocStatus),
) -> Result<()> {
let mut state = DocWatchState::new(options);
let mut last_reported: Option<WatchDocStatus> = None;
while !stop.load(Ordering::Relaxed) {
match state.step(store, session, out, err)? {
WatchStep::Stop => break,
WatchStep::Continue { frozen } => {
let next_status = match frozen {
Some(true) => WatchDocStatus::Frozen,
Some(false) => WatchDocStatus::Live,
None => WatchDocStatus::Waiting,
};
if last_reported != Some(next_status) {
on_status_change(next_status);
last_reported = Some(next_status);
}
}
}
if stop.load(Ordering::Relaxed) {
break;
}
let mut remaining = options.poll_interval;
let slice = Duration::from_millis(50);
while !remaining.is_zero() && !stop.load(Ordering::Relaxed) {
let nap = remaining.min(slice);
std::thread::sleep(nap);
remaining = remaining.saturating_sub(nap);
}
}
Ok(())
}
fn cmd_doc_watch(session: Option<&str>, store: &MeetingDocStore, config: &Config) -> Result<()> {
let stop = Arc::new(AtomicBool::new(false));
let stop_clone = Arc::clone(&stop);
let _ = ctrlc::set_handler(move || {
stop_clone.store(true, Ordering::Relaxed);
});
#[cfg(unix)]
unsafe {
libc::signal(libc::SIGHUP, libc::SIG_DFL);
libc::signal(libc::SIGTERM, libc::SIG_DFL);
}
let mut resume_argv: Vec<&str> = vec!["minutes", "doc", "watch"];
if let Some(s) = session.map(str::trim).filter(|s| !s.is_empty()) {
resume_argv.push("--session");
resume_argv.push(s);
}
let _resume_guard = program_resume::ResumeGuard::register_view(&resume_argv);
let status = ProgramStatus::from_config(config);
status.report(program_status::State::Working, None, "Watching meeting doc");
let options = WatchOptions::for_cli();
let mut stdout = io::stdout().lock();
let mut stderr = io::stderr().lock();
watch_doc(
store,
session,
options,
&stop,
&mut stdout,
&mut stderr,
|doc_status| match doc_status {
WatchDocStatus::Frozen => {
status.report(program_status::State::Done, None, "Meeting doc frozen");
}
WatchDocStatus::Live => {
status.report(program_status::State::Working, None, "Watching meeting doc");
}
WatchDocStatus::Waiting => {
status.report(
program_status::State::Working,
None,
"Waiting for meeting doc",
);
}
},
)
}
fn decide(
store: &MeetingDocStore,
session: Option<String>,
section: &str,
item: &str,
action: &str,
out: &mut impl std::io::Write,
) -> Result<()> {
let outcome = store.decide_proposal(
session.as_deref(),
SectionKind::parse(section)?,
item,
UserDecisionAction::parse(action)?,
)?;
let what = if action == "accept" {
"Accepted"
} else {
"Dismissed"
};
report(&outcome, what, out)
}
#[cfg(test)]
mod tests {
use super::*;
fn store(dir: &std::path::Path) -> MeetingDocStore {
MeetingDocStore::in_dir(
dir.join("live-doc"),
dir.join("agents.allow"),
Some(dir.join("current-notes.md")),
)
}
fn run_ok(action: DocAction, store: &MeetingDocStore) -> String {
let mut out = Vec::new();
run(action, store, &mut out).unwrap();
String::from_utf8(out).unwrap()
}
fn write(section: &str, rev: u64, text: &str) -> DocAction {
DocAction::Write {
section: section.into(),
rev,
agent: "claude".into(),
cite: vec!["transcript_final:line-3".into()],
text: Some(text.into()),
ttl: None,
session: None,
}
}
#[test]
fn doc_cli_round_trip_respects_grants_revisions_and_freeze() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
run_ok(
DocAction::Init {
session: Some("s-1".into()),
title: Some("Pricing".into()),
agenda: vec!["Q1 pricing".into()],
},
&store,
);
let mut out = Vec::new();
assert!(run(write("outline", 0, "1. Pricing"), &store, &mut out).is_err());
std::fs::write(
dir.path().join("agents.allow"),
"claude: live_doc.outline\n",
)
.unwrap();
assert!(run_ok(write("outline", 0, "1. Pricing"), &store).contains("Section written"));
assert!(run(write("outline", 0, "x"), &store, &mut out).is_err());
assert!(run(write("advice", 0, "x"), &store, &mut out).is_err());
run_ok(
DocAction::Note {
text: "my note".into(),
session: None,
},
&store,
);
let md = run_ok(
DocAction::Show {
session: None,
section: None,
format: "md".into(),
},
&store,
);
assert!(md.contains("1. Pricing") && md.contains("my note"));
assert!(!md.contains("__"), "projection must not nest italics: {md}");
let outline = run_ok(
DocAction::Show {
session: None,
section: Some("outline".into()),
format: "json".into(),
},
&store,
);
let outline: serde_json::Value = serde_json::from_str(&outline).unwrap();
assert_eq!(outline["rev"], 1);
assert!(run(
DocAction::Show {
session: Some("other".into()),
section: None,
format: "md".into(),
},
&store,
&mut out,
)
.is_err());
run_ok(DocAction::Freeze { session: None }, &store);
assert!(run(write("outline", 1, "late"), &store, &mut out).is_err());
run_ok(
DocAction::Note {
text: "after".into(),
session: None,
},
&store,
);
}
#[test]
fn show_section_requires_json() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
run_ok(
DocAction::Init {
session: Some("s-1".into()),
title: None,
agenda: Vec::new(),
},
&store,
);
let mut out = Vec::new();
let err = run(
DocAction::Show {
session: None,
section: Some("outline".into()),
format: "md".into(),
},
&store,
&mut out,
)
.unwrap_err();
assert!(err.to_string().contains("--format json"));
}
#[test]
fn sanitize_terminal_multiline_strips_ansi_and_bidi_controls_preserving_newlines() {
let raw = "# Safe\r\n\x1b[31mred\x07\n\tindented\u{202E}spoof\u{2066}text\u{200F}\n";
let clean = sanitize_terminal_multiline(raw);
assert_eq!(clean, "# Safe\n[31mred\n indentedspooftext\n");
}
#[test]
fn agenda_progress_formats_covered_and_skipped_counts() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let doc = store
.init(
"s-1",
Some("Review".into()),
&["A".into(), "B".into(), "C".into(), "D".into()],
)
.unwrap();
assert_eq!(
format_agenda_progress(&doc).as_deref(),
Some("Agenda: 0/4 covered [░░░░░░░░░░░░]")
);
std::fs::write(dir.path().join("agents.allow"), "claude: live_doc.agenda\n").unwrap();
let out1 = store
.apply_agent_agenda_status(AgentAgendaUpdate {
session_id: None,
item_id: "a1".into(),
status: AgendaStatus::Covered,
expected_rev: 1,
agent_id: "claude".into(),
citations: vec![Citation::parse_spec("transcript_final:line-1").unwrap()],
})
.unwrap();
let out2 = store
.apply_agent_agenda_status(AgentAgendaUpdate {
session_id: None,
item_id: "a2".into(),
status: AgendaStatus::Skipped,
expected_rev: out1.doc.agenda.rev,
agent_id: "claude".into(),
citations: vec![Citation::parse_spec("transcript_final:line-2").unwrap()],
})
.unwrap();
assert_eq!(
format_agenda_progress(&out2.doc).as_deref(),
Some("Agenda: 1/4 covered (1 skipped) [███░░░░░░░░░]")
);
}
#[test]
fn watch_state_waits_renders_deduplicates_updates_and_handles_freeze() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
let opts = WatchOptions {
poll_interval: Duration::from_millis(10),
is_tty: false,
use_color: false,
};
let mut state = DocWatchState::new(opts);
let mut out = Vec::new();
let mut err = Vec::new();
assert_eq!(
state.step(&store, None, &mut out, &mut err).unwrap(),
WatchStep::Continue { frozen: None }
);
assert_eq!(
state.step(&store, None, &mut out, &mut err).unwrap(),
WatchStep::Continue { frozen: None }
);
let err_str = String::from_utf8(err.clone()).unwrap();
assert_eq!(err_str.matches("Waiting for active meeting doc").count(), 1);
assert!(out.is_empty());
store
.init("s-1", Some("Weekly Sync".into()), &["Roadmap".into()])
.unwrap();
assert_eq!(
state.step(&store, None, &mut out, &mut err).unwrap(),
WatchStep::Continue {
frozen: Some(false)
}
);
let first_len = out.len();
let first_out = String::from_utf8(out.clone()).unwrap();
assert!(first_out.contains("# Weekly Sync"));
assert!(first_out.contains("Agenda: 0/1 covered"));
assert_eq!(
state.step(&store, None, &mut out, &mut err).unwrap(),
WatchStep::Continue {
frozen: Some(false)
}
);
assert_eq!(out.len(), first_len);
std::fs::write(
dir.path().join("agents.allow"),
"claude: live_doc.outline\n",
)
.unwrap();
store
.apply_agent_write(AgentSectionWrite {
session_id: Some("s-1".into()),
section: SectionKind::Outline,
expected_rev: 0,
agent_id: "claude".into(),
content: "Point \x1b[31m\u{202E}one".into(),
citations: vec![Citation::parse_spec("transcript_final:line-4").unwrap()],
ttl_secs: None,
})
.unwrap();
assert_eq!(
state.step(&store, None, &mut out, &mut err).unwrap(),
WatchStep::Continue {
frozen: Some(false)
}
);
let after_write = String::from_utf8(out.clone()).unwrap();
assert!(after_write.contains("\n---\n"));
assert!(!after_write.contains('\x1b'));
assert!(!after_write.contains('\u{202E}'));
assert!(after_write.contains("Point [31mone"));
store.freeze(None).unwrap();
assert_eq!(
state.step(&store, None, &mut out, &mut err).unwrap(),
WatchStep::Continue { frozen: Some(true) }
);
let after_freeze = String::from_utf8(out).unwrap();
assert!(after_freeze.contains("`frozen`"));
}
#[test]
fn watch_state_session_mismatch_waits_without_leaking_session_id() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
store.init("secret-session-42", None, &[]).unwrap();
let opts = WatchOptions {
poll_interval: Duration::from_millis(10),
is_tty: false,
use_color: false,
};
let mut state = DocWatchState::new(opts);
let mut out = Vec::new();
let mut err = Vec::new();
assert_eq!(
state
.step(&store, Some("other-session"), &mut out, &mut err)
.unwrap(),
WatchStep::Continue { frozen: None }
);
assert!(out.is_empty());
let err_str = String::from_utf8(err).unwrap();
assert!(err_str.contains("belongs to a different session"));
assert!(!err_str.contains("secret-session-42"));
assert!(!err_str.contains("other-session"));
}
struct BrokenPipeWriter;
impl Write for BrokenPipeWriter {
fn write(&mut self, _buf: &[u8]) -> io::Result<usize> {
Err(io::Error::new(io::ErrorKind::BrokenPipe, "closed"))
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
#[test]
fn watch_state_exits_cleanly_on_broken_pipe() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
store.init("s-1", None, &[]).unwrap();
let opts = WatchOptions {
poll_interval: Duration::from_millis(10),
is_tty: false,
use_color: false,
};
let mut state = DocWatchState::new(opts);
let mut out = BrokenPipeWriter;
let mut err = Vec::new();
assert_eq!(
state.step(&store, None, &mut out, &mut err).unwrap(),
WatchStep::Stop
);
}
#[test]
fn watch_doc_resets_status_when_frozen_doc_is_deleted() {
let dir = tempfile::tempdir().unwrap();
let store = store(dir.path());
store.init("s-1", Some("Weekly".into()), &[]).unwrap();
let opts = WatchOptions {
poll_interval: Duration::from_millis(5),
is_tty: false,
use_color: false,
};
let stop = AtomicBool::new(false);
let mut out = Vec::new();
let mut err = Vec::new();
let mut transitions = Vec::new();
watch_doc(&store, None, opts, &stop, &mut out, &mut err, |status| {
transitions.push(status);
match status {
WatchDocStatus::Live => {
store.freeze(None).unwrap();
}
WatchDocStatus::Frozen => {
std::fs::remove_file(store.store_path()).unwrap();
}
WatchDocStatus::Waiting => {
stop.store(true, Ordering::Relaxed);
}
}
})
.unwrap();
assert_eq!(
transitions,
vec![
WatchDocStatus::Live,
WatchDocStatus::Frozen,
WatchDocStatus::Waiting,
]
);
let err_str = String::from_utf8(err).unwrap();
assert!(err_str.contains("Waiting for active meeting doc"));
}
}