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 to tui::loop_::run_loop for 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 (parse resolves argv against the config into a typed OneShot or a typed OneShotError; run delegates to output::write_update). It lives in the library rather than main.rs so the parse layer is testable — integration tests link the lib, not the binary. pour <module> with no field argument parses to None and falls through to the existing TUI fast path unchanged. v1 wires the grammar for toggle/counter fields on update modules only.
  • src/init.rs: First-run setup. Implements the pour init flow — generates a starter config.toml with interactive vault path selection and example modules. Also hosts the canonical module_order(&config) helper used by both app.rs and the dashboard.
  • src/tui/: Presentation layer. Routes events to screen handlers (dashboard.rs, form/, summary.rs, configure/) and dispatches Action enums. tui/loop_.rs (post-Slice-13) owns the event-poll/draw/dispatch loop and a handler for each Action variant (25 besides None and Quit). It also holds the form-open fetches fetch_dynamic_options, fetch_current_values and resolve_priors, which tui/mod.rs re-exports along with run_loop and handle_submit so main.rs can call them on the direct-entry path; tui/mod.rs::render is 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.rs owns FormAction and the NavCtx shared with key handlers. render/{mod,fields,clip,composite,panel}.rs split rendering by concern; clip.rs cuts one row of editable text to the cells it has. cells.rs measures 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}.rs split the 930-line handle_key by mode. overlays/{mod,preset_picker,sub_form,small}.rs colocate the four overlays with their key-handlers (small.rs merges 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.rs owns ConfigureAction and re-exports the public surface. render.rs holds 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}.rs split the 1000-line handle_key by mode. key/modules.rs and key/presets.rs are empty placeholders kept for the planned layout; module-list navigation lives in the dashboard, and the configure screen has no preset editing yet. autosave.rs invokes crate::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 on App.
  • src/app.rs: State management. Owns FormState, ConfigureState, BrowserState, active field indices, and input validation. FormState.active_field is a visible-set index; active_config_idx mirrors it as the config-level index. FormState.cursor_position is a char-index (post-v1-hardening), never a raw byte offset — emoji and CJK in textareas no longer panic on backspace. FormState.callout_overrides holds 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_values holds an update module's target-note frontmatter, read once at form open by tui::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 given show_when rules. Called on every form key event. Integration points: src/app.rs uses it to compute FormState.active_field bounds; src/output/ skips hidden fields during generation; src/config.rs validates show_when constraints at load time; src/tui/configure/ serializes show_when when writing fields back via add_field_on_disk / update_field_on_disk.
  • src/output/: Write execution. Orchestrates frontmatter.rs generation and template.rs path/template rendering (including {{callout}} resolution and field-level callout wrapping). write_create merges [modules.<n>.frontmatter] statics after the captured fields (skipping any key the capture already claimed, including the injected icon/daily) and renders the auto-injected date with the module's frontmatter_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_title mirrors 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.rs shares a substitute_keys kernel between render_path and render_append_template; the 8 intentional behavioral divergences between the two are explicit configuration of the kernel and pinned by snapshots in tests/output/template_snapshot.rs. Literal % in user templates is preserved by escape_nonspecifier_percent (post-v1-hardening). output/update.rs (habit-capture v1) owns write_update — the third write mode. It reads the target note's current frontmatter, computes new values per field type (toggle flips, counter accumulates, =N sets), 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.rs gained the read/patch half of that: read_frontmatter (top-level scalars only, no type coercion) and patch_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 through data/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.rs backs dynamic-select dropdowns. history.rs tracks capture events at ~/.pour/cache/history.jsonl (append-only JSONL); statistical computation lives in history_summary.rs; legacy-format reader lives in history_legacy.rs. presets.rs stores per-module saved field-value sets at ~/.pour/presets.json; field_presets.rs stores per-field row-set presets for composite_array fields. preset_tree.rs builds a hierarchical PresetTree from Vec<PresetEntry> + preset_axes. frontmatter_read.rs (priors L1) is the hand-rolled frontmatter reader — parses a note's --- block into Frontmatter (BTreeMap<String, FrontmatterValue>), scoped to Pour's writer subset and degrading gracefully on richer YAML (see ADR-007-Frontmatter-Reader); wikilink.rs is the [[Target|Alias]]/#Frag → Target stripper. 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 one std::fs::rename call that resolves to MoveFileExW(MOVEFILE_REPLACE_EXISTING) on Windows. It is paired with resolve_write_target(path), which every writer calls before choosing where to put its temp file. rename swaps a directory entry, so renaming onto a symlink replaces the link with a regular file and strands the edit: a ~/.pour/config.toml stowed out of a dotfiles repo lost its link on the first TUI write, and the tracked file kept its old contents. resolve_write_target follows a symlink at path to 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 with EXDEV. The resolution is confined to the symlink branch on purpose: std::fs::canonicalize returns 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 both fs.rs write paths. Pinned by tests/util_atomic.rs and tests/config_symlink.rs, the latter driving the real append_option_to_field_on_disk API over a stow layout. fs::resolve_path_validated (post-v1-hardening) rejects .., absolute paths, and ~-prefixes on every public method. Exposes execute_command() for Obsidian plugin commands, read_file() for vault reads, and patch_frontmatter() for the single-key mutation behind update mode. patch_frontmatter is 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 sends Operation: 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 returns TransportPatchError::Conflict without 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_since takes 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) returns Unsupported, and write_update retries over a filesystem writer built from the module's root — Transport::Api carries no vault path of its own, which is why write_update takes a fallback_root. Transport::connect remains one app-level instance; Transport::for_module(module) is a second, write-time selector returning Some(Fs) rooted at a module's base_path override (or None to 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.rs itself is unchanged by the override: resolve_path_validated simply 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.rs defines the value layer (Config, ModuleConfig, FieldConfig, ConfigError, etc.) plus the 15 *_on_disk mutator methods (post-Slice-3 they all share one Config::write_atomic; post-Slice-8 they're thin facades over Config::edit). config_edit.rs defines Config::edit(path, |draft| { … }) — the transactional load → mutate → validate → write entry point with ConfigDraft<'_> exposing both &mut DocumentMut and &Config. config_updates.rs (post-Slice-5) is the canonical home for build_module_updates, build_vault_updates, build_field_updates, build_sub_field_updates — previously duplicated between main.rs and tui/configure.rs. See ADR-006-V1-Lock-In-Patterns.
  • src/server/: axum HTTP server powering the mobile PWA companion. Post-decomposition layout: mod.rs is lifecycle (auth middleware, AppState, run/run_with_shutdown); routing.rs owns the router builder; static_assets.rs owns the embedded PWA shell. dto/{mod,response,requests,mapping}.rs split wire types by concern — mapping.rs isolates Config → DTO translation so response.rs is Config-free. handlers/submit/{mod,validate,idempotency_lookup,autocreate_step,write_step,history_step}.rs split the 607-line submit handler into a thin orchestrator + 5 phase modules using a SubmitContext struct. idempotency.rs is an in-memory LRU (1024 cap, 60s in-flight TTL, 5min done TTL). startup.rs contains resolve_token and print_banner. See ADR-005-PWA-Companion for the architectural decision and pour-api-contract for the wire shape.
  • TUI ↔ Serve handoff (src/tui/loop_.rs run_loop, Action::Serve): pressing s from the dashboard suspends the TUI (ratatui::restore()), probes port 8421 (TOCTOU-free: the bound listener is passed directly into run_with_shutdown), prints the banner via startup::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 to app.deferred_stderr and printed after TUI restoration. The pour serve CLI path is unchanged.
  • web/: Embedded PWA shell. Vanilla HTML/CSS/JS, compiled into the binary at build time via rust-embed. Served at /; static assets require no auth. Phase 1: module list, per-module form rendering from GET /api/v1/config, submit. Phase 1.5/1.5++: preset chip row, show_when cascade, 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 a dynamic_select field with create_template set. The overlay renders template fields (text/number/static_select with inline cycling, no <select>), collects values into _pendingAutoCreateInputs, and includes them as auto_create_inputs in 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 with Cache-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/*. Intercepts POST /api/v1/submit/* when offline or server 5xx: writes to IDB via web/queue.js and 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.online fallback 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 original Idempotency-Key. Version bump rule: any change to web/ requires a CACHE_VERSION bump in sw.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 guard navigator.onLine and show a toast if offline — no mutation queueing (offline queue is scoped to submits only). _activePreset is cleared by refreshPresetChipRowFromList whenever 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's next_cursor (never timestamp-derived — same-millisecond entries from offline-queue replay are immune). Tap-to-read panel: GET /api/v1/captures/{id} → <pre> + textContent only (never innerHTML); 404/502 error states. 90-day heatmap: client-side rollup from /api/v1/history entries (Open Q2 resolution — path (a), no new endpoint); columns-of-weeks CSS grid; count tiers 0/1/2-3/4+ (cyan accent family); aria-label per cell; tap-popover; prefers-reduced-motion respected. Heatmap fetch loop terminates when has_more===false OR oldest entry in last page is outside the 90-day window. history.pushState/popstate wired 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 via pour_home() and friends. POUR_HOME env var overrides the base directory. No other module constructs these paths manually.
  • src/util.rs: Backwards-compatibility re-export. The canonical atomic_replace and resolve_write_target live at src/transport/atomic.rs (post-Slice-1); util.rs keeps pub 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 in ALLOWED_TOKENS ({{base_path}}, {{rel_path}}, {{abs_path}}, {{slug}}, {{slug_or_time}}) and runs it through the OS shell (sh -c / cmd /C) from base_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_serve defaulting to false, 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 extend ALLOWED_TOKENS.
  • src/sound.rs: The completion sound ([sound] on_save). Every audio call in pour lives here, so swapping the voice or dropping the cpal dependency touches one file. synthesize is a pure function that renders the tone (a 500 ms decaying sine) into a sample buffer. A Chime pairs a Player with a channel for failures. App owns a Chime, and handle_submit calls play() in its Ok arm only when the key is on. DevicePlayer hands every tone to one process-wide SoundThread, 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's cpal_alsa_out thread, 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's pw_log. Failures come back as one line on the channel. App::tick_status turns the first one into a status toast once no other toast is up, and drops any later ones. Tests substitute a fake Player, or a SoundThread over 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.rs derives a resolver-ready PriorsPlan from a module's [priors] config or the zero-config default: match keys and modes, hard-filter gates (every field another field's show_when names), rank_by, show fields, limit, summary. trigger_fields() lists the fields whose change re-resolves the panel. jsonlogic.rs is the injection-safe /search/ predicate builder. match_on values 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.rs wraps the transport (ADR-001 API→FS): it lists the folder part of the module's path (tokens not expanded), then the API path fetches note+json per note and the FS path reads and parses each file via frontmatter_read, stopping at 500 notes. Both build the same Vec<Capture> corpus, so the resolver behaves identically. resolver.rs applies the gate hard filter, scores each survivor by match_on agreement, orders by score, earlier-field agreement, rank_by, then recency, and returns a ResolvedPanel of PriorColumns (raw cell values per show field, rank_by value, dimmed flag, recency) plus the opt-in summary column. same_as_current and age_label are the render-time helpers, so the · marks follow the live form without another fetch. mod.rs::resolve_panel is the TUI's entry point; it passes the resolver only the values of fields show_when currently shows (visible_form_values, the same rule submit uses), and trigger_values is the snapshot the loop compares to decide whether to re-resolve. TUI integration: FormState.priors_panel (None until resolved; no columns = empty state) and priors_collapsed. tui/loop_.rs resolves at form-open and when a trigger field changes (mirrors fetch_dynamic_options). Ctrl+R toggles collapse. tui/form/render/panel.rs draws the columns to the right of the form, placing each row from the item heights tui/form/render/fields.rs returns, 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, scans dynamic_select fields with allow_create = true for 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 (minimal date-only frontmatter) for fields without create_template, and template-driven (full frontmatter from [templates.<name>] fields via sub-form overlay) for fields with create_template. Template path resolution expands strftime tokens before {{name}} substitution to prevent injection. Also handles post_create_command dispatch 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.

For the integrated event loop and subsystem wiring, see v0.1.0-report (sprint 6).