Self-hosted, sharable kanban for humans and agents. One 4.7 MB binary, 5 MB of RAM, 10 to 60 tokens per agent reply, starts in 3 ms, zero setup.
Rust ai-agentsclaude-codeclicodexcoding-agentskanbanlocal-firstmcpmcp-servermodel-context-protocolproductivityproject-managementraspberry-pirustself-hostedsqlitetask-manager
Let a task wait on other tasks
emanuele-em5d8be10036d1
diff --git a/README.md b/README.mdindex 6b11022..daabd27 100644--- a/README.md+++ b/README.md@@ -90,6 +90,13 @@ Turn on Backlog in Settings for a column agents leave alone, until you move its<img alt="The board with the Backlog column on, left of Todo" src="docs/img/backlog-light.jpg"></picture>+## Make a task wait on others++> [!TIP]+> **Just ask your agent:** *"make kanzo#12 wait on #10 and #11."*++List what a task waits on in its panel, or have agents pass `waits_on`. Until those tasks are done, `next_task` skips it, and its card is dimmed and says what it waits on. Only `done` counts: a task in `review` still blocks. Nothing stops you from moving a waiting task yourself.+## Filter and search> [!TIP]@@ -111,6 +118,7 @@ The board's filter (`f`), search (`/`) and the `filter` of `list_tasks` and `nex| `id:`, `comments:`, `images:` | a number, or a range | `id:12`, `comments:>2`, `images:1..3` || `created:`, `updated:` | a date, or a range | `created:2026-11-05`, `updated:<2026-01-31` || `is:human` | tasks for you, not agents | `-is:human` |+| `is:waiting` | tasks waiting on unfinished ones | `-is:waiting` || `has:`, `no:` | `description`, `tags`, `url`, `comments` or `images` | `has:url`, `no:tags` |Anything else is plain text. Use quotes for a phrase, `"on hold"`, or to look for text that reads like a qualifier, `"tag:bug"`. Agents can't filter through a property you've hidden in Settings.diff --git a/src/app.js b/src/app.jsindex 5f449de..ca01f83 100644--- a/src/app.js+++ b/src/app.js@@ -595,7 +595,7 @@ const QUALIFIERS = new Map([["tag", anyText], ["status", anyText], ["project", anyText], ["title", anyText], ["description", anyText],["url", anyText], ["comment", anyText], ["id", inRange(isNumber)], ["comments", inRange(isNumber)],["images", inRange(isNumber)], ["created", inRange(isDate)], ["updated", inRange(isDate)],- ["is", (v) => v === "human"], ["has", isField], ["no", isField],+ ["is", (v) => v === "human" || v === "waiting"], ["has", isField], ["no", isField],]);// A part of a query, read as the server reads it. Null for a word.@@ -655,8 +655,8 @@ function highlight(name, root, words) {CSS.highlights.set(name, new Highlight(...ranges));}-function summary(t, link = null) {- const chips = [...(link ? [link] : []), ...(isPropertyHidden("tags") ? [] : t.tags.map((tag) => el("span", { class: "tag" }, tag)))];+function summary(t, ...extra) {+ const chips = [...extra.filter(Boolean), ...(isPropertyHidden("tags") ? [] : t.tags.map((tag) => el("span", { class: "tag" }, tag)))];return [t.description ? el("span", { class: "desc" }, plainText(t.description)) : null,chips.length ? el("span", { class: "tags" }, chips) : null,@@ -671,6 +671,11 @@ function urlChip(t) {icon("url"), t.url.split("/")[2].replace(/^www\./, ""));}+// Only on cards, like the URL. Most tasks have no waiting_on at all, to keep the board's reply small.+function waitChip(t) {+ return t.waiting_on ? el("span", { class: "tag waits" }, `Waits on ${t.waiting_on.map((id) => `#${id}`).join(", ")}`) : null;+}+// A board on an older version sends no hidden_properties.function isPropertyHidden(property) {return (state.board?.hidden_properties || []).includes(property);@@ -725,14 +730,14 @@ function plainText(md) {}function card(t, showProject) {- const node = el("div", { class: "card" + (state.task === t.id ? " open" : ""), draggable: "true", "data-id": t.id,+ const node = el("div", { class: "card" + (state.task === t.id ? " open" : "") + (t.waiting_on ? " waiting" : ""), draggable: "true", "data-id": t.id,onclick: () => openTask(t.id) },el("div", { class: "head" },el("div", { class: "title" }, t.title),t.human ? el("span", { class: "human-mark", title: "Human task: agents skip it" }, icon("human")) : null,el("span", { class: "num", title: `Copy ${key(t)}`, onclick: (e) => { e.stopPropagation(); copyKey(key(t)); } },showProject ? el("span", { class: "dot", style: `background:${projectColor(t.project)}` }) : null, `#${t.id}`)),- ...summary(t, urlChip(t)));+ ...summary(t, waitChip(t), urlChip(t)));node.addEventListener("dragstart", (e) => {state.dragging = t.id;e.dataTransfer.effectAllowed = "move";@@ -849,6 +854,10 @@ $("#new-project").addEventListener("submit", async (e) => {const panel = $("#panel");let panelTask = null;+let panelWaits = "";++const taskLink = (t) => el("button", { type: "button", class: "tag", title: key(t), onclick: () => pick(t) },+ statusIcon(t.status), el("span", {}, t.title));async function openTask(id) {leavePanelField();@@ -895,13 +904,15 @@ async function refreshTask() {}// Another task may have taken the panel meanwhile.if (state.task !== id) return;- const { task, comments, images } = data;+ // A board on an older version sends neither list.+ const { task, comments, images, waits_on = [], blocks = [] } = data;panelTask = task;+ panelWaits = waits_on.map(key).join(", ");$("#p-key").textContent = key(task);$("#p-key").title = `Copy ${key(task)}`;// Never overwrite what is being typed or picked.if (!$("#p-project").contains(document.activeElement)) renderProjectPick(task);- for (const [field, value] of [[$("#p-title"), task.title], [$("#p-desc"), task.description], [$("#p-tags"), task.tags.join(", ")], [$("#p-url"), task.url || ""]]) {+ for (const [field, value] of [[$("#p-title"), task.title], [$("#p-desc"), task.description], [$("#p-tags"), task.tags.join(", ")], [$("#p-url"), task.url || ""], [$("#p-waits"), panelWaits]]) {if (document.activeElement !== field) { field.value = value; fit(field); }}showDesc();@@ -911,6 +922,9 @@ async function refreshTask() {if (!statuses.includes(task.status)) status.append(el("option", { value: task.status }, task.status));status.value = task.status;$("#p-human").checked = task.human;+ $("#p-waits-links").replaceChildren(...waits_on.map(taskLink));+ $("#p-blocks").replaceChildren(...blocks.map(taskLink));+ $("#p-blocks-row").hidden = !blocks.length;$("#p-created").replaceChildren(timeEl(task.created_at));$("#p-updated").replaceChildren(timeEl(task.updated_at));$("#p-comment-count").textContent = comments.length ? String(comments.length) : "";@@ -1117,6 +1131,14 @@ $("#p-url").addEventListener("blur", (e) => {else e.target.value = url;});+$("#p-waits").addEventListener("keydown", (e) => {+ if (e.key === "Enter") { e.preventDefault(); e.target.blur(); }+ else if (e.key === "Escape") cancelField(e, panelWaits);+});+$("#p-waits").addEventListener("blur", (e) => {+ if (panelTask && e.target.value.trim() !== panelWaits) patchTask({ waits_on: e.target.value });+});+$("#p-comment-form").addEventListener("submit", async (e) => {e.preventDefault();const body = $("#p-comment").value.trim();@@ -1503,7 +1525,7 @@ async function saveSetting(box, fields) {} catch (err) { box.checked = !box.checked; toast(err.message); }}$("#settings-backlog").addEventListener("change", (e) => saveSetting(e.target, { backlog: e.target.checked }));-$('.settings-pane[data-section="board"]').append(...["Description", "Tags", "URL", "Human", "Created", "Updated", "Comments", "Images"].map((name) => {+$('.settings-pane[data-section="board"]').append(...["Description", "Tags", "URL", "Human", "Waiting", "Created", "Updated", "Comments", "Images"].map((name) => {const property = name.toLowerCase();return el("label", { class: "setting" }, el("span", { class: "text" }, name),el("span", { class: "switch" },diff --git a/src/export.rs b/src/export.rsindex 322e9c3..a3e4d24 100644--- a/src/export.rs+++ b/src/export.rs@@ -36,6 +36,7 @@ struct TaskOut {tags: Vec<String>,url: String,human: bool,+ waits_on: Vec<String>,images: Vec<String>,status: String,created_at: String,@@ -44,7 +45,7 @@ struct TaskOut {}impl TaskOut {- fn new(task: Task, comments: Vec<Comment>, images: Vec<String>) -> Self {+ fn new(task: Task, comments: Vec<Comment>, images: Vec<String>, waits_on: Vec<String>) -> Self {Self {key: task.key(),id: task.id,@@ -53,6 +54,7 @@ impl TaskOut {tags: task.tags,url: task.url,human: task.human,+ waits_on,images,status: task.status,created_at: task.created_at,@@ -91,7 +93,8 @@ fn collect(store: &Store, only: Option<&str>, images: &Path) -> Result<Board> {for task in store.list_tasks(Some(project.id), None)? {let comments = store.list_comments(task.id)?;let paths = store.list_images(task.id)?.into_iter().map(|i| images.join(i.file).display().to_string());- tasks.push(TaskOut::new(task, comments, paths.collect()));+ let waits = store.task_links(task.id, false)?.into_iter().map(|t| format!("{}#{}", t.project, t.id));+ tasks.push(TaskOut::new(task, comments, paths.collect(), waits.collect()));}out.push(ProjectOut { project, tasks });}@@ -140,6 +143,9 @@ fn markdown(board: &Board) -> String {if !t.tags.is_empty() {let _ = writeln!(md, "Tags: {}.", t.tags.join(", "));}+ if !t.waits_on.is_empty() {+ let _ = writeln!(md, "Waits on: {}.", t.waits_on.join(", "));+ }if !t.url.is_empty() {let _ = writeln!(md, "URL: <{}>", t.url);}@@ -178,12 +184,15 @@ mod tests {store.add_comment(t.id, "claude-code", "Found it\nin auth.rs", &[]).unwrap();let done = store.create_task(api.id, "Old work", "").unwrap();store.move_task(done.id, "done", None).unwrap();+ let waits = store::TaskPatch { waits_on: Some(done.key()), ..Default::default() };+ store.update_task(t.id, waits).unwrap();let board = collect(&store, None, Path::new("/k/images")).unwrap();let md = markdown(&board);assert!(md.contains("## API `api` ([me/api](https://github.com/me/api))"), "{md}");assert!(md.contains("### todo\n\n#### api#1 Fix login"), "{md}");assert!(md.contains("Steps:\n1. log in"), "{md}");+ assert!(md.contains("Waits on: api#2."), "{md}");assert!(md.contains("- **claude-code**, ") && md.contains("Found it\n in auth.rs"), "{md}");assert!(md.contains("### done\n\n#### api#2 Old work"), "{md}");assert!(md.contains("## Web `web`"), "{md}");@@ -192,6 +201,7 @@ mod tests {assert_eq!(json["statuses"][0], "todo");assert_eq!(json["projects"][0]["slug"], "api");assert_eq!(json["projects"][0]["tasks"][0]["key"], "api#1");+ assert_eq!(json["projects"][0]["tasks"][0]["waits_on"][0], "api#2");assert_eq!(json["projects"][0]["tasks"][0]["comments"][0]["author"], "claude-code");let only = collect(&store, Some("web"), Path::new("/k/images")).unwrap();diff --git a/src/index.html b/src/index.htmlindex 5d87c8e..82e870c 100644--- a/src/index.html+++ b/src/index.html@@ -216,6 +216,7 @@ header .repo-link .icon svg { width: 14px; height: 14px; }}.card:hover { background: var(--card-hover); }.card.open { background: var(--active); }+html:not([data-hide~="waiting"]) .card.waiting:not(:hover) { opacity: .6; }.card.dragging { opacity: .4; }.card .head { display: flex; align-items: flex-start; gap: 10px; }.card .title { overflow-wrap: anywhere; flex: 1; min-width: 0; }@@ -294,10 +295,16 @@ header .repo-link .icon svg { width: 14px; height: 14px; }[data-hide~="description"] .desc, [data-hide~="description"] [data-prop="description"],[data-hide~="tags"] [data-prop="tags"], [data-hide~="url"] [data-prop="url"],[data-hide~="human"] .human-mark, [data-hide~="human"] [data-prop="human"],+[data-hide~="waiting"] .waits, [data-hide~="waiting"] [data-prop="waiting"],[data-hide~="created"] [data-prop="created"],[data-hide~="updated"] [data-prop="updated"],[data-hide~="comments"] .result .comments, [data-hide~="comments"] [data-prop="comments"],[data-hide~="images"] .panel .thumbs { display: none; }+.links { display: flex; flex-wrap: wrap; gap: 4px; }+#p-waits-links:not(:empty) { margin-top: 8px; }+.links .tag { border: 0; max-width: 100%; }+.links .tag:hover, .links .tag:focus-visible { background: var(--active); }+.links span:last-child { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: inherit; }.section h3 {font-size: 13px; color: var(--muted); margin: 0 0 8px; font-weight: 600;display: flex; align-items: center; gap: 8px;@@ -515,6 +522,8 @@ label.setting { cursor: pointer; }<div data-prop="tags">Tags <span><input class="inline" id="p-tags" placeholder="Add tags, like bug, ui" autocomplete="off" spellcheck="false"></span></div><div data-prop="url">URL <span><input class="inline" id="p-url" type="url" placeholder="Add a link, like a pull request" autocomplete="off" spellcheck="false"></span></div><div data-prop="human">Human <span class="human-field"><label class="switch"><input type="checkbox" id="p-human" aria-label="Human task"><span></span></label><span class="hint">Agents skip it</span></span></div>+ <div data-prop="waiting">Waits on <span><input class="inline" id="p-waits" placeholder="Add tasks, like api#12" autocomplete="off" spellcheck="false"><span class="links" id="p-waits-links"></span></span></div>+ <div data-prop="waiting" id="p-blocks-row">Blocks <span class="links" id="p-blocks"></span></div><div data-prop="created">Created <span id="p-created"></span></div><div data-prop="updated">Updated <span id="p-updated"></span></div></div>diff --git a/src/mcp.rs b/src/mcp.rsindex 523fdae..3dd9864 100644--- a/src/mcp.rs+++ b/src/mcp.rs@@ -196,7 +196,7 @@ struct ListTasksArgs {/// One column, or "all". Done is left out by default.status: Option<String>,/// Words, or tag: status: project: title: description: url: comment: id: comments: images: created: updated:- /// is:human has: no:, like tag:bug -status:done. Includes done.+ /// is:human is:waiting has: no:, like tag:bug -status:done. Includes done.filter: Option<String>,}@@ -220,6 +220,8 @@ struct CreateTaskArgs {status: Option<String>,/// For the user, not for agents.human: Option<bool>,+ /// Tasks it waits on, like api#12.+ waits_on: Option<String>,}#[derive(Deserialize, JsonSchema)]@@ -238,6 +240,8 @@ struct UpdateTaskArgs {human: Option<bool>,/// A link; "" clears.url: Option<String>,+ /// Tasks it waits on, like api#12; "" clears.+ waits_on: Option<String>,}#[derive(Deserialize, JsonSchema)]@@ -469,12 +473,12 @@ impl Kanzo {) -> Result<CallToolResult, ErrorData> {Ok(self.run_for(&ext, move |ctx, store| {- let CreateTaskArgs { title, description, project, tags, status, human } = args;+ let CreateTaskArgs { title, description, project, tags, status, human, waits_on } = args;let project = ctx.project(store, project.as_deref())?;let status = status.map(|s| s.trim().to_ascii_lowercase()).filter(|s| !s.is_empty());- let patch = TaskPatch { description, status, tags, human, ..Default::default() };+ let patch = TaskPatch { description, status, tags, human, waits_on, ..Default::default() };let t = store.create_task_in(project.id, &title, patch)?;- Ok(format!("Created {} in {}: {}", t.key(), t.status, t.title))+ Ok(format!("Created {} in {}: {}{}", t.key(), t.status, t.title, waits_note(store, &t)?))}).await)}@@ -495,6 +499,7 @@ impl Kanzo {project_id: None,human: args.human,url: args.url,+ waits_on: args.waits_on,},)?;let moved = if before.status != after.status {@@ -502,7 +507,7 @@ impl Kanzo {} else {String::new()};- Ok(format!("Updated {}{moved}: {}", after.key(), after.title))+ Ok(format!("Updated {}{moved}: {}{}", after.key(), after.title, waits_note(store, &after)?))}).await)}@@ -533,11 +538,18 @@ impl Kanzo {Ok(self.run_for(&ext, move |ctx, store| {let project = ctx.scope(store, args.project.as_deref())?;- match store.next_task_matching(project.as_ref().map(|p| p.id), args.filter.as_deref().unwrap_or(""))? {+ let id = project.as_ref().map(|p| p.id);+ let filter = args.filter.as_deref().unwrap_or("");+ match store.next_task_matching(id, filter)? {Some(task) => Ok(format!("Moved to {}:\n{}", task.status, task_detail(ctx, store, &task)?)),None => {+ let waiting = store.waiting_in_todo(id, filter)?;let scope = project.map_or("any project".into(), |p| p.slug);- Ok(format!("Nothing in todo for {scope}."))+ Ok(match waiting {+ 0 => format!("Nothing in todo for {scope}."),+ 1 => format!("Nothing ready in todo for {scope}: 1 task waits on others."),+ n => format!("Nothing ready in todo for {scope}: {n} tasks wait on others."),+ })}}})@@ -605,6 +617,9 @@ fn task_line(out: &mut String, t: &Task, hidden: &[String]) {if shown(hidden, "tags") {write_tags(out, t);}+ if shown(hidden, "waiting") {+ write_waits(out, t);+ }match if shown(hidden, "comments") { t.comments } else { 0 } {0 => {}1 => out.push_str(" (1 comment)"),@@ -620,6 +635,22 @@ fn write_tags(out: &mut String, t: &Task) {}}+fn write_waits(out: &mut String, t: &Task) {+ if !t.waiting_on.is_empty() {+ let ids: Vec<String> = t.waiting_on.iter().map(|id| format!("#{id}")).collect();+ let _ = write!(out, " (waits on {})", ids.join(", "));+ }+}++/// Tells an agent that moved or changed a task that it's still waiting; moving one anyway is allowed.+fn waits_note(store: &Store, t: &Task) -> store::Result<String> {+ let mut note = String::new();+ if !t.waiting_on.is_empty() && shown(&store.hidden_properties()?, "waiting") {+ write_waits(&mut note, t);+ }+ Ok(note)+}+fn task_detail(ctx: &Ctx, store: &Store, t: &Task) -> store::Result<String> {let hidden = store.hidden_properties()?;let comments = if shown(&hidden, "comments") { store.list_comments(t.id)? } else { Vec::new() };@@ -634,6 +665,9 @@ fn task_detail(ctx: &Ctx, store: &Store, t: &Task) -> store::Result<String> {write_tags(&mut out, t);}let _ = write!(out, "\nstatus: {}", t.status);+ if shown(&hidden, "waiting") {+ write_waits(&mut out, t);+ }if t.human && shown(&hidden, "human") {out.push_str(", human: for the user, not for agents");}@@ -754,6 +788,36 @@ mod tests {meta}+ #[test]+ fn agents_see_what_a_task_waits_on_and_why_nothing_is_ready() {+ block_on(async {+ let (dir, home, blocker) = board();+ let mut agent = Agent::start(home.clone(), dir.path());+ let mut call = async |name: &str, args: Value| -> String {+ let params = json!({ "name": name, "arguments": args, "_meta": stateless(None) });+ let message = json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": params });+ let reply = agent.send(message).await.unwrap();+ reply["result"]["content"][0]["text"].as_str().unwrap().to_string()+ };+ let waiting =+ call("create_task", json!({ "title": "Then this", "project": "api", "waits_on": blocker.key() })).await;+ assert_eq!(waiting, "Created api#2 in todo: Then this (waits on #1)");+ assert!(call("list_tasks", json!({ "project": "api" })).await.contains("Then this (waits on #1)"));+ assert!(call("get_task", json!({ "id": "api#2" })).await.contains("status: todo (waits on #1)"));++ call("update_task", json!({ "id": "api#1", "status": "doing" })).await;+ let next = call("next_task", json!({ "project": "api" })).await;+ assert_eq!(next, "Nothing ready in todo for api: 1 task waits on others.");+ let moved = call("update_task", json!({ "id": "api#2", "status": "doing" })).await;+ assert_eq!(moved, "Updated api#2, todo -> doing: Then this (waits on #1)");+ let next = call("next_task", json!({ "project": "api" })).await;+ assert_eq!(next, "Nothing in todo for api.");++ home.store().unwrap().set_property("waiting", false).unwrap();+ assert!(!call("get_task", json!({ "id": "api#2" })).await.contains("waits on"));+ });+ }+#[test]fn a_joined_board_takes_calls_from_a_client_that_never_initialized() {block_on(async {diff --git a/src/store.rs b/src/store.rsindex 91edd38..7eea117 100644--- a/src/store.rs+++ b/src/store.rs@@ -44,6 +44,14 @@ const MIGRATIONS: &[&str] = &[CREATE TRIGGER images_delete AFTER DELETE ON images BEGIN UPDATE meta SET value = value + 1 WHERE key = 'changes'; END;","ALTER TABLE tasks ADD COLUMN human INTEGER NOT NULL DEFAULT 0;","ALTER TABLE tasks ADD COLUMN url TEXT NOT NULL DEFAULT '';",+ "CREATE TABLE task_waits (+ task_id INTEGER NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,+ waits_on_id INTEGER NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,+ PRIMARY KEY (task_id, waits_on_id)+ ) WITHOUT ROWID;+ CREATE INDEX task_waits_by_blocker ON task_waits(waits_on_id);+ CREATE TRIGGER task_waits_insert AFTER INSERT ON task_waits BEGIN UPDATE meta SET value = value + 1 WHERE key = 'changes'; END;+ CREATE TRIGGER task_waits_delete AFTER DELETE ON task_waits BEGIN UPDATE meta SET value = value + 1 WHERE key = 'changes'; END;",];const PROJECT_COLORS: &[&str] = &["gray", "red", "orange", "yellow", "green", "teal", "blue", "purple", "pink"];@@ -111,6 +119,9 @@ pub struct Task {pub created_at: String,pub updated_at: String,pub comments: i64,+ /// The tasks this one waits on that aren't done yet. Left out when there are none, as on most tasks.+ #[serde(skip_serializing_if = "Vec::is_empty")]+ pub waiting_on: Vec<i64>,}impl Task {@@ -119,6 +130,15 @@ impl Task {}}+/// A task another one waits on or blocks.+#[derive(Debug, Clone, Serialize)]+pub struct TaskLink {+ pub id: i64,+ pub project: String,+ pub title: String,+ pub status: String,+}+#[derive(Debug, Clone, Serialize)]pub struct Comment {pub id: i64,@@ -145,6 +165,8 @@ pub struct TaskPatch {pub tags: Option<String>,pub url: Option<String>,pub human: Option<bool>,+ /// Task keys, comma-separated; it replaces the list.+ pub waits_on: Option<String>,}const STATUSES: [&str; 4] = ["todo", "doing", "review", "done"];@@ -154,7 +176,8 @@ pub const DONE: &str = STATUSES[3];pub const BACKLOG: &str = "backlog";/// What a task shows besides its id, title and status; each can be turned off in Settings.-const PROPERTIES: [&str; 8] = ["description", "tags", "url", "human", "created", "updated", "comments", "images"];+const PROPERTIES: [&str; 9] =+ ["description", "tags", "url", "human", "waiting", "created", "updated", "comments", "images"];pub struct Store {conn: Connection,@@ -457,7 +480,8 @@ impl Store {const TASK_SELECT: &str = "SELECT t.id, p.slug, t.title, t.description, t.status, t.position,t.created_at, t.updated_at, (SELECT count(*) FROM comments c WHERE c.task_id = t.id), t.tags, t.human,- t.url+ t.url, (SELECT group_concat(w.waits_on_id, ',' ORDER BY w.waits_on_id) FROM task_waits w+ JOIN tasks b ON b.id = w.waits_on_id WHERE w.task_id = t.id AND b.status <> 'done')FROM tasks t JOIN projects p ON p.id = t.project_id";fn task_row(r: &Row) -> rusqlite::Result<Task> {@@ -474,6 +498,10 @@ impl Store {created_at: r.get(6)?,updated_at: r.get(7)?,comments: r.get(8)?,+ waiting_on: r+ .get::<_, Option<String>>(12)?+ .map(|ids| ids.split(',').filter_map(|id| id.parse().ok()).collect())+ .unwrap_or_default(),})}@@ -596,7 +624,8 @@ impl Store {self.create_task_in(project, title, TaskPatch { description: Some(description.into()), ..Default::default() })}- // One write, or an agent could take a task before it's human. Uses description, status, tags, human.+ // One write, or an agent could take a task before it's human, or before it waits.+ // Uses description, status, tags, human, waits_on.pub fn create_task_in(&self, project_id: i64, title: &str, patch: TaskPatch) -> Result<Task> {let title = clean_title(title)?;let status = patch.status.as_deref().unwrap_or(STATUSES[0]);@@ -610,11 +639,58 @@ impl Store {VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",params![project_id, title, description, status, position, tags, patch.human.unwrap_or(false)],)?;- Ok(c.last_insert_rowid())+ let id = c.last_insert_rowid();+ if let Some(keys) = &patch.waits_on {+ self.set_waits(c, id, keys)?;+ }+ Ok(id)})?;self.get_task(id)}+ /// Replaces what a task waits on. Part of the task's write, so a refused list changes nothing.+ fn set_waits(&self, c: &Connection, id: i64, keys: &str) -> Result<()> {+ let mut ids = Vec::new();+ for key in keys.split(',').map(str::trim).filter(|k| !k.is_empty()) {+ ids.push(self.find_task(key)?.id);+ }+ ids.sort_unstable();+ ids.dedup();+ if ids.iter().copied().eq(self.task_links(id, false)?.iter().map(|t| t.id)) {+ return Ok(());+ }+ c.execute("DELETE FROM task_waits WHERE task_id = ?1", [id])?;+ for other in ids {+ let loops: bool = c.query_row(+ "WITH RECURSIVE chain(id) AS (+ SELECT ?1 UNION SELECT w.waits_on_id FROM task_waits w JOIN chain ON w.task_id = chain.id+ ) SELECT EXISTS (SELECT 1 FROM chain WHERE id = ?2)",+ [other, id],+ |r| r.get(0),+ )?;+ if loops {+ return Err(Error::Invalid(format!("#{id} can't wait on #{other}: that would make a loop")));+ }+ c.execute("INSERT INTO task_waits (task_id, waits_on_id) VALUES (?1, ?2)", [id, other])?;+ }+ c.execute(&format!("UPDATE tasks SET updated_at = {NOW} WHERE id = ?1"), [id])?;+ Ok(())+ }++ /// What a task waits on, done or not, or with `blocks`, the tasks waiting on it.+ pub fn task_links(&self, id: i64, blocks: bool) -> Result<Vec<TaskLink>> {+ let (this, other) = if blocks { ("waits_on_id", "task_id") } else { ("task_id", "waits_on_id") };+ let sql = format!(+ "SELECT t.id, p.slug, t.title, t.status FROM task_waits w JOIN tasks t ON t.id = w.{other}+ JOIN projects p ON p.id = t.project_id WHERE w.{this} = ?1 ORDER BY t.id"+ );+ let mut stmt = self.conn.prepare_cached(&sql)?;+ let rows = stmt.query_map([id], |r| {+ Ok(TaskLink { id: r.get(0)?, project: r.get(1)?, title: r.get(2)?, status: r.get(3)? })+ })?;+ Ok(rows.collect::<rusqlite::Result<_>>()?)+ }+pub fn update_task(&self, id: i64, patch: TaskPatch) -> Result<Task> {let title = patch.title.as_deref().map(clean_title).transpose()?;let url = patch.url.as_deref().map(clean_url).transpose()?;@@ -653,6 +729,9 @@ impl Store {params![s, position, id],)?;}+ if let Some(keys) = &patch.waits_on {+ self.set_waits(c, id, keys)?;+ }Ok(())})?;self.get_task(id)@@ -722,23 +801,36 @@ impl Store {self.next_task_matching(project_id, "")}- pub fn next_task_matching(&self, project_id: Option<i64>, query: &str) -> Result<Option<Task>> {+ /// The todo tasks for agents that match `query`, from FROM on, with its values.+ fn agents_todo(&self, project_id: Option<i64>, query: &str) -> Result<(String, Vec<Value>)> {let filter = if query.trim().is_empty() {Filter::default()} else {self.add_has_word()?;Filter::new(query, 3, &self.hidden_properties()?)};- let [from, to, ..] = STATUSES;+ let sql = format!(+ "FROM tasks t JOIN projects p ON p.id = t.project_id+ WHERE t.status = ?1 AND t.human = 0 AND (?2 IS NULL OR t.project_id = ?2){}",+ filter.sql+ );+ let mut values: Vec<Value> = vec![STATUSES[0].to_string().into(), project_id.into()];+ values.extend(filter.values.into_iter().map(Value::from));+ Ok((sql, values))+ }++ /// How many tasks `next_task` skips because they wait on others.+ pub fn waiting_in_todo(&self, project_id: Option<i64>, query: &str) -> Result<i64> {+ let (todo, values) = self.agents_todo(project_id, query)?;+ let sql = format!("SELECT count(*) {todo} AND {WAITING}");+ Ok(self.conn.query_row(&sql, rusqlite::params_from_iter(values), |r| r.get(0))?)+ }++ pub fn next_task_matching(&self, project_id: Option<i64>, query: &str) -> Result<Option<Task>> {+ let (todo, values) = self.agents_todo(project_id, query)?;+ let to = STATUSES[1];let id = self.write(|c| {- let sql = format!(- "SELECT t.id FROM tasks t JOIN projects p ON p.id = t.project_id- WHERE t.status = ?1 AND t.human = 0 AND (?2 IS NULL OR t.project_id = ?2){}- ORDER BY t.position LIMIT 1",- filter.sql- );- let mut values: Vec<Value> = vec![from.to_string().into(), project_id.into()];- values.extend(filter.values.iter().cloned().map(Value::from));+ let sql = format!("SELECT t.id {todo} AND NOT {WAITING} ORDER BY t.position LIMIT 1");let id: Option<i64> = c.query_row(&sql, rusqlite::params_from_iter(values), |r| r.get(0)).optional()?;if let Some(id) = id {let position = Self::end_of_column(c, to, id)?;@@ -910,6 +1002,9 @@ pub fn short_time(ts: &str) -> String {const COMMENT_COUNT: &str = "(SELECT count(*) FROM comments WHERE task_id = t.id)";const IMAGE_COUNT: &str = "(SELECT count(*) FROM images WHERE task_id = t.id)";+/// Computed, never stored: reopening a task blocks what waits on it again, with nothing to keep in step.+const WAITING: &str = "EXISTS (SELECT 1 FROM task_waits w JOIN tasks b ON b.id = w.waits_on_id+ WHERE w.task_id = t.id AND b.status <> 'done')";const QUALIFIERS: [&str; 15] = ["tag","status",@@ -981,8 +1076,7 @@ impl Filter {let property = match name {"tag" => "tags","comment" => "comments",- "is" => "human",- "has" | "no" => value,+ "is" | "has" | "no" => value,other => other,};if hidden.iter().any(|h| h == property) {@@ -1007,6 +1101,7 @@ impl Filter {("created", range) => range_sql("substr(t.created_at, 1, 10)", range, date)?,("updated", range) => range_sql("substr(t.updated_at, 1, 10)", range, date)?,("is", "human") => "t.human".to_string(),+ ("is", "waiting") => WAITING.to_string(),("has" | "no", "description") => "t.description <> ''".to_string(),("has" | "no", "tags") => "t.tags <> ''".to_string(),("has" | "no", "url") => "t.url <> ''".to_string(),@@ -1172,6 +1267,105 @@ mod tests {assert_eq!(v, MIGRATIONS.len().to_string());}+ fn waits(keys: &str) -> TaskPatch {+ TaskPatch { waits_on: Some(keys.into()), ..Default::default() }+ }++ #[test]+ fn next_task_skips_a_task_until_what_it_waits_on_is_done() {+ let (_dir, s) = store();+ let p = s.create_project("api", "", None).unwrap();+ let blocked = s.create_task_in(p.id, "blocked", TaskPatch { tags: Some("bug".into()), ..Default::default() });+ let blocked = blocked.unwrap();+ let blocker = s.create_task(p.id, "blocker", "").unwrap();+ let other = s.create_task(p.id, "other", "").unwrap();+ s.move_task(blocker.id, "review", None).unwrap();+ s.update_task(blocked.id, waits(&format!("#{}, api#{}", blocker.id, other.id))).unwrap();+ assert_eq!(s.get_task(blocked.id).unwrap().waiting_on, [blocker.id, other.id]);++ assert_eq!(s.next_task_matching(None, "tag:bug").unwrap().map(|t| t.id), None);+ assert_eq!(s.waiting_in_todo(None, "tag:bug").unwrap(), 1);+ assert_eq!(s.waiting_in_todo(None, "tag:nope").unwrap(), 0);+ assert_eq!(s.next_task(None).unwrap().map(|t| t.id), Some(other.id));+ s.move_task(other.id, "done", None).unwrap();+ assert_eq!(s.get_task(blocked.id).unwrap().waiting_on, [blocker.id]);+ assert_eq!(s.next_task(None).unwrap().map(|t| t.id), None, "review isn't done");++ s.move_task(blocker.id, "done", None).unwrap();+ assert!(s.get_task(blocked.id).unwrap().waiting_on.is_empty());+ s.move_task(blocker.id, "doing", None).unwrap();+ assert_eq!(s.next_task(None).unwrap().map(|t| t.id), None, "reopening blocks it again");+ s.move_task(blocker.id, "done", None).unwrap();+ assert_eq!(s.next_task(None).unwrap().map(|t| t.id), Some(blocked.id));+ }++ #[test]+ fn a_loop_or_a_bad_key_changes_nothing() {+ let (_dir, s) = store();+ let p = s.create_project("api", "", None).unwrap();+ let [a, b, c] = ["a", "b", "c"].map(|t| s.create_task(p.id, t, "").unwrap().id);+ s.update_task(a, waits(&b.to_string())).unwrap();+ s.update_task(b, waits(&c.to_string())).unwrap();+ for keys in [a.to_string(), format!("{c}"), "999".to_string(), format!("nope#{a}")] {+ assert!(s.update_task(c, waits(&keys)).is_err(), "{keys}");+ assert!(s.get_task(c).unwrap().waiting_on.is_empty(), "{keys}");+ }+ assert!(s.update_task(a, waits(&format!("{c}, {a}"))).is_err());+ assert_eq!(s.get_task(a).unwrap().waiting_on, [b], "a refused list keeps the old one");++ let new = TaskPatch { waits_on: Some("999".into()), ..Default::default() };+ assert!(s.create_task_in(p.id, "bad", new).is_err());+ assert_eq!(s.list_tasks(None, None).unwrap().len(), 3, "a bad key creates no task");++ s.update_task(a, waits("")).unwrap();+ assert!(s.get_task(a).unwrap().waiting_on.is_empty());+ }++ #[test]+ fn deleting_what_a_task_waits_on_frees_it() {+ let (_dir, s) = store();+ let p = s.create_project("api", "", None).unwrap();+ let blocker = s.create_task(p.id, "blocker", "").unwrap();+ s.move_task(blocker.id, "doing", None).unwrap();+ let new = TaskPatch { waits_on: Some(blocker.id.to_string()), ..Default::default() };+ let task = s.create_task_in(p.id, "task", new).unwrap();+ assert_eq!(task.waiting_on, [blocker.id]);+ assert_eq!(s.task_links(blocker.id, true).unwrap()[0].id, task.id);+ assert_eq!(s.task_links(task.id, false).unwrap()[0].id, blocker.id);+ s.delete_task(blocker.id).unwrap();+ assert_eq!(s.next_task(None).unwrap().map(|t| t.id), Some(task.id));+ }++ #[test]+ fn editing_the_same_list_changes_nothing() {+ let (_dir, s) = store();+ let p = s.create_project("api", "", None).unwrap();+ let blocker = s.create_task(p.id, "blocker", "").unwrap();+ let task = s.create_task(p.id, "task", "").unwrap();+ s.update_task(task.id, waits(&blocker.id.to_string())).unwrap();+ let before = s.changes().unwrap();+ s.update_task(task.id, waits(&format!("#{}", blocker.id))).unwrap();+ assert_eq!(s.changes().unwrap(), before);+ }++ #[test]+ fn filters_by_waiting_and_leaves_it_out_of_json_when_empty() {+ let (_dir, s) = store();+ let p = s.create_project("api", "", None).unwrap();+ let blocker = s.create_task(p.id, "blocker", "").unwrap();+ let task = s.create_task(p.id, "task", "").unwrap();+ s.update_task(task.id, waits(&blocker.id.to_string())).unwrap();+ assert_eq!(titles(&s.search("is:waiting", None).unwrap()), ["task"]);+ assert_eq!(titles(&s.search("-is:waiting", None).unwrap()), ["blocker"]);+ let json = serde_json::to_value(s.get_task(blocker.id).unwrap()).unwrap();+ assert!(json.get("waiting_on").is_none(), "{json}");+ let json = serde_json::to_value(s.get_task(task.id).unwrap()).unwrap();+ assert_eq!(json["waiting_on"], serde_json::json!([blocker.id]));++ s.set_property("waiting", false).unwrap();+ assert_eq!(s.search_for_agent("is:waiting").unwrap().len(), 0, "a hidden property finds nothing");+ }+#[test]fn keeps_only_the_newest_done_tasks() {let (_dir, s) = store();diff --git a/src/web.rs b/src/web.rsindex 7245bbf..95b4df3 100644--- a/src/web.rs+++ b/src/web.rs@@ -527,14 +527,22 @@ async fn update_settings(State(home): Shared, Json(r): Json<Settings>) -> Respon#[derive(Serialize)]struct TaskReply {+ blocks: Vec<store::TaskLink>,comments: Vec<store::Comment>,images: Vec<store::Image>,task: store::Task,+ waits_on: Vec<store::TaskLink>,}async fn get_task(State(home): Shared, Path(id): Path<i64>) -> Response {with_store(home, move |_, s| {- Ok(TaskReply { comments: s.list_comments(id)?, images: s.list_images(id)?, task: s.get_task(id)? })+ Ok(TaskReply {+ blocks: s.task_links(id, true)?,+ comments: s.list_comments(id)?,+ images: s.list_images(id)?,+ task: s.get_task(id)?,+ waits_on: s.task_links(id, false)?,+ })}).await}@@ -548,6 +556,7 @@ struct Patch {tags: Option<String>,human: Option<bool>,url: Option<String>,+ waits_on: Option<String>,}async fn update_task(State(home): Shared, Path(id): Path<i64>, Json(p): Json<Patch>) -> Response {@@ -563,6 +572,7 @@ async fn update_task(State(home): Shared, Path(id): Path<i64>, Json(p): Json<Pattags: p.tags,human: p.human,url: p.url,+ waits_on: p.waits_on,},)})