Board store
Board store
internal/board owns the task and config state, independent of HTTP. main.go
embeds the frontend and dispatches to runServe in serve.go by default, or to
runTUI in tui.go for mk tui. internal/tui consumes the same snapshots and
watcher, and uses the task-writing API for card actions.
Both front ends must keep the same task-file rules. Writes go through
Store.Apply or its batch methods, never around them. The one exception is the
archive move, which renames an unchanged file; see Archive moves.
Opening and reading
board.Open(dir, board.Options{Logf: ...}) resolves an absolute
task directory, creates it if needed, scans tasks, bootstraps an absent
.kanban.yml, and loads columns. Directory resolution/creation errors are
returned. Initial scan/bootstrap/config errors are logged and opening continues.
Malformed YAML on initial config load can therefore leave columns empty; on a
later failed reload the previous columns remain.
Logf receives warnings. Nil falls back to log.Printf.
Store.Dir() returns the absolute directory. Store.Snapshot() returns
independent copies of columns, tasks, tags, dependencies, order pointers, and
archived filenames. Consumers can modify them without changing the store. Scan, ReloadConfig,
and Apply serialize their I/O; a separate read/write lock protects state.
Scan() reads regular top-level .md files in filename order. Unreadable
files are logged and skipped. Malformed typed frontmatter produces a task with
ParseError and its real body, so the card remains visible. ParseTask(path)
can also be used directly. Conflict detection takes precedence over YAML parsing.
Each task carries the SHA-256 hash of the same bytes used to parse it.
Scan() also lists top-level .md names in the archive folder into
Snapshot.Archived, without parsing them. ArchiveDir() returns the configured
archive_dir, or archive when unset. A missing archive folder is empty. If
the archive path has a symlink or a non-directory component, Scan returns an
error but still publishes the top-level tasks. Archive read errors
behave the same way; archived names are unavailable for that scan. Open logs
the error and continues with the scanned tasks.
Config bootstrapping happens only at open. ReloadConfig() never rewrites config;
missing or empty/unusable columns retain previous columns, or use
TODO / IN PROGRESS / DONE if none exist. Duplicate, empty, and reserved
(CONFLICT, OTHER) column names are ignored. Invalid YAML returns an error.
Writes
Store.Apply(board.UpdateRequest{...}) reads an existing file, changes its
frontmatter or body, and parses the replacement into the store immediately. It
rejects files with Git conflict markers and non-regular files, including
symlinks. Task replacements, batch rollback, and config bootstrap stage a
temporary file in the same directory, preserve existing permission bits, sync,
and rename. The watcher notifies consumers after a later scan.
TaskPath(file) accepts a single filename in the task directory.
| Field | Meaning |
|---|---|
File | Existing task filename |
Content *string | Nil preserves the body; a pointer to an empty string explicitly empties it |
Status string | Empty means no change; CONFLICT and OTHER assignments are rejected |
Order *float64 | Nil preserves order; a pointer sets it |
Tags []string | Nil preserves tags; an empty non-nil slice writes tags: [] |
Unset []string | Deletes only status, order, or tags; setting and unsetting the same key is rejected |
ExpectedHash *[32]byte | Rejects the write with ErrChanged unless the current bytes match |
Restore []byte | TUI-only exact-byte undo; see the paragraph below (not exposed by HTTP) |
An unset-only request preserves the bytes of a file without frontmatter. Frontmatter updates edit a YAML node tree so key order, comments, and scalar styles carry through serialization. Body-only updates retain the frontmatter bytes. Invalid YAML mappings are rejected. The web UI makes cards with typed parse errors read-only. See task-file rules for task semantics.
Callers can use errors.Is with ErrMissingFile, ErrInvalidFile,
ErrInvalidUnset, ErrConflictStatus, ErrOtherStatus, ErrNothingToUpdate,
ErrInvalidFrontmatter, ErrChanged, ErrConflictFile, ErrInvalidRestore,
and ErrEmptyClobber. Read and write errors include operation and path context.
ApplyBatch serializes related updates and rolls back completed writes if a
later request fails. Rollback checks the bytes written by the batch before
restoring each file. ApplyBatchWithHashes also returns hashes of
the exact bytes written in request order, so the TUI can record undo without a
post-write disk read. ExpectedHash verifies the current bytes under
the store I/O lock. TUI-only Restore restores exact original bytes for undo;
it requires ExpectedHash and rejects changes to the body or frontmatter keys
other than status/order/tags. The HTTP API exposes ExpectedHash.
FrontmatterKeys(path) returns top-level YAML nodes using ParseTask’s delimiter
rules, retaining the distinction between missing keys and explicit empty values.
Archive moves
Store.Archive(file, expected) and Store.Unarchive(file, expected) are the
non-Apply write path. They rename an unchanged .md file between the task
folder and the archive folder, and the TUI uses them for A and its undo. They
do not change file content, so Restore and ExpectedHash are not involved.
- Both hold the store I/O lock.
expectedis the SHA-256 of the file’s current bytes. A mismatch returnsErrChanged; a non-regular source returnsErrInvalidFile. Archivereparses the file on disk and refuses CONFLICT and parse-error cards, even if the caller’s snapshot is stale.- The archive folder is created on first use. A symlink or non-directory in the archive path is refused.
- A destination that already exists returns
name taken. The check is a stat followed byos.Rename, so an external writer can still race it. - Callers run
Scanafterwards to update the in-memory tasks.
Watching
Store.Watch(ctx, onChange) attaches fsnotify to the task directory and blocks
until cancellation or watcher termination. Start it after Open. It watches
Write/Create/Remove/Rename events for .md and .kanban.yml, with a 50 ms
trailing debounce. The archive folder is not watched, so changes made only inside
it appear after a rescan (r in the TUI). Each flush reloads config first if a
.kanban.yml event arrived, then scans once if any .md or config event arrived,
then invokes onChange synchronously, even if an operation logged an error.
Keep the callback short. A nil callback is allowed; cancellation returns nil
and closes the watcher. Watcher creation/attachment errors are returned;
runtime watcher errors are logged.
View helpers
These helpers operate on snapshots and tasks. Both frontends use the Go ordering and dependency analysis. The browser applies its own filters.
ByOrdersorts ascending with nil order last, then compares filenames by byte order.ComputeOrderaverages two neighbours, steps one past a sole neighbour, or returns 1.DropOrderexpects the full target column, already sorted byByOrderand excluding the moving card. Pass the visible card below the drop asbeforeFile, or the last visible card for an end drop. Hidden neighbours still participate in the calculation. It returns(order float64, updates []UpdateRequest). An end drop following an unordered card assigns orders to the unordered tail without modifying the input. Apply the returned updates throughStore.Applyalong with the moving card’s order; a numeric order alone cannot place a card after cards with unset orders.Sectionclassifies CONFLICT, a configured column, or OTHER.Sections(snapshot)uses all unfiltered tasks: optional non-droppable CONFLICT first, all configured droppable columns, optional non-droppable OTHER last.SortForTablereturns independent task copies in this section order, thenByOrder; this differs from the web table’s status text sorting.Filtercombines true selections with OR within project/epic/tag groups and AND across groups. False map values are unselected.Activecounts selected chips plus one for a nonblank query;Visibletests a task.QueryANDs whitespace-separated terms using fuzzyTitleorHeadingmatches, or substrings in metadata/body; the web leaves it empty.Scoresums each term’s bestTitleorHeadingmatch, andMatchesQueryaccepts a cached lowercase body for the terminal consumer.NoEpic(NO EPIC) matches empty epic.Facetsreturns sorted unique values, omitting empty projects.AnalyzeDeps(tasks, archived...)returns filename-keyedKnown,Cycles, andArchivedmaps. Tarjan’s strongly connected components mark only cycle members (including self-loops), ignoring missing edges.DepInfo.Missing(slug)checksslug + ".md".DepInfo.IsArchived(slug)is true for an unknown slug whose.mdis in the archive folder, andMissingis false for those slugs.
HTTP and SSE
The web adapter is in serve.go. The endpoints are documented in the
HTTP API reference.
Each server owns its store and SSE clients. /api/board serves task hashes
and dependency states from the same snapshot. Archived dependencies are
included in that analysis. /api/update accepts a hash as expectedHash and
returns 409 when the file has changed or contains Git conflict markers.
/api/drop delegates to Store.Move. It validates the destination and
visible neighbour, calculates the order with DropOrder against the full
column, and applies the move and any tail renumbering in one batch.
The watcher callback broadcasts update to /api/events clients. Each client has a one-message buffer;
nonblocking broadcasts coalesce duplicate notifications so a slow browser
cannot stall the watcher. Browsers fetch the latest board after notification.
Watcher termination is monitored alongside the HTTP server and causes
runServe to return; cancellation closes the watcher on shutdown.