Skip to content

Architecture Overview ​

This page records structure and invariants only. Runtime data (document counts, store size, session counts) is returned live by GET /kb/collections, GET /system/storage and GET /health, and is never transcribed here.

Layers ​

Client · React 19 + Vite 6
16 screensfetch + SSEBearer profile token
Agent Host · Hono 127.0.0.1:8787 · single process
API + auth · 214 routes · PIN/scrypt · Idempotency-KeyAgent Kernel · 8 agents · 16 zod tools · event log / checkpoints / interruptsBackground jobs · reindex worker · retention / inbox / audit
Capabilities
Hybrid retrieval · FTS5 BM25 + vector RRFLocal ONNX embedding · Sync / Local / AsyncCode sandbox · seatbelt · process groupVoice TTS/ASR · OCR / visionWeb search/fetch · MCP
Local storage · SQLite + files only
system.db · profiles / providersshared.db · shared KB ACLprofiles/<id>/ · app.db + lineage.db
External · egress with a key
Provider LLM / voice / OCRMCP servers · Webegress audit

The frontend talks to the server over fetch and SSE (Server-Sent Events), authenticated with a Bearer profile token. The server is a single-process Hono app, routes split by domain into routes/*, with api.ts handling only assembly and middleware. Colors encode layers: violet=client, indigo=Host/Kernel, sky=capabilities, green=local storage, amber=background jobs, rose=external egress.

For the complete chain from input to report (import → index → question → interview → score → report → provenance → consolidation) see End-to-End Flow.

Module map ​

ModuleStorage (tables)API (main)Key logic
Auth / Profilesystem.db: profiles profile_tokens audit/profiles /profiles/:id/{unlock,lock,pin,reset-pin} /me /tokensscrypt PIN; HMAC profile token (ver/jti, rotatable & revocable); per-profile directory
Providers / routingproviders provider_key_history capability_routes/providers* /capability-routes/:key /probeKeys AES-256-GCM encrypted; members can't rewrite routes or probes; UI must warn when a key is set but the route still points at mock
Sessions / interviewsapp.db: sessions events runs checkpoints interrupts tool_calls/sessions*append-only events; checkpoint recovery; pause/resume; first question up front, rest in background; topic dedup within a session
Scoring / reportsreport_versions (hash+HMAC+meta)/versions* /rescore /citations/verifyJudge panel median; failed runs marked unavailable; reports assembled only in report-builder
Knowledge base (private)kb_collections/documents/chunks/fts kb_eval_sets/runs web_snapshots/kb/*Structure-aware chunking; FTS5 + vector RRF; URL/file/inbox import; eval recall/MRR; background reindex
Topics (graph)kb_topics kb_topic_sources kb_topic_merges/kb/topics (incl. /rebuild, /merges*, /merge, PATCH /:id)Heading extraction → normalize & cluster → merge suggestions awaiting confirmation; kind separates technical topics from project narratives; rename/merge undoable
Shared libraryshared.db: shared_collections/documents/chunks/versions/acl/audit/kb/shared/* /kb/collections/:id/{acl,transfer}use/edit/admin; revocation immediate; ownership transfer; audit CSV
Resumeresumes/resumes*PDF/DOCX/MD/TXT parsing; heading-less PDFs structured by a model (merged, not overwritten); version compare & activate
OCR / visionegress, events(vision.analyzed)/ocr /vision/analyzePaginated OCR; vision results insertable into answers; configurable command fallback without a key
Voicesettings.tts.* settings.asr.* recordings/tts /asr/transcribe /asr/benchTTS/ASR only via real providers; missing key errors explicitly, never fakes text
Codetool_calls + events/code/run /code/quota /code/poolSandbox inherits only PATH/LANG/TMPDIR, HOME points at a temp dir, timeout & output caps hardcoded; Pyodide in an isolated subprocess
Memory / reviewmemory_blocks facts episodes reflections learner_kp review_queue/log kp_snapshots/memory* /review/wrong-book /heatmapPost-session consolidation; spaced repetition; wrong-book; ask the coach
Webweb_snapshots egress/kb/web/snapshots, tools web.search / web.fetchForced allow/deny by webTiming
Provenancelineage.db: calls claims nodes edges payloads/lineage/*outbox → projection; SAW/PRODUCED/CITES; citation verification; every conclusion leads back to source
Modelsmodels/models/catalog /models/:id/{download,pause,activate}Recommended catalog; HF→mirror; resumable; auto-registers vector catalog on install
MCPmcp_servers/mcp/servers* /mcpHTTP + stdio long connections; tool toggles; approval; audit
Jobs / retentionjob_runs retention_overrides/admin/jobs* /settings/retentionDaily cleanup + inbox sync + audit export; retryable on failure
Observabilityusage egress audit/usage /egress /system/storage /admin/runtime/infoCost/budget; egress records; runtime probes
CLISame DBs (attached or --standalone)—ifg doctor/sessions/verify/export/kb*/asr bench/judge calibrate/lineage gc

