thcThought Control

Architecture

How Thought Control is built, end to end. One Rust binary, an append-only log as the truth, a database you can delete, and a TUI whose every pixel comes from one serializable state.

This is the deep end of the docs: how the pieces of thc fit together, why they are shaped the way they are, and where each one lives in the source. Every page links to the files it describes, so you can read the code beside it.

1binary: CLI, TUI and daemon in one
4crates in the workspace
~90klines of Rust
800+unit and integration tests, plus goldens
0servers, accounts or network calls to work

The whole system

thc, the whole systemAgents, the CLI, the TUI and $EDITOR all enter thc-core. Writes go capture, builder, policy, transact; transact appends to this device's log and applies to the SQLite store. Reads go from the store through the query compiler and views to output. The daemon watches the log, fires alerts and pushes changes to the TUI and ThoughtBar. On disk, the vault folder is synced; the cache is local and rebuildable.surfaces◆ agentsclaude · codex · youthcthe CLI · --jsonthc tuiElm state · ui socket$EDITOR · drop/plain text in and outThoughtBarmenu bar · no filesui socket: patch · keys · render · layerssocketthc-corethe model, the log, the store, the query compilerwrites →captureparsed onceTxBuilderids · order · datespolicy · --expecttiers · --if-matchtransactlock · HLC · fsyncapply← readsout--json · --fieldsviews · why@today · reasons[]queryq → one SQL WHEREstoreSQLite · a cachealso: recurrence · dates · outline (documents ↔ ops) · review · federated vault queriesthc-daemonoptionalwatch log/ (~100 ms)replay others' linespush changed · agendaalert schedulerMarkdown exportdrop/ ingestone per vault, threadsa cache warmer, a bus,an alarm clockappendreplaywatchlives inlocal cachenever syncedstore.dbrebuildable from the logwrite.lockone writer per devicedaemon.jsonwhere the socket isthe vaultsynced folderlog/<device>/YYYY-MM.jsonlappend-onlythc-vault.tomlfiles/write-oncedrop/inboundexport/never read backone writer per directory: no conflicted copies
fig. 1Everything on one sheet. Writes run left to right along the top of the core and land in this device's log; reads run right to left along the bottom, out of a store that is only a cache of the log.

Read it from the edges in. Surfaces at the top are every way in: you at the CLI or in the TUI, an agent running the same CLI (or steering the TUI through its socket), a file dropped into drop/, a round trip through $EDITOR, the menu bar. None of them has behaviour of its own; they all call thc-core.

A write is parsed once (due:fri becomes a date field and is never re-read from text), turned into validated operations by the builder, checked against the actor’s policy and any preconditions, then committed: lock, catch up, stamp each event with a hybrid logical clock, append to log/<this-device>/, fsync, apply to SQLite. A read compiles a query into one SQL WHERE over the store and renders rows, as JSON or for people.

At the bottom, the vault is a plain folder you sync with whatever you like. Only the log in it is the truth. The store next to it is a cache in the local cache directory: delete it and thc rebuild replays the log into an identical one.

The rules of the house

Every page in this section follows from a short list. When something in the code looks odd, it usually traces back to one of these.

  1. The log is the truth. Every change is one JSON line, appended, never rewritten. The SQLite store, the Markdown export and every screen are derived from it.

  2. Replay is a pure function of the events. Clocks, randomness, timezones and recurrence math live in the writer. Two devices with the same lines build the same state, byte for byte.

  3. One writer per file. A device appends only to its own log directory, so a sync tool never sees two writers on one file and never makes a “conflicted copy”.

  4. One primitive. A page, a day, a task, a tag and a saved view are all nodes. “Task” is a status, “reminder” is an alert. Fewer kinds, fewer edge cases.

  5. Text at the edges, structure in the core. Capture syntax is parsed once, into typed fields. Stored text is never re-parsed to learn what something is.

  6. The CLI is the API. People and agents use the same commands, with —json, stable exit codes and attribution on every write.

  7. State is serializable, or it is a bug. The TUI is one UiState, changed only by messages, drawn by a pure view. What isn’t in the state can’t be replayed, patched or tested.

  8. One source of truth, instantiated. A document lives in one place and every view holds a reference to it. The same component appears wherever that thing does; differences are data, not a second code path.

The crates

Crate graph: thc depends on thc-tui, thc-daemon and thc-core; thc-tui on thc-core and the caretline crates; thc-daemon on thc-core.thcthe one binary · clapthc-tuiratatui · Elm statethc-daemonwatch · bus · alertsthc-coremodel · log · storecrates.io · own repocaretlinethe editor enginecaretline-layershints · spotlightscaretline-tourwalkthroughsschemaarrows point at what a crate depends on
fig. 2The workspace. thc-core knows nothing about terminals, sockets or editors; the editor engine is a separate project on crates.io.
CrateWhat it holdsSize
thc-coreThe node model, the event log, HLC, merge and replay, the SQLite store, capture syntax, dates and recurrence, the query compiler, outline (documents ↔ ops), review, policy, vaults~16.6k lines
thc-daemonThe optional background process: log watcher, socket server and subscriptions, alert scheduler, OS notifications, export, drop/ ingest~2k lines
thc-tuiThe ratatui app: UiState, Session, the pure update and view, the keymap, the sidebar, layers, and the editor built on caretline~43.9k lines
thcThe binary: clap dispatch, one module per command in the registry, JSON output, schemas, setup and update, the team launcher~28.6k lines
caretlineThe editor engine, its own repository and site (caretline.app): text, selection, motion, undo, the layout mapexternal

The life of a write

Follow one command all the way down:

$ THC_ACTOR=claude thc todo "Call the dentist due:fri #health !high"
  1. Parse. capture.rs splits the text into words, finds due:fri, #health and !high, resolves fri against the writer’s clock and timezone, and keeps the rest as text.
  2. Build. TxBuilder makes the operations: today’s journal day if it doesn’t exist yet (its id is keyed from the date, so every device makes the same one), a node.create for the task with a fresh 12-character id, a fractional order key after the last sibling, and its status, due and priority as props, the health tag (keyed from its name), and an edge.add linking the two.
  3. Check. The actor claude is an agent, so its tier in the device config decides whether this verb is allowed, needs confirmation, or is refused. --expect and --if-match would be checked here too, under the lock.
  4. Commit. Vault::transact takes the device write lock, catches up on any lines it hasn’t applied, stamps each op with the HLC, the device id, the actor and one shared transaction id, appends the lines, fsyncs, and applies them to SQLite in one transaction.
  5. Notify. The daemon, if it runs, sees the append and pushes changed to every subscriber. An open TUI flashes the new row, marked ◆ claude. The transaction sits in thc review until a person accepts or reverts it.

The life of a read

$ thc q 'status:open due<=+3d #health sort:due' --json

The query compiler parses the terms into an AST (which --explain prints in plain words) and one SQL WHERE over nodes, with relative dates resolved once. SQLite answers from partial indexes on open tasks. The output layer renders node objects with a stable, additive JSON shape. No daemon is involved: the CLI opens the store directly, because a round trip through a socket would cost more than it saves.

Read on

PageCovers
The event logThe vault on disk, the envelope, every op, ids and keyed ids, the version rules
Replay and mergeTotal order, per-field last-writer-wins, text conflicts, cycles, convergence
The write pathCapture, the builder, the lock, policy tiers, preconditions, undo and review
Reads and queriesThe store schema, the query language and its compiler, views, vaults, time travel
The daemonWatching, the socket protocol, push, alerts and notifications, export
The TUI as stateUiState, messages, the pure update, effects, traces, the thc ui socket
The editorcaretline inside thc: documents, views, saving, tasks on extension points
Agents and teamsActors, tiers, review, claims, messages and the team board
How it’s testedConvergence simulation, goldens, snapshots, flows, the sandbox
DecisionsThe choices that shaped it, what each one costs, and what it rules out