01Title

Technical Architecture · August 2026

Narra.

The architecture of a presenter that
answers for itself.

§ docs/architecture-mvp.md · Decisions D1–D7

02System

System Overview

Three services. One database. Four trust boundaries.

browser ──HTTPS, session cookie──▶ frontend · Next.js :4567 │ ┌───────── trust boundary A · control plane ─────┴──────────────┐ │ backend · Spring Boot :8084 │ │ authN/authZ · tenancy · workflow state · approvals · audit │ └────┬──────────────────────────────────────────┬─────────────────┘ │ sync REST + X-Internal-Token │ outbox ▸ Redis Streams :6380 ▼ ▼ ┌───────── trust boundary B · AI execution plane ──────────────────┐ │ ai-service · FastAPI :4568 ingest worker · consumer group │ │ hybrid retrieval · pipelines · grounded Q&A · citation validation │ └────┬──────────────────────────────────────────┬─────────────────┘ ▼ ▼ trust boundary C · data trust boundary D · external Postgres + pgvector :5434 Ollama :11434 (models) Redis :6380 · MinIO :9002/:9003 behind the model gateway

Ports are non-default on purpose — 5432, 6379 and 8080–8083 belong to other local stacks. The client never supplies tenant_id; every identifier is re-resolved server-side.

§ docs/ports-and-endpoints.md · Port map + call flow · docs/architecture-mvp.md §1

03Ingestion

Ingestion Pipeline · Live

Outbox → stream → worker → pgvector.

17docs indexed 348chunks · 768-dim ~9son an RTX 5070 0dead-letter entries
  1. Transactional outbox. State change and job enqueue commit together — never a presentation stuck INGESTING with no job behind it.
  2. Redis Streams consumer group. Each message goes to exactly one worker; four jobs in flight, capped by a semaphore.
  3. Idempotent writes. Key sourceId:sourceVersion; delete-then-insert per source in one short transaction. A redelivery rewrites identical rows.
  4. Bounded failure. Three attempts, then a visible FAILED plus a dead-letter entry. Never a silent retry loop.
  5. Guarded transitions. WHERE ingestion_status = expected — the same optimistic pattern as the presentation versionNo 409.

never held open:
a DB transaction across
a network call.

embeddings happen outside
any transaction; results
land in a short tx after.

that is the deadlock rule,
written down once.

§ docs/rag-ingestion-spec.md · Concurrency safety · TODO.md · Ingestion pipeline live (d956e0b)

04Chunk + Embed

Chunking & Embeddings

Token-aware everything.
Structure first, tokens second.

Token counterThe embed model's own tokenizercharacters lie; tokens don't
Chunk budget512 target · 1024 hard maxwell under nomic's 2048 context
Overlap64–96 tokens, in-section onlycrossing a heading pollutes retrieval
Provenanceheading path + char offsetsthis is the citation system
Embeddingsnomic-embed-text · 768-dim · L2-normalizedlocal, free, cosine ≡ dot product
Task prefixessearch_document: / search_query:Mandatory. Enforced in the gateway, not left to callers — omitting them degrades quality with no error.

§ docs/rag-ingestion-spec.md · Tokenization · Chunking · Embedding

05Retrieval

Hybrid Retrieval

Dense + BM25, fused. Tenant filter first, always.

Exhibit A · Live retrieval, GCS corpus

"How does the GCS talk to drones without internet?"

Keyword arm: zero hits. No chunk contains that phrasing. Semantic arm carried it alone — "without internet" and "air-gapped" are neighbors in 768-dimension meaning space[2].

Confidence
0.756
04-air-gap-and-comms.md · Architecture — air-gap & device communicationShow source ↗
  1. Scope, then search. WHERE tenant_id = %s AND project_id = %s — the predicate exists before the query text does. In plain words: first lock the search inside your organization's documents — the walls go up before any searching starts.
  2. Two arms, top-20 each. pgvector cosine (HNSW) + Postgres FTS over a GIN-indexed column. In plain words: two searchers work in parallel — one is Ctrl+F (finds exact words), the other is a librarian who knows "without internet" and "air-gapped" mean the same thing (finds meaning).
  3. RRF fusion, k = 60. No normalization across two incomparable scales — the failure mode of naive weighted sums. In plain words: like merging two judges' top-10 lists by position — whatever ranks high on either list wins, without pretending their scoring systems are comparable.
  4. Truncate to topK = 8. Reranker port exists with a no-op today; a cross-encoder is a config flip when the evals demand it. In plain words: keep the best 8 passages and hand only those to the writer — small enough to stay focused, big enough to cover the question.

known sharp edge:
HNSW with a restrictive
WHERE can under-return.

mitigations, in order:
iterative index scan,
raise hnsw.ef_search,
partial indexes per tenant.

stated honestly, tested
with two seeded tenants.

§ ai-service/README.md · Grounded Q&A · docs/architecture-mvp.md §8 · RAG Pipeline

06Agentic

Agentic Retrieval · Next

Search the way an agent searches — then land.

  1. Decompose. "What is this project about?" is a terrible retrieval query. Split it: purpose, architecture, goals — three sharp searches instead of one vague one.
  2. Gap-hop. "Compare the comms security requirements with what the CONOPS promises." No single query gets both halves. Hop one retrieves the requirements; reading them defines hop two.
  3. Follow the thread. The first result mentions "the recorder" and never defines it — the agent notices and issues a lookup before answering.
  4. Bound it. Max 2–3 hops, then answer or refuse. The agent must always land.

the latency lesson,
learned the hard way:

first live Q&A returned
an empty answer at full
token spend — the local
model "thought" through
its whole budget before
writing a word.

one reasoning_effort
control later:
35s → 1.5s.

know where your
tokens go.

§ blogs/2026-08-02-agentic-retrieval-and-what-im-learning.md · Agentic retrieval

07Generation

Grounded Generation

Every stage can only reduce what gets claimed.

  1. Refusal gate — before the model. Best cosine below 0.35 and we refuse without spending a token.
  2. Injection-hardened envelopes. Chunks numbered, wrapped in <source> delimiters, declared data, not instructions, defanged against delimiter escape.
  3. Cite or don't claim. Every factual sentence carries a [n] marker resolving to a retrieved chunk.
  4. Citation validation. Fabricated markers stripped; an answer with no valid citation gets one stricter retry, then refuses.
  5. Verbatim excerpts. Show Source displays the retrieved text, never a model rewrite — you check its work against the original.

"I could not find enough information in the approved sources to answer that confidently."

One fixed string, byte for byte. A refusal is a 200 with grounded: false, confidence: 0.0, and no citations — a refusal dressed up with citations is the exact failure the requirement names.

§ ai-service/README.md · Grounded Q&A pipeline · ai-prompt.md · Core Trust Principle

08Confidence

The Confidence Bar, Explained

It measures finding, not proving.

A librarian, three questions. "What does TR-002 say?" — she finds the exact page; it matches your words. High closeness. "What is this whole library about?" — six books from six sections, each only loosely similar, together perfect. Low closeness, great answer. "Is this library only for lawyers?" — a page saying open to everyone, which refutes rather than resembles. Low closeness, great answer.

confidence = (mean cosine of cited chunks − 0.35) ÷ 0.5 Below 0.35 = no evidence, Maria refuses. 0.45–0.60 related · 0.60–0.75 strong · above 0.75 your question nearly quotes the document. Chunks the vector arm never saw count 0.0 — measured similarity only.

the roadmap replaces
closeness with two
better ingredients:

faithfulness — a judge
scoring how well the
evidence supports
each claim.

calibration — refit until
80% means right four
times out of five.

only then does a
"minimum confidence"
policy make sense.

You seeIt means
Refusal (0%)Nothing cleared the evidence bar. Maria working, not failing.
~35–50%Evidence found by synthesis or refutation — judge the citation spread: many documents agreeing = strong answer.
~50–70%Direct, on-topic evidence. Typical for good factual answers.
70%+The sources nearly contain your question verbatim.

The bar never lies high — it only lies low. That direction was chosen on purpose.

§ docs/confidence-explained.md · The library analogy · How to read the bar today

09Human Gates

Workflow State Machine · Human-in-the-Loop

Illegal transitions raise. Approvals never silently pass.

CREATED └▶ SOURCES_INGESTING ──▶ SOURCES_READY └▶ OUTLINE_GENERATING ──▶ OUTLINE_READY ◀── HUMAN GATE 1 └▶ OUTLINE_APPROVED └▶ SLIDES_GENERATING ──▶ VERIFYING ──▶ REVIEW_READY ◀── HUMAN GATE 2 └▶ APPROVED ──▶ EXPORTING ──▶ EXPORTED any generating/verifying state ──▶ FAILED (retryable to its predecessor) any non-terminal state ──▶ CANCELLED user edits an approved artifact ──▶ new version, prior approval voided

POST /outline:approve {versionNo} returns 409 Conflict if that version is not current. You must re-read what changed before you approve. Python has no PATCH /presentations capability of its own — it calls a narrow internal callback and Java validates the transition, which is what keeps the orchestrator genuinely in control.

non-bypassable by design:
outline approval
final deck approval
tool writes
external sharing

live Q&A is gated by
verification + refusal
instead — and logged
for review.

§ docs/architecture-mvp.md §7 · Generation Workflow · ai-prompt.md · Human-in-the-Loop Requirements

10Security

Security Guardrails

Assume every document is hostile.

  1. Tenant isolation, proven live. Asserted inside every query, not around it — a wrong tenant retrieves zero chunks. Not few. Zero.
  2. Internal-only AI service. Browsers never reach :4568. X-Internal-Token must match, or 401 — the same control on the worker's callbacks.
  3. Injection screening at ingestion. Flagged source ⇒ QUARANTINED, zero chunks written. It never reaches a prompt.
  4. Parameterized-only SQL. Bound parameters in both languages; least-privilege DB roles; no dynamic table or column names from input.
  5. Output is untrusted input. Schema-validated, never executed, never raw HTML, never unvalidated into a query or tool argument.

threat-modeled against:
OWASP Top 10
OWASP LLM Top 10
OWASP ASVS
NIST AI RMF

invariants that no
config key can disable:
isolation · citations
refusal · audit
write approvals
injection defenses

a test asserts the union
of writable keys and
reserved keys is empty.

§ ai-prompt.md · Security Requirements · docs/architecture-mvp.md §1 · Trust boundaries · §9 · Invariants are code, not config

11Evals

Evaluation Harness · Queued

A quality claim is only as real as the eval that can reject it.

ChassisRAGAS core fourfaithfulness · answer relevancy · context precision · context recall
ConstitutionPrinciple-based gradingcites-or-refuses · injection-is-data · evidence-bounded tone
AdversarialPass/fail gates, one failure blocksoff-corpus refuses · injected sources don't steer · cross-tenant = zero
CalibrationP(True) self-check + reliability curverefit until 80% means right four times in five
The judgePluggable through the model gatewayLocal model for everyday runs, Claude via CLI for release-grade — judging is exactly where the better model earns its keep.

The 33%-confidence bug was caught by one user asking one question. The harness is that same scrutiny, automated, on every change, forever.

§ blogs/2026-08-02-evaluating-maria-ragas-plus-constitution.md · TODO.md · Eval harness: RAGAS + Narra constitution

12Free-First

Free-First Engineering

Capability from architecture.
Budget buys quality only.

StageBound byWhat that means
Parse + chunkCPU, single-core per doc<1% of job time for markdown/text
EmbeddingGPU (VRAM + compute)The dominant cost — ~14 chunks/s warm on RTX 5070; CPU-only is 5–10× slower
Chat generationGPU VRAM, or an external API4B ≈ 4GB · 14B ≈ 10GB — 14B and embeddings is tight on 12GB; claude-cli offloads it entirely
pgvector writes + HNSWCPU + diskTrivial until 100k+ chunks
Worker orchestration, RedisI/ONever the bottleneck — which is why worker language doesn't affect throughput
Maria's voiceClient deviceZero server cost by design

Buy VRAM for chat models, not embeddings — nomic-embed-text needs under 1GB. And before any hardware spend, the free lever is the claude-cli provider: a subscription driving claude -p headless, no API key, moving the biggest VRAM consumer off the GPU.

§ docs/rag-ingestion-spec.md · Bottleneck map & hardware requirements · ai-prompt.md · Free-First Provider Strategy

13Roadmap

Roadmap

Substrate first. Then reach. Then language.

Next — on the same substrate

  • Outline generation → gate 1 → slides + notes → verify → gate 2
  • Agentic retrieval: bounded search-read-search
  • claude-cli gateway provider; contextual enrichment ON
  • Eval harness gating every retrieval change
  • PowerPoint export with tenant branding

Then — reach & language

  • GitHub as a source (read-only repo ingestion)
  • MCP live tools with policy engine + write approvals
  • Localization: ask and hear in your own language
  • Voice input (browser SpeechRecognition, Whisper later)
  • Full-stack Docker profile

§ TODO.md · Next + Phase 5 · Localization (flagship) · STATUS.md · Next Actions

Narra. 01 · 13