System-Architecture-Overview
System Architecture Overview
The codebase strictly separates concerns to isolate terminal drawing from data logic. This note is the short-form companion to pour-design-spec.
src/main.rs: Entry point only. CLI parsing (pour,pour init,pour serve,pour <module>,pour <module> <field> [value]), config load, transport connect, terminal lifecycle. Hands off totui::loop_::run_loopfor the event loop. Slimmed from 1945 LOC pre-decomposition to ~205 LOC post-Slice-13 (229 today). See also ADR-003-Synchronous-TUI-Async-Operations.src/oneshot.rs: One-shot argv capture —pour <module> <field> [value]writes and exits without entering the TUI. Owns the grammar only (parseresolves argv against the config into a typedOneShotor a typedOneShotError;rundelegates tooutput::write_update). It lives in the library rather thanmain.rsso the parse layer is testable — integration tests link the lib, not the binary.pour <module>with no field argument parses toNoneand falls through to the existing TUI fast path unchanged. v1 wires the grammar fortoggle/counterfields onupdatemodules only.src/init.rs: First-run setup. Implements thepour initflow — generates a starterconfig.tomlwith interactive vault path selection and example modules. Also hosts the canonicalmodule_order(&config)helper used by bothapp.rsand the dashboard.src/tui/: Presentation layer. Routes events to screen handlers (dashboard.rs,form/,summary.rs,configure/) and dispatchesActionenums.tui/loop_.rs(post-Slice-13) owns the event-poll/draw/dispatch loop and a handler for eachActionvariant (25 besidesNoneandQuit). It also holds the form-open fetchesfetch_dynamic_options,fetch_current_valuesandresolve_priors, whichtui/mod.rsre-exports along withrun_loopandhandle_submitsomain.rscan call them on the direct-entry path;tui/mod.rs::renderis the central render dispatcher and paints the ephemeral status-bar toast overlay. The dashboard acts as an ambient capture surface — showing recent activity, capture rhythm stats, and module gaps rather than a simple launcher. Built with ratatui and crossterm.src/tui/form/: Form screen module (post-Slice-11 decomposition).mod.rsownsFormActionand theNavCtxshared with key handlers.render/{mod,fields,clip,composite,panel}.rssplit rendering by concern;clip.rscuts one row of editable text to the cells it has.cells.rsmeasures each char's terminal cells per glyph, the way ratatui draws them, for both the renderer and the key handlers' scroll math.key/{mod,text,select,composite,navigation,submit}.rssplit the 930-linehandle_keyby mode.overlays/{mod,preset_picker,sub_form,small}.rscolocate the four overlays with their key-handlers (small.rsmerges callout-title and preset-save per the "<100 LOC = bad seam" heuristic). No editor/ subdirectory — text-input logic was already cohesive within key/ files.src/tui/configure/: In-app configurator (post-Slice-12 decomposition).mod.rsownsConfigureActionand re-exports the public surface.render.rsholds the configure screen's render functions: settings, field and sub-field lists, list editor, confirm dialog, file browser, and the path-help and quick-select overlays.key/{mod,fields,sub_fields,vault}.rssplit the 1000-linehandle_keyby mode.key/modules.rsandkey/presets.rsare empty placeholders kept for the planned layout; module-list navigation lives in the dashboard, and the configure screen has no preset editing yet.autosave.rsinvokescrate::config_updates::*builders to persist setting changes on navigate.init.rs(post-Slice-14) hosts the four configure-init helpers (build_field_settings,build_sub_field_settings,init_vault_configure,init_new_module_configure) that previously lived as methods onApp.src/app.rs: State management. OwnsFormState,ConfigureState,BrowserState, active field indices, and input validation.FormState.active_fieldis a visible-set index;active_config_idxmirrors it as the config-level index.FormState.cursor_positionis a char-index (post-v1-hardening), never a raw byte offset — emoji and CJK in textareas no longer panic on backspace.FormState.callout_overridesholds per-entry callout type selections.FormState.selected_preset_name: Option<String>is the source of truth for the active preset (name-keyed, survives reorder).FormState.preset_picker: Option<PresetPickerState>is the drilldown picker overlay state.FormState.current_valuesholds anupdatemodule's target-note frontmatter, read once at form open bytui::loop_::fetch_current_values; toggles are seeded from it, counters are not, and a failed read leaves it empty.App::status_message: Option<StatusMessage>is the ephemeral toast slot —set_status_warning(msg)populates it with a 5-second expiry;tick_status()clears expired messages each frame.src/visibility.rs: Conditional field visibility.visible_field_indices(fields, values)returns the subset of config field indices that are currently visible givenshow_whenrules. Called on every form key event. Integration points:src/app.rsuses it to computeFormState.active_fieldbounds;src/output/skips hidden fields during generation;src/config.rsvalidatesshow_whenconstraints at load time;src/tui/configure/serializesshow_whenwhen writing fields back viaadd_field_on_disk/update_field_on_disk.src/output/: Write execution. Orchestratesfrontmatter.rsgeneration andtemplate.rspath/template rendering (including{{callout}}resolution and field-level callout wrapping).write_createmerges[modules.<n>.frontmatter]statics after the captured fields (skipping any key the capture already claimed, including the injectedicon/daily) and renders the auto-injecteddatewith the module'sfrontmatter_date_format(absent →%Y-%m-%d; emitted unquoted, so a format containing": "yields invalid YAML — an accepted, config-file-only footgun).template.rs::slug_from_titlemirrors an editor-side Templater's JS slug regex exactly (filename parity with hand-templated notes) and backs the{{slug}}/{{slug_or_time}}special path tokens — they must be registered as specials, since unknown placeholders are stripped and an unregistered{{slug}}would silently render to nothing.template.rsshares asubstitute_keyskernel betweenrender_pathandrender_append_template; the 8 intentional behavioral divergences between the two are explicit configuration of the kernel and pinned by snapshots intests/output/template_snapshot.rs. Literal%in user templates is preserved byescape_nonspecifier_percent(post-v1-hardening).output/update.rs(habit-capture v1) ownswrite_update— the third write mode. It reads the target note's current frontmatter, computes new values per field type (toggleflips,counteraccumulates,=Nsets), and patches only the keys the module names; blank values are skipped, so a blank counter means "no change", not zero. The patch operation is single-key on both transports, so a multi-field update is a sequence of independent writes and is not atomic across keys — every value-level error is raised while planning, before the first write, and a transport failure mid-sequence returns an error naming the keys that already landed rather than reporting a half-applied capture as a clean failure.frontmatter.rsgained the read/patch half of that:read_frontmatter(top-level scalars only, no type coercion) andpatch_frontmatter_line, which edits exactly one line's bytes and copies everything else verbatim — key order, quoting style, comments, line terminators, and the whole body survive byte-for-byte. It is deliberately not a YAML round-trip: parsing is safe, re-emitting is what destroys formatting. A key whose value spans multiple lines (block sequence or block scalar) is refused rather than orphaned. Related: ADR-002-Custom-YAML-Serialization.src/data/: Fetch, cache, and history tier. All persistence routes throughdata/json_store.rs::JsonStore<T>— generic load/save with optional migration hook, the single sanctioned JSON write path (see ADR-006-V1-Lock-In-Patterns).cache.rsbacks dynamic-select dropdowns.history.rstracks capture events at~/.pour/cache/history.jsonl(append-only JSONL); statistical computation lives inhistory_summary.rs; legacy-format reader lives inhistory_legacy.rs.presets.rsstores per-module saved field-value sets at~/.pour/presets.json;field_presets.rsstores per-field row-set presets forcomposite_arrayfields.preset_tree.rsbuilds a hierarchicalPresetTreefromVec<PresetEntry>+preset_axes.frontmatter_read.rs(priors L1) is the hand-rolled frontmatter reader — parses a note's---block intoFrontmatter(BTreeMap<String, FrontmatterValue>), scoped to Pour's writer subset and degrading gracefully on richer YAML (see ADR-007-Frontmatter-Reader);wikilink.rsis the[[Target|Alias]]/#Frag→Targetstripper. Both are shared foundation reused by pour-review-priors and (next) pour-lookup-fields. See pour-preset-hierarchy and The-3-Tier-Data-Fallback.src/transport/: Network/disk boundary. Hides API vs filesystem from the rest of the application.transport/atomic.rs(post-Slice-1) is the single sanctioned atomic-write primitive:atomic_replace(src, dst)is onestd::fs::renamecall that resolves toMoveFileExW(MOVEFILE_REPLACE_EXISTING)on Windows. It is paired withresolve_write_target(path), which every writer calls before choosing where to put its temp file.renameswaps a directory entry, so renaming onto a symlink replaces the link with a regular file and strands the edit: a~/.pour/config.tomlstowed out of a dotfiles repo lost its link on the first TUI write, and the tracked file kept its old contents.resolve_write_targetfollows a symlink atpathto the real file (chains included) and returns everything else untouched — regular files, paths that do not exist yet, and dangling links, which have no target worth preserving. A symlinked parent directory needs no handling, since the temp file and the rename target already resolve through it. Placing the temp file beside the resolved target also keeps the rename on one filesystem, so a link crossing a mount point no longer fails withEXDEV. The resolution is confined to the symlink branch on purpose:std::fs::canonicalizereturns an extended-length\\?\path on Windows, and ordinary files must keep the caller's path verbatim in their error messages. All five writers route through it —Config::write_atomic,JsonStore::save,history_summary::write_summary, and bothfs.rswrite paths. Pinned bytests/util_atomic.rsandtests/config_symlink.rs, the latter driving the realappend_option_to_field_on_diskAPI over a stow layout.fs::resolve_path_validated(post-v1-hardening) rejects.., absolute paths, and~-prefixes on every public method. Exposesexecute_command()for Obsidian plugin commands,read_file()for vault reads, andpatch_frontmatter()for the single-key mutation behindupdatemode.patch_frontmatteris pour's first PATCH request — every other API write is a read-splice-write PUT (see ADR-004-API-Append-Read-Modify-Write); it is safe here because the mutation is a single named property handled by Obsidian's own metadata layer, not a positional splice whose result pour cannot predict. It sendsOperation: replace,Target-Type: frontmatter,Target: <key>,Create-Target-If-Missing: true. The filesystem side is a guarded surgical edit — capture mtime → read → line-level replace → re-verify mtime →atomic_replace; a mismatch returnsTransportPatchError::Conflictwithout writing. The baseline stat comes before the read on purpose: capturing it afterwards would leave the read itself outside the protected window, so a concurrent writer landing in that gap would set the baseline to its own post-write value and the guard would pass while pour overwrote it.FsWriter::patch_frontmatter_sincetakes the baseline as a parameter so that exact interleaving is directly testable. A backend that cannot serve the patch (a Local REST API older than v3.0, or one that has gone away mid-capture) returnsUnsupported, andwrite_updateretries over a filesystem writer built from the module's root —Transport::Apicarries no vault path of its own, which is whywrite_updatetakes afallback_root.Transport::connectremains one app-level instance;Transport::for_module(module)is a second, write-time selector returningSome(Fs)rooted at a module'sbase_pathoverride (orNoneto use the app transport). A root-overriding module is always filesystem — the Obsidian API can only address notes inside the vault it serves — so both write call sites (tui/loop_.rs,server/handlers/submit/write_step.rs) report the transport mode of the transport they actually used, not the app-level one.fs.rsitself is unchanged by the override:resolve_path_validatedsimply now guards a different root. Related: ADR-001-Hybrid-Transport-Layer.src/config.rs/src/config_edit.rs/src/config_updates.rs: Schema, mutation, and update-builder layer.config.rsdefines the value layer (Config,ModuleConfig,FieldConfig,ConfigError, etc.) plus the 15*_on_diskmutator methods (post-Slice-3 they all share oneConfig::write_atomic; post-Slice-8 they're thin facades overConfig::edit).config_edit.rsdefinesConfig::edit(path, |draft| { … })— the transactional load → mutate → validate → write entry point withConfigDraft<'_>exposing both&mut DocumentMutand&Config.config_updates.rs(post-Slice-5) is the canonical home forbuild_module_updates,build_vault_updates,build_field_updates,build_sub_field_updates— previously duplicated betweenmain.rsandtui/configure.rs. See ADR-006-V1-Lock-In-Patterns.src/server/: axum HTTP server powering the mobile PWA companion. Post-decomposition layout:mod.rsis lifecycle (auth middleware, AppState,run/run_with_shutdown);routing.rsowns the router builder;static_assets.rsowns the embedded PWA shell.dto/{mod,response,requests,mapping}.rssplit wire types by concern —mapping.rsisolatesConfig → DTOtranslation soresponse.rsis Config-free.handlers/submit/{mod,validate,idempotency_lookup,autocreate_step,write_step,history_step}.rssplit the 607-line submit handler into a thin orchestrator + 5 phase modules using aSubmitContextstruct.idempotency.rsis an in-memory LRU (1024 cap, 60s in-flight TTL, 5min done TTL).startup.rscontainsresolve_tokenandprint_banner. See ADR-005-PWA-Companion for the architectural decision and pour-api-contract for the wire shape.- TUI ↔ Serve handoff (
src/tui/loop_.rsrun_loop,Action::Serve): pressingsfrom the dashboard suspends the TUI (ratatui::restore()), probes port 8421 (TOCTOU-free: the bound listener is passed directly intorun_with_shutdown), prints the banner viastartup::print_banner, runs the server until Ctrl+C fires (tokio::signal::ctrl_c()), applies a 5s drain timeout, then re-enters the TUI (ratatui::init()+terminal.clear()). Port conflicts surface as a one-line error; server errors are pushed toapp.deferred_stderrand printed after TUI restoration. Thepour serveCLI path is unchanged. web/: Embedded PWA shell. Vanilla HTML/CSS/JS, compiled into the binary at build time viarust-embed. Served at/; static assets require no auth. Phase 1: module list, per-module form rendering fromGET /api/v1/config, submit. Phase 1.5/1.5++: preset chip row,show_whencascade, visual identity, idempotency-key persistence. Phase 2 Stream B:<section id="subform-overlay" role="dialog" aria-modal>— a modal sub-form that opens when the user types a novel value into adynamic_selectfield withcreate_templateset. The overlay renders template fields (text/number/static_select with inline cycling, no<select>), collects values into_pendingAutoCreateInputs, and includes them asauto_create_inputsin the parent submit body (contract §6.4). Cancel reverts the parent input to its open-time value. Server-side errors relay back into the overlay or summary view. Phase 2 Stream A (offline queue + service worker):web/sw.js— registered at root scope (/sw.js, served withCache-Control: no-cache). Shell cache: pre-caches/, /app.js, /queue.js, /styles.css, /manifest.json, /static/icon.svg; cache-first for shell assets; network-only for/api/v1/*. InterceptsPOST /api/v1/submit/*when offline or server 5xx: writes to IDB viaweb/queue.jsand returns a synthetic 202 (contract §6.4 note; server never returns 202). Background Sync (pour-queue-drain) drains the IDB queue when network returns;window.onlinefallback for iOS Safari. Queue badge ("Queued (n)") in header updates via SW postMessages without polling. Conflict UX: Discard/Retry/Edit per record; edit pre-fills form with queued body, retains originalIdempotency-Key. Version bump rule: any change toweb/requires aCACHE_VERSIONbump insw.js. Phase 2 Stream C (preset mutation client surface): inline "Save as preset" zone below the chip row; long-press/right-click on any named chip opens an inline edit panel (name + description editable, Save + Delete + Cancel); delete uses a single-tap-confirm (2s window); drag-to-reorder via pointer events with a ghost clone + placeholder; reorder PUT is serialized (latest-wins queue); all mutations guardnavigator.onLineand show a toast if offline — no mutation queueing (offline queue is scoped to submits only)._activePresetis cleared byrefreshPresetChipRowFromListwhenever the active preset name is absent from the re-fetched list (covers delete). PUT-then-DELETE rename has a known minor page-close-mid-rename leak (a duplicate may survive); the user can remove it on next mutation. Phase 2 Stream D (history view + heatmap):<section id="history">— lazy-loaded on first history-tab tap. Bottom-tab nav (role="tablist", 2 tabs: capture/history, cyan active underline, hidden on form/summary). History list renders module key + relative time + first_field per entry; cursor-paginated via server'snext_cursor(never timestamp-derived — same-millisecond entries from offline-queue replay are immune). Tap-to-read panel:GET /api/v1/captures/{id}→<pre>+textContentonly (neverinnerHTML); 404/502 error states. 90-day heatmap: client-side rollup from/api/v1/historyentries (Open Q2 resolution — path (a), no new endpoint); columns-of-weeks CSS grid; count tiers 0/1/2-3/4+ (cyan accent family);aria-labelper cell; tap-popover;prefers-reduced-motionrespected. Heatmap fetch loop terminates whenhas_more===falseOR oldest entry in last page is outside the 90-day window.history.pushState/popstatewired so browser back from history returns to dashboard. See ADR-005-PWA-Companion.src/paths.rs: Centralized path resolution. All runtime file locations (~/.pour/,config.toml,secrets.toml,presets.json,field_presets.json,cache/) are computed here viapour_home()and friends.POUR_HOMEenv var overrides the base directory. No other module constructs these paths manually.src/util.rs: Backwards-compatibility re-export. The canonicalatomic_replaceandresolve_write_targetlive atsrc/transport/atomic.rs(post-Slice-1);util.rskeepspub use crate::transport::atomic::{atomic_replace, resolve_write_target};so all existing callsites compile unchanged.src/hooks.rs: Post-write shell hooks (post_write_shell). Renders a module's command with the Pour-generated tokens inALLOWED_TOKENS({{base_path}},{{rel_path}},{{abs_path}},{{slug}},{{slug_or_time}}) and runs it through the OS shell (sh -c/cmd /C) frombase_path, with null stdin and piped stdout/stderr so a child can neither hang on a prompt nor scribble over the raw-mode TUI. This is arbitrary command execution from config, held safe by: safe-token-only interpolation (no token can carry raw user text — the slug is[a-z0-9-]by construction, which is why no quoting is needed), rejection of unknown tokens at config-load time rather than stripping them,post_write_shell_on_servedefaulting tofalse, and best-effort semantics (the note is written first; a failing hook is a warning, never a lost capture). Awaited with a 30s timeout at both call sites. If a hook ever needs a token carrying user text, that is the trigger to move to argv-style exec, not to extendALLOWED_TOKENS.src/sound.rs: The completion sound ([sound] on_save). Every audio call in pour lives here, so swapping the voice or dropping thecpaldependency touches one file.synthesizeis a pure function that renders the tone (a 500 ms decaying sine) into a sample buffer. AChimepairs aPlayerwith a channel for failures.Appowns aChime, andhandle_submitcallsplay()in itsOkarm only when the key is on.DevicePlayerhands every tone to one process-wideSoundThread, which starts on the first tone and then lives until the process exits. That thread opens the default output, plays, and holds the stream until the buffer drains, so the summary never waits, and tones requested during a tone queue behind it. The thread is long-lived because on Windows cpal caches its device enumerator inside the COM apartment of the first thread that touched it, and a second thread after the first one exits crashes the process (cpal#1302). On Linux, alsa-lib's thread-local error handler keeps library diagnostics off the raw-mode terminal. It is installed on pour's sound thread before each tone, which covers every alsa-lib call there. It is also installed inside the stream callback on cpal'scpal_alsa_outthread, where it covers only the first callback onward. alsa-lib calls cpal makes on that thread before the first callback are not covered, and neither are plugins that log through their own logger, such as PipeWire'spw_log. Failures come back as one line on the channel.App::tick_statusturns the first one into a status toast once no other toast is up, and drops any later ones. Tests substitute a fakePlayer, or aSoundThreadover a fake tone.src/priors/: Read-only priors review panel (L1.5 reference columns, TUI; see pour-review-priors). Decoupled from the TUI and fully unit-testable.plan.rsderives a resolver-readyPriorsPlanfrom a module's[priors]config or the zero-config default: match keys and modes, hard-filter gates (every field another field'sshow_whennames),rank_by,showfields,limit,summary.trigger_fields()lists the fields whose change re-resolves the panel.jsonlogic.rsis the injection-safe/search/predicate builder.match_onvalues ride as JSON data ({"var": "frontmatter.<key>"}, confirmed from the Obsidian OpenAPI), never interpolated into a query string. Nothing calls it at runtime yet.search.rswraps the transport (ADR-001 API→FS): it lists the folder part of the module'spath(tokens not expanded), then the API path fetches note+json per note and the FS path reads and parses each file viafrontmatter_read, stopping at 500 notes. Both build the sameVec<Capture>corpus, so the resolver behaves identically.resolver.rsapplies the gate hard filter, scores each survivor bymatch_onagreement, orders by score, earlier-field agreement,rank_by, then recency, and returns aResolvedPanelofPriorColumns (raw cell values pershowfield,rank_byvalue, dimmed flag, recency) plus the opt-in summary column.same_as_currentandage_labelare the render-time helpers, so the·marks follow the live form without another fetch.mod.rs::resolve_panelis the TUI's entry point; it passes the resolver only the values of fieldsshow_whencurrently shows (visible_form_values, the same rule submit uses), andtrigger_valuesis the snapshot the loop compares to decide whether to re-resolve. TUI integration:FormState.priors_panel(Noneuntil resolved; no columns = empty state) andpriors_collapsed.tui/loop_.rsresolves at form-open and when a trigger field changes (mirrorsfetch_dynamic_options).Ctrl+Rtoggles collapse.tui/form/render/panel.rsdraws the columns to the right of the form, placing each row from the item heightstui/form/render/fields.rsreturns, elides a prefix a long cell shares with another value on its row, and drops columns or falls back to a one-line hint as the terminal narrows. Related: ADR-001-Hybrid-Transport-Layer, ADR-007-Frontmatter-Reader.src/autocreate.rs: Inline note creation. On form submit, scansdynamic_selectfields withallow_create = truefor novel values (not in the existing options list), sanitizes the value into a safe cross-platform filename, and creates a note via the transport layer. Updates the in-memory cache on success. Supports two creation modes: bare stub (minimaldate-only frontmatter) for fields withoutcreate_template, and template-driven (full frontmatter from[templates.<name>]fields via sub-form overlay) for fields withcreate_template. Template path resolution expands strftime tokens before{{name}}substitution to prevent injection. Also handlespost_create_commanddispatch after successful template-driven creation.
Update-Mode Note Resolution
update mode never creates the note it mutates — the daily-note template owns that shape, and a bare file with three keys poisons the note the template would have generated. Over the API, a missing note fires the fixed daily-notes command via execute_command, waits briefly, and retries the read once; over the filesystem it fails loudly with an actionable message. A note that exists but lacks the key gets the key inserted into its existing frontmatter block plus a one-line "your template is stale" notice — capture-first. A note with no frontmatter block at all is an error on both transports: pour mutates properties, it does not restructure notes.
The /periodic/{period}/ endpoint family was evaluated and rejected for this path: a module's path is strftime-configured and need not agree with Obsidian's own daily-note settings, so writing through /periodic/ could target a different file than the module declares.
Append-Mode Filesystem Fallback
When a module uses `mode = "append"` and the API is unavailable, FsWriter::append_under_heading edits the target note in place. It reads the file, splices the rendered entry in before the next heading of the same or higher level (any heading when append_shallow = true), and writes the result through resolve_write_target and atomic_replace. The API path does the same splice in memory after a GET and PUTs the file back (ADR-004-API-Append-Read-Modify-Write), so both transports produce the same output.
Neither transport creates anything when the target is missing. If the note does not exist or the heading is not in it, the write fails, the summary reads Write failed: …, and the form input is discarded. Earlier versions of this note described a standalone timestamped "atomic note" written instead; that fallback was never built. The timestamped filename that does exist belongs to create mode, for a path with no file extension. Config::check_paths warns at startup when an append or update target is missing, but it skips any path containing {{ or %, which covers most daily notes. The missing-note case is specced in pour-append-target-recovery, not implemented.
See also ADR-001-Hybrid-Transport-Layer.
For the integrated event loop and subsystem wiring, see v0.1.0-report (sprint 6).