Server file layout ​

text
server/
  api.ts           middleware, error mapping, health, profile & MCP entry, mounts routes
  http.ts          shared deps: runtime, token issuance, profileOf, sessionDto, readJson
  routes/
    sessions.ts    start/answer/hint/pause/code/score/report/export
    knowledge.ts   private KB, topics, shared KB, eval sets, import, audit, background reindex
    runs.ts        run checkpoints, replay, SSE
    providers.ts   providers, capability routes, TTS/ASR settings, port
    provenance.ts  call chains, citations, lineage graph, redacted export JSON
    memory.ts      memory blocks, facts, reflections, review, resume
  interview/
    engine.ts      session state machine, per-question scoring, end & rescore, pause/resume, code run
    scoring.ts     the single entry for per-question scoring (panel, repair, failed → unavailable)
    report-builder.ts  the single report assembly point (shared by first score & rescore; fills derived fields before signing)
  capabilities/
    kb.ts                retrieval, embedding bridges, background reindex jobs
    kb-topics.ts         topic extraction: filter, normalize, cluster, kind decision
    kb-topics-store.ts   topic persistence, rebuild (idempotent), merge suggestions & undo
    resume-structure.ts  model structuring of PDF resumes (failure doesn't block import)
    async-embed.ts       dedicated-worker async embedding bridge (for reindex)

Each route module depends only on http.ts, with no cross-references; register*(app) mounts them in order in api.ts. This domain split keeps each route's responsibility clear and independently testable.

Session lifecycle ​

Three design guarantees:

  1. The first question doesn't wait for all questions. The first question is ready up front and the rest fill in in the background, so the user enters the interview immediately without waiting for full preparation.
  2. No repeated topic. Planning and question generation both dedup by normalized topic (prefix match); duplicates are replaced with an unused topic first.
  3. Background generation stays consistent with new state. Appending questions goes through withSessionLock, waiting for an in-progress scoring rather than returning 409; on host shutdown engine.dispose() stops the background immediately so the process exits cleanly.

See Agent Kernel & Sessions.

Data isolation (measured) ​

CheckResult
New profile imports a private documentVisible to itself
Another profile reads that document listNot visible
Another profile reads by session ID404
File systemEach profile has its own profiles/<id>/{app,lineage}.db
Delete profileDirectory and DBs removed together, verified
Provider keysMachine-shared but encrypted; API returns only hasKey
Profile creation responseContains no pin_hash/pin_salt

See Provenance & Storage.

Engineering quality ​

The system is guarded by 14 verify gates: file-system health, privacy scan, lint, strict types, reachability, doc endpoint/claim checks, Mermaid parsing, i18n completeness, backend tests & coverage (272 tests, thresholds 75/60/65), frontend unit tests, 30 trajectory-invariant evals, and the frontend build. See Testing & Gates.

Module deep-dive index ​

ModuleDeep dive
Data model & four-database isolationData Model
Auth, tokens, keys & egress guardsAuth & Security
Lexical + semantic rescue retrievalRetrieval Pipeline
Local embeddings, pooling & vector indexEmbedding & Vector Index
Topic extraction, clustering & mergesTopic Graph
8 agents / 16 tools / event sourcingAgent Kernel & Sessions
Judge panel, reports & signingScoring & Reports
Voice / vision / web / MCPCapabilities
Providers, routing & degradationProviders & Routing
Shared collections, ACL & versionsShared Library & ACL
Memory consolidation, BKT & spaced reviewMemory & Review
Provenance ledger & storage isolationProvenance & Storage
Multi-language sandbox & quotasCode Sandbox
Worker-based background rebuildBackground Reindex
Full-chain timingEnd-to-End Flow
All 214 routesAPI Reference

Local-first · inference egresses on demand · fully traceable