From eef8acae1ddf7a2d1738401a6f93d3fb2532940b Mon Sep 17 00:00:00 2001 From: "DeepSeek V4.1 Flash" Date: Fri, 6 Nov 2026 14:00:39 -0500 Subject: [PATCH 1/3] feat(p3b1): add mission intelligence foundation (data model, persistence, CLI) --- crates/zet-blocks/src/lib.rs | 202 +++++++++++++++ crates/zet-blocks/tests/missions.rs | 118 +++++++++ crates/zet-pty/src/lib.rs | 1 + crates/zet/src/main.rs | 244 ++++++++++++++++++ .../P3-B1-MISSION-INTELLIGENCE-CONTRACT.md | 62 +++++ 5 files changed, 627 insertions(+) create mode 100644 crates/zet-blocks/tests/missions.rs create mode 100644 docs/design/P3-B1-MISSION-INTELLIGENCE-CONTRACT.md diff --git a/crates/zet-blocks/src/lib.rs b/crates/zet-blocks/src/lib.rs index 5ef757c..4a0cef0 100644 --- a/crates/zet-blocks/src/lib.rs +++ b/crates/zet-blocks/src/lib.rs @@ -66,6 +66,27 @@ impl std::ops::Deref for OutputPreview { } } +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Mission { + pub id: i64, + pub title: String, + pub description: String, + pub created_at: i64, + pub updated_at: i64, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MissionCommand { + pub mission_id: i64, + pub block_id: i64, + pub session: String, + pub provenance: String, + pub created_at: i64, + /// Whether the referenced block still exists in the recorded store + /// with the same session. False means the evidence is unavailable. + pub available: bool, +} + pub struct Store { conn: Connection, } @@ -113,6 +134,30 @@ impl Store { "CREATE INDEX IF NOT EXISTS idx_blocks_session ON blocks (session, id)", (), )?; + // P3-B1: additive mission tables. These are separate from blocks and + // never modify recorded command data. Foreign keys are best-effort; + // availability is re-checked against blocks at read time. + self.conn.execute_batch( + "CREATE TABLE IF NOT EXISTS missions ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + title TEXT NOT NULL, + description TEXT NOT NULL DEFAULT '', + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL + ); + CREATE TABLE IF NOT EXISTS mission_commands ( + mission_id INTEGER NOT NULL, + block_id INTEGER NOT NULL, + session TEXT NOT NULL, + provenance TEXT NOT NULL DEFAULT 'user', + created_at INTEGER NOT NULL, + PRIMARY KEY (mission_id, block_id, session) + ); + CREATE INDEX IF NOT EXISTS idx_mission_commands_mission + ON mission_commands (mission_id, created_at); + CREATE INDEX IF NOT EXISTS idx_mission_commands_block + ON mission_commands (block_id, session);", + )?; Ok(()) } @@ -461,6 +506,163 @@ impl Store { } Ok(out) } + + fn now_millis() -> i64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_millis() as i64) + .unwrap_or(0) + } + + pub fn create_mission(&self, title: &str, description: &str) -> Result { + let now = Self::now_millis(); + self.conn.execute( + "INSERT INTO missions (title, description, created_at, updated_at) VALUES (?1, ?2, ?3, ?4)", + rusqlite::params![title.trim(), description.trim(), now, now], + )?; + Ok(self.conn.last_insert_rowid()) + } + + pub fn get_mission(&self, id: i64) -> Result> { + let mut stmt = self.conn.prepare( + "SELECT id, title, description, created_at, updated_at FROM missions WHERE id = ?1", + )?; + let mut rows = stmt.query(rusqlite::params![id])?; + if let Some(row) = rows.next()? { + Ok(Some(Mission { + id: row.get(0)?, + title: row.get(1)?, + description: row.get(2)?, + created_at: row.get(3)?, + updated_at: row.get(4)?, + })) + } else { + Ok(None) + } + } + + pub fn list_missions(&self) -> Result> { + let mut stmt = self.conn.prepare("SELECT id, title, description, created_at, updated_at FROM missions ORDER BY created_at ASC, id ASC")?; + let rows = stmt.query_map([], |row| { + Ok(Mission { + id: row.get(0)?, + title: row.get(1)?, + description: row.get(2)?, + created_at: row.get(3)?, + updated_at: row.get(4)?, + }) + })?; + rows.collect() + } + + pub fn update_mission(&self, id: i64, title: &str, description: &str) -> Result { + let now = Self::now_millis(); + let changed = self.conn.execute( + "UPDATE missions SET title = ?1, description = ?2, updated_at = ?3 WHERE id = ?4", + rusqlite::params![title.trim(), description.trim(), now, id], + )?; + Ok(changed > 0) + } + + pub fn delete_mission(&self, id: i64) -> Result { + self.conn.execute( + "DELETE FROM mission_commands WHERE mission_id = ?1", + rusqlite::params![id], + )?; + let changed = self + .conn + .execute("DELETE FROM missions WHERE id = ?1", rusqlite::params![id])?; + Ok(changed > 0) + } + + pub fn link_command( + &self, + mission_id: i64, + block_id: i64, + session: &str, + provenance: &str, + ) -> Result { + if self.get_mission(mission_id)?.is_none() { + return Err(rusqlite::Error::QueryReturnedNoRows); + } + let now = Self::now_millis(); + let provenance = if provenance.trim().is_empty() { + "user" + } else { + provenance.trim() + }; + let inserted = self.conn.execute( + "INSERT OR IGNORE INTO mission_commands (mission_id, block_id, session, provenance, created_at) VALUES (?1, ?2, ?3, ?4, ?5)", + rusqlite::params![mission_id, block_id, session, provenance, now], + )?; + if inserted > 0 { + self.conn.execute( + "UPDATE missions SET updated_at = ?1 WHERE id = ?2", + rusqlite::params![now, mission_id], + )?; + } + Ok(inserted > 0) + } + + pub fn unlink_command(&self, mission_id: i64, block_id: i64, session: &str) -> Result { + let changed = self.conn.execute( + "DELETE FROM mission_commands WHERE mission_id = ?1 AND block_id = ?2 AND session = ?3", + rusqlite::params![mission_id, block_id, session], + )?; + if changed > 0 { + self.conn.execute( + "UPDATE missions SET updated_at = ?1 WHERE id = ?2", + rusqlite::params![Self::now_millis(), mission_id], + )?; + } + Ok(changed > 0) + } + + pub fn mission_commands(&self, mission_id: i64) -> Result> { + let mut stmt = self.conn.prepare("SELECT mission_id, block_id, session, provenance, created_at FROM mission_commands WHERE mission_id = ?1 ORDER BY created_at ASC, block_id ASC")?; + let rows = stmt.query_map(rusqlite::params![mission_id], |row| { + Ok(MissionCommand { + mission_id: row.get(0)?, + block_id: row.get(1)?, + session: row.get(2)?, + provenance: row.get(3)?, + created_at: row.get(4)?, + available: false, + }) + })?; + let mut out: Vec = rows.collect::>>()?; + for mc in &mut out { + mc.available = self.block_available(mc.block_id, &mc.session)?; + } + Ok(out) + } + + fn block_available(&self, block_id: i64, session: &str) -> Result { + let count: i64 = self.conn.query_row( + "SELECT COUNT(*) FROM blocks WHERE id = ?1 AND session = ?2", + rusqlite::params![block_id, session], + |row| row.get(0), + )?; + Ok(count > 0) + } + + pub fn missions_for_block(&self, block_id: i64, session: &str) -> Result> { + let mut stmt = self.conn.prepare( + "SELECT mission_id FROM mission_commands WHERE block_id = ?1 AND session = ?2", + )?; + let rows = stmt.query_map(rusqlite::params![block_id, session], |row| row.get(0))?; + rows.collect() + } + + pub fn mission_command_block(&self, block_id: i64, session: &str) -> Result> { + let mut stmt = self.conn.prepare("SELECT id, session, command, output, exit_code, cwd, git_branch, duration_ms FROM blocks WHERE id = ?1 AND session = ?2")?; + let mut rows = stmt.query(rusqlite::params![block_id, session])?; + if let Some(row) = rows.next()? { + Ok(Some(row_to_block(row)?)) + } else { + Ok(None) + } + } } fn row_to_block(row: &rusqlite::Row<'_>) -> Result { diff --git a/crates/zet-blocks/tests/missions.rs b/crates/zet-blocks/tests/missions.rs new file mode 100644 index 0000000..57e8b33 --- /dev/null +++ b/crates/zet-blocks/tests/missions.rs @@ -0,0 +1,118 @@ +use zet_blocks::{Block, Store}; + +fn sample(session: &str) -> Block { + Block { + id: 0, + session: session.to_string(), + command: "echo hi".to_string(), + output: "hi\n".to_string(), + exit_code: 0, + cwd: "/tmp".to_string(), + git_branch: String::new(), + duration_ms: 3, + } +} + +#[test] +fn mission_create_persist_and_list() { + let store = Store::open_in_memory().unwrap(); + let id = store.create_mission("Fix build", "track build commands").unwrap(); + assert!(id > 0); + let got = store.get_mission(id).unwrap().unwrap(); + assert_eq!(got.title, "Fix build"); + assert_eq!(got.description, "track build commands"); + let list = store.list_missions().unwrap(); + assert_eq!(list.len(), 1); + assert_eq!(list[0].id, id); +} + +#[test] +fn mission_link_unlink_and_availability() { + let store = Store::open_in_memory().unwrap(); + let mission_id = store.create_mission("M", "").unwrap(); + let block_id = store.append(&sample("s1")).unwrap(); + + assert!(store.link_command(mission_id, block_id, "s1", "user").unwrap()); + assert!(!store.link_command(mission_id, block_id, "s1", "user").unwrap()); + + let cmds = store.mission_commands(mission_id).unwrap(); + assert_eq!(cmds.len(), 1); + assert!(cmds[0].available); + + assert!(store.mission_command_block(block_id, "s1").unwrap().is_some()); + + assert!(store.unlink_command(mission_id, block_id, "s1").unwrap()); + assert!(!store.unlink_command(mission_id, block_id, "s1").unwrap()); + assert!(store.get(block_id).is_ok()); + assert!(store.mission_commands(mission_id).unwrap().is_empty()); +} + +#[test] +fn missing_evidence_is_reported() { + let store = Store::open_in_memory().unwrap(); + let mission_id = store.create_mission("M", "").unwrap(); + assert!(store.link_command(mission_id, 999, "s1", "user").unwrap()); + let cmds = store.mission_commands(mission_id).unwrap(); + assert_eq!(cmds.len(), 1); + assert!(!cmds[0].available); + assert!(store.mission_command_block(999, "s1").unwrap().is_none()); +} + +#[test] +fn cross_session_membership() { + let store = Store::open_in_memory().unwrap(); + let mission_id = store.create_mission("Cross", "").unwrap(); + let b1 = store.append(&sample("s1")).unwrap(); + let b2 = store.append(&sample("s2")).unwrap(); + store.link_command(mission_id, b1, "s1", "user").unwrap(); + store.link_command(mission_id, b2, "s2", "user").unwrap(); + let cmds = store.mission_commands(mission_id).unwrap(); + assert_eq!(cmds.len(), 2); +} + +#[test] +fn update_and_delete_mission() { + let store = Store::open_in_memory().unwrap(); + let id = store.create_mission("Old", "desc").unwrap(); + assert!(store.update_mission(id, "New", "desc2").unwrap()); + let got = store.get_mission(id).unwrap().unwrap(); + assert_eq!(got.title, "New"); + assert_eq!(got.description, "desc2"); + assert!(store.delete_mission(id).unwrap()); + assert!(store.get_mission(id).unwrap().is_none()); + assert!(store.list_missions().unwrap().is_empty()); +} + +#[test] +fn link_requires_existing_mission() { + let store = Store::open_in_memory().unwrap(); + let res = store.link_command(42, 1, "s1", "user"); + assert!(res.is_err()); +} + +#[test] +fn missions_for_block_reports_memberships() { + let store = Store::open_in_memory().unwrap(); + let m1 = store.create_mission("A", "").unwrap(); + let m2 = store.create_mission("B", "").unwrap(); + let b = store.append(&sample("s1")).unwrap(); + store.link_command(m1, b, "s1", "user").unwrap(); + store.link_command(m2, b, "s1", "user").unwrap(); + let mut memberships = store.missions_for_block(b, "s1").unwrap(); + memberships.sort(); + assert_eq!(memberships, vec![m1, m2]); +} + +#[test] +fn migration_adds_mission_tables_to_existing_db() { + let path = std::env::temp_dir().join(format!("zet-mig-{}.sqlite", std::process::id())); + let _ = std::fs::remove_file(&path); + { + let store = Store::open(path.to_str().unwrap()).unwrap(); + store.append(&sample("s1")).unwrap(); + } + let store = Store::open(path.to_str().unwrap()).unwrap(); + let id = store.create_mission("M", "").unwrap(); + assert!(id > 0); + std::fs::remove_file(&path).unwrap(); +} diff --git a/crates/zet-pty/src/lib.rs b/crates/zet-pty/src/lib.rs index cf10bcd..bafe19b 100644 --- a/crates/zet-pty/src/lib.rs +++ b/crates/zet-pty/src/lib.rs @@ -510,6 +510,7 @@ pub const CLI_SUBCOMMANDS: &[&str] = &[ "schedules", "unschedule", "daemon", + "mission", ]; pub fn zet_fallback(line: &str) -> Option { diff --git a/crates/zet/src/main.rs b/crates/zet/src/main.rs index 7698c56..7c27b3b 100644 --- a/crates/zet/src/main.rs +++ b/crates/zet/src/main.rs @@ -38,6 +38,7 @@ fn cli_dispatch(args: &[String]) { ["inline", spec] => inline_set(spec), ["models", rest @ ..] => models_cmd(rest), ["blocks", rest @ ..] => blocks(rest), + ["mission", rest @ ..] => mission(rest), ["replay", rest @ ..] => replay(rest), ["journal", rest @ ..] => journal(rest), ["undo"] => undo(), @@ -69,6 +70,11 @@ fn cli_dispatch(args: &[String]) { eprintln!(" (openrouter / opencode-go keys, local server, compat URL)"); eprintln!(" zet blocks [--db PATH] [--limit N] [--session S]"); eprintln!(" list recorded command blocks"); + eprintln!(" zet mission create [--description TEXT]"); + eprintln!(" zet mission list"); + eprintln!(" zet mission show <id>"); + eprintln!(" zet mission link <id> <block_id> [--session S]"); + eprintln!(" zet mission unlink <id> <block_id> [--session S]"); eprintln!(" (--session defaults to $ZET_SESSION)"); eprintln!(" zet replay [--db PATH] <session>"); eprintln!(" print a session's transcript, block by block"); @@ -492,6 +498,244 @@ fn blocks(argv: &[&str]) { /// `zet replay [--db PATH] <session>`: print one session's transcript. /// Arg parsing and exits stay at this edge so the transcript itself is /// testable in-process. +fn mission(argv: &[&str]) { + // Open store + let mut db: Option<String> = None; + // We'll parse subcommand first. + if argv.is_empty() { + eprintln!("usage: zet mission create|list|show|link|unlink ..."); + std::process::exit(2); + } + match argv[0] { + "create" => { + let mut title = String::new(); + let mut description = String::new(); + let mut i = 1; + while i < argv.len() { + match argv[i] { + "--db" => { + i += 1; + db = argv.get(i).map(|v| v.to_string()); + } + "--description" => { + i += 1; + description = argv.get(i).copied().unwrap_or("").to_string(); + } + other => { + if title.is_empty() { + title = other.to_string(); + } else { + if !title.is_empty() { + title.push(' '); + } + title.push_str(other); + } + } + } + i += 1; + } + if title.trim().is_empty() { + eprintln!("mission create needs a title"); + std::process::exit(2); + } + let store = open_store(db.as_deref()); + let id = store + .create_mission(&title, &description) + .unwrap_or_else(|e| { + eprintln!("cannot create mission: {e}"); + std::process::exit(1); + }); + println!("created mission #{}", id); + } + "list" => { + // parse db flag + let mut i = 1; + while i < argv.len() { + if argv[i] == "--db" { + i += 1; + db = argv.get(i).map(|v| v.to_string()); + } + i += 1; + } + let store = open_store(db.as_deref()); + let missions = store.list_missions().unwrap_or_else(|e| { + eprintln!("cannot list missions: {e}"); + std::process::exit(1); + }); + if missions.is_empty() { + println!("no missions"); + } else { + for m in missions { + println!("#{} {}", m.id, m.title); + } + } + } + "show" => { + let mut id: Option<i64> = None; + let mut i = 1; + while i < argv.len() { + if argv[i] == "--db" { + i += 1; + db = argv.get(i).map(|v| v.to_string()); + } else if id.is_none() { + id = argv[i].parse().ok(); + } + i += 1; + } + let id = id.unwrap_or_else(|| { + eprintln!("mission show needs an id"); + std::process::exit(2); + }); + let store = open_store(db.as_deref()); + match store.get_mission(id).unwrap_or_else(|e| { + eprintln!("{e}"); + std::process::exit(1); + }) { + None => { + println!("mission #{} not found", id); + } + Some(m) => { + println!("#{} {}", m.id, m.title); + if !m.description.is_empty() { + println!(" {}", m.description); + } + let cmds = store.mission_commands(id).unwrap_or_default(); + if cmds.is_empty() { + println!(" (no linked commands)"); + } else { + for c in cmds { + let avail = if c.available { "" } else { " [unavailable]" }; + println!( + " block #{} session={} provenance={}{}", + c.block_id, c.session, c.provenance, avail + ); + if let Some(b) = store + .mission_command_block(c.block_id, &c.session) + .unwrap_or(None) + { + println!(" {} [exit {}]", b.command, b.exit_code); + } + } + } + } + } + } + "link" => { + let mut mission_id: Option<i64> = None; + let mut block_id: Option<i64> = None; + let mut session: Option<String> = None; + let mut i = 1; + while i < argv.len() { + match argv[i] { + "--db" => { + i += 1; + db = argv.get(i).map(|v| v.to_string()); + } + "--session" => { + i += 1; + session = argv.get(i).map(|v| v.to_string()); + } + other => { + if mission_id.is_none() { + mission_id = other.parse().ok(); + } else if block_id.is_none() { + block_id = other.parse().ok(); + } + } + } + i += 1; + } + let mission_id = mission_id.unwrap_or_else(|| { + eprintln!("mission link needs <mission_id>"); + std::process::exit(2); + }); + let block_id = block_id.unwrap_or_else(|| { + eprintln!("mission link needs <block_id>"); + std::process::exit(2); + }); + let session = session.or_else(env_session).unwrap_or_default(); + if session.is_empty() { + eprintln!("mission link needs --session (or run inside a zet window)"); + std::process::exit(2); + } + let store = open_store(db.as_deref()); + match store.link_command(mission_id, block_id, &session, "user") { + Ok(true) => println!("linked block #{} to mission #{}", block_id, mission_id), + Ok(false) => println!("already linked"), + Err(e) => { + eprintln!("cannot link: {e}"); + std::process::exit(1); + } + } + } + "unlink" => { + let mut mission_id: Option<i64> = None; + let mut block_id: Option<i64> = None; + let mut session: Option<String> = None; + let mut i = 1; + while i < argv.len() { + match argv[i] { + "--db" => { + i += 1; + db = argv.get(i).map(|v| v.to_string()); + } + "--session" => { + i += 1; + session = argv.get(i).map(|v| v.to_string()); + } + other => { + if mission_id.is_none() { + mission_id = other.parse().ok(); + } else if block_id.is_none() { + block_id = other.parse().ok(); + } + } + } + i += 1; + } + let mission_id = mission_id.unwrap_or_else(|| { + eprintln!("mission unlink needs <mission_id>"); + std::process::exit(2); + }); + let block_id = block_id.unwrap_or_else(|| { + eprintln!("mission unlink needs <block_id>"); + std::process::exit(2); + }); + let session = session.or_else(env_session).unwrap_or_default(); + if session.is_empty() { + eprintln!("mission unlink needs --session (or run inside a zet window)"); + std::process::exit(2); + } + let store = open_store(db.as_deref()); + match store.unlink_command(mission_id, block_id, &session) { + Ok(true) => println!("unlinked block #{} from mission #{}", block_id, mission_id), + Ok(false) => println!("not linked"), + Err(e) => { + eprintln!("cannot unlink: {e}"); + std::process::exit(1); + } + } + } + _ => { + eprintln!("unknown mission subcommand"); + std::process::exit(2); + } + } +} + +fn open_store(db: Option<&str>) -> zet_blocks::Store { + match db { + Some(path) => zet_blocks::Store::open(path).unwrap_or_else(|e| { + eprintln!("cannot open {path}: {e}"); + std::process::exit(1); + }), + None => zet_blocks::Store::open_default().unwrap_or_else(|e| { + eprintln!("cannot open block store: {e}"); + std::process::exit(1); + }), + } +} + fn replay(argv: &[&str]) { let mut db: Option<String> = None; let mut session: Option<String> = None; diff --git a/docs/design/P3-B1-MISSION-INTELLIGENCE-CONTRACT.md b/docs/design/P3-B1-MISSION-INTELLIGENCE-CONTRACT.md new file mode 100644 index 0000000..242c18c --- /dev/null +++ b/docs/design/P3-B1-MISSION-INTELLIGENCE-CONTRACT.md @@ -0,0 +1,62 @@ +# P3-B1 — Mission Intelligence Foundation Contract + +**Status:** Implementation contract and record for the P3-B1 bounded slice. +**Base:** master at `609da784bb20371f744c4e6427c90cdde11c288d` +**Branch:** `feat/p3b1-mission-intelligence` + +## 1. Source capabilities used + +- `zet-blocks::Store` SQLite persistence for recorded commands (`blocks` table). +- `Block` identity: global SQLite `id` plus `session` string. +- CLI dispatch in `crates/zet/src/main.rs`. +- Existing `env_session()` for session identity. + +## 2. Mission data model + +- `Mission { id, title, description, created_at, updated_at }` +- `MissionCommand { mission_id, block_id, session, provenance, created_at, available }` +- Stable command identity is `(block_id, session)`, not row position. +- Availability is resolved against `blocks` at read time; missing evidence is reported, not reassigned. + +## 3. Persistence and migration + +- Additive tables in the existing `blocks.sqlite`: + - `missions` + - `mission_commands` (composite PK `(mission_id, block_id, session)`) +- Created with `CREATE TABLE IF NOT EXISTS` on every open, including legacy databases. +- No existing recorded command data is modified. + +## 4. Provenance + +- All associations are explicit user actions (`provenance = "user"` by default). +- No automatic inference, no fabricated verification state. +- Mission completion is not inferred from command exit codes. + +## 5. Implemented interactions (CLI vertical slice) + +- `zet mission create <title> [--description TEXT]` +- `zet mission list` +- `zet mission show <id>` +- `zet mission link <mission_id> <block_id> [--session S]` +- `zet mission unlink <mission_id> <block_id> [--session S]` + +Linking is idempotent; unlinking does not delete the underlying command. + +## 6. Native UI + +Native panel integration is deferred to a follow-up slice. The data model and CLI provide the evidence-connected foundation and are independently testable. + +## 7. Performance + +- No per-frame database queries added to the UI; mission data is only read on explicit CLI invocation. +- Terminal rendering and PTY paths are untouched. + +## 8. Tests + +- `cargo fmt --all -- --check` +- `cargo check --workspace --all-targets` +- `cargo clippy --workspace --all-targets -- -D warnings` +- `cargo test --workspace` +- Added `crates/zet-blocks/tests/missions.rs` (8 tests). +EOF +echo done \ No newline at end of file From c1b0b0001cde874bc03d6bb354e873f0c73a7647 Mon Sep 17 00:00:00 2001 From: "DeepSeek V4.1 Flash" <implementor@zet.local> Date: Fri, 6 Nov 2026 15:09:48 -0500 Subject: [PATCH 2/3] fix(p3b1): repair CI formatting, transactional mission updates, focused tests --- crates/zet-blocks/Cargo.toml | 1 + crates/zet-blocks/src/lib.rs | 44 ++++++++++- crates/zet-blocks/tests/missions.rs | 77 ++++++++++++++++++- crates/zet/src/main.rs | 20 +++-- .../P3-B1-MISSION-INTELLIGENCE-CONTRACT.md | 12 ++- 5 files changed, 142 insertions(+), 12 deletions(-) diff --git a/crates/zet-blocks/Cargo.toml b/crates/zet-blocks/Cargo.toml index e7b0d21..87918b6 100644 --- a/crates/zet-blocks/Cargo.toml +++ b/crates/zet-blocks/Cargo.toml @@ -9,6 +9,7 @@ rusqlite = { version = "0.40", features = ["bundled"] } zet-term = { path = "../zet-term" } [dev-dependencies] +rusqlite = { version = "0.40", features = ["bundled"] } zet-pty = { path = "../zet-pty" } # Dev-only: the gate/store agreement test crosses into the policy crate. # Not a runtime dependency, and not a cycle (zet-policy depends on serde). diff --git a/crates/zet-blocks/src/lib.rs b/crates/zet-blocks/src/lib.rs index 4a0cef0..4fc1428 100644 --- a/crates/zet-blocks/src/lib.rs +++ b/crates/zet-blocks/src/lib.rs @@ -87,6 +87,19 @@ pub struct MissionCommand { pub available: bool, } +struct TransactionGuard<'a> { + conn: &'a Connection, + committed: bool, +} + +impl Drop for TransactionGuard<'_> { + fn drop(&mut self) { + if !self.committed { + let _ = self.conn.execute("ROLLBACK", []); + } + } +} + pub struct Store { conn: Connection, } @@ -565,6 +578,11 @@ impl Store { } pub fn delete_mission(&self, id: i64) -> Result<bool> { + self.conn.execute("BEGIN IMMEDIATE", [])?; + let mut __tx_guard = TransactionGuard { + conn: &self.conn, + committed: false, + }; self.conn.execute( "DELETE FROM mission_commands WHERE mission_id = ?1", rusqlite::params![id], @@ -572,6 +590,8 @@ impl Store { let changed = self .conn .execute("DELETE FROM missions WHERE id = ?1", rusqlite::params![id])?; + __tx_guard.committed = true; + self.conn.execute("COMMIT", [])?; Ok(changed > 0) } @@ -582,7 +602,20 @@ impl Store { session: &str, provenance: &str, ) -> Result<bool> { - if self.get_mission(mission_id)?.is_none() { + self.conn.execute("BEGIN IMMEDIATE", [])?; + let mut __tx_guard = TransactionGuard { + conn: &self.conn, + committed: false, + }; + let exists: i64 = self + .conn + .query_row( + "SELECT COUNT(*) FROM missions WHERE id = ?1", + rusqlite::params![mission_id], + |row| row.get(0), + ) + .unwrap_or(0); + if exists == 0 { return Err(rusqlite::Error::QueryReturnedNoRows); } let now = Self::now_millis(); @@ -601,10 +634,17 @@ impl Store { rusqlite::params![now, mission_id], )?; } + __tx_guard.committed = true; + self.conn.execute("COMMIT", [])?; Ok(inserted > 0) } pub fn unlink_command(&self, mission_id: i64, block_id: i64, session: &str) -> Result<bool> { + self.conn.execute("BEGIN IMMEDIATE", [])?; + let mut __tx_guard = TransactionGuard { + conn: &self.conn, + committed: false, + }; let changed = self.conn.execute( "DELETE FROM mission_commands WHERE mission_id = ?1 AND block_id = ?2 AND session = ?3", rusqlite::params![mission_id, block_id, session], @@ -615,6 +655,8 @@ impl Store { rusqlite::params![Self::now_millis(), mission_id], )?; } + __tx_guard.committed = true; + self.conn.execute("COMMIT", [])?; Ok(changed > 0) } diff --git a/crates/zet-blocks/tests/missions.rs b/crates/zet-blocks/tests/missions.rs index 57e8b33..9179c7c 100644 --- a/crates/zet-blocks/tests/missions.rs +++ b/crates/zet-blocks/tests/missions.rs @@ -16,7 +16,9 @@ fn sample(session: &str) -> Block { #[test] fn mission_create_persist_and_list() { let store = Store::open_in_memory().unwrap(); - let id = store.create_mission("Fix build", "track build commands").unwrap(); + let id = store + .create_mission("Fix build", "track build commands") + .unwrap(); assert!(id > 0); let got = store.get_mission(id).unwrap().unwrap(); assert_eq!(got.title, "Fix build"); @@ -32,14 +34,21 @@ fn mission_link_unlink_and_availability() { let mission_id = store.create_mission("M", "").unwrap(); let block_id = store.append(&sample("s1")).unwrap(); - assert!(store.link_command(mission_id, block_id, "s1", "user").unwrap()); - assert!(!store.link_command(mission_id, block_id, "s1", "user").unwrap()); + assert!(store + .link_command(mission_id, block_id, "s1", "user") + .unwrap()); + assert!(!store + .link_command(mission_id, block_id, "s1", "user") + .unwrap()); let cmds = store.mission_commands(mission_id).unwrap(); assert_eq!(cmds.len(), 1); assert!(cmds[0].available); - assert!(store.mission_command_block(block_id, "s1").unwrap().is_some()); + assert!(store + .mission_command_block(block_id, "s1") + .unwrap() + .is_some()); assert!(store.unlink_command(mission_id, block_id, "s1").unwrap()); assert!(!store.unlink_command(mission_id, block_id, "s1").unwrap()); @@ -116,3 +125,63 @@ fn migration_adds_mission_tables_to_existing_db() { assert!(id > 0); std::fs::remove_file(&path).unwrap(); } + +#[test] +fn mission_persists_across_reopen() { + let path = + std::env::temp_dir().join(format!("zet-mission-persist-{}.sqlite", std::process::id())); + let _ = std::fs::remove_file(&path); + let id = { + let store = Store::open(path.to_str().unwrap()).unwrap(); + let id = store.create_mission("Persist", "desc").unwrap(); + let b = store.append(&sample("s1")).unwrap(); + store.link_command(id, b, "s1", "user").unwrap(); + id + }; + let store = Store::open(path.to_str().unwrap()).unwrap(); + let m = store.get_mission(id).unwrap().unwrap(); + assert_eq!(m.title, "Persist"); + let cmds = store.mission_commands(id).unwrap(); + assert_eq!(cmds.len(), 1); + assert!(cmds[0].available); + std::fs::remove_file(&path).unwrap(); +} + +#[test] +fn legacy_database_migration() { + let path = std::env::temp_dir().join(format!("zet-legacy-{}.sqlite", std::process::id())); + let _ = std::fs::remove_file(&path); + // Create an old-style database with only the blocks table (no git_branch, no missions). + { + let conn = rusqlite::Connection::open(&path).unwrap(); + conn.execute( + "CREATE TABLE blocks ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + session TEXT NOT NULL, + command TEXT NOT NULL, + output TEXT NOT NULL DEFAULT '', + exit_code INTEGER NOT NULL DEFAULT 0, + cwd TEXT NOT NULL DEFAULT '', + duration_ms INTEGER NOT NULL DEFAULT 0 + )", + [], + ) + .unwrap(); + conn.execute( + "INSERT INTO blocks (session, command, output, exit_code, cwd, duration_ms) VALUES ('s1','echo hi','hi',0,'/tmp',3)", + [], + ) + .unwrap(); + } + let store = Store::open(path.to_str().unwrap()).unwrap(); + // git_branch column migrated; mission tables created. + let b = store.list("s1").unwrap(); + assert_eq!(b.len(), 1); + let id = store.create_mission("M", "").unwrap(); + let block_id = b[0].id; + store.link_command(id, block_id, "s1", "user").unwrap(); + let cmds = store.mission_commands(id).unwrap(); + assert_eq!(cmds.len(), 1); + assert!(cmds[0].available); + std::fs::remove_file(&path).unwrap(); +} diff --git a/crates/zet/src/main.rs b/crates/zet/src/main.rs index 7c27b3b..7681f8b 100644 --- a/crates/zet/src/main.rs +++ b/crates/zet/src/main.rs @@ -599,7 +599,13 @@ fn mission(argv: &[&str]) { if !m.description.is_empty() { println!(" {}", m.description); } - let cmds = store.mission_commands(id).unwrap_or_default(); + let cmds = match store.mission_commands(id) { + Ok(v) => v, + Err(e) => { + eprintln!("cannot read mission commands: {e}"); + std::process::exit(1); + } + }; if cmds.is_empty() { println!(" (no linked commands)"); } else { @@ -609,10 +615,14 @@ fn mission(argv: &[&str]) { " block #{} session={} provenance={}{}", c.block_id, c.session, c.provenance, avail ); - if let Some(b) = store - .mission_command_block(c.block_id, &c.session) - .unwrap_or(None) - { + let block = match store.mission_command_block(c.block_id, &c.session) { + Ok(v) => v, + Err(e) => { + eprintln!("cannot read command evidence: {e}"); + std::process::exit(1); + } + }; + if let Some(b) = block { println!(" {} [exit {}]", b.command, b.exit_code); } } diff --git a/docs/design/P3-B1-MISSION-INTELLIGENCE-CONTRACT.md b/docs/design/P3-B1-MISSION-INTELLIGENCE-CONTRACT.md index 242c18c..6d12d88 100644 --- a/docs/design/P3-B1-MISSION-INTELLIGENCE-CONTRACT.md +++ b/docs/design/P3-B1-MISSION-INTELLIGENCE-CONTRACT.md @@ -58,5 +58,13 @@ Native panel integration is deferred to a follow-up slice. The data model and CL - `cargo clippy --workspace --all-targets -- -D warnings` - `cargo test --workspace` - Added `crates/zet-blocks/tests/missions.rs` (8 tests). -EOF -echo done \ No newline at end of file + +## 9. Scope reconciliation + +This slice is **P3-B1 Foundation — CLI and Persistence Only**. + +It provides the mission data model, additive SQLite persistence, explicit +command associations, missing-evidence reporting, and CLI create/list/show/ +link/unlink commands. Native Mission Rail and Inspector integration is +explicitly deferred to a separately reviewed follow-up slice. No native +visual acceptance is claimed. From d8fe0bf8426cad62ddfe456965f26e4147d7b091 Mon Sep 17 00:00:00 2001 From: "DeepSeek V4.1 Flash" <implementor@zet.local> Date: Fri, 6 Nov 2026 15:45:54 -0500 Subject: [PATCH 3/3] fix(p3-b1): remediate audit findings (transaction commit order, dangling --db, error propagation, CLI hygiene) --- crates/zet-blocks/src/lib.rs | 39 ++-- crates/zet-blocks/tests/missions.rs | 48 ++++ crates/zet/src/main.rs | 211 +++++++++++++++--- .../P3-B1-MISSION-INTELLIGENCE-CONTRACT.md | 2 +- 4 files changed, 253 insertions(+), 47 deletions(-) diff --git a/crates/zet-blocks/src/lib.rs b/crates/zet-blocks/src/lib.rs index 4fc1428..3982c1d 100644 --- a/crates/zet-blocks/src/lib.rs +++ b/crates/zet-blocks/src/lib.rs @@ -527,11 +527,25 @@ impl Store { .unwrap_or(0) } + /// Sanitize mission title/description text before persistence: + /// scrub secret-like tokens and drop control characters, while + /// preserving legitimate UTF-8 text. + pub fn sanitize_mission_text(text: &str) -> String { + scrub_secrets(text) + .chars() + .filter(|c| !c.is_control()) + .collect::<String>() + .trim() + .to_string() + } + pub fn create_mission(&self, title: &str, description: &str) -> Result<i64> { + let title = Self::sanitize_mission_text(title); + let description = Self::sanitize_mission_text(description); let now = Self::now_millis(); self.conn.execute( "INSERT INTO missions (title, description, created_at, updated_at) VALUES (?1, ?2, ?3, ?4)", - rusqlite::params![title.trim(), description.trim(), now, now], + rusqlite::params![title, description, now, now], )?; Ok(self.conn.last_insert_rowid()) } @@ -569,10 +583,12 @@ impl Store { } pub fn update_mission(&self, id: i64, title: &str, description: &str) -> Result<bool> { + let title = Self::sanitize_mission_text(title); + let description = Self::sanitize_mission_text(description); let now = Self::now_millis(); let changed = self.conn.execute( "UPDATE missions SET title = ?1, description = ?2, updated_at = ?3 WHERE id = ?4", - rusqlite::params![title.trim(), description.trim(), now, id], + rusqlite::params![title, description, now, id], )?; Ok(changed > 0) } @@ -590,8 +606,8 @@ impl Store { let changed = self .conn .execute("DELETE FROM missions WHERE id = ?1", rusqlite::params![id])?; - __tx_guard.committed = true; self.conn.execute("COMMIT", [])?; + __tx_guard.committed = true; Ok(changed > 0) } @@ -607,14 +623,11 @@ impl Store { conn: &self.conn, committed: false, }; - let exists: i64 = self - .conn - .query_row( - "SELECT COUNT(*) FROM missions WHERE id = ?1", - rusqlite::params![mission_id], - |row| row.get(0), - ) - .unwrap_or(0); + let exists: i64 = self.conn.query_row( + "SELECT COUNT(*) FROM missions WHERE id = ?1", + rusqlite::params![mission_id], + |row| row.get(0), + )?; if exists == 0 { return Err(rusqlite::Error::QueryReturnedNoRows); } @@ -634,8 +647,8 @@ impl Store { rusqlite::params![now, mission_id], )?; } - __tx_guard.committed = true; self.conn.execute("COMMIT", [])?; + __tx_guard.committed = true; Ok(inserted > 0) } @@ -655,8 +668,8 @@ impl Store { rusqlite::params![Self::now_millis(), mission_id], )?; } - __tx_guard.committed = true; self.conn.execute("COMMIT", [])?; + __tx_guard.committed = true; Ok(changed > 0) } diff --git a/crates/zet-blocks/tests/missions.rs b/crates/zet-blocks/tests/missions.rs index 9179c7c..f48d864 100644 --- a/crates/zet-blocks/tests/missions.rs +++ b/crates/zet-blocks/tests/missions.rs @@ -147,6 +147,20 @@ fn mission_persists_across_reopen() { std::fs::remove_file(&path).unwrap(); } +#[test] +fn mission_metadata_is_sanitized() { + let store = Store::open_in_memory().unwrap(); + let id = store + .create_mission( + "title sk-proj-abcdefghijklmnopqrstuvwxyz", + "desc \u{001b}[31m", + ) + .unwrap(); + let m = store.get_mission(id).unwrap().unwrap(); + assert!(!m.title.contains("sk-proj-"), "{:?}", m.title); + assert!(!m.description.contains('\u{001b}'), "{:?}", m.description); +} + #[test] fn legacy_database_migration() { let path = std::env::temp_dir().join(format!("zet-legacy-{}.sqlite", std::process::id())); @@ -185,3 +199,37 @@ fn legacy_database_migration() { assert!(cmds[0].available); std::fs::remove_file(&path).unwrap(); } + +#[test] +fn transaction_rollback_on_failed_commit() { + let path = std::env::temp_dir().join(format!("zet-tx-fail-{}.sqlite", std::process::id())); + let _ = std::fs::remove_file(&path); + let mission_id; + let block_id; + { + let store = Store::open(path.to_str().unwrap()).unwrap(); + mission_id = store.create_mission("M", "").unwrap(); + block_id = store.append(&sample("s1")).unwrap(); + } + let blocker = rusqlite::Connection::open(&path).unwrap(); + blocker.execute("BEGIN", []).unwrap(); + let _: i64 = blocker + .query_row("SELECT COUNT(*) FROM missions", [], |r| r.get(0)) + .unwrap(); + + let store = Store::open(path.to_str().unwrap()).unwrap(); + let res = store.link_command(mission_id, block_id, "s1", "user"); + assert!(res.is_err(), "expected failed COMMIT, got {:?}", res); + + drop(blocker); + + // Connection must remain usable after the failed commit. + let new_mission = store.create_mission("After", "").unwrap(); + assert!(new_mission > 0); + + let store2 = Store::open(path.to_str().unwrap()).unwrap(); + let cmds = store2.mission_commands(mission_id).unwrap(); + assert!(cmds.is_empty(), "link should have rolled back"); + + let _ = std::fs::remove_file(&path); +} diff --git a/crates/zet/src/main.rs b/crates/zet/src/main.rs index 7681f8b..195e2ea 100644 --- a/crates/zet/src/main.rs +++ b/crates/zet/src/main.rs @@ -499,9 +499,6 @@ fn blocks(argv: &[&str]) { /// Arg parsing and exits stay at this edge so the transcript itself is /// testable in-process. fn mission(argv: &[&str]) { - // Open store - let mut db: Option<String> = None; - // We'll parse subcommand first. if argv.is_empty() { eprintln!("usage: zet mission create|list|show|link|unlink ..."); std::process::exit(2); @@ -510,16 +507,37 @@ fn mission(argv: &[&str]) { "create" => { let mut title = String::new(); let mut description = String::new(); + let mut db: Option<String> = None; let mut i = 1; while i < argv.len() { match argv[i] { "--db" => { i += 1; - db = argv.get(i).map(|v| v.to_string()); + db = match argv.get(i) { + Some(v) if !v.is_empty() => Some(v.to_string()), + Some(_) => { + eprintln!("--db needs a nonempty value"); + std::process::exit(2); + } + None => { + eprintln!("--db needs a value"); + std::process::exit(2); + } + }; } "--description" => { i += 1; - description = argv.get(i).copied().unwrap_or("").to_string(); + description = match argv.get(i) { + Some(v) => v.to_string(), + None => { + eprintln!("--description needs a value"); + std::process::exit(2); + } + }; + } + other if other.starts_with("--") => { + eprintln!("unknown mission flag {other:?}"); + std::process::exit(2); } other => { if title.is_empty() { @@ -548,12 +566,32 @@ fn mission(argv: &[&str]) { println!("created mission #{}", id); } "list" => { - // parse db flag + let mut db: Option<String> = None; let mut i = 1; while i < argv.len() { - if argv[i] == "--db" { - i += 1; - db = argv.get(i).map(|v| v.to_string()); + match argv[i] { + "--db" => { + i += 1; + db = match argv.get(i) { + Some(v) if !v.is_empty() => Some(v.to_string()), + Some(_) => { + eprintln!("--db needs a nonempty value"); + std::process::exit(2); + } + None => { + eprintln!("--db needs a value"); + std::process::exit(2); + } + }; + } + other if other.starts_with("--") => { + eprintln!("unknown mission flag {other:?}"); + std::process::exit(2); + } + other => { + eprintln!("unexpected mission list argument {other:?}"); + std::process::exit(2); + } } i += 1; } @@ -566,19 +604,51 @@ fn mission(argv: &[&str]) { println!("no missions"); } else { for m in missions { - println!("#{} {}", m.id, m.title); + println!( + "#{} {}", + m.id, + zet_blocks::Store::sanitize_mission_text(&m.title) + ); } } } "show" => { let mut id: Option<i64> = None; + let mut db: Option<String> = None; let mut i = 1; while i < argv.len() { - if argv[i] == "--db" { - i += 1; - db = argv.get(i).map(|v| v.to_string()); - } else if id.is_none() { - id = argv[i].parse().ok(); + match argv[i] { + "--db" => { + i += 1; + db = match argv.get(i) { + Some(v) if !v.is_empty() => Some(v.to_string()), + Some(_) => { + eprintln!("--db needs a nonempty value"); + std::process::exit(2); + } + None => { + eprintln!("--db needs a value"); + std::process::exit(2); + } + }; + } + other if other.starts_with("--") => { + eprintln!("unknown mission flag {other:?}"); + std::process::exit(2); + } + other => match other.parse::<i64>() { + Ok(v) => { + if id.is_some() { + eprintln!("mission show takes one id"); + std::process::exit(2); + } + id = Some(v); + } + Err(_) => { + eprintln!("mission show needs a numeric id"); + std::process::exit(2); + } + }, } i += 1; } @@ -592,7 +662,8 @@ fn mission(argv: &[&str]) { std::process::exit(1); }) { None => { - println!("mission #{} not found", id); + eprintln!("mission #{} not found", id); + std::process::exit(1); } Some(m) => { println!("#{} {}", m.id, m.title); @@ -634,24 +705,54 @@ fn mission(argv: &[&str]) { let mut mission_id: Option<i64> = None; let mut block_id: Option<i64> = None; let mut session: Option<String> = None; + let mut db: Option<String> = None; let mut i = 1; while i < argv.len() { match argv[i] { "--db" => { i += 1; - db = argv.get(i).map(|v| v.to_string()); + db = match argv.get(i) { + Some(v) if !v.is_empty() => Some(v.to_string()), + Some(_) => { + eprintln!("--db needs a nonempty value"); + std::process::exit(2); + } + None => { + eprintln!("--db needs a value"); + std::process::exit(2); + } + }; } "--session" => { i += 1; - session = argv.get(i).map(|v| v.to_string()); + session = match argv.get(i) { + Some(v) => Some(v.to_string()), + None => { + eprintln!("--session needs a value"); + std::process::exit(2); + } + }; } - other => { - if mission_id.is_none() { - mission_id = other.parse().ok(); - } else if block_id.is_none() { - block_id = other.parse().ok(); - } + other if other.starts_with("--") => { + eprintln!("unknown mission flag {other:?}"); + std::process::exit(2); } + other => match other.parse::<i64>() { + Ok(v) => { + if mission_id.is_none() { + mission_id = Some(v); + } else if block_id.is_none() { + block_id = Some(v); + } else { + eprintln!("unexpected mission link argument {other:?}"); + std::process::exit(2); + } + } + Err(_) => { + eprintln!("mission link needs numeric <mission_id> <block_id>"); + std::process::exit(2); + } + }, } i += 1; } @@ -670,7 +771,21 @@ fn mission(argv: &[&str]) { } let store = open_store(db.as_deref()); match store.link_command(mission_id, block_id, &session, "user") { - Ok(true) => println!("linked block #{} to mission #{}", block_id, mission_id), + Ok(true) => { + let evidence = store + .mission_command_block(block_id, &session) + .ok() + .flatten() + .is_some(); + if evidence { + println!("linked block #{} to mission #{}", block_id, mission_id); + } else { + println!( + "linked block #{} to mission #{} (evidence unavailable)", + block_id, mission_id + ); + } + } Ok(false) => println!("already linked"), Err(e) => { eprintln!("cannot link: {e}"); @@ -682,24 +797,54 @@ fn mission(argv: &[&str]) { let mut mission_id: Option<i64> = None; let mut block_id: Option<i64> = None; let mut session: Option<String> = None; + let mut db: Option<String> = None; let mut i = 1; while i < argv.len() { match argv[i] { "--db" => { i += 1; - db = argv.get(i).map(|v| v.to_string()); + db = match argv.get(i) { + Some(v) if !v.is_empty() => Some(v.to_string()), + Some(_) => { + eprintln!("--db needs a nonempty value"); + std::process::exit(2); + } + None => { + eprintln!("--db needs a value"); + std::process::exit(2); + } + }; } "--session" => { i += 1; - session = argv.get(i).map(|v| v.to_string()); + session = match argv.get(i) { + Some(v) => Some(v.to_string()), + None => { + eprintln!("--session needs a value"); + std::process::exit(2); + } + }; } - other => { - if mission_id.is_none() { - mission_id = other.parse().ok(); - } else if block_id.is_none() { - block_id = other.parse().ok(); - } + other if other.starts_with("--") => { + eprintln!("unknown mission flag {other:?}"); + std::process::exit(2); } + other => match other.parse::<i64>() { + Ok(v) => { + if mission_id.is_none() { + mission_id = Some(v); + } else if block_id.is_none() { + block_id = Some(v); + } else { + eprintln!("unexpected mission unlink argument {other:?}"); + std::process::exit(2); + } + } + Err(_) => { + eprintln!("mission unlink needs numeric <mission_id> <block_id>"); + std::process::exit(2); + } + }, } i += 1; } diff --git a/docs/design/P3-B1-MISSION-INTELLIGENCE-CONTRACT.md b/docs/design/P3-B1-MISSION-INTELLIGENCE-CONTRACT.md index 6d12d88..ca7677f 100644 --- a/docs/design/P3-B1-MISSION-INTELLIGENCE-CONTRACT.md +++ b/docs/design/P3-B1-MISSION-INTELLIGENCE-CONTRACT.md @@ -57,7 +57,7 @@ Native panel integration is deferred to a follow-up slice. The data model and CL - `cargo check --workspace --all-targets` - `cargo clippy --workspace --all-targets -- -D warnings` - `cargo test --workspace` -- Added `crates/zet-blocks/tests/missions.rs` (8 tests). +- Added `crates/zet-blocks/tests/missions.rs` (12 tests). ## 9. Scope reconciliation