Build a Todo CLI
A todo CLI is the smallest project where every production habit still applies: parsing, persistence, concurrency, errors, migrations, tests, packaging, and support. It is a good calibration exercise because there is no server, no cache, and no load balancer to hide behind. If the data file is corrupted, it is your bug.
This chapter focuses on the command contract and the failure process. Code is illustrative; the state transitions and guarantees are the point.
Scope
In scope for v1
todo add "buy milk" --due 2025-01-10 --tag errands
todo list [--all] [--tag errands] [--json]
todo done 3
todo rm 3
todo edit 3 --text "buy oat milk"
todo export --format json
todo migrate
- One local data store.
- Human and machine-readable output.
- Stable IDs, tags, due dates, completion state.
- Atomic writes, locking, schema versioning.
- Exit codes and stderr/stdout discipline.
Out of scope for v1
- Sync across devices.
- A server or multi-user permissions.
- Notifications and background daemons.
- Recurring tasks.
- A TUI.
Actors and journeys
| Actor | Goal | What can go wrong |
|---|---|---|
| Human user | Add, find, complete, and remove tasks | Lost updates, confusing errors, data in the wrong directory |
| Shell script | Parse output and rely on exit codes | Human text on stdout, wrong exit code |
| Maintainer | Ship an upgrade without losing data | Migration failure, old file unreadable |
| Operator | Recover from a corrupted store | No backup, no repair path |
Critical journeys:
- First run creates a valid store in the platform data directory.
addanddonefrom two terminals do not lose an update.- An upgrade migrates an old file with a backup and a clear failure path.
- A script can run
list --jsonand distinguish “empty” from “failed.”
Invariants
- No successful command leaves a partially written store. Writes are atomic.
- No read-modify-write is lost. Concurrent commands are serialized or use compare-and-swap.
- IDs are never reused. Deleting task 3 does not make task 3 refer to a different task later.
- The on-disk format is versioned. Old files are migrated deliberately, never guessed.
- Data goes to stdout; diagnostics go to stderr.
--jsonoutput is parseable with no banners. - Exit codes are meaningful:
0success,1runtime failure,2usage error,3not found,4conflict/lock failure. - The store is not tied to the current directory. It lives under the platform data directory unless the user overrides it.
- A crash at any point leaves either the old state or the new state, never a half-written file.
Command contract
Every command needs four things:
- Input contract: arguments, flags, defaults, validation.
- Output contract: human format,
--jsonschema, stderr usage. - Exit contract: success, usage error, not found, conflict, runtime failure.
- Side effects: which files change, which locks are taken, what happens on failure.
Example contract for done:
todo done <id>
success: task exists and is not already done → mark done, print summary to stdout, exit 0
already done: idempotent success? or exit 0 with "already done" on stderr?
not found: no change, stderr message, exit 3
lock held: no change, stderr message, exit 4
store corrupt: no change, stderr repair hint, exit 1
Decide idempotency explicitly. done twice is usually a success with a note, not an error. rm twice is usually “not found” unless the product wants idempotent delete.
End-to-end flows
1. First run
todo <command>
→ resolve data dir: $TODO_DATA_DIR or platform default
→ ensure directory exists with user-only permissions
→ if store missing: create empty store with formatVersion=1
→ acquire lock
→ load + validate schema
→ run command
→ save atomically
→ release lock
If the directory is not writable, fail before doing any work and print the exact path. Do not silently fall back to the current directory.
2. Add
add
→ parse text, due date, tags
→ validate: non-empty text, date format, tag format, size limit
→ acquire lock
→ load store
→ nextId → id
→ append task with createdAt, done=false
→ increment nextId
→ save to temp file, fsync, rename
→ release lock
→ print "added #<id>"
Failure branches:
- Validation error: exit 2, no lock needed.
- Disk full: temp write fails; original file untouched; exit 1.
- Crash before rename: temp file remains; the original is valid.
- Crash after rename: new state is valid.
- Lock held: wait with a bounded timeout, then exit 4 with a clear message.
3. List and filter
list
→ load store (read lock or no lock if reads are atomic)
→ apply filters: all, tag, due, search
→ sort deterministically: created_at, then id
→ output human table or JSON
Rules:
- Empty list is success (
0), not an error. --jsonalways emits a valid document, even when empty.- Do not colorize when stdout is not a TTY or
NO_COLORis set. - Do not truncate IDs or text in human output without a hint; scripts use
--json.
4. Done / undone
done <id>
→ lock
→ load
→ find task
→ if missing: exit 3
→ if already done: policy (idempotent success or exit 0 with note)
→ set done=true, completedAt=now
→ save atomically
State transitions are the product. Define whether done is reversible (undone/reopen) and whether completing a task changes its sort position.
5. Edit and remove
editvalidates the new values before writing; a failed edit must not partially update.rmremoves the task, keepsnextIdunchanged, and does not reuse the ID.- If tasks are referenced by external scripts, consider soft delete (
deleted_at) with a--purgecommand. - Bulk operations (
done 1,2,3) are all-or-nothing or report per-ID results; do not leave a half-applied batch without saying so.
6. Export and import
- Export is a stable, documented schema with
formatVersion. - Import validates the entire document before writing; do not merge partially.
- Define conflict policy: new IDs, skip duplicates, or fail.
- Exports must not include secrets or absolute paths unless requested.
7. Migration
startup
→ read formatVersion
→ if current: continue
→ if older: acquire exclusive lock
→ copy store to <store>.bak.<timestamp>
→ apply migrations in order in memory
→ validate result
→ write new store atomically
→ verify by reloading
→ release lock
→ if anything fails: restore is unnecessary (old file untouched), print recovery path
Rules:
- Never migrate in place without a backup.
- Never skip a version; migrations compose.
- A migration must be idempotent enough to retry after a crash.
- If the new binary cannot read an old format, fail with a message that names the backup and the required version.
Data model and file format
JSON is fine for a small store. SQLite is better if you need concurrent writers, queries, or growth.
{
"formatVersion": 1,
"nextId": 4,
"tasks": [
{
"id": 1,
"text": "buy milk",
"done": false,
"due": "2025-01-10",
"tags": ["errands"],
"createdAt": "2025-01-01T10:00:00Z",
"completedAt": null,
"deletedAt": null
}
]
}
Rules:
- Validate the entire document on load: types, ranges, duplicate IDs,
nextId > max(id). - Unknown fields are preserved on read/write when possible, to avoid data loss across versions.
- Dates are stored as ISO-8601 UTC; display in local time.
- Tags are normalized (trim, dedupe, case policy).
- File permissions are
0600on Unix.
Atomicity and concurrency
The write protocol:
- Acquire an exclusive lock on a sibling lock file.
- Read and validate the current store.
- Apply the mutation in memory.
- Write the full document to a temp file in the same directory.
fsyncthe temp file.renameover the target (atomic on the same filesystem).- Optionally
fsyncthe directory. - Release the lock.
Why the temp file must be in the same directory: rename is only atomic within a filesystem.
Concurrency options:
- Advisory file lock (
flock/LockFile) with a timeout. - SQLite with
BEGIN IMMEDIATEand a busy timeout. - Optimistic CAS on a version field, retrying on conflict.
Do not rely on “the CLI is single-user.” Users open two terminals, run scripts, and sync directories. Lost updates are real.
Edge cases
| Case | Expected behavior | Notes |
|---|---|---|
| Empty task text | Reject with usage error | Exit 2 |
| Text with newlines/tabs | Preserve or reject with a clear rule | Output escaping |
| Unicode/emoji | Preserve; use UTF-8 | Width calculation in tables |
| Very long text | Enforce a limit; suggest a note field | Storage/output safety |
| Invalid due date | Reject, do not silently ignore | Date parsing is product behavior |
| Due date timezone | Store date-only or UTC instant; display local | Ambiguous “today” |
| Duplicate tags | Dedupe case-insensitively or by policy | Document it |
| ID does not exist | Exit 3, no change | Scripts depend on it |
done twice |
Idempotent success or explicit note | Define it |
| Delete missing ID | Exit 3 unless --force |
Avoid silent success |
| Malformed JSON | Refuse to write; print repair/backup path | Never overwrite blindly |
| Truncated file after crash | Detect, offer backup restore | Atomic writes prevent this |
| Disk full | Original untouched; exit 1 | Test it |
| Permission denied | Clear path + remediation | Do not fall back to CWD |
| Two processes add at once | Both succeed with unique IDs | Lock + fresh read |
| Two processes edit same task | Last writer wins or CAS conflict | Document |
| SIGINT during write | Temp file may remain; original valid | No partial target |
| Stale lock after crash | Timeout + lock metadata; safe recovery | Do not delete a live lock blindly |
| Clock moves backwards | Sort by stored ID as tiebreaker | Do not reorder unexpectedly |
| stdout is a pipe | No color/spinners; valid JSON only | CI-friendly |
| Locale differences | Stable machine output; localize only human text | Tests must be deterministic |
| File manually edited | Validate; reject or repair | Schema errors are user-visible |
| Store in a synced folder | Warn about multi-device conflicts | Sync is not locking |
| Huge store | Stream list/export; avoid loading twice | Memory bound |
Failure modes and recovery
| Failure | Impact | Detection | Mitigation | Recovery |
|---|---|---|---|---|
| Non-atomic write | Corrupt/empty store | Load validation error | Temp + fsync + rename | Restore .bak, rerun |
| Lost update | Task disappears | User report, concurrency test | Lock or CAS | Reconcile from backups/log |
| Migration bug | App cannot start | Startup error, tests | Backup + validate + rollback path | Restore backup; ship fix |
| Disk full | Write fails | Write error | Check before write; clear message | Free space; retry |
| Stale lock | Commands hang | Lock timeout | Lock metadata + timeout | Remove stale lock with a documented tool |
| Malformed manual edit | Load fails | Validation | Strict schema + repair command | Restore backup or repair |
| Permission change | Cannot read/write | Access error | Clear path + mode guidance | Fix ownership/permissions |
| Interrupted upgrade | Old/new mismatch | Version error | Backup and atomic replace | Restore backup |
Recovery command: ship todo doctor or equivalent that checks file existence, permissions, schema version, and backups, and prints a safe next step. Do not make users guess.
Testing strategy
- Unit: parsing, date handling, tag normalization, filters, exit codes.
- Integration: run the compiled binary against a temp data dir; assert stdout/stderr/exit code.
- Concurrency: N processes add/done simultaneously; assert no lost updates and unique IDs.
- Atomicity: inject a crash between temp write and rename; assert old state.
- Migration: fixtures for every format version, including corrupt/partial files.
- Golden files:
--jsonoutput and human output snapshots. - Platform: Linux/macOS/Windows path and permission behavior.
- Fuzz: malformed JSON, huge fields, weird Unicode, control characters.
Operations and release process
- Version the binary and the data format separately.
- Ship migrations with a downgrade note: “backup is required; old binary may not read the new file.”
- Keep a changelog for command/flag changes.
- Add shell completions and man-page style help if the CLI is used daily.
- Keep startup under ~100 ms; lazy-load heavy modules.
- Provide a single binary where possible; otherwise document the runtime and install path.
- Publish checksums and signed releases.
- Test the install path from a clean machine.
Milestones and acceptance criteria
| Milestone | Build | Accept when |
|---|---|---|
| 1. Store + add/list | Data dir, schema, atomic write, basic commands | A task survives restart; no partial file on crash |
| 2. Contracts | Help, exit codes, stdout/stderr, --json |
Shell tests pass; empty vs error is distinguishable |
| 3. Mutations | done/rm/edit with validation | Not-found and duplicate actions follow the documented contract |
| 4. Concurrency | Lock/CAS + contended tests | Parallel adds produce unique IDs and no lost updates |
| 5. Migration | Versioned format + backup + doctor | Old fixtures migrate and are recoverable |
| 6. Packaging | Binary/entry point + install docs | A clean machine can install and run it |
| 7. Hardening | Crash/disk/permission tests | Recovery instructions are accurate |
Review questions
- What happens if the process is killed between write and rename?
- How do two
todo addcommands avoid the same ID? - Is
doneidempotent? Isrm? - Where does the data live, and what happens if it is not writable?
- How does an old file get migrated, and how do you roll back?
- Can a script reliably parse the output and detect failure?
- What does
todo doctorcheck, and what does it not fix? - What happens if the user syncs the data directory across devices?
Checklist
- Commands have explicit input, output, exit, and side-effect contracts.
- Writes are atomic and durable on the same filesystem.
- Concurrent commands cannot lose updates.
- IDs are never reused.
- Data lives in a platform-appropriate directory with safe permissions.
- The format is versioned and migrated with a backup.
-
stdoutis data;stderris diagnostics; colors respect TTY/NO_COLOR. -
--jsonis stable and documented. - Crash, disk-full, and permission failures are tested.
- A repair/doctor path exists for corrupted or stale state.
- Packaging is reproducible and documented.