feat: scaffold Brain of Reese — FastAPI RAG chat over Postgres 17 + pgvector

Foundation (phase 01, verified):
- FastAPI app: /api/health, /api/suggestions, /api/chat (placeholder),
  static frontend served locally (no CDN)
- Postgres 17 + pgvector via db/Containerfile + compose.yaml
  (podman compose up -d db), Alembic initial migration (documents,
  chunks with vector(768), query_log)
- LLM client targeting https://aipi.reeseapps.com/v1 (turbo/embed);
  scripts/llm_probe.py verified models + 768-dim embeddings live
- Conditional debugpy: imported only when DEBUGPY=1 (attach on demand,
  :5678); logging config for clean single-line logs
- Frontend shell: mobile-first chat + Sources pages, tokens, a11y baselines
- Tests: 24 unit+integration (99% coverage on app/), ruff + pyright clean,
  Playwright smoke E2E (3 tests) against a deterministic mock LLM
- Planning: .agent/PLAN.md (architecture + LOCKED decisions), AGENTS.md,
  6 user stories, 7 phase files (one story / one phase / one Playwright
  suite each)
This commit is contained in:
2026-08-21 13:42:21 -04:00
commit 022da8e2bc
63 changed files with 5225 additions and 0 deletions
+189
View File
@@ -0,0 +1,189 @@
/* Brain of Reese — chat shell.
*
* Scaffolding-stage behavior: renders suggestions, shows KB health, and
* echoes a friendly placeholder answer. The real RAG streaming chat is
* implemented in the chat-rag phase (see .agent/user_stories/).
* All DOM ids match frontend/index.html.
*/
const messagesEl = document.querySelector("#messages");
const emptyState = document.querySelector("#empty-state");
const suggestionsEl = document.querySelector("#suggestions");
const composer = document.querySelector("#composer");
const input = document.querySelector("#message-input");
const sendBtn = document.querySelector("#send-btn");
const sendLabel = document.querySelector("#send-label");
const sendStatus = document.querySelector("#send-status");
const banner = document.querySelector("#kb-banner");
const bannerText = document.querySelector("#kb-banner-text");
const versionEl = document.querySelector("#app-version");
/* ---------- tiny, safe markdown renderer (no external libs, no CDN) ---------- */
export function escapeHtml(s) {
return s.replace(/[&<>"']/g, (c) => ({
"&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;",
}[c]));
}
export function renderMarkdown(md) {
// 1. Protect fenced code blocks.
const codeBlocks = [];
let text = md.replace(/```(\w*)\n([\s\S]*?)```/g, (_m, _lang, code) => {
codeBlocks.push(`<pre><code>${escapeHtml(code.replace(/\n$/, ""))}</code></pre>`);
return `\u0000CODE${codeBlocks.length - 1}\u0000`;
});
// 2. Escape everything else, then apply inline + block transforms.
text = escapeHtml(text)
.replace(/`([^`\n]+)`/g, "<code>$1</code>")
.replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>")
.replace(/(^|[\s(])\*([^*\n]+)\*/g, "$1<em>$2</em>")
.replace(/^### (.*)$/gm, "<h4>$1</h4>")
.replace(/^## (.*)$/gm, "<h3>$1</h3>")
.replace(/^# (.*)$/gm, "<h3>$1</h3>")
.replace(/^\s*[-*] (.*)$/gm, "<li>$1</li>")
.replace(/(<li>[\s\S]*?<\/li>)(?!\s*<li>)/g, "<ul>$1</ul>")
.replace(/^\d+\. (.*)$/gm, "<li>$1</li>");
// 3. Paragraphs (double newline separated).
text = text
.split(/\n{2,}/)
.map((block) => {
const b = block.trim();
if (!b) return "";
if (/^<(h\d|ul|ol|pre|li)/.test(b)) return b;
return `<p>${b.replace(/\n/g, "<br>")}</p>`;
})
.join("");
// 4. Restore code blocks.
return text.replace(/\u0000CODE(\d+)\u0000/g, (_m, i) => codeBlocks[Number(i)]);
}
/* ---------- messages ---------- */
function addMessage(who, html) {
if (emptyState) emptyState.hidden = true;
const wrap = document.createElement("div");
wrap.className = `msg ${who}`;
wrap.innerHTML = `
<span class="avatar" aria-hidden="true">${who === "brain" ? "🧠" : "🧑"}</span>
<div class="msg-body">
<div class="bubble">${html}</div>
</div>`;
messagesEl.appendChild(wrap);
wrap.scrollIntoView({ behavior: "smooth", block: "end" });
return wrap;
}
function addTyping() {
if (emptyState) emptyState.hidden = true;
const wrap = document.createElement("div");
wrap.className = "msg brain";
wrap.id = "typing-indicator";
wrap.innerHTML = `
<span class="avatar" aria-hidden="true">🧠</span>
<div class="msg-body">
<div class="bubble typing" role="status" aria-label="Brain of Reese is thinking">
<span></span><span></span><span></span>
</div>
</div>`;
messagesEl.appendChild(wrap);
wrap.scrollIntoView({ behavior: "smooth", block: "end" });
}
function removeTyping() {
document.querySelector("#typing-indicator")?.remove();
}
/* ---------- suggestions ---------- */
async function loadSuggestions() {
try {
const r = await fetch("/api/suggestions");
if (!r.ok) return;
const { suggestions } = await r.json();
suggestionsEl.innerHTML = "";
for (const s of suggestions) {
const btn = document.createElement("button");
btn.type = "button";
btn.className = "suggestion-chip";
btn.textContent = s;
btn.setAttribute("role", "listitem");
btn.addEventListener("click", () => {
input.value = s;
input.focus();
});
suggestionsEl.appendChild(btn);
}
} catch {
/* suggestions are progressive enhancement */
}
}
/* ---------- health / version ---------- */
async function loadHealth() {
try {
const r = await fetch("/api/health");
const body = await r.json();
versionEl.textContent = `v${body.version}`;
if (body.db === "down") {
bannerText.textContent =
"Knowledge base is offline — start Postgres with `podman compose up -d db`.";
banner.hidden = false;
}
} catch {
/* API unreachable: page still renders, composer will explain on send */
}
}
/* ---------- composer ---------- */
function setBusy(busy) {
sendBtn.disabled = busy;
sendBtn.querySelector(".spinner").hidden = !busy;
sendLabel.textContent = busy ? "Thinking…" : "Send";
sendStatus.textContent = busy ? "Brain of Reese is working" : "";
}
function autoGrow() {
input.style.height = "auto";
input.style.height = `${Math.min(input.scrollHeight, 192)}px`;
}
async function handleSend(e) {
e.preventDefault();
const text = input.value.trim();
if (!text || sendBtn.disabled) return;
addMessage("user", renderMarkdown(text));
input.value = "";
autoGrow();
setBusy(true);
addTyping();
try {
// TODO(chat-rag phase): replace with POST /api/chat (SSE streaming).
await new Promise((res) => setTimeout(res, 500));
const reply =
"I'm still getting my neurons wired up — the real me ships in the " +
"next phase! Keep the questions coming, you're on a roll. 🚀";
removeTyping();
addMessage("brain", renderMarkdown(reply));
} catch {
removeTyping();
addMessage("brain", "Something went wrong on my side — please try again in a moment.");
} finally {
setBusy(false);
input.focus();
}
}
input.addEventListener("input", autoGrow);
input.addEventListener("keydown", (e) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
composer.requestSubmit();
}
});
composer.addEventListener("submit", handleSend);
loadSuggestions();
loadHealth();
+69
View File
@@ -0,0 +1,69 @@
/* Brain of Reese — Sources page (knowledge base index view).
* Scaffolding-stage: fetches /api/docs (implemented in the import phase);
* until then it renders the empty state.
*/
const tbody = document.querySelector("#docs-tbody");
const emptyEl = document.querySelector("#sources-empty");
const tableWrap = document.querySelector(".table-wrap");
const statDocs = document.querySelector("#stat-docs");
const statChunks = document.querySelector("#stat-chunks");
const statLast = document.querySelector("#stat-last");
function fmtDate(iso) {
try {
return new Date(iso).toLocaleString();
} catch {
return iso;
}
}
async function loadDocs() {
let r;
try {
r = await fetch("/api/docs");
} catch {
showEmpty();
return;
}
if (!r.ok) {
showEmpty();
return;
}
const { documents } = await r.json();
if (!documents.length) {
showEmpty();
return;
}
tbody.innerHTML = "";
let totalChunks = 0;
let last = "";
for (const d of documents) {
totalChunks += d.chunks;
if (d.indexed_at > last) last = d.indexed_at;
const tr = document.createElement("tr");
tr.innerHTML = `
<td>${d.source}</td>
<td title="${d.path}">${d.path}</td>
<td>${d.title}</td>
<td>${d.chunks}</td>
<td>${fmtDate(d.indexed_at)}</td>`;
tbody.appendChild(tr);
}
statDocs.textContent = String(documents.length);
statChunks.textContent = String(totalChunks);
statLast.textContent = last ? fmtDate(last) : "–";
emptyEl.hidden = true;
tableWrap.hidden = false;
}
function showEmpty() {
statDocs.textContent = "0";
statChunks.textContent = "0";
statLast.textContent = "–";
emptyEl.hidden = false;
if (tableWrap) tableWrap.hidden = true;
}
loadDocs();
+460
View File
@@ -0,0 +1,460 @@
/* ==========================================================================
Brain of Reese — design system (no CDN; system fonts only)
========================================================================== */
:root {
/* Palette — all text/background pairs meet WCAG 2.1 AA (>= 4.5:1) */
--bg: #f4f5fb;
--surface: #ffffff;
--ink: #1c2130; /* 14.9:1 on --surface */
--ink-soft: #4a5168; /* 7.6:1 on --surface */
--line: #e3e6f0;
--brand: #4f46e5; /* white on brand: 6.3:1 */
--brand-soft: #eef0fe;
--brand-ink: #3730a3;
--accent-bg: #fff7e8;
--accent-ink: #92400e; /* 8.7:1 on --accent-bg */
--accent-line: #f59e0b;
--ok-ink: #15803d;
--ok-bg: #f0fdf4;
--err-ink: #b91c1c;
--err-bg: #fef2f2;
--err-line: #fecaca;
--radius: 14px;
--radius-sm: 9px;
--shadow: 0 1px 2px rgb(28 33 48 / 0.06), 0 4px 16px rgb(28 33 48 / 0.07);
--shadow-lg: 0 4px 10px rgb(28 33 48 / 0.08), 0 12px 32px rgb(28 33 48 / 0.12);
--font: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
--mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
--header-h: 64px;
}
* { box-sizing: border-box; }
html, body { height: 100%; }
body {
margin: 0;
font-family: var(--font);
font-size: 16px;
line-height: 1.55;
color: var(--ink);
background: var(--bg);
display: flex;
flex-direction: column;
min-height: 100dvh;
}
.container {
width: 100%;
max-width: 72rem;
margin-inline: auto;
padding-inline: 1.25rem;
}
/* ---------- Accessibility helpers ---------- */
.visually-hidden {
position: absolute !important;
width: 1px; height: 1px;
margin: -1px; padding: 0;
overflow: hidden;
clip: rect(0 0 0 0);
white-space: nowrap;
border: 0;
}
.skip-link {
position: absolute;
left: -9999px;
top: 0;
background: var(--brand);
color: #fff;
padding: 0.6rem 1rem;
border-radius: 0 0 var(--radius-sm) 0;
z-index: 100;
}
.skip-link:focus { left: 0; }
:focus-visible {
outline: 3px solid var(--brand);
outline-offset: 2px;
border-radius: 4px;
}
/* ---------- Header ---------- */
.app-header {
height: var(--header-h);
background: var(--surface);
border-bottom: 1px solid var(--line);
position: sticky;
top: 0;
z-index: 20;
}
.header-inner {
height: 100%;
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
}
.brand {
display: inline-flex;
align-items: center;
gap: 0.55rem;
font-size: 1.125rem;
color: var(--ink);
text-decoration: none;
}
.brand-mark { font-size: 1.4rem; }
.brand-text strong { color: var(--brand-ink); font-weight: 700; }
.app-nav { display: flex; gap: 0.25rem; }
.nav-link {
padding: 0.5rem 0.9rem;
border-radius: 999px;
text-decoration: none;
color: var(--ink-soft);
font-weight: 600;
font-size: 0.95rem;
min-height: 44px;
display: inline-flex;
align-items: center;
}
.nav-link:hover { background: var(--brand-soft); color: var(--brand-ink); }
.nav-link.is-active { background: var(--brand); color: #fff; }
/* ---------- Main frame ---------- */
.app-main {
flex: 1;
display: flex;
flex-direction: column;
padding-block: 1.25rem;
}
/* Chat is a vertical conversation: a centered, capped column is the
correct layout here (PLAN §UI/UX). The surrounding frame keeps it
from collapsing into a hairline on wide screens. */
.chat-shell {
max-width: 46rem;
margin-inline: auto;
display: flex;
flex-direction: column;
gap: 1rem;
flex: 1;
}
.messages {
display: flex;
flex-direction: column;
gap: 0.9rem;
min-height: 200px;
}
/* ---------- Messages ---------- */
.msg { display: flex; gap: 0.6rem; max-width: 100%; }
.msg .avatar {
flex: 0 0 auto;
width: 34px; height: 34px;
border-radius: 50%;
display: grid;
place-items: center;
font-size: 1.05rem;
background: var(--brand-soft);
border: 1px solid var(--line);
}
.msg-body {
max-width: 85%;
display: flex;
flex-direction: column;
gap: 0.35rem;
}
.bubble {
padding: 0.7rem 1rem;
border-radius: var(--radius);
background: var(--surface);
border: 1px solid var(--line);
box-shadow: var(--shadow);
overflow-wrap: anywhere;
}
.bubble p { margin: 0.2rem 0; }
.bubble pre {
background: #10131c;
color: #e6e9f2;
padding: 0.7rem 0.9rem;
border-radius: var(--radius-sm);
overflow-x: auto;
font-size: 0.85rem;
font-family: var(--mono);
}
.bubble code { font-family: var(--mono); font-size: 0.88em; background: var(--brand-soft); padding: 0.08em 0.35em; border-radius: 5px; }
.bubble pre code { background: none; padding: 0; }
.msg.user { justify-content: flex-end; }
.msg.user .msg-body { align-items: flex-end; }
.msg.user .bubble {
background: var(--brand);
border-color: var(--brand);
color: #fff;
border-bottom-right-radius: 4px;
}
.msg.user .bubble code { background: rgb(255 255 255 / 0.18); }
.msg.brain .bubble { border-bottom-left-radius: 4px; }
.msg.brain.is-deflected .bubble {
background: var(--accent-bg);
border-color: var(--accent-line);
}
.msg-meta {
font-size: 0.75rem;
color: var(--ink-soft);
padding-inline: 0.25rem;
display: flex;
flex-wrap: wrap;
gap: 0.35rem;
align-items: center;
}
.source-chip {
display: inline-flex;
align-items: center;
gap: 0.3rem;
font-family: var(--mono);
font-size: 0.72rem;
background: var(--brand-soft);
color: var(--brand-ink);
border: 1px solid var(--line);
border-radius: 999px;
padding: 0.15rem 0.6rem;
text-decoration: none;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.source-chip:hover { background: #e2e5fd; }
/* typing indicator */
.typing { display: inline-flex; gap: 5px; padding: 0.9rem 1rem; }
.typing span {
width: 8px; height: 8px;
border-radius: 50%;
background: var(--ink-soft);
opacity: 0.5;
animation: typing 1.2s infinite ease-in-out;
}
.typing span:nth-child(2) { animation-delay: 0.15s; }
.typing span:nth-child(3) { animation-delay: 0.3s; }
@keyframes typing {
0%, 60%, 100% { transform: translateY(0); opacity: 0.4; }
30% { transform: translateY(-5px); opacity: 1; }
}
@media (prefers-reduced-motion: reduce) {
.typing span { animation: none; opacity: 0.7; }
}
/* ---------- Empty state & suggestions ---------- */
.empty-state {
background: var(--surface);
border: 1px solid var(--line);
border-radius: var(--radius);
box-shadow: var(--shadow);
padding: 2.5rem 1.75rem;
text-align: center;
margin-top: 1rem;
}
.empty-state-emoji { font-size: 2.6rem; line-height: 1; }
.empty-state-title { margin: 0.8rem 0 0.4rem; font-size: 1.5rem; color: var(--ink); }
.empty-state-sub { margin: 0 auto 1.25rem; max-width: 34rem; color: var(--ink-soft); }
.empty-state-sub code { font-family: var(--mono); font-size: 0.85em; background: var(--brand-soft); padding: 0.1em 0.35em; border-radius: 5px; }
.suggestions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
justify-content: center;
list-style: none;
margin: 0;
padding: 0;
}
.suggestion-chip {
font: inherit;
font-size: 0.92rem;
font-weight: 600;
color: var(--brand-ink);
background: var(--brand-soft);
border: 1px solid var(--line);
border-radius: 999px;
padding: 0.55rem 1rem;
min-height: 44px;
cursor: pointer;
transition: background 0.15s ease, transform 0.05s ease;
}
.suggestion-chip:hover { background: #e2e5fd; }
.suggestion-chip:active { transform: scale(0.98); }
/* ---------- Composer ---------- */
.composer {
display: flex;
align-items: flex-end;
gap: 0.6rem;
background: var(--surface);
border: 1px solid var(--line);
border-radius: var(--radius);
box-shadow: var(--shadow);
padding: 0.6rem;
}
.composer:focus-within { border-color: var(--brand); box-shadow: 0 0 0 3px var(--brand-soft), var(--shadow); }
.composer textarea {
flex: 1;
font: inherit;
color: var(--ink);
border: 0;
resize: none;
max-height: 12rem;
padding: 0.55rem 0.5rem;
background: transparent;
}
.composer textarea:focus { outline: none; }
.send-btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.45rem;
min-width: 84px;
min-height: 44px;
border: 0;
border-radius: var(--radius-sm);
background: var(--brand);
color: #fff;
font: inherit;
font-weight: 700;
cursor: pointer;
padding-inline: 1rem;
}
.send-btn:hover:not(:disabled) { background: #4338ca; }
.send-btn:disabled { background: #a5b4fc; cursor: not-allowed; }
.spinner {
width: 16px; height: 16px;
border: 2.5px solid rgb(255 255 255 / 0.4);
border-top-color: #fff;
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
@keyframes spin { to { transform: rotate(360deg); } }
@media (prefers-reduced-motion: reduce) {
.spinner { animation-duration: 2s; }
}
/* ---------- Banners ---------- */
.kb-banner {
display: flex;
align-items: center;
gap: 0.5rem;
background: var(--accent-bg);
color: var(--accent-ink);
border: 1px solid var(--accent-line);
border-radius: var(--radius-sm);
padding: 0.6rem 0.9rem;
font-size: 0.92rem;
font-weight: 600;
}
.kb-banner.is-error { background: var(--err-bg); color: var(--err-ink); border-color: var(--err-line); }
/* ---------- Sources page ---------- */
.sources-shell {
display: flex;
flex-direction: column;
gap: 1.25rem;
flex: 1;
}
.page-head h1 { margin: 0 0 0.25rem; font-size: 1.7rem; }
.page-sub { margin: 0; color: var(--ink-soft); }
.page-sub code { font-family: var(--mono); font-size: 0.85em; background: var(--brand-soft); padding: 0.1em 0.35em; border-radius: 5px; }
.stat-cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(170px, 1fr));
gap: 0.9rem;
}
.stat-card {
background: var(--surface);
border: 1px solid var(--line);
border-radius: var(--radius);
box-shadow: var(--shadow);
padding: 1.1rem 1.25rem;
display: flex;
flex-direction: column;
gap: 0.15rem;
}
.stat-value { font-size: 2rem; font-weight: 800; color: var(--brand-ink); line-height: 1.1; }
.stat-value-sm { font-size: 1.15rem; font-weight: 700; }
.stat-label { color: var(--ink-soft); font-size: 0.88rem; font-weight: 600; }
.table-wrap {
background: var(--surface);
border: 1px solid var(--line);
border-radius: var(--radius);
box-shadow: var(--shadow);
overflow-x: auto;
}
.docs-table {
width: 100%;
border-collapse: collapse;
min-width: 640px;
font-size: 0.93rem;
}
.docs-table th, .docs-table td {
text-align: left;
padding: 0.7rem 1rem;
border-bottom: 1px solid var(--line);
white-space: nowrap;
}
.docs-table th {
background: var(--brand-soft);
color: var(--brand-ink);
font-size: 0.82rem;
text-transform: uppercase;
letter-spacing: 0.04em;
position: sticky;
top: 0;
}
.docs-table td:nth-child(2) { font-family: var(--mono); font-size: 0.82rem; max-width: 30rem; overflow: hidden; text-overflow: ellipsis; }
.docs-table tbody tr:hover { background: var(--bg); }
.docs-table tbody tr:last-child td { border-bottom: 0; }
/* ---------- Footer ---------- */
.app-footer {
border-top: 1px solid var(--line);
background: var(--surface);
padding-block: 0.8rem;
margin-top: 1rem;
}
.footer-inner {
display: flex;
justify-content: space-between;
gap: 1rem;
color: var(--ink-soft);
font-size: 0.85rem;
}
/* ---------- Responsive (mobile-first adjustments) ---------- */
@media (max-width: 640px) {
:root { --header-h: 58px; }
.container { padding-inline: 0.9rem; }
.brand-text { font-size: 1rem; }
.nav-link { padding: 0.45rem 0.7rem; font-size: 0.9rem; }
.msg-body { max-width: 92%; }
.empty-state { padding: 1.75rem 1.1rem; margin-top: 0.25rem; }
.empty-state-title { font-size: 1.25rem; }
.suggestions { flex-wrap: nowrap; overflow-x: auto; justify-content: flex-start;
padding-bottom: 0.4rem; -webkit-overflow-scrolling: touch; scrollbar-width: thin; }
.suggestion-chip { flex: 0 0 auto; }
.composer { padding: 0.5rem; }
.footer-inner { flex-direction: column; gap: 0.2rem; text-align: center; }
main { padding-bottom: env(safe-area-inset-bottom, 0); }
}