diff --git a/oxa/oxa-cli/src/lead/cards.rs b/oxa/oxa-cli/src/lead/cards.rs new file mode 100644 index 00000000..f297d14b --- /dev/null +++ b/oxa/oxa-cli/src/lead/cards.rs @@ -0,0 +1,194 @@ +//! Bounded, deterministic cards for the lead commands. Callers fetch the situation +//! through the runner API; this module never reads files or reconstructs logs. +use oxa_proto::work::{Snapshot, Subject}; + +/// A successfully decoded snapshot is still an observation at its sequence, not a +/// fresh assertion about the machine. The caller supplies its freshness policy. +pub struct Cards { + snapshot: Snapshot, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Unavailable { + Invalid, + Stale, + Future, +} + +impl Cards { + /// Accept the typed result of the runner's public situation read. Validation + /// needs no JSON reparse and does not expose the storage location to cards. + pub fn from_snapshot(snapshot: Snapshot, now_ms: u64, max_age_ms: u64) -> Result { + snapshot.to_json().map_err(|_| Unavailable::Invalid)?; + Self::observed(snapshot, now_ms, max_age_ms) + } + + pub fn decode(bytes: &[u8], now_ms: u64, max_age_ms: u64) -> Result { + let snapshot = Snapshot::from_json(bytes).map_err(|_| Unavailable::Invalid)?; + Self::observed(snapshot, now_ms, max_age_ms) + } + + fn observed(snapshot: Snapshot, now_ms: u64, max_age_ms: u64) -> Result { + let age = now_ms.checked_sub(snapshot.at_ms).ok_or(Unavailable::Future)?; + if age > max_age_ms { + return Err(Unavailable::Stale); + } + Ok(Self { snapshot }) + } + + fn source(&self) -> String { + let s = &self.snapshot; + let standing = if s.standing_revision == 0 { + "unavailable".to_owned() + } else { + s.standing_revision.to_string() + }; + format!( + "Runner observation: seq {} · standing {standing} · at {} ms", + s.as_of_seq, s.at_ms + ) + } + + /// At most 12 physical lines, source included. No queue or hold fact exists in + /// the current Snapshot type, so neither is inferred from blocks or chat. + pub fn status(&self) -> String { + let s = &self.snapshot; + let mut lines = vec![ + self.source(), + format!( + "Goal: {}", + s.goal + .as_deref() + .map(field) + .unwrap_or_else(|| "unavailable".into()) + ), + format!( + "Running: {} · locally accepted: {} · published: {} · merged: {}", + s.running.len(), + s.local_accepted.len(), + s.published.len(), + s.landed.len() + ), + format!( + "Blocked: {} · asks: {} · incidents: {}", + s.blocked.len(), + s.asks.len(), + s.incidents.len() + ), + "Queue / holds / external validation: unavailable in this snapshot".into(), + ]; + for task in s.running.iter().take(2) { + lines.push(format!( + "Running {} on {} · {}", + field(&task.task), + field(&task.host), + field(&task.branch) + )); + } + if s.running.len() > 2 { + lines.push(format!("{} more running tasks", s.running.len() - 2)); + } + if let Some(block) = s.blocked.first() { + lines.push(format!( + "Block: {} · {}", + subject(&block.subject), + field(&block.code) + )); + } + if let Some(ask) = s.asks.first() { + lines.push(format!("Ask {}: {}", field(&ask.id), field(&ask.question))); + } + if s.history_truncated { + lines.push("Terminal / incident history shortened by runner".into()); + } + lines.join("\n") + } + + /// One item at a time. Missing decision metadata is explicit, never invented + /// from the question. This renderer grants no permission to resolve an ask. + pub fn asks(&self) -> String { + let s = &self.snapshot; + let mut lines = vec![self.source()]; + if let Some(ask) = s.asks.first() { + lines.extend([ + format!("Ask {} · {}", field(&ask.id), subject(&ask.subject)), + format!("Question: {}", field(&ask.question)), + "Options / recommendation / meanwhile: unavailable in current facts".into(), + "Ask revision: unavailable; decision write disabled".into(), + format!("{} other open asks", s.asks.len() - 1), + ]); + } else { + lines.push("No open asks in this runner observation".into()); + } + lines.join("\n") + } +} + +/// Fetch a fresh typed observation for each supported command. The lead adapter +/// supplies `|| facts.situation()`; no model, private file or log read is involved. +/// Unknown commands never invoke the reader. Storage errors stay opaque. +pub fn command( + command: &str, + now_ms: u64, + max_age_ms: u64, + read: impl FnOnce() -> Result, +) -> Option { + let render = match command.trim() { + "/status" => Cards::status, + "/asks" => Cards::asks, + _ => return None, + }; + Some( + match read() + .map_err(|_| Unavailable::Invalid) + .and_then(|s| Cards::from_snapshot(s, now_ms, max_age_ms)) + { + Ok(cards) => render(&cards), + Err(reason) => unavailable(reason).to_owned(), + }, + ) +} + +/// No raw error or rejected input is reflected into the terminal. +pub fn unavailable(reason: Unavailable) -> &'static str { + match reason { + Unavailable::Invalid => "Runner facts unavailable: missing or invalid situation; status unknown", + Unavailable::Stale => "Runner facts unavailable: stale situation; status unknown", + Unavailable::Future => "Runner facts unavailable: observation clock is ahead; status unknown", + } +} + +fn subject(value: &Subject) -> String { + match value { + Subject::Repository => "repository".into(), + Subject::Task(id) => format!("task {}", field(id)), + Subject::PullRequest(number) => format!("PR #{number}"), + Subject::Host(id) => format!("host {}", field(id)), + Subject::Inbox(id) => format!("inbox {}", field(id)), + } +} + +// Bounded single-line terminal text even when typed fixtures bypass the decoder. +// Escape controls and bidi formatting; truncate by characters, not UTF-8 bytes. +fn field(value: &str) -> String { + let mut out = String::new(); + for ch in value.chars().take(160) { + if unsafe_glyph(ch) { + out.extend(ch.escape_unicode()); + } else { + out.push(ch); + } + } + if value.chars().count() > 160 { + out.push('…'); + } + out +} + +// Controls and bidi formatting change how one terminal line is displayed. +fn unsafe_glyph(ch: char) -> bool { + let marks = matches!(ch, '\u{061c}' | '\u{200e}' | '\u{200f}'); + let overrides = ('\u{202a}'..='\u{202e}').contains(&ch); + let isolates = ('\u{2066}'..='\u{2069}').contains(&ch); + ch.is_control() || marks || overrides || isolates || matches!(ch, '\u{2028}' | '\u{2029}') +} diff --git a/oxa/oxa-cli/src/lead/mod.rs b/oxa/oxa-cli/src/lead/mod.rs new file mode 100644 index 00000000..8ea5fe15 --- /dev/null +++ b/oxa/oxa-cli/src/lead/mod.rs @@ -0,0 +1,2 @@ +//! Lead presentation over runner-independent typed facts. No state reads or writes. +pub mod cards; diff --git a/oxa/oxa-cli/src/lib.rs b/oxa/oxa-cli/src/lib.rs index a5a074d4..812e7995 100644 --- a/oxa/oxa-cli/src/lib.rs +++ b/oxa/oxa-cli/src/lib.rs @@ -27,6 +27,7 @@ mod home_cwd; mod hooks; mod identity_cmd; mod in_process; +pub mod lead; pub mod lead_access; pub mod lead_input; pub mod lead_page; diff --git a/oxa/oxa-cli/tests/lead_cards.rs b/oxa/oxa-cli/tests/lead_cards.rs new file mode 100644 index 00000000..faaaece9 --- /dev/null +++ b/oxa/oxa-cli/tests/lead_cards.rs @@ -0,0 +1,152 @@ +use oxa_cli::lead::cards::{command, unavailable, Cards, Unavailable}; +use oxa_proto::work::{Ask, Blocked, Running, Snapshot, Subject, TaskStep}; + +fn snapshot() -> Snapshot { + Snapshot { + as_of_seq: 18, + at_ms: 1000, + standing_revision: 4, + goal: Some("Ship a tested change".into()), + running: Vec::new(), + local_accepted: Vec::new(), + published: Vec::new(), + landed: Vec::new(), + blocked: Vec::new(), + asks: Vec::new(), + incidents: Vec::new(), + history_truncated: false, + } +} + +#[test] +fn absent_standing_revision_stays_unavailable() { + let mut observation = snapshot(); + observation.standing_revision = 0; + let cards = Cards::from_snapshot(observation, 1000, 100).unwrap(); + for card in [cards.status(), cards.asks()] { + assert!( + card.lines().next().unwrap().contains("standing unavailable"), + "{card}" + ); + assert!(!card.contains("standing 0")); + } +} + +#[test] +fn crowded_card_keeps_source_and_counts_within_twelve_lines() { + let mut s = snapshot(); + for n in 0..40 { + s.running.push(Running { + task: format!("task-{n}"), + host: "helper".into(), + branch: "feature".into(), + worktree: "worktree".into(), + session_id: None, + step: TaskStep::Preparing, + }); + } + s.blocked.push(Blocked { + subject: Subject::PullRequest(7), + code: "review_needed".into(), + ask_id: Some("A1".into()), + }); + s.asks.push(Ask { + id: "A1".into(), + subject: Subject::PullRequest(7), + question: "Choose scope".into(), + }); + s.history_truncated = true; + let cards = Cards::decode(&s.to_json().unwrap(), 1001, 100).unwrap(); + let card = cards.status(); + assert!(card.lines().count() <= 12, "{card}"); + assert!(card.starts_with("Runner observation: seq 18 · standing 4")); + assert!(card.contains("38 more running tasks")); + assert!(card.contains("merged: 0")); + assert!(card.contains("holds / external validation: unavailable")); + assert!(!card.contains("held: 1")); + let asks = cards.asks(); + assert!(asks.contains("Ask A1 · PR #7")); + assert!(asks.contains("Options / recommendation / meanwhile: unavailable")); + assert!(asks.contains("decision write disabled")); +} + +#[test] +fn commands_fetch_current_typed_facts_and_never_route_mutations() { + let reads = std::cell::Cell::new(0); + let read = || { + reads.set(reads.get() + 1); + let mut s = snapshot(); + s.as_of_seq = reads.get(); + Ok::<_, ()>(s) + }; + assert!(command("/status", 1000, 100, read).unwrap().contains("seq 1 ·")); + assert!(command("/asks", 1000, 100, read).unwrap().contains("seq 2 ·")); + assert_eq!(reads.get(), 2); + for unknown in ["/hold 7", "/status extra", "/approve 7", "/decide A1 yes"] { + assert_eq!(command(unknown, 1000, 100, read), None); + } + assert_eq!(reads.get(), 2); + let missing = command("/status", 1000, 100, || Err::("private diagnostic")); + assert_eq!(missing.as_deref(), Some(unavailable(Unavailable::Invalid))); + assert!(!missing.unwrap().contains("private diagnostic")); + assert_eq!( + command("/asks", 1101, 100, || Ok::<_, ()>(snapshot())).as_deref(), + Some(unavailable(Unavailable::Stale)) + ); + let mut invalid = snapshot(); + invalid.goal = Some("injected\nstatus".into()); + assert!(matches!( + Cards::from_snapshot(invalid, 1000, 100), + Err(Unavailable::Invalid) + )); +} + +#[test] +fn stale_future_and_corrupt_facts_never_turn_into_empty_success() { + let bytes = snapshot().to_json().unwrap(); + assert!(matches!( + Cards::decode(&bytes, 1101, 100), + Err(Unavailable::Stale) + )); + assert!(matches!( + Cards::decode(&bytes, 999, 100), + Err(Unavailable::Future) + )); + assert!(matches!( + Cards::decode(b"{}", 1000, 100), + Err(Unavailable::Invalid) + )); + assert!(matches!(Cards::decode(b"", 1000, 100), Err(Unavailable::Invalid))); + assert!(Cards::decode(&bytes, 1100, 100).is_ok()); + assert!(unavailable(Unavailable::Stale).contains("status unknown")); +} + +#[test] +fn invalid_multiline_snapshot_is_rejected_and_long_unicode_is_bounded() { + let mut s = snapshot(); + s.goal = Some("injected\nRunning: fake".into()); + assert!(s.to_json().is_err()); + s.goal = Some("界".repeat(300)); + let cards = Cards::decode(&s.to_json().unwrap(), 1000, 100).unwrap(); + assert!(cards.status().lines().nth(1).unwrap().ends_with('…')); + assert!(cards.asks().contains("No open asks in this runner observation")); +} + +#[test] +fn accepted_directional_marks_are_escaped_in_goal_and_ask_cards() { + let mut observation = snapshot(); + let text = "before\u{061c}\u{200e}\u{200f}after"; + observation.goal = Some(text.into()); + observation.asks.push(Ask { + id: "A1".into(), + subject: Subject::Repository, + question: text.into(), + }); + let cards = Cards::decode(&observation.to_json().unwrap(), 1000, 100).unwrap(); + for output in [cards.status(), cards.asks()] { + assert!(output.contains(r"before\u{61c}\u{200e}\u{200f}after")); + assert!(!output + .chars() + .any(|ch| matches!(ch, '\u{061c}' | '\u{200e}' | '\u{200f}'))); + } +} diff --git a/oxa/oxa-cli/tests/lead_storage.rs b/oxa/oxa-cli/tests/lead_storage.rs new file mode 100644 index 00000000..d4e909f6 --- /dev/null +++ b/oxa/oxa-cli/tests/lead_storage.rs @@ -0,0 +1,125 @@ +//! Compose the lead cards with the runner's public facts store. +use oxa_cli::lead::cards::command; +use oxa_fake::TestEnv; +use oxa_proto::work::{ + Ask, AskClosed, Blocked, Checkpoint, Evidence, EvidenceKind, Fact, Landed, LocalAcceptance, Publication, + PullRequest, Running, Subject, TaskStep, +}; +use oxa_work::events::Facts; + +#[test] +fn missing_public_store_stays_unknown_without_initialization() { + let env = TestEnv::new(); + let root = env.root().join("absent-facts"); + for name in ["/status", "/asks"] { + let card = command(name, 1000, 100, || Facts::open(&root)?.situation()).unwrap(); + assert!(card.contains("status unknown")); + assert!(!root.exists()); + } +} + +#[test] +fn commands_read_fresh_public_storage_and_keep_acceptance_distinct_from_landing() { + let env = TestEnv::new(); + let facts = Facts::initialize(&env.root().join("facts")).unwrap(); + let head = "1".repeat(40); + let observations = [ + Fact::TaskStarted(Running { + task: "task-1".into(), + host: "helper".into(), + branch: "agent/task-1".into(), + worktree: "~/project/task-1".into(), + session_id: None, + step: TaskStep::Preparing, + }), + Fact::LocalAcceptance(LocalAcceptance { + task: "task-1".into(), + commit: head.clone(), + evidence: Evidence { + kind: EvidenceKind::LocalCheck, + id: "checks-1".into(), + }, + }), + Fact::Blocked(Blocked { + subject: Subject::PullRequest(7), + code: "needs_review".into(), + ask_id: Some("ask-1".into()), + }), + Fact::AskOpened(Ask { + id: "ask-1".into(), + subject: Subject::PullRequest(7), + question: "Choose scope".into(), + }), + ]; + for (index, fact) in observations.into_iter().enumerate() { + facts + .append( + Checkpoint { + source: "fixture".into(), + revision: index as u64 + 1, + }, + 1000, + fact, + ) + .unwrap(); + } + let status = command("/status", 1000, 100, || facts.situation()).unwrap(); + assert!(status.contains("seq 4 ·")); + assert!(status.contains("standing unavailable")); + assert!(status.contains("Running: 1 · locally accepted: 1 · published: 0 · merged: 0")); + assert!(status.contains("Queue / holds / external validation: unavailable")); + assert!(status.contains("Block: PR #7 · needs_review")); + assert!(status.lines().count() <= 12); + let asks = command("/asks", 1000, 100, || facts.situation()).unwrap(); + assert!(asks.contains("Ask ask-1 · PR #7")); + facts + .append( + Checkpoint { + source: "fixture".into(), + revision: 5, + }, + 1001, + Fact::AskClosed(AskClosed { id: "ask-1".into() }), + ) + .unwrap(); + let next = command("/asks", 1001, 100, || facts.situation()).unwrap(); + assert!(next.contains("seq 5 ·")); + assert!(next.contains("No open asks")); + let pr = PullRequest { + number: 7, + head: head.clone(), + }; + facts + .append( + Checkpoint { + source: "fixture".into(), + revision: 6, + }, + 1002, + Fact::Published(Publication { + task: "task-1".into(), + pr: pr.clone(), + }), + ) + .unwrap(); + let published = command("/status", 1002, 100, || facts.situation()).unwrap(); + assert!(published.contains("seq 6 ·")); + assert!(published.contains("locally accepted: 1 · published: 1 · merged: 0")); + facts + .append( + Checkpoint { + source: "fixture".into(), + revision: 7, + }, + 1003, + Fact::PrMerged(Landed { + pr, + merge_commit: head, + merged_at_ms: 1003, + }), + ) + .unwrap(); + let landed = command("/status", 1003, 100, || facts.situation()).unwrap(); + assert!(landed.contains("seq 7 ·")); + assert!(landed.contains("locally accepted: 0 · published: 0 · merged: 1")); +}