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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions .cubil/done/deepen-the-task-store.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
---
created: 2026-11-12
---

# Deepen the Task store

Create a Task store module that owns finding, listing, creating, moving and removing Tasks across Statuses.

## Problem
Every command repeats root discovery, scanning and slug resolution. `commands/mv.rs` repeats `transition()` in `commands/mod.rs` almost line for line. `roadmap/show.rs`, `roadmap/next.rs` and `roadmap/add.rs` each build their own slug-to-status lookup. The "backlog" literal appears in several files.

## Scope
- Interface: find(slug), tasks(), create(slug, text), move_to(slug, status), remove(slug).
- Collision, ambiguity, reserved-directory and missing-Status rules live behind the interface.
- Files: src/core/slug.rs, src/commands/{mod,mv,rm,new,show,edit,start,finish,list}.rs, src/commands/roadmap/{show,next,add}.rs.

## Done when
- mv and start/finish share one move path.
- The roadmap commands take their lookup from the Task store.
- Tests exercise the Task store through its interface against a tempdir.
3 changes: 2 additions & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@ src/
├── main.rs CLI definition (clap) and command dispatch
├── core/
│ ├── root.rs Find the .cubil/ directory from any working directory
│ ├── slug.rs Slugify titles, scan status folders, resolve a slug
│ ├── slug.rs Slugify titles into kebab-case slugs
│ ├── store.rs Task store: find, list, create, move and remove tasks
│ ├── frontmatter.rs YAML frontmatter parse and assemble
│ ├── roadmap.rs Roadmap line grammar: task lines, headings, milestones
│ ├── updater.rs Self-update: target detection, download, atomic replace
Expand Down
6 changes: 2 additions & 4 deletions src/commands/edit.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use std::process::Command;

use crate::core::error::Result;
use crate::core::root::find_root;
use crate::core::slug::resolve_slug;
use crate::core::store::TaskStore;

/// Open the task identified by `slug` in the user's editor.
///
Expand All @@ -20,8 +19,7 @@ use crate::core::slug::resolve_slug;
/// `:wq` from a deliberate `:cq`, so any successful spawn-and-wait is
/// treated as success regardless of the editor's exit code.
pub fn run(slug: &str) -> Result<()> {
let root = find_root(None)?;
let (_task_status, path) = resolve_slug(&root, slug)?;
let path = TaskStore::discover()?.find(slug)?.path;

let editor = std::env::var("EDITOR").unwrap_or_default();
let mut parts = editor.split_ascii_whitespace();
Expand Down
2 changes: 1 addition & 1 deletion src/commands/finish.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::core::error::Result;

/// Move task `<slug>` from `doing/` to `done/`.
pub fn run(slug: String) -> Result<()> {
pub fn run(slug: &str) -> Result<()> {
super::transition(slug, "doing", "done")
}
14 changes: 6 additions & 8 deletions src/commands/list.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
use std::cmp::Ordering;
use std::fmt::Write as _;
use std::path::Path;

use crate::core::error::{CubilError, Result};
use crate::core::frontmatter::parse_frontmatter;
use crate::core::root::find_root;
use crate::core::slug::{TaskEntry, scan_all};
use crate::core::store::{TaskEntry, TaskStore};

const DONE: &str = "done";

Expand All @@ -17,8 +15,8 @@ struct Row {
}

pub fn run(all: bool, status: Option<&str>, json: bool) -> Result<()> {
let root = find_root(None)?;
let rows = collect_rows(&root, all, status)?;
let store = TaskStore::discover()?;
let rows = collect_rows(&store, all, status)?;
if json {
println!("{}", render_json(&rows));
} else {
Expand All @@ -27,9 +25,9 @@ pub fn run(all: bool, status: Option<&str>, json: bool) -> Result<()> {
Ok(())
}

fn collect_rows(root: &Path, all: bool, status: Option<&str>) -> Result<Vec<Row>> {
fn collect_rows(store: &TaskStore, all: bool, status: Option<&str>) -> Result<Vec<Row>> {
if let Some(name) = status
&& !root.join(name).is_dir()
&& !store.has_status(name)
{
return Err(CubilError::StatusMissing(name.to_string()));
}
Expand All @@ -38,7 +36,7 @@ fn collect_rows(root: &Path, all: bool, status: Option<&str>) -> Result<Vec<Row>
status: entry_status,
slug,
path,
} in scan_all(root)?
} in store.tasks()?
{
let keep = match status {
Some(name) => entry_status == name,
Expand Down
46 changes: 7 additions & 39 deletions src/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,46 +10,14 @@ pub mod show;
pub mod start;
pub mod update;

use crate::core::error::{CubilError, Result};
use crate::core::{root, slug as slug_mod};
use crate::core::error::Result;
use crate::core::store::TaskStore;

/// Move a task from `expected` status to `target` status.
///
/// Errors with [`CubilError::StatusMismatch`] if the task exists but is in a
/// different status folder. `SlugNotFound` / `SlugAmbiguous` propagate from
/// [`slug_mod::resolve_slug`]. Errors with [`CubilError::StatusMissing`] if
/// the destination folder does not exist, and [`CubilError::SlugCollision`]
/// if a file with the same slug already exists at the destination.
pub(crate) fn transition(slug: String, expected: &str, target: &str) -> Result<()> {
let root = root::find_root(None)?;
let (current_status, current_path) = slug_mod::resolve_slug(&root, &slug)?;

if current_status != expected {
return Err(CubilError::StatusMismatch {
slug,
expected: expected.to_string(),
actual: current_status,
});
}

let dest_dir = root.join(target);
if !dest_dir.is_dir() {
return Err(CubilError::StatusMissing(target.to_string()));
}

let file_name = current_path
.file_name()
.expect("resolve_slug returns a file path");
let dest_path = dest_dir.join(file_name);
// NOTE: local single-user tool — TOCTOU window between exists() check and
// rename() is acceptable.
if dest_path.exists() {
return Err(CubilError::SlugCollision {
slug,
status: target.to_string(),
});
}

std::fs::rename(&current_path, &dest_path)?;
Ok(())
/// Errors with [`crate::core::error::CubilError::StatusMismatch`] if the task
/// exists but is in a different status folder. Every other rule lives in
/// [`TaskStore::transition`].
pub(crate) fn transition(slug: &str, expected: &str, target: &str) -> Result<()> {
TaskStore::discover()?.transition(slug, expected, target)
}
43 changes: 7 additions & 36 deletions src/commands/mv.rs
Original file line number Diff line number Diff line change
@@ -1,40 +1,11 @@
use crate::core::error::{CubilError, Result};
use crate::core::{root, slug as slug_mod};
use crate::core::error::Result;
use crate::core::store::TaskStore;

/// Move task `<slug>` into `<root>/<status>/`.
///
/// - Errors with [`CubilError::SlugNotFound`] / [`CubilError::SlugAmbiguous`]
/// via [`slug_mod::resolve_slug`].
/// - Errors with [`CubilError::StatusMissing`] if the destination folder does
/// not exist (users create status folders themselves).
/// - Errors with [`CubilError::SlugCollision`] if a file with the same slug
/// already exists in the destination.
/// - If the resolved status equals the target, returns `Ok(())` without
/// touching the file or printing anything.
/// - Otherwise, atomically renames the file via [`std::fs::rename`].
pub fn run(slug: String, status: String) -> Result<()> {
let root = root::find_root(None)?;
let (current_status, current_path) = slug_mod::resolve_slug(&root, &slug)?;

if current_status == status {
return Ok(());
}

let dest_dir = root.join(&status);
if !dest_dir.is_dir() {
return Err(CubilError::StatusMissing(status));
}

let file_name = current_path
.file_name()
.expect("resolve_slug returns a file path");
let dest_path = dest_dir.join(file_name);
// NOTE: local single-user tool — TOCTOU window between exists() check and
// rename() is acceptable.
if dest_path.exists() {
return Err(CubilError::SlugCollision { slug, status });
}

std::fs::rename(&current_path, &dest_path)?;
Ok(())
/// If the task is already in `status`, returns `Ok(())` without touching the
/// file or printing anything. Every other rule (missing status folder, slug
/// collision, ambiguity) lives in [`TaskStore::move_to`].
pub fn run(slug: &str, status: &str) -> Result<()> {
TaskStore::discover()?.move_to(slug, status)
}
24 changes: 10 additions & 14 deletions src/commands/new.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,24 @@ use std::path::Path;

use crate::core::error::{CubilError, Result};
use crate::core::frontmatter::{TaskMeta, render_frontmatter};
use crate::core::root::find_root;
use crate::core::slug::{scan_all, slugify};

const BACKLOG: &str = "backlog";
use crate::core::slug::slugify;
use crate::core::store::TaskStore;

/// Create a new task file under `.cubil/backlog/`.
///
/// Prints the resulting slug to stdout on success. `message` and `file` are
/// mutually exclusive (enforced by clap); passing neither produces an empty
/// body. When `file` is `Some("-")`, the body is read from stdin.
pub fn run(title: &str, message: Option<String>, file: Option<&Path>) -> Result<()> {
let root = find_root(None)?;
let store = TaskStore::discover()?;
let slug = slugify(title)?;

for entry in scan_all(&root)? {
if entry.slug == slug {
return Err(CubilError::SlugCollision {
slug,
status: entry.status,
});
}
// Fail on a collision before reading the body, which may block on stdin.
if let Some(existing) = store.lookup()?.get(&slug) {
return Err(CubilError::SlugCollision {
slug,
status: existing.status.clone(),
});
}

let body = read_body(message, file)?;
Expand All @@ -36,8 +33,7 @@ pub fn run(title: &str, message: Option<String>, file: Option<&Path>) -> Result<

let contents = assemble(&meta, title, &body);

let path = root.join(BACKLOG).join(format!("{slug}.md"));
std::fs::write(&path, contents)?;
store.create(&slug, &contents)?;

println!("{slug}");
Ok(())
Expand Down
11 changes: 4 additions & 7 deletions src/commands/rm.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
use crate::core::error::Result;
use crate::core::{root, slug};
use crate::core::store::TaskStore;

/// Delete a task file.
///
/// Locates `.cubil/` by walking upward from cwd, resolves the slug across all
/// status folders, and removes the file. Silent on success.
/// Resolves the slug across all status folders and removes the file. Silent
/// on success.
pub fn run(slug: &str) -> Result<()> {
let root = root::find_root(None)?;
let (_status, path) = slug::resolve_slug(&root, slug)?;
std::fs::remove_file(&path)?;
Ok(())
TaskStore::discover()?.remove(slug)
}
20 changes: 6 additions & 14 deletions src/commands/roadmap/add.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@ use crate::core::error::{CubilError, Result};
use crate::core::roadmap::{
parse_h2_heading, parse_milestone_heading, parse_task_line, resolve_roadmap,
};
use crate::core::root::find_root;
use crate::core::slug::scan_all;
use crate::core::store::TaskStore;

/// Append `- [ ] <task_slug>` to a roadmap.
///
Expand All @@ -18,18 +17,11 @@ use crate::core::slug::scan_all;
/// done, or any custom one). No forward references. Errors if the task is
/// already listed anywhere in this roadmap.
pub fn run(roadmap_slug: String, task_slug: String, milestone: Option<&str>) -> Result<()> {
let root = find_root(None)?;
let path = resolve_roadmap(&root, &roadmap_slug)?;

// Validate task exists somewhere.
let mut found = false;
for entry in scan_all(&root)? {
if entry.slug == task_slug {
found = true;
break;
}
}
if !found {
let store = TaskStore::discover()?;
let path = resolve_roadmap(store.root(), &roadmap_slug)?;

// Validate task exists somewhere. Ambiguity is tolerated here.
if !store.lookup()?.contains_key(&task_slug) {
return Err(CubilError::SlugNotFound(task_slug));
}

Expand Down
21 changes: 10 additions & 11 deletions src/commands/roadmap/next.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@ use std::collections::HashMap;

use crate::core::error::Result;
use crate::core::roadmap::{TaskStatus, parse_task_line, resolve_roadmap};
use crate::core::root::find_root;
use crate::core::slug::scan_all;
use crate::core::store::TaskStore;

/// Print the slug of the next not-done task in the roadmap.
///
Expand All @@ -12,23 +11,23 @@ use crate::core::slug::scan_all;
/// skipped, since `next` exists to drive `cubil start <slug>`). Empty stdout
/// + zero exit if all tasks are done. Designed for shell pipelines.
pub fn run(slug: &str) -> Result<()> {
let root = find_root(None)?;
let path = resolve_roadmap(&root, slug)?;
let store = TaskStore::discover()?;
let path = resolve_roadmap(store.root(), slug)?;
let src = std::fs::read_to_string(&path)?;

let lookup = build_status_lookup(&root)?;
let lookup = build_status_lookup(&store)?;
if let Some(next) = first_not_done(&src, &lookup) {
println!("{next}");
}
Ok(())
}

fn build_status_lookup(root: &std::path::Path) -> Result<HashMap<String, String>> {
let mut map = HashMap::new();
for entry in scan_all(root)? {
map.entry(entry.slug).or_insert(entry.status);
}
Ok(map)
fn build_status_lookup(store: &TaskStore) -> Result<HashMap<String, String>> {
Ok(store
.lookup()?
.into_iter()
.map(|(slug, entry)| (slug, entry.status))
.collect())
}

fn first_not_done(src: &str, lookup: &HashMap<String, String>) -> Option<String> {
Expand Down
27 changes: 13 additions & 14 deletions src/commands/roadmap/show.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@ use std::path::{Path, PathBuf};

use crate::core::error::Result;
use crate::core::roadmap::{TaskStatus, parse_task_line, read_task_title, resolve_roadmap};
use crate::core::root::find_root;
use crate::core::slug::scan_all;
use crate::core::store::TaskStore;

/// Render the roadmap with task statuses resolved from the actual task files,
/// then write the resolved view back to disk.
Expand All @@ -20,11 +19,11 @@ use crate::core::slug::scan_all;
/// through byte-for-byte. Only lines parsed as `- [<x>] <slug>` checkbox
/// items are rewritten.
pub fn run(slug: &str) -> Result<()> {
let root = find_root(None)?;
let path = resolve_roadmap(&root, slug)?;
let store = TaskStore::discover()?;
let path = resolve_roadmap(store.root(), slug)?;
let src = std::fs::read_to_string(&path)?;

let lookup = build_lookup(&root)?;
let lookup = build_lookup(&store)?;
let new_src = rewrite(&src, &lookup)?;

write_atomic(&path, new_src.as_bytes())?;
Expand All @@ -40,15 +39,15 @@ struct TaskInfo {
title: Option<String>,
}

fn build_lookup(root: &Path) -> Result<HashMap<String, (String, PathBuf)>> {
let mut map = HashMap::new();
for entry in scan_all(root)? {
// First-write-wins for ambiguous slugs. Roadmap rendering is robust
// to ambiguity: it just picks one. Users discover the duplicate via
// `cubil list` or `cubil show`.
map.entry(entry.slug).or_insert((entry.status, entry.path));
}
Ok(map)
fn build_lookup(store: &TaskStore) -> Result<HashMap<String, (String, PathBuf)>> {
// First-write-wins for ambiguous slugs. Roadmap rendering is robust
// to ambiguity: it just picks one. Users discover the duplicate via
// `cubil list` or `cubil show`.
Ok(store
.lookup()?
.into_iter()
.map(|(slug, entry)| (slug, (entry.status, entry.path)))
.collect())
}

fn resolve(slug: &str, lookup: &HashMap<String, (String, PathBuf)>) -> Result<TaskInfo> {
Expand Down
Loading
Loading