PeaNote is a local-first application with three layers and no build step:
Browser (static/index.html + static/app.js + static/style.css)
│ fetch('/api/...')
▼
app.py — localhost HTTP host: routing, headers, static allowlist, CSRF guard
│ imports ── contracts described in
▼ api/routes.py
core/vault.py — paths, front matter, SQLite index, history, recovery, integrity, migrations
core/tasks.py — task syntax constants + parser model
core/version.py — single runtime version source
│
▼
vault/*.md (source of truth) data/index.db (disposable projection)
The server binds to 127.0.0.1, preferring port 8765 and falling back to a free local port when it is busy. The active URL is published in data/server.json and used by start.bat / start.sh for status, stop, open, and capture. There is no telemetry, account, external API, or packaged runtime.
app.pyThreadingHTTPServer + Handler class; owns runtime dispatch tables and response writing for the documented endpoints.do_GET / do_POST / do_PUT / do_DELETE look up verb/path tables and call named handlers; legacy raw-query matching, content-type ordering, and guards are preserved.serve_static() is an allowlist: only real files under static/, no hidden files, no directory listings, no repository files. / maps to static/index.html; /?debug=1 maps to static/debug.html.origin_ok() blocks cross-origin state changes; JSON bodies require Content-Type: application/json.GET /api/health calls the incremental refresh() (scandir-cached mtime + size), not a full rebuild.GET/POST /api/onboarding read and merge the local-only first-run state in data/onboarding.json; unknown keys are ignored.POST /api/reindex starts a daemon-thread full rebuild and returns a job (202); GET /api/reindex?job=… polls it. Only one rebuild runs at a time.GET /api/diagnostics reports uptime, vault path, request count / avg / max / last path, and the latest reindex job. Request timings are also printed as one JSON line per request in the terminal.GET /api/routes returns the typed contract registry from api/routes.py; it is additive and read-only.--ask-launch prompts, --launch browser|window overrides for one run, and one-shot --set-launch persists a local default. Window mode detects Edge/Chrome/Chromium and passes --app=<url>; if none exists it falls back to webbrowser.open(url).core/vault.refresh(), stored under .portable-notes/, and exposed read-only via GET /api/sync. PUT /api/note rejects stale expected_updated / expected_sha values with 409 before writing; no sync vendor SDK, account, or network client is introduced./api/notes and /api/search accept optional limit, offset, and preview (backwards compatible — omitting them returns the full original payload). The UI requests 200-note pages with 160-character previews.parse_capture() understands plain text and pn:// / portable-notes:// / peanote:// URLs; create_note() is the single note writer reused by the API, captures, and imports; scan_drop_folder() imports .eml / .txt / .md files from data/drop/ (or drop_dir / PN_DROP_DIR) into Inbox and moves processed files aside.GET /api/export/markdown returns a single portable Markdown document; GET /Attachments/<name> serves vault-relative image links. Existing GET /api/export ZIP is unchanged.main() applies --vault, seeds the vault, rebuilds the index once at startup, starts the optional backup daemon, and prints the version from core.vault.VERSION. --capture "text|peanote://…", --backup, --migrate plan|apply, and --rollback TOKEN are one-shot: they write locally without persisting a temporary vault choice.core/vault.py — canonical vault layerThis is the single source of truth for filesystem and index behaviour; app.py imports it directly. It provides:
| Concern | Functions |
|---|---|
| Paths | norm_rel(), md_path(), safe_name(), vault() |
| Front matter | parse_front(), front(), boolv() |
| Index | init_db(), index_note(), refresh(), rebuild(), prune_index(), serialize(), note_count() |
| Fast scans | iter_note_entries() and iter_tree_entries() use os.scandir cached stats, skipping hidden/internal dirs |
| Search safety | fts_query() tokenizes user input into a quoted FTS5 AND query |
| History | snapshot(), note_history(), history_path(), history_dir(), save_history_label(), snapshot_diff() |
| Recovery | front_matter_errors(), vault_integrity(), migration_status(), migration_plan(), apply_migrations(), rollback_migration() |
| Sync safety | sync_ledger_path(), load_sync_ledger(), save_sync_ledger(), record_external_change(), sync_status() |
| Settings | cfg_bool(), cfg_int() — bounded, allowlisted reads from data/config.json |
| Onboarding | default_onboarding(), load_onboarding(), update_onboarding() |
| Maintenance | iter_notes(), orphan_attachments(), seed() |
Important invariants:
.portable-notes/ (history, trash, verified backups, and sync.json) is never indexed, exported, or link-rewritten.notes table stores content (searchable body) and disk_text (exact Markdown). refresh() compares disk_text with the file, snapshots the old text, and records an event before reindexing, so a sync tool cannot silently erase recoverable text.notes and notes_fts are pruned together, so deleted/renamed notes cannot keep stale FTS hits.parse_front() normalizes CRLF; front() writes booleans via boolv() so the string 'false' stays false.norm_rel() decodes percent-encoding before validation and rejects absolute, drive-qualified, dot-prefixed, and traversing paths.safe_name() strips control/reserved characters, caps length at 120, and prefixes Windows device names.init_db() migrates older indexes by adding the size column used by incremental refresh.data/; corrupt or missing files fall back to safe defaults.index.db or rewrites config. Apply copies config and the index into data/migrations/<token>.* before stamping versions; rollback restores those local files.rebuild() uses one SQLite connection and clears FTS once; it never issues a per-note DELETE ... WHERE path = ?, which would scan the whole FTS table because path is UNINDEXED.refresh() reindexes only changed files using scandir-cached mtime/size. Vaults over 2,000 notes re-scan at most once per second (refresh(force=True) overrides); app-originated writes call index_note() directly, so only external edits wait for the next pass.core/version.pyVERSION = "3.11.0" is the one runtime version source. core.vault re-exports it so existing imports keep working. scripts/check_version.py verifies every pinned runtime source (app header, UI assets, config, launcher, E2E pins) and fails on drift; historical release notes keep their old versions.
core/tasks.pyDefines the compiled regex constants for task syntax (completion, due, baseline, project, priority, estimate, task ID, dependencies, milestone), the Task model, and parse_task_line() / parse_tasks(). Route handlers currently import the constants and run their own parse loops; unifying those loops is planned for 3.6.
core/errors.py, services/task_repository.pyTyped error classes and a reusable task filter boundary. services/task_repository.py is currently exercised by tests only; it is not on the HTTP path.
api/api/routes.py: the typed registry imported by the running server. Every route has a method, path, category, request shape, response name, and read-only flag. It powers GET /api/routes, contract tests, and generated docs.api/system.py: health / rebuild / ZIP export payload builders.api/search.py: search, mentions, duplicates, backlinks, history payloads.api/notes.py: re-exports the canonical core.vault helpers.api/__init__.py: exports the registry; adapters stay importable without divergent logic.Only api/routes.py is on the HTTP path today. The other modules remain thin reference adapters so a future extraction cannot reintroduce a second vault implementation, which caused several 3.1 defects.
scripts/generate_api_docs.py renders docs/API_REFERENCE.md from the registry; --check fails in CI when the checked-in file is stale. tests/test_api_contracts.py also verifies registry uniqueness, that every exact /api/ path in app.py is registered (and vice versa), and that docs are current.
static/Vanilla JS single-page UI. app.js owns state (st), rendering, autosave, dialogs, command palette, board/graph/tags/trash views, and global shortcuts. Note cards use one delegated handler on #list; the folder tree filters that list rather than duplicating note rows; open() uses a sequence guard so stale responses cannot overwrite a newer click. A local undo/redo stack records editor input and direct toolbar/restore mutations, while native undo stays active in other fields. style.css is a token-driven design system with light/dark/auto themes, a narrow-screen navigation toggle, and aligned side-by-side diff columns.
Markdown files are authoritative. SQLite (data/index.db) contains:
notes — metadata + front-matter-stripped body + extracted wiki links.notes_fts — FTS5 index over path, title, content, tags, folder.The index can be deleted at any time; startup or POST /api/rebuild recreates it. All task/project reports are read-only projections derived from indexed Markdown; they never write a competing task database.
Internal state lives in .portable-notes/ inside the vault (history snapshots with .labels.json, trash, and verified ZIP backups). It is excluded from indexing, graph/tree views, exports, and link rewrites. Application-local UI state lives in data/config.json (including the allowlisted launch_mode) and data/onboarding.json; migration backups live in data/migrations/. All stay on this machine and are not served over HTTP.
127.0.0.1; no authentication by design because the app is local-only.static/; repository source, config, onboarding state, DB, and parent directories return JSON 404.Origin/Referer and non-JSON mutation bodies.shell=False is mandatory, and request bodies can only name a vault-local attachment.Known limitation: any local process can call the localhost API; this is inherent to an unauthenticated local app and is why the browser origin check exists.
| Layer | Command | Coverage |
|---|---|---|
| Unit | python -m unittest discover tests -v |
110 tests: front matter, path safety, vault/index invariants, onboarding state, background reindex, diagnostics, capture/drop-folder/Markdown bundle, recovery helpers, migrations, launch modes, sync safety, revamp regressions, task parser/repository, scroll layout, dispatch tables, local transcription |
| Live E2E | python tests/e2e_ui_actions.py |
132 checks against a temporary vault: API payload shapes, paging, onboarding persistence, reindex lifecycle, task endpoints, capture, drop folder, exports, attachments, history labels, trash recovery, backups, integrity, migrations, launch flags, sync conflict guard, security, local transcription wiring, and source-level UI wiring |
| Benchmark | python scripts/benchmark.py |
1k / 10k / 50k note runs with seeded vaults, real handler, median request timings |
| Contract | python -m unittest discover tests -v (test_api_contracts.py) |
86 registered routes, live-path parity, generated-doc freshness |
| Version | python scripts/check_version.py |
10 pinned runtime sources agree with core.version.VERSION |
| Syntax | python -m compileall -q app.py core api services scripts tests and node --check static/app.js |
All Python modules and the browser script |
The E2E suite starts app.py with a throwaway vault on port 8913 and restores the user’s real data/config.json and data/onboarding.json afterwards. It also sets PN_INDEX_DB inside that throwaway vault so deleting it cannot be mistaken for an external removal in the real vault. It writes UI_TEST_REPORT_v3.11.0.md. Because it is stdlib-only, dialog interactions are verified by source tokens rather than a browser driver; see AUDIT_REPORT.md for the remaining gap.
ROADMAP 3.6 landed the route registry, generated API reference, core.version drift guard, contract tests, Make/CI gates, and runtime dispatch tables in app.py. Incremental/background indexing, paged lists, and browser-native list/tree virtualization are already in the runtime; a runtime plugin loader remains deferred. None of these is required to understand the current runtime.