Skip to main content

agentmux_srv_core/backend/user_sync/
kanban.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! The Kanban's side of the sync layer (SPEC_SHARED_KANBAN_ACROSS_MACHINES §3.3, build step K1): what a board's
5//! tasks look like as records in the change log, and the merge rule for each kind of record.
6//!
7//! [`capture`] reads the Kanban's tables and writes whatever changed since the last capture into the log of the
8//! task's board, one record per field (so two machines editing different fields of a card both keep their edit),
9//! one for the task's lifecycle (state, holder, attempts, result: these move together), one per dependency and
10//! one per history line. It sends nothing and changes no Kanban table: taking a record from another machine into
11//! the tables comes with the numbering of the next step. A lease's expiry is not recorded (every heartbeat would
12//! write a row); the number a card has on a machine is not either (numbers are per board, see the spec §3.2).
13//!
14//! Records of a board are in the collection [`collection_id`] names; a record id is `<task>.<field>`,
15//! `<task>.life`, `<task>.after.<other task>` or `<task>.event.<machine>.<line>`.
16
17use std::collections::BTreeMap;
18
19use rusqlite::types::ValueRef;
20use rusqlite::{params, Connection, OptionalExtension};
21use serde_json::{json, Map, Value};
22use sha2::{Digest, Sha256};
23
24use super::adapter::{Adapter, Merge, NewestWins};
25use super::log::{self, Signer, SyncError};
26use super::record::Header;
27
28/// The kind of a Kanban board's collection.
29pub const KIND: &str = "kanban";
30
31/// The collection a board's records are in.
32pub fn collection_id(board_id: &str) -> String {
33    format!("kanban.{board_id}")
34}
35
36/// The lifecycle fields: written as one record, because they only make sense together.
37const LIFE_FIELDS: [&str; 5] = ["state", "claimed_by", "claimed_by_uid", "attempts", "result"];
38
39/// What a capture reads: the task's own columns and its card's. The first two columns name the task and its board;
40/// every other one is a field (or a lifecycle field).
41const TASK_SQL: &str = "SELECT q.id AS id, c.board_id AS board_id,
42    q.title, q.payload, q.kind, q.target_agent, q.target_agent_uid, q.target_group, q.priority, q.max_attempts,
43    q.created_by, q.created_by_uid, q.not_before,
44    q.state, q.claimed_by, q.claimed_by_uid, q.attempts, q.result,
45    c.repo, c.branch, c.pr_url, c.rank, c.review_required, c.checklist, c.question, c.note,
46    c.requested_by, c.requested_by_kind, c.request_text, c.filed_by
47  FROM db_work_queue q LEFT JOIN db_work_cards c ON c.work_id = q.id";
48
49/// What a capture remembers: per task its board, a digest of what was recorded (so an unchanged task costs one
50/// lookup) and the record ids written; and how far the history lines have been read.
51const SCHEMA: &str = "
52    CREATE TABLE IF NOT EXISTS db_sync_kanban_seen (
53        work_id TEXT PRIMARY KEY,
54        board   TEXT NOT NULL,
55        hash    TEXT NOT NULL,
56        records TEXT NOT NULL
57    );
58    CREATE TABLE IF NOT EXISTS db_sync_kanban_mark (
59        name  TEXT PRIMARY KEY,
60        value INTEGER NOT NULL
61    );";
62
63/// Creates the log's tables and this module's.
64pub fn init(conn: &Connection) -> rusqlite::Result<()> {
65    log::init(conn)?;
66    conn.execute_batch(SCHEMA)
67}
68
69/// What a capture did.
70#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
71pub struct Captured {
72    /// Records written (a new value, or a task's first).
73    pub written: usize,
74    /// Records ended with a tombstone (a task gone, moved to another board, or a dependency taken off).
75    pub tombstoned: usize,
76}
77
78/// A task as it is now: its board and every record it should have.
79struct Task {
80    board: String,
81    records: BTreeMap<String, Value>,
82}
83
84fn json_of(v: ValueRef<'_>) -> Value {
85    match v {
86        ValueRef::Integer(i) => json!(i),
87        ValueRef::Real(f) => json!(f),
88        ValueRef::Text(t) => Value::String(String::from_utf8_lossy(t).into_owned()),
89        ValueRef::Null | ValueRef::Blob(_) => Value::Null,
90    }
91}
92
93fn read_tasks(conn: &Connection, default_board: &str) -> rusqlite::Result<BTreeMap<String, Task>> {
94    let mut stmt = conn.prepare(TASK_SQL)?;
95    let names: Vec<String> = stmt.column_names().into_iter().map(|s| s.to_string()).collect();
96    let mut rows = stmt.query([])?;
97    let mut tasks = BTreeMap::new();
98    while let Some(r) = rows.next()? {
99        let work_id: String = r.get(0)?;
100        let board = r.get::<_, Option<String>>(1)?.filter(|b| !b.is_empty()).unwrap_or_else(|| default_board.to_string());
101        let mut records = BTreeMap::new();
102        let mut life = Map::new();
103        for (i, name) in names.iter().enumerate().skip(2) {
104            let v = json_of(r.get_ref(i)?);
105            if LIFE_FIELDS.contains(&name.as_str()) {
106                life.insert(name.clone(), v);
107            } else {
108                records.insert(format!("{work_id}.{name}"), v);
109            }
110        }
111        records.insert(format!("{work_id}.life"), Value::Object(life));
112        tasks.insert(work_id, Task { board, records });
113    }
114    let mut deps = conn.prepare("SELECT work_id, after_id FROM db_work_deps")?;
115    let pairs = deps.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?;
116    for pair in pairs {
117        let (work_id, after) = pair?;
118        if let Some(t) = tasks.get_mut(&work_id) {
119            t.records.insert(format!("{work_id}.after.{after}"), Value::Bool(true));
120        }
121    }
122    Ok(tasks)
123}
124
125fn digest(records: &BTreeMap<String, Value>) -> String {
126    let bytes = serde_json::to_vec(records).unwrap_or_default();
127    Sha256::digest(bytes).iter().map(|b| format!("{b:02x}")).collect()
128}
129
130/// What was last recorded of a task: its board, the digest and the record ids.
131struct Seen {
132    board: String,
133    hash: String,
134    records: Vec<String>,
135}
136
137fn seen_of(conn: &Connection, work_id: &str) -> rusqlite::Result<Option<Seen>> {
138    conn.query_row("SELECT board, hash, records FROM db_sync_kanban_seen WHERE work_id = ?1", params![work_id], |r| {
139        let records: String = r.get(2)?;
140        Ok(Seen { board: r.get(0)?, hash: r.get(1)?, records: serde_json::from_str(&records).unwrap_or_default() })
141    })
142    .optional()
143}
144
145fn save_seen(conn: &Connection, work_id: &str, task: &Task, hash: &str) -> rusqlite::Result<()> {
146    let ids: Vec<&String> = task.records.keys().collect();
147    conn.execute(
148        "INSERT OR REPLACE INTO db_sync_kanban_seen (work_id, board, hash, records) VALUES (?1, ?2, ?3, ?4)",
149        params![work_id, task.board, hash, serde_json::to_string(&ids).unwrap_or_else(|_| "[]".into())],
150    )?;
151    Ok(())
152}
153
154/// Writes a record unless the log's current state already holds exactly this value.
155fn write_if_changed(
156    conn: &Connection,
157    signer: &mut Signer,
158    collection: &str,
159    record: &str,
160    body: Vec<u8>,
161    now_ms: i64,
162) -> Result<bool, SyncError> {
163    if let Some(cur) = log::current(conn, collection, record)? {
164        if !cur.header.tombstone && cur.body == body {
165            return Ok(false);
166        }
167    }
168    log::append_local(conn, signer, collection, record, body, false, now_ms)?;
169    Ok(true)
170}
171
172/// Ends a record, if it is live.
173fn tombstone(conn: &Connection, signer: &mut Signer, collection: &str, record: &str, now_ms: i64) -> Result<bool, SyncError> {
174    match log::current(conn, collection, record)? {
175        Some(cur) if !cur.header.tombstone => {
176            log::append_local(conn, signer, collection, record, Vec::new(), true, now_ms)?;
177            Ok(true)
178        }
179        _ => Ok(false),
180    }
181}
182
183fn capture_task(conn: &Connection, signer: &mut Signer, work_id: &str, task: &Task, now_ms: i64, out: &mut Captured) -> Result<(), SyncError> {
184    let hash = digest(&task.records);
185    let seen = seen_of(conn, work_id)?;
186    if seen.as_ref().is_some_and(|s| s.board == task.board && s.hash == hash) {
187        return Ok(());
188    }
189    let collection = collection_id(&task.board);
190    log::ensure_collection(conn, &collection, KIND, now_ms)?;
191    for (record, value) in &task.records {
192        let body = serde_json::to_vec(value).unwrap_or_default();
193        if write_if_changed(conn, signer, &collection, record, body, now_ms)? {
194            out.written += 1;
195        }
196    }
197    // What the task had before and no longer has: a dependency taken off, or everything when it changed board.
198    if let Some(old) = seen {
199        let old_collection = collection_id(&old.board);
200        for record in old.records.iter().filter(|r| old.board != task.board || !task.records.contains_key(*r)) {
201            if tombstone(conn, signer, &old_collection, record, now_ms)? {
202                out.tombstoned += 1;
203            }
204        }
205    }
206    save_seen(conn, work_id, task, &hash)?;
207    Ok(())
208}
209
210/// Ends the records of tasks that are no longer in the Kanban.
211fn capture_gone(conn: &Connection, signer: &mut Signer, tasks: &BTreeMap<String, Task>, now_ms: i64, out: &mut Captured) -> Result<(), SyncError> {
212    let mut stmt = conn.prepare("SELECT work_id, board, records FROM db_sync_kanban_seen")?;
213    let rows = stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, String>(2)?)))?;
214    let gone: Vec<(String, String, String)> = rows.collect::<Result<_, _>>()?;
215    for (work_id, board, records) in gone.into_iter().filter(|(w, _, _)| !tasks.contains_key(w)) {
216        let ids: Vec<String> = serde_json::from_str(&records).unwrap_or_default();
217        let collection = collection_id(&board);
218        for record in ids {
219            if tombstone(conn, signer, &collection, &record, now_ms)? {
220                out.tombstoned += 1;
221            }
222        }
223        conn.execute("DELETE FROM db_sync_kanban_seen WHERE work_id = ?1", params![work_id])?;
224    }
225    Ok(())
226}
227
228const EVENT_BATCH: i64 = 500;
229
230fn event_mark(conn: &Connection) -> rusqlite::Result<i64> {
231    let v: Option<i64> = conn.query_row("SELECT value FROM db_sync_kanban_mark WHERE name = 'events'", [], |r| r.get(0)).optional()?;
232    Ok(v.unwrap_or(0))
233}
234
235/// History lines are written once each, after the id of the last one read. A line of a task that is not in the
236/// Kanban any more is skipped.
237fn capture_events(conn: &Connection, signer: &mut Signer, tasks: &BTreeMap<String, Task>, now_ms: i64, out: &mut Captured) -> Result<(), SyncError> {
238    loop {
239        let after = event_mark(conn)?;
240        let mut stmt = conn.prepare(
241            "SELECT id, work_id, at, actor, actor_kind, kind, from_state, to_state, body FROM db_work_events
242             WHERE id > ?1 ORDER BY id LIMIT ?2",
243        )?;
244        let lines = stmt
245            .query_map(params![after, EVENT_BATCH], |r| {
246                let body = json!({
247                    "at": r.get::<_, i64>(2)?, "actor": r.get::<_, String>(3)?, "actor_kind": r.get::<_, String>(4)?,
248                    "kind": r.get::<_, String>(5)?, "from_state": r.get::<_, String>(6)?, "to_state": r.get::<_, String>(7)?,
249                    "body": r.get::<_, String>(8)?,
250                });
251                Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?, body))
252            })?
253            .collect::<Result<Vec<_>, _>>()?;
254        let Some(last) = lines.last().map(|l| l.0) else { return Ok(()) };
255        for (id, work_id, body) in &lines {
256            let Some(task) = tasks.get(work_id) else { continue };
257            let collection = collection_id(&task.board);
258            log::ensure_collection(conn, &collection, KIND, now_ms)?;
259            let record = format!("{work_id}.event.{}.{id}", signer.machine);
260            if write_if_changed(conn, signer, &collection, &record, serde_json::to_vec(body).unwrap_or_default(), now_ms)? {
261                out.written += 1;
262            }
263        }
264        conn.execute("INSERT OR REPLACE INTO db_sync_kanban_mark (name, value) VALUES ('events', ?1)", params![last])?;
265        if (lines.len() as i64) < EVENT_BATCH {
266            return Ok(());
267        }
268    }
269}
270
271/// Writes into the log whatever changed in the Kanban since the last capture. `default_board` is the board a
272/// task with no board of its own is on. Safe to run again at any time: a record is written only when its value
273/// differs from what the log holds, so a run that stopped half way is finished by the next.
274pub fn capture(conn: &Connection, signer: &mut Signer, default_board: &str, now_ms: i64) -> Result<Captured, SyncError> {
275    let tasks = read_tasks(conn, default_board)?;
276    let mut out = Captured::default();
277    for (work_id, task) in &tasks {
278        capture_task(conn, signer, work_id, task, now_ms, &mut out)?;
279    }
280    capture_gone(conn, signer, &tasks, now_ms, &mut out)?;
281    capture_events(conn, signer, &tasks, now_ms, &mut out)?;
282    Ok(out)
283}
284
285/// The Kanban's merge rule: a field, the lifecycle, a dependency: the newest version is current (a deletion is
286/// the newest version of its record, so it wins over an older edit and loses to a newer one); a history line is
287/// written once, and the first one held stays. Which machine may write a task's lifecycle (its home) comes with
288/// the home field of the numbering step.
289pub struct KanbanAdapter;
290
291impl Adapter for KanbanAdapter {
292    fn merge(&self, local: Option<&Header>, incoming: &Header) -> Merge {
293        match local {
294            Some(_) if incoming.record.contains(".event.") => Merge::KeptLocal,
295            _ => NewestWins.merge(local, incoming),
296        }
297    }
298}