Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
194 changes: 194 additions & 0 deletions oxa/oxa-cli/src/lead/cards.rs
Original file line number Diff line number Diff line change
@@ -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<Self, Unavailable> {
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<Self, Unavailable> {
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<Self, Unavailable> {
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<E>(
command: &str,
now_ms: u64,
max_age_ms: u64,
read: impl FnOnce() -> Result<Snapshot, E>,
) -> Option<String> {
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}')
}
2 changes: 2 additions & 0 deletions oxa/oxa-cli/src/lead/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
//! Lead presentation over runner-independent typed facts. No state reads or writes.
pub mod cards;
1 change: 1 addition & 0 deletions oxa/oxa-cli/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
152 changes: 152 additions & 0 deletions oxa/oxa-cli/tests/lead_cards.rs
Original file line number Diff line number Diff line change
@@ -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::<Snapshot, _>("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}')));
}
}
Loading
Loading