diff --git a/.claude/skills/create-verification-skill/SKILL.md b/.claude/skills/create-verification-skill/SKILL.md new file mode 100644 index 0000000..f5bb5c8 --- /dev/null +++ b/.claude/skills/create-verification-skill/SKILL.md @@ -0,0 +1,46 @@ +--- +name: create-verification-skill +description: "Generate a project-local verification skill that drives your app the way a user does — any language, framework, or platform. Use for /create-verification-skill, \"make a control skill for this repo\", or when a project has no scripted way to prove UI/CLI/service behavior." +disable-model-invocation: true +--- + +# Create a verification skill + +Every serious project needs a scripted way to drive the real app and prove behavior: launch it, exercise a feature the way a user would, and capture evidence. This skill generates that as a project-local skill (`.claude/skills/verify-/`) tailored to the repo. You write the generator's output for the next agent, not for a human: it will be read cold, mid-task, by an agent that has never seen the app. + +In this repo the generated skill already exists: `.claude/skills/verify-root/`. Prefer `/maintain-verification-skill` over regenerating it. + +## 1. Interview the repo, not the user + +Answer these from the codebase and only ask the user what you cannot observe: + +- **Surface:** what does a user actually touch? A web UI, a CLI/TUI, a desktop app, an API, a mobile app, a library? A repo can have several; pick the primary one and note the rest. +- **Run:** how does the app start locally? Prefer the repo's own documented dev command (package scripts, Makefile, README quickstart). Note ports, env vars, seed data, auth. +- **Drive:** how can an agent interact with it programmatically? Existing harnesses first — Playwright/Cypress specs, expect scripts, PTY helpers, curl-able endpoints, a debug port. Only then pick a generic recipe: browser/CDP for web and Electron, a tmux/PTY harness for CLI/TUI, plain HTTP for services. +- **Observe:** what evidence can be captured? Screenshots, terminal transcripts, response bodies, logs, exit codes, DB state. +- **Isolate:** can two instances run side by side (ports, data dirs, profiles)? If not, say so in the generated skill: refusing to double-drive a shared instance beats corrupting the user's session. + +If the checkout doesn't build or start as-is, fix that first (or report it precisely) before generating; a skill written against a broken base teaches wrong steps. When an irrelevant missing asset blocks startup (a static dir the API never serves, a sample config), the generated skill may create it, clearly marked as verification scaffolding, and remove it in cleanup. + +## 2. Generate the skill + +Write `.claude/skills/verify-/SKILL.md` with YAML frontmatter (`name: verify-` and a `description` that names the app, the surface, and when to reach for it — without frontmatter the skill never registers) and these sections, each grounded in what the interview actually found (no placeholders left): + +- **Launch:** the exact command that starts the app for verification, and how to tell it's ready (a log line, a port answering, a prompt). Include teardown. For a short-lived CLI or TUI there is no server to keep alive: launch means build the binary (or install deps) once, then start each drive in its own isolated PTY or tmux session. +- **Doctor:** one read-only check that answers "is this instance worth driving?" — process up, right version/build, port owned by us, auth valid. An agent runs this first whenever anything looks off. +- **Drive:** the harness recipe with real selectors/commands from this repo, not examples. Prefer stable handles (ARIA labels, data attributes, prompt strings, route paths) over coordinates and tab order. +- **Evidence:** what to capture for a proof and where it goes. State the proof standards: exercise the real user path, not internal setters or test-only endpoints; capture the action and the resulting state, not just the final screen; verify side effects (files written, rows inserted, messages sent) alongside what's visible; mocks only where a production boundary already isolates the external system. When the safe path is a dry-run or test mode, verify what it actually skips by observing (files, network, git refs) rather than trusting its name: some dry-runs still touch the network or open a browser. +- **Cleanup:** how to tear down instances the run created. Never kill by process name; kill what you started. Cleanup removes instances and scratch state, never the evidence: proof artifacts survive the teardown, in a location the skill names. +- **Helpers:** any script the skill ships is executable and its invocation is shown in the skill body. A helper the reader has to reverse-engineer is not a helper. + +## 3. Seed the feature map + +Create `.claude/skills/verify-/features/README.md` plus one file per user-facing feature you can identify (aim for the top 3-5 to start, from routes, commands, menus, or docs). Follow the shape in [`references/feature-map-example/`](references/feature-map-example/), with a README index and one file per feature. Each file answers, from the user's point of view: what the feature is, how to reach it, how to drive it with the harness, and what observable end state proves it works. The four H2s are `Sub-features`, `How to get to it (user POV)`, `Driving it with `, and `Gotchas`. The map is the repo's maintained verification source; a proof that drives one convenient entry point is incomplete when the map lists others. + +## 4. Prove the generated skill before handing it over + +Run its own instructions end to end once: launch, doctor, drive ONE mapped feature (one is enough; the map exists so later runs can cover the rest), capture evidence, clean up. After cleanup, confirm the evidence still exists at the named location — a cleanup that eats the proof fails this step. Fix what fails, and run the generated cleanup after every failed iteration too, so broken attempts don't strand processes and ports. A generated skill that was never executed is a draft, not a deliverable. + +## 5. Offer the maintenance loop + +Point the user at `/maintain-verification-skill` for keeping the map honest as the app changes. Suggest a cadence only if they ask. diff --git a/.claude/skills/create-verification-skill/references/feature-map-example/README.md b/.claude/skills/create-verification-skill/references/feature-map-example/README.md new file mode 100644 index 0000000..c0e2b98 --- /dev/null +++ b/.claude/skills/create-verification-skill/references/feature-map-example/README.md @@ -0,0 +1,9 @@ +# feature map + +This is the index of user-facing features and how to prove each one works. It has one file per feature, and each file uses the same four H2s. + +| Feature | File | Scenario / command | Last live result | +|---|---|---|---| +| Create a project | [create-project.md](create-project.md) | `node run.mjs create-project` | pass | + +Surfaces not mapped yet: . diff --git a/.claude/skills/create-verification-skill/references/feature-map-example/create-project.md b/.claude/skills/create-verification-skill/references/feature-map-example/create-project.md new file mode 100644 index 0000000..a355dfc --- /dev/null +++ b/.claude/skills/create-verification-skill/references/feature-map-example/create-project.md @@ -0,0 +1,29 @@ +# Create a project + +The user creates a named project from the dashboard, and it appears in their project list. + +## Sub-features + +- New Project dialog (name, optional description, visibility). +- Project list with search and sort. +- Project detail page `/projects/$id`. + +## How to get to it (user POV) + +Sidebar **Projects** → **New Project** (top right), or the empty-state button **Create your first project**. + +## Driving it with Playwright + +1. `/projects` → `getByRole("button", { name: "New Project" })`. +2. In `getByRole("dialog", { name: "New Project" })`: fill `textbox "Name"` with a unique name, then click `button "Create"`. +3. Wait for the dialog to close, then for `getByText(name)` in the list. + +**Proof:** +- the list shows the name (screenshot before and after) +- `/projects/$id` renders it +- `select name from projects where name = ''` returns one row + +## Gotchas + +- Two buttons named "New Project" exist when the list is empty. Use `.first()` or scope to the header. +- Names must be unique per instance. Suffix them with `Date.now()`. diff --git a/.claude/skills/maintain-verification-skill/SKILL.md b/.claude/skills/maintain-verification-skill/SKILL.md new file mode 100644 index 0000000..f68af99 --- /dev/null +++ b/.claude/skills/maintain-verification-skill/SKILL.md @@ -0,0 +1,41 @@ +--- +name: maintain-verification-skill +description: "Periodic pass that keeps a project's verification skill and feature map honest: parallel source readers per feature, one live session driving every feature, at most one PR of proven corrections. Use for /maintain-verification-skill or \"audit the verify skill\"." +disable-model-invocation: true +--- + +# Maintain a verification skill + +A feature map rots the moment the app changes. This skill is the upkeep loop for a skill generated by `/create-verification-skill` (or any project-local verification skill with a feature map). The unit of rigor is the feature, not every sentence: cover every feature file from source and exercise every feature live, without terminalising every bullet. + +In this repo the target is `.claude/skills/verify-root/`. + +## Outcomes + +Pick one, and say which: + +- **clean** — every feature got source and live coverage; nothing worth shipping. No branch, no PR. +- **changed** — one PR ships proven doc, harness, or map corrections. +- **blocked** — coverage could not finish or a proven fix could not ship safely. Say exactly what blocked it. + +## Edit scope + +Only edit the verification skill's own directory (its SKILL.md, features/, and any harness scripts it owns). Never edit product code during a run: a behavior the map describes that the app no longer does is either doc drift (fix the map) or a product regression (report it, don't paper over it in docs). + +## Pass + +0. **Locate the target.** Find the verification skill to maintain: the project-local skill whose body has launch/drive sections and a feature map (usually `.claude/skills/verify-*/`). Several candidates → ask which one; none → stop and point at `/create-verification-skill` instead of inventing a target. + +1. **Index hygiene.** Read the feature map README and glob its sibling files. Fix missing, extra, duplicate, or dead entries. Lightweight; no generated inventory. + +2. **Source wave.** One read-only subagent per feature file, launched concurrently. Each explains "how does this user-facing feature work?" from source, flags likely doc drift with citations, and returns one concise live-verification recipe. Children never drive the app and never edit files. Return shape: feature summary / source entry points / likely drift or none / one recipe. + +3. **Reconcile.** Every feature file has a returned summary. Merge overlapping recipes into as few app states as practical. Spot-check cited drift; don't re-prove clean claims. Sweep recent churn for user-facing surfaces missing from the map — require a concrete source path before calling one missing. + +4. **Live pass.** Required even when source looks clean. The coordinator owns all driving; follow the verification skill's own launch model — one long-lived instance driven serially for servers and UIs, or a fresh isolated session per drive for short-lived CLIs (the skill's Launch section decides, not this one). Exercise every feature at least once, and hold three invariants the whole pass, whatever the failure: (1) never drive an instance you haven't health-checked since it last did something surprising — doctor before first drive, doctor on each fresh session where sessions are the unit, doctor again after any failed drive, and where doctor can't see the failure (a wedged UI state on a healthy process), reset to a known state or relaunch rather than hoping; (2) evidence captured so far survives every cleanup, checked at its named location, not assumed; (3) nothing a drive started outlives that drive's usefulness — failed-iteration residue is cleaned whether the session is stuck, exited, or shared (for a shared instance, clean the residue, not the instance). A doctor failure caused by skill drift is drift: fix it under edit scope and retry once — restart whatever the fix invalidated, nothing more — before calling the pass `blocked`. A feature that can't be reached is `verified-unreachable` only with the concrete prerequisite (auth, entitlement, OS, external state) and the route attempted; if the map omits that prerequisite, that's drift. Any harness fix from triage gets re-driven live before it ships. Final teardown happens after the last drive of the run — including those re-proofs — so nothing outlives the run (evidence stays, per the skill). + +5. **Triage.** Wrong or missing user-POV description → doc drift, fix it. Working behavior the harness can't drive → harness gap, fix it; a harness fix follows the same helpers rule as generation (scripts executable, invocation documented in the skill body). App behavior that's actually broken → product gap; record it for the user, keep it out of this PR. + +6. **Ship or stop.** For changed: one PR of proven corrections, re-read every changed file first. For clean or blocked: no PR, report the outcome and the coverage honestly. + +Keep concise run notes (features covered, unreachable prerequisites, confirmed drift, outcome) in a scratch location; don't commit them. diff --git a/.claude/skills/verify-root/SKILL.md b/.claude/skills/verify-root/SKILL.md new file mode 100644 index 0000000..4610f62 --- /dev/null +++ b/.claude/skills/verify-root/SKILL.md @@ -0,0 +1,152 @@ +--- +name: verify-root +description: Launch the Root web app (Vite SPA + auth-server + FastAPI + local Postgres) fully locally with stubbed AI/R2, drive it in a real browser with Playwright as a logged-in user, and capture proof (screenshots, video, DB rows, provider call logs). Use to prove a UI/API change works, to record before/after evidence for a PR, or whenever you need to see the app running. No Doppler, Neon, real R2 or AI keys needed. +--- + +# verify-root + +Drives the Root web app the way a user does and writes evidence to disk. Everything runs in this checkout. The container gets a local Postgres; fast-api, auth-server and Vite run on the host. External providers are replaced at their HTTP boundary: + +| Real | Stand-in | How | +|---|---|---| +| Neon Postgres | `paradedb/paradedb:0.20.5` container (same image as CI) | fresh DB per `up.sh`, removed by `down.sh` | +| Cloudflare R2 | moto S3 server, bucket `root-verify`, via the real `R2Client` (so presigned URLs work in the browser) | `OBJECT_STORE_PROVIDER=r2` + `R2_ENDPOINT_URL` | +| Voyage embed/rerank | `scripts/fake_providers.py` (hashed bag-of-words vectors, 1024-d) | `EMBEDDING_BASE_URL` | +| All LLMs (Gemini, OpenAI, Anthropic), default | in-process `FakeLLMClient` (`fast-api/app/providers/llm.py`): answers `[fake-llm] ...`, calls the real search tool once, fills structured outputs (follow-ups, sectioning, voice match) | `LLM_PROVIDER=fake` | +| Gemini, with `VERIFY_LLM=http` | the live Jetflow Gemini client → `fake_providers.py`: `[stub-llm] ...` text, plus forced function calls for follow-ups and sectioning | `GOOGLE_GEMINI_BASE_URL` | +| AssemblyAI, YouTube, ElevenLabs, Resend, Turnstile | **not stubbed** (keys blank) | features using them are unreachable | + +**Safety.** Services start with `env -i` plus an explicit variable list, so nothing leaks in from your shell or Doppler (`DATABASE_URL`, `LOGFIRE_TOKEN`, real keys). FastAPI runs from an isolated working directory so it cannot read the checkout’s `.env`; Bun starts with `--no-env-file` for both migrations and auth. The scripts refuse any `DATABASE_URL` that isn't `127.0.0.1` or `localhost`. + +Paths below are relative to the repo root. `S=.claude/skills/verify-root`. + +## Launch + +```bash +$S/scripts/up.sh # ~25s warm; first run also installs deps and pulls images +``` + +- **Ready when:** it prints the state file path (`.verify/run/i0/state.env`) and `up: http://localhost:13000`. +- **Order:** postgres → auth migrations (`bun run db:migrate`) → app migrations (golang-migrate docker image, like CI) → fakes → auth-server → fast-api → Vite → seed user. +- **Seeded user:** `verify@example.com` / `verify-password-123`, with role `admin`. It is created through the real `/api/auth/sign-up/email` endpoint. +- **Ports for instance `i0`:** + + | Service | Port | + |---|---| + | web (Vite, same-origin proxy like nginx) | 13000 | + | fast-api | 18081 | + | auth-server | 18082 | + | fakes | 18090 | + | S3 | 19000 | + | Postgres | 55432 | + +- **More instances:** `VERIFY_PORT_OFFSET=N` adds `N*10` to every port, giving instance `iN`. +- **Other source tree:** `VERIFY_APP_ROOT=` runs the app from another checkout (a worktree); `compare.sh` uses this. +- **Prerequisites:** Docker, Bun (with `--no-env-file` support), uv/uvx, pnpm, Python 3, and curl. Linux and macOS Bash 3.2 are supported; Python creates process groups, and the migration container shares the Postgres container’s network (no host networking needed). +- **Docker:** in a cloud container `up.sh` starts `dockerd` itself when no daemon is running (root only). +- **Rerunning:** if the instance is already healthy, `up.sh` exits 0. If it is stale, `up.sh` tells you to run `down.sh` first. +- **LLM mode:** `VERIFY_LLM=fake` (the default) covers every model in-process. `VERIFY_LLM=http` exercises the real Gemini SDK over HTTP instead, which is useful when a change touches Jetflow or client wiring. Switching modes requires `down.sh` first, and `up.sh` refuses to reuse an instance started in the other mode. +- **Code changes:** fast-api runs without `--reload`. After changing backend code, run `down.sh` then `up.sh`. Vite picks up frontend changes live. + +## Doctor + +```bash +$S/scripts/doctor.sh # read-only; exit 0 = worth driving +``` + +It checks: +- the database is local and the schema is migrated (not dirty) +- every recorded pid is alive +- each service answers on its own health endpoint +- `/rag-api` works through the web proxy +- the seeded user can sign in + +It also prints the git sha the instance was started from. When that sha differs from the current checkout, the instance is running stale code. Run doctor before the first drive and after any failed or surprising drive. + +## Drive + +Playwright (Chromium) from `$S/harness`. The harness finds the global `playwright` package, which is preinstalled in cloud containers. Elsewhere, install it once with `npm install --prefix $S/harness playwright-core`. + +```bash +cd $S/harness +node run.mjs library-add-source # one feature scenario → evidence dir (JSON on stdout) +node run.mjs quote-embed-ask --no-video +EXPLORE_ROUTES="/,/library,/ask" node run.mjs _explore --no-video # screenshots + ARIA snapshot (aria.yml) for finding selectors +VERIFY_PORT_OFFSET=1 node run.mjs # drive another instance +``` + +- **Scenarios** live in `harness/scenarios/.mjs`. Each one exports `default async ({ page, shot, sql, state, expect }) => result`: + - `page` is already logged in, with `baseURL` set. + - `shot(name)` waits for network idle, then takes a full-page screenshot. + - `sql(q)` returns `psql -tA` output from the instance's DB. + - `expect(cond, msg)` throws on failure. +- **One-off checks:** write an ad-hoc scenario anywhere and pass its path: `node run.mjs /tmp/x.mjs`. +- **Selectors:** use roles and accessible names first (`getByRole("button", { name: "Add Source" })`, `getByRole("dialog", { name: "Add Citation" })`, `getByRole("textbox", { name: "Title *" })`). Use `input#email` / `input#password` on `/login`. Don't rely on coordinates or nth-child. When a name is unknown, run `_explore` and read `aria.yml`. +- **Helpers for evidence outside the browser:** + - `$S/scripts/db.sh ""` runs psql against the instance. + - `.verify/run/i0/fake-providers.jsonl` logs one line per call to the HTTP fakes (Voyage, and Gemini in `http` mode). Each run also copies its own lines into `provider-calls.jsonl` in the evidence dir. + - `.verify/run/i0/*.log` holds each service's logs. +- **API calls without the UI:** sign in with `POST /api/auth/sign-in/email` (cookie jar, `Origin: http://localhost:13000`). Then `GET /api/auth/token` returns a JWT; send it as `Authorization: Bearer ` to `/rag-api/*` on port 13000. + +Feature-by-feature recipes are in [features/README.md](features/README.md). + +## Evidence + +Each run writes to `.verify/evidence/-/`: +- numbered `NN-.png` screenshots +- `video.webm` of the whole session +- `events.json`: every `/rag-api` and `/api/auth` response status, plus console errors and page errors +- `provider-calls.jsonl`: the HTTP-fake provider calls this run made (embeds, reranks, Gemini calls, forced function calls) +- `result.json`: `ok`, `git_head`, and whatever the scenario returned (ids, urls), or the error plus a `failure.png` + +`.verify/` is gitignored and `down.sh` never deletes evidence. + +**Before/after for a PR:** + +```bash +$S/scripts/compare.sh origin/main # ~1 min; prints the compare dir +``` + +- The base ref runs from a temporary worktree as instance `i1`. Head is this checkout as `i0`. +- It writes `compare.html`: both videos, both results, and screenshot pairs side by side. +- The base instance and worktree are removed afterwards unless you pass `--keep`. +- Base refs from before `EMBEDDING_BASE_URL` existed (before this skill landed) can't stub Voyage. Compare on UI-only scenarios there. + +**Proof standards:** +- Drive the real user path (dialogs, buttons, routes), not internal setters or seeded shortcuts. Seeding is for preconditions only. +- Capture the action and the resulting state (a before shot, the filled form, the after state), not just the final screen. +- Check side effects next to what's visible: DB rows via `sql()`, provider calls in `fake-providers.jsonl`, objects in S3 (`curl http://127.0.0.1:19000/root-verify`). +- Stubs replace only the external provider boundary. Everything from the SDK call inward is real app code. A `[fake-llm]` or `[stub-llm]` answer proves the pipeline end to end. It says nothing about answer quality. + +## Cleanup + +```bash +$S/scripts/down.sh # instance i0 +VERIFY_PORT_OFFSET=1 $S/scripts/down.sh # instance i1 +``` + +- `down.sh` kills only the process groups recorded in `.verify/run/iN/*.pid`, never by process name. +- It removes that instance's Postgres container and its run dir. +- Evidence in `.verify/evidence/` stays. +- Run it after every failed `up.sh` too, so broken attempts don't strand ports. + +## Helpers + +All of these are executable and live in `$S/scripts` unless noted. + +| Helper | Invocation | +|---|---| +| launch | `up.sh` | +| health | `doctor.sh` | +| teardown | `down.sh` | +| SQL | `db.sh ""` | +| before/after | `compare.sh [--keep]` | +| fakes (started by `up.sh`) | `fake_providers.py ` | +| drive | `harness/run.mjs [--no-video]` | + +## Gotchas + +- **Ask/agents:** `tiktoken` tries to download its encoding from `openaipublic.blob.core.windows.net`, which the cloud proxy blocks. Ask still completes. Ignore the proxy warning. +- **Stub limits:** the fakes have no judgement. Structured outputs are canned (one 0–60s section; voice matches are always `uncertain`), and a flow with no scripted responder fails loudly with `FakeLLMError: ... no responder for `. Add responders in `fast-api/app/providers/llm.py` (`DEFAULT_RESPONDERS`). In `http` mode only Gemini is stubbed, so other models fail. +- **State accumulates on `i0`:** every scenario creates its own uniquely named data, but lists grow. For a clean slate, run `down.sh && up.sh`. In `compare.sh` the base is always fresh while head may not be. +- **Not portable yet:** `setsid` and `/proc` make the scripts Linux-first. They target the cloud container. On macOS, use `docker-compose.local.yml` for now. diff --git a/.claude/skills/verify-root/features/README.md b/.claude/skills/verify-root/features/README.md new file mode 100644 index 0000000..7d757f4 --- /dev/null +++ b/.claude/skills/verify-root/features/README.md @@ -0,0 +1,25 @@ +# verify-root feature map + +These are the user-facing features of the Root web app and how to prove each one works with the verify-root harness. Each file has four sections: **Sub-features**, **How to get to it (user POV)**, **Driving it with Playwright**, and **Gotchas**. + +| Feature | File | Scenario | Last live result | +|---|---|---|---| +| Library & sources | [library-sources.md](library-sources.md) | `library-add-source` | pass | +| Highlights → embeddings | [highlights-embeddings.md](highlights-embeddings.md) | `quote-embed-ask` (first half) | pass (was failing before the `get_db` scope fix) | +| Ask (RAG chat) | [ask.md](ask.md) | `quote-embed-ask` (second half) | pass (fake LLM; real search tool) | +| Reflect + follow-ups | [reflect.md](reflect.md) | `reflect-followups` | pass in both LLM modes (chips were silently empty before the fix) | +| PDF sources | [pdf.md](pdf.md) | `pdf-upload` | pass (viewer never showed uploads before the fix) | +| Notes | [notes.md](notes.md) | none yet (recipe in file) | reached: editor opens, row created | +| Auth & admin | [auth-admin.md](auth-admin.md) | covered by every scenario's login; admin recipe in file | pass | + +These features aren't mapped yet, so add a file when you touch one: +- collections (`/library/collections`) +- takeaways (`/library/$id/takeaways`) +- transcripts, podcasts and videos (these need AssemblyAI or YouTube, which aren't stubbed) +- graph (`/graph`) +- suggestions (`/suggestions`) +- command palette +- voice (ElevenLabs, not stubbed) +- profile + +A proof that only drives one convenient entry point is incomplete when a file here lists others. diff --git a/.claude/skills/verify-root/features/ask.md b/.claude/skills/verify-root/features/ask.md new file mode 100644 index 0000000..e690085 --- /dev/null +++ b/.claude/skills/verify-root/features/ask.md @@ -0,0 +1,34 @@ +# Ask (RAG chat) + +Ask is chat over the user's own knowledge base. A Jetflow agent searches the user's citations and notes (hybrid vector + BM25), then answers with the selected model. Answers stream back over SSE. + +## Sub-features + +- Question box `Ask anything...`, send with Enter or the send button. +- `Dictate question` (voice; not stubbed). +- Model picker, default `Gemini 3.6 Flash`, and a reasoning picker (`Reasoning: Medium`). +- `Clear Chat`. +- Follow-up questions; answers show citations when search returns hits. + +## How to get to it (user POV) + +Sidebar **Ask** → `/ask`. + +## Driving it with Playwright + +Scenario: `node run.mjs quote-embed-ask`, second half. + +1. `/ask`: fill `textbox "Ask anything..."` and press Enter. +2. Wait for `[fake-llm] Stubbed answer`. The fake LLM first calls the real `search` tool (you'll see "Searching for …" and "Found N result(s)"), then answers `… Tool results: 1 …`. With `VERIFY_LLM=http` the answer is `[stub-llm] …` instead, and no tool is called. + +**Proof:** +- the answer is rendered under the question +- in `http` mode, `provider-calls.jsonl` has `"provider": "gemini"` lines +- `events.json` shows the `/rag-api/ask...` calls returning 2xx +- in `fake` mode, `provider-calls.jsonl` shows the search's `"input_type": "query"` embed and a `rerank` + +## Gotchas + +- In `fake` mode every model in the picker works (the answer names the model). In `http` mode only Gemini does. +- The fake LLM calls `search` exactly once, with your question verbatim, then answers. Other tools never run, and retrieval quality can't be judged here: the vectors are bag-of-words. +- The `tiktoken` download from `openaipublic.blob.core.windows.net` is blocked by the cloud proxy. The answer still completes. diff --git a/.claude/skills/verify-root/features/auth-admin.md b/.claude/skills/verify-root/features/auth-admin.md new file mode 100644 index 0000000..0e0bfa6 --- /dev/null +++ b/.claude/skills/verify-root/features/auth-admin.md @@ -0,0 +1,34 @@ +# Auth & admin + +Email/password auth runs through Better-Auth in auth-server. FastAPI validates the JWT from the auth-server's JWKS endpoint. Admins get an Admin section for user management. + +## Sub-features + +- `/login` (`input#email`, `input#password`, submit), `/signup`, `/forgot-password`, `/reset-password`. +- Session cookie, plus a JWT from `GET /api/auth/token` that is sent to `/rag-api/*`. +- Admin (role `admin` only): + - `/admin` overview + - `/admin/users` (`Manage Users`, `Create User`, user cards) + - `/admin/users/$id` + +## How to get to it (user POV) + +Logged out: any route redirects to `/login`. Logged in as an admin: the sidebar shows an **Admin** group with **Overview** and **Users**. + +## Driving it with Playwright + +- **Login:** every scenario already logs in through `/login` (`harness/lib.mjs`). Waiting for the URL to leave `/login` proves it worked. +- **Admin:** go to `/admin/users` and check that `heading "Manage Users"` and a card link containing `verify@example.com` and `Role: admin` are visible. +- **Signup:** run a session with `login: false` (`session({ login: false })` in `lib.mjs`), go to `/signup`, and use a fresh email. + +**Proof for signup:** + +```sql +select email, role from auth."user" where email = '' +``` + +## Gotchas + +- Turnstile captcha is off locally: auth-server only enables it when `APP_ENV != local` and a secret is set. +- Email (Resend) isn't configured, so forgot-password and reset-password can't deliver mail. They count as `verified-unreachable` until an email sink is added. +- The seeded user becomes admin through a direct `update auth."user"` in `up.sh`. That is a precondition, not something under test. diff --git a/.claude/skills/verify-root/features/highlights-embeddings.md b/.claude/skills/verify-root/features/highlights-embeddings.md new file mode 100644 index 0000000..527b917 --- /dev/null +++ b/.claude/skills/verify-root/features/highlights-embeddings.md @@ -0,0 +1,37 @@ +# Highlights → embeddings + +Highlights are what the user captures from a source: quotes (citations) and comments/thoughts (captures). Saving one triggers a background task that embeds it with Voyage and writes to `rag_embeddings`. Ask and search depend on those embeddings. + +## Sub-features + +- **Quote:** the `Add Citation` dialog with Quote/Paraphrase, `Text *`, speaker, context, pages, and inline "Thoughts" (captures). +- **Comment:** a capture on the source. +- **Highlights page** `/library/$id/highlights`: sections (`Create Section`), and moving highlights between sections. +- **Embedding side effect:** a `rag_embeddings` row with `citation_id` or `capture_id`, `model = voyage-4-large`, 1024 dims. + +## How to get to it (user POV) + +Source detail `/library/$id` → **Quote** or **Comment** button. The Highlights tab (`/library/$id/highlights`) lists them, and its empty state has **Add your first quote**. + +## Driving it with Playwright + +Scenario: `node run.mjs quote-embed-ask`, first half. + +1. Create a source (see library-sources). +2. On `/library/$id`, click `button "Quote"`. +3. In `dialog "Add Citation"`, fill `textbox "Text *"`, then click `button "Create Citation"`. +4. `/library/$id/highlights` shows the quote text. + +**Proof:** +- the `citations` row exists +- `rag_embeddings` has a row for that `citation_id` +- `.verify/run/i0/fake-providers.jsonl` has a new `"op": "embed"` line with `"input_type": "document"` + +## Gotchas + +- **Fixed 2026-09-26:** before the fix, creating a citation never embedded it. The route's `get_db` committed only *after* FastAPI ran the background embedding task, so the task couldn't see the row and skipped silently. + - Routes that take `BackgroundTasks` now use `Depends(get_db, scope="function")`, enforced by `fast-api/tests/test_background_task_db_scope.py`. + - A skipped row now logs `... embedding skipped: row not found`. Grep `fast-api.log` for it when this fails. + - Rows created before the fix still lack embeddings until the admin refresh backfills them. +- Voyage calls go through the real `VoyageEmbedder` → SDK → the HTTP fake (`EMBEDDING_BASE_URL`). To bypass HTTP entirely, set `EMBEDDING_PROVIDER=fake` (the in-process `FakeEmbedder`); nothing is logged to `fake-providers.jsonl` then. +- Embedding vectors come from the fake: hashed bag-of-words. Texts that share words score as similar; nothing more semantic than that. diff --git a/.claude/skills/verify-root/features/library-sources.md b/.claude/skills/verify-root/features/library-sources.md new file mode 100644 index 0000000..5ef21df --- /dev/null +++ b/.claude/skills/verify-root/features/library-sources.md @@ -0,0 +1,43 @@ +# Library & sources + +A source is a book, video, article, PDF or podcast the user is working through. The library lists sources; each source has a detail page that holds its highlights, notes and takeaways. + +## Sub-features + +- Add a source manually: **Add Source** dialog with Type (Book/Video/Article/PDF), `Title *`, `Author`, and an optional "Add details" section. +- Library list: search box `Search library...`, type filters (`All`, `Books`, `Articles`, `Videos`, `Podcasts`, `PDFs`, with keyboard shortcuts A/B/R/V/P/D), and a "Hide in collections" toggle. +- Source detail `/library/$id`: + - status button (`To do` → in progress → done) + - tags (`Add tag`) + - summary (`Edit`) + - "About this source" + - Recent notes + - Key takeaways + - `More actions` menu (edit/archive/delete) +- Adding a Video or PDF source goes through YouTube or R2 upload. Those can only be reached partially here: R2 is moto, YouTube isn't stubbed. + +## How to get to it (user POV) + +Sidebar **Library** → `/library` → **Add Source** (top right) or **Add your first source** (empty state). The home page (`/`) also has **Add source**. Clicking a source card opens `/library/$id`. + +## Driving it with Playwright + +Scenario: `node run.mjs library-add-source`. + +1. `/library` → `getByRole("button", { name: "Add Source" })`. +2. `getByRole("dialog", { name: "Add Source" })`: + - fill `textbox "Title *"` and `textbox "Author"` + - click `button "Create Source"` + - wait for the dialog to close +3. Revisit `/library`, click the card by its title text, and wait for the URL `/library/\d+`. + +**Proof:** the card is listed; the detail page shows the title and author; and this query returns `book|Verify Author` for that title: + +```sql +select type, author from sources s join auth."user" u on u.id = s.user_id where u.email = 'verify@example.com' +``` + +## Gotchas + +- `/sources` is gone; old Cypress specs still use it. Sources live under `/library`. +- On a busy `i0` instance the list isn't empty. Always use unique titles (`Date.now()`) and match by title, never by position. diff --git a/.claude/skills/verify-root/features/notes.md b/.claude/skills/verify-root/features/notes.md new file mode 100644 index 0000000..3cd5e04 --- /dev/null +++ b/.claude/skills/verify-root/features/notes.md @@ -0,0 +1,38 @@ +# Notes + +Free-form rich-text notes (Tiptap), either standalone or linked to a source. + +## Sub-features + +- Notes list `/notes`: `Search notes…`, `Sort: Updated`, `List view` / `Grid view`, `New Note`. +- Note editor `/notes/$id`: + - title textbox (accessible name `Untitled` until set) + - Tiptap body + - `Saved` indicator + - `Type:` toggle (`NOTE` / insight) +- Source-scoped notes under `/library/$id/notes`. + +## How to get to it (user POV) + +Sidebar **Notes** → `/notes` → **New Note**. This creates the note right away and opens `/notes/$id`. + +## Driving it with Playwright + +There's no scenario file yet. Write `harness/scenarios/notes-create.mjs` the first time you need it: + +1. `/notes` → `getByRole("button", { name: "New Note" }).first()`. The empty state shows a second button with the same name. +2. `page.waitForURL(/\/notes\/\d+/)`. +3. `getByRole("textbox", { name: "Untitled" }).fill(title)`. +4. Type the body into `locator(".ProseMirror")`. +5. Wait for `Saved`. + +**Proof:** the note shows in `/notes` by title, and this query returns the text you typed: + +```sql +select title, plain_text, kind from notes where title = '' +``` + +## Gotchas + +- `New Note` creates a row before you type anything. Empty `Untitled` notes pile up on a reused instance. +- The editor body isn't exposed as a named textbox in the ARIA tree; target `.ProseMirror`. diff --git a/.claude/skills/verify-root/features/pdf.md b/.claude/skills/verify-root/features/pdf.md new file mode 100644 index 0000000..0003b06 --- /dev/null +++ b/.claude/skills/verify-root/features/pdf.md @@ -0,0 +1,40 @@ +# PDF sources + +A PDF-type source stores its file in object storage (R2). Users read and highlight it in the PDF viewer slideover. + +## Sub-features + +- Create a source with Type **PDF** (Add Source dialog). +- Upload from the source page (`Choose File`, `accept=application/pdf`) or from the viewer's **Upload PDF**. Max 50MB and 500 pages. Replacing a PDF deletes highlights derived from the old one. +- Viewer slideover (the `PDF [P]` button): zoom, fit, and highlighting that creates citations with `pdf_v1` locations. +- "Open in new tab" through a presigned URL (`GET /rag-api/sources/{id}/pdf/url`). +- Deleting the source removes the stored object. + +## How to get to it (user POV) + +Library → **Add Source** → Type **PDF** → create → the source page shows **Choose File** and **PDF [P]**. + +## Driving it with Playwright + +Scenario: `node run.mjs pdf-upload`. + +1. Select the type by clicking its label: `dialog.getByText("PDF", { exact: true })`. The radio input itself is visually hidden. +2. `setInputFiles` on `input[type=file][accept='application/pdf']`. The scenario generates a one-page PDF, and the step waits for `POST /rag-api/sources/{id}/pdf` to return 2xx. + +3. Open the viewer (`PDF [P]`) and wait for the page's text ("Verify PDF upload") in the pdf.js text layer. +4. Legacy-row check: remove `page_count` from the row, reload, and open the viewer again. + +**Proof:** +- `sources.pdf_object_key` is set, and `metadata.page_count` is `1`. +- The object is in the S3 stand-in. The bucket listing `GET $S3_URL/root-verify?list-type=2&prefix=<key>` is open; objects themselves are private, so unsigned GET and HEAD return 403. +- The presigned URL from `/pdf/url` serves bytes starting `%PDF-` of the uploaded size. Fetch it with `page.request`, not `window.fetch`, because the bucket sends no CORS headers. +- The viewer renders the page, both freshly uploaded and for a legacy row. + +## Gotchas + +- **Fixed 2026-09-26:** the viewer never showed an uploaded PDF ("No PDF uploaded • N B"). + - Cause: `hasPdf` depended on `metadata.page_count`, which the backend stripped on every upload and nothing ever set. + - The backend now counts pages with `pypdf` on upload. It stores `page_count`, rejects unreadable or over-500-page files with 400, and citation bounds-validation uses the stored count. + - The viewer treats `size_bytes` as enough, so PDFs uploaded before the fix open without a backfill. + - `compare.sh HEAD~1 pdf-upload` shows the base failing. +- The annotator's `PdfLoader` used to fetch its pdf.js worker from `unpkg.com`, which the cloud proxy blocks. It now gets the bundled worker (`workerSrc={PDF_WORKER_SRC}`), so the viewer works offline and prod no longer depends on that CDN. diff --git a/.claude/skills/verify-root/features/reflect.md b/.claude/skills/verify-root/features/reflect.md new file mode 100644 index 0000000..8a15049 --- /dev/null +++ b/.claude/skills/verify-root/features/reflect.md @@ -0,0 +1,32 @@ +# Reflect + follow-ups + +Reflect is the per-source chat. It works like Ask, scoped to one source, and after each answer it offers follow-up chips generated by a small follow-up agent. + +## Sub-features + +- Question box `Ask anything...`, the model picker, and `Clear Chat`. +- Streamed answer, with the search tool steps shown ("Searching for …", "Found N result(s)"). +- Follow-up chips under the answer. Clicking a chip submits it as the next question. +- The session persists per user and source (`reflect_session_store`). + +## How to get to it (user POV) + +Library → a source → sidebar sub-item **Reflect** (`/library/$id/reflect`). The page heading is "Reflect on this source". + +## Driving it with Playwright + +Scenario: `node run.mjs reflect-followups`. It works in both `VERIFY_LLM` modes. + +1. Create a source, go to `/library/$id/reflect`, fill `textbox "Ask anything..."`, and press Enter. +2. Wait for the `<tag> Stubbed answer` text, where `<tag>` is `[fake-llm]` in fake mode and `[stub-llm]` in http mode. +3. Wait for `button "<tag> Tell me more"`. Expect exactly two chips. +4. Click the chip. It appears as a user bubble, and a second answer streams in. + +**Proof:** +- screenshots of the chips and of the answer after the chip was followed +- in http mode, `provider-calls.jsonl` shows `"function_call": "FollowUpPrompts"` on `gemini-3.5-flash-lite` + +## Gotchas + +- **Fixed 2026-09-26:** chips were always empty. `generate_followups` read `response.parsed`, which Jetflow leaves unset after an exit action (the run ends on the tool message). It now parses `response.content`, the same way transcript sectioning does. `compare.sh HEAD~1 reflect-followups` with `VERIFY_LLM=http` shows the base failing. +- Follow-ups are generated for Reflect only, not Ask. diff --git a/.claude/skills/verify-root/harness/lib.mjs b/.claude/skills/verify-root/harness/lib.mjs new file mode 100644 index 0000000..6f0c71c --- /dev/null +++ b/.claude/skills/verify-root/harness/lib.mjs @@ -0,0 +1,117 @@ +// Playwright harness for verify-root. Drives the real SPA as the seeded user and +// writes evidence to .verify/evidence/<timestamp>-<label>/ (survives down.sh). +import { createRequire } from "node:module"; +import { execSync } from "node:child_process"; +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +export const SKILL_DIR = path.resolve(HERE, ".."); +export const REPO_ROOT = path.resolve(SKILL_DIR, "../../.."); + +function loadPlaywright() { + const require = createRequire(import.meta.url); + const roots = [HERE]; + try { roots.push(execSync("npm root -g", { encoding: "utf8" }).trim()); } catch {} + for (const name of ["playwright", "playwright-core"]) { + try { return require(require.resolve(name, { paths: roots })); } catch {} + } + throw new Error( + "playwright not found. Install once: npm install --prefix .claude/skills/verify-root/harness playwright-core" + ); +} + +export function readState() { + const offset = process.env.VERIFY_PORT_OFFSET ?? "0"; + const file = path.join(REPO_ROOT, ".verify/run", `i${offset}`, "state.env"); + if (!fs.existsSync(file)) throw new Error(`no instance state at ${file}; run scripts/up.sh`); + return Object.fromEntries( + fs.readFileSync(file, "utf8").split("\n").filter(Boolean).map((l) => { + const i = l.indexOf("="); + return [l.slice(0, i), l.slice(i + 1)]; + }) + ); +} + +export function sql(query) { + const state = readState(); + return execSync( + `docker exec -i ${state.PG_CONTAINER} psql -U postgres -d root -tA -F '|' -c ${JSON.stringify(query)}`, + { encoding: "utf8" } + ).trim(); +} + +/** + * Open a logged-in browser session. + * opts.label evidence folder suffix + * opts.video record video (default true) + * opts.login log in through /login first (default true) + */ +export async function session(opts = {}) { + const { chromium } = loadPlaywright(); + const state = readState(); + const stamp = new Date().toISOString().replace(/[:.]/g, "-"); + const dir = path.join(REPO_ROOT, ".verify/evidence", `${stamp}-${opts.label ?? "run"}`); + fs.mkdirSync(dir, { recursive: true }); + + // Provider calls made during this session end up in the evidence (the run dir + // itself is deleted by down.sh). + const providerLog = path.join(state.RUN_DIR ?? "", "fake-providers.jsonl"); + const readProviderLog = () => + fs.existsSync(providerLog) ? fs.readFileSync(providerLog, "utf8").split("\n").filter(Boolean) : []; + const providerLinesBefore = readProviderLog().length; + + const browser = await chromium.launch(); + const context = await browser.newContext({ + baseURL: state.WEB_URL, + viewport: { width: 1280, height: 800 }, + ...(opts.video === false ? {} : { recordVideo: { dir, size: { width: 1280, height: 800 } } }), + }); + const page = await context.newPage(); + const events = []; + page.on("console", (m) => { if (m.type() === "error") events.push({ kind: "console.error", text: m.text() }); }); + page.on("pageerror", (e) => events.push({ kind: "pageerror", text: String(e) })); + page.on("response", (r) => { + if (r.url().includes("/rag-api/") || r.url().includes("/api/auth/")) { + events.push({ kind: "api", status: r.status(), method: r.request().method(), url: r.url().replace(state.WEB_URL, "") }); + } + }); + + let n = 0; + const shot = async (name) => { + const file = path.join(dir, `${String(++n).padStart(2, "0")}-${name}.png`); + // Let queries settle so shots show data, not loading skeletons. + await page.waitForLoadState("networkidle", { timeout: 5000 }).catch(() => {}); + await page.screenshot({ path: file, fullPage: true }); + return file; + }; + + if (opts.login !== false) { + await page.goto("/login"); + await page.locator("input#email").fill(state.VERIFY_EMAIL); + await page.locator("input#password").fill(state.VERIFY_PASSWORD); + await page.locator("button[type=submit]").click(); + await page.waitForURL((u) => !u.pathname.startsWith("/login"), { timeout: 15000 }); + } + + const finish = async (result = {}) => { + const video = page.video(); + await context.close(); + await browser.close(); + if (video) { + const src = await video.path(); + fs.renameSync(src, path.join(dir, "video.webm")); + } + fs.writeFileSync(path.join(dir, "events.json"), JSON.stringify(events, null, 2)); + const calls = readProviderLog().slice(providerLinesBefore); + fs.writeFileSync(path.join(dir, "provider-calls.jsonl"), calls.join("\n") + (calls.length ? "\n" : "")); + fs.writeFileSync( + path.join(dir, "result.json"), + JSON.stringify({ label: opts.label, git_head: state.GIT_HEAD, web_url: state.WEB_URL, ...result }, null, 2) + ); + return dir; + }; + + return { page, context, state, dir, shot, events, finish }; +} diff --git a/.claude/skills/verify-root/harness/run.mjs b/.claude/skills/verify-root/harness/run.mjs new file mode 100755 index 0000000..d93aef2 --- /dev/null +++ b/.claude/skills/verify-root/harness/run.mjs @@ -0,0 +1,34 @@ +#!/usr/bin/env node +// Run one feature scenario and print its evidence directory. +// Usage: node run.mjs <scenario> [--no-video] +// <scenario> is a file in scenarios/ (with or without .mjs), or a path. +// A scenario exports `default async ({ page, shot, sql, state, expect }) => result`. +// Throwing fails the run; evidence is still written (result.json has "ok": false). +import fs from "node:fs"; +import path from "node:path"; +import { pathToFileURL, fileURLToPath } from "node:url"; +import { session, sql } from "./lib.mjs"; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const arg = process.argv[2]; +if (!arg) { + console.error("usage: run.mjs <scenario> [--no-video]\nscenarios:", fs.readdirSync(path.join(HERE, "scenarios")).join(", ")); + process.exit(2); +} +const file = fs.existsSync(arg) ? path.resolve(arg) : path.join(HERE, "scenarios", arg.endsWith(".mjs") ? arg : `${arg}.mjs`); +const name = path.basename(file, ".mjs"); +const { default: scenario } = await import(pathToFileURL(file).href); + +const expect = (cond, msg) => { if (!cond) throw new Error(`expectation failed: ${msg}`); }; +const s = await session({ label: name, video: !process.argv.includes("--no-video") }); +let result; +try { + const out = await scenario({ page: s.page, shot: s.shot, sql, state: s.state, expect }); + result = { ok: true, ...out }; +} catch (err) { + await s.shot("failure").catch(() => {}); + result = { ok: false, error: String(err?.stack ?? err) }; +} +const dir = await s.finish(result); +console.log(JSON.stringify({ ok: result.ok, evidence: dir, ...(result.ok ? {} : { error: result.error.split("\n")[0] }) }, null, 2)); +process.exit(result.ok ? 0 : 1); diff --git a/.claude/skills/verify-root/harness/scenarios/_explore.mjs b/.claude/skills/verify-root/harness/scenarios/_explore.mjs new file mode 100644 index 0000000..21791e5 --- /dev/null +++ b/.claude/skills/verify-root/harness/scenarios/_explore.mjs @@ -0,0 +1,18 @@ +// Discovery helper: screenshot + ARIA snapshot of routes. Not a proof. +// Usage: EXPLORE_ROUTES="/,/library,/ask" node run.mjs _explore --no-video +import fs from "node:fs"; +import path from "node:path"; + +export default async ({ page, shot }) => { + const routes = (process.env.EXPLORE_ROUTES ?? "/").split(","); + const snapshots = {}; + for (const route of routes) { + await page.goto(route); + await page.waitForLoadState("networkidle"); + await shot(route.replace(/\W+/g, "_") || "root"); + snapshots[route] = await page.locator("body").ariaSnapshot(); + } + const dir = path.dirname(await shot("last")); + fs.writeFileSync(path.join(dir, "aria.yml"), Object.entries(snapshots).map(([r, s]) => `# ${r}\n${s}`).join("\n\n")); + return { routes }; +}; diff --git a/.claude/skills/verify-root/harness/scenarios/library-add-source.mjs b/.claude/skills/verify-root/harness/scenarios/library-add-source.mjs new file mode 100644 index 0000000..fdb198d --- /dev/null +++ b/.claude/skills/verify-root/harness/scenarios/library-add-source.mjs @@ -0,0 +1,36 @@ +// Feature: library — add a source through the Add Source dialog, see it listed, +// open it, and confirm the row landed in `sources` for the seeded user. +export default async ({ page, shot, sql, state, expect }) => { + const title = `Verify Book ${Date.now()}`; + + await page.goto("/library"); + await page.getByRole("heading", { name: "Library", level: 1 }).waitFor(); + await shot("library-before"); + + await page.getByRole("button", { name: "Add Source" }).click(); + const dialog = page.getByRole("dialog", { name: "Add Source" }); + await dialog.getByRole("textbox", { name: "Title *" }).fill(title); + await dialog.getByRole("textbox", { name: "Author" }).fill("Verify Author"); + await shot("dialog-filled"); + await dialog.getByRole("button", { name: "Create Source" }).click(); + await dialog.waitFor({ state: "hidden" }); + + await page.goto("/library"); + const card = page.getByText(title).first(); + await card.waitFor(); + await shot("library-after"); + + await card.click(); + await page.waitForURL(/\/library\/\d+/); + await page.getByText(title).first().waitFor(); + await shot("source-detail"); + + const row = sql( + `select s.id, s.type, s.author from sources s join auth."user" u on u.id = s.user_id ` + + `where u.email = '${state.VERIFY_EMAIL}' and s.title = '${title}'` + ); + expect(row, `sources row for "${title}"`); + const [id, type, author] = row.split("|"); + expect(type === "book" && author === "Verify Author", `row fields (got ${row})`); + return { title, source_id: Number(id), url: page.url() }; +}; diff --git a/.claude/skills/verify-root/harness/scenarios/pdf-upload.mjs b/.claude/skills/verify-root/harness/scenarios/pdf-upload.mjs new file mode 100644 index 0000000..03d024a --- /dev/null +++ b/.claude/skills/verify-root/harness/scenarios/pdf-upload.mjs @@ -0,0 +1,99 @@ +// Feature: PDF source — upload a PDF through the source page, then read it in +// the viewer. Proves the ObjectStore write (object in the S3 stand-in, key and +// page_count on the source row), the presigned-URL read, and the viewer render. + +// Minimal one-page PDF with visible text (xref offsets computed below). +function makePdf(text) { + const objs = [ + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>", + null, // content stream, filled below + "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>", + ]; + const stream = `BT /F1 24 Tf 72 700 Td (${text}) Tj ET`; + objs[3] = `<< /Length ${stream.length} >>\nstream\n${stream}\nendstream`; + let out = "%PDF-1.4\n"; + const offsets = []; + objs.forEach((o, i) => { + offsets.push(out.length); + out += `${i + 1} 0 obj\n${o}\nendobj\n`; + }); + const xref = out.length; + out += `xref\n0 ${objs.length + 1}\n0000000000 65535 f \n`; + out += offsets.map((o) => `${String(o).padStart(10, "0")} 00000 n \n`).join(""); + out += `trailer\n<< /Size ${objs.length + 1} /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF\n`; + return Buffer.from(out, "latin1"); +} + +export default async ({ page, shot, sql, state, expect }) => { + const title = `Verify PDF ${Date.now()}`; + + await page.goto("/library"); + await page.getByRole("button", { name: "Add Source" }).click(); + const dialog = page.getByRole("dialog", { name: "Add Source" }); + await dialog.getByText("PDF", { exact: true }).click(); + await dialog.locator("#type-pdf").isChecked().then((c) => expect(c, "PDF type selected")); + await dialog.getByRole("textbox", { name: "Title *" }).fill(title); + await dialog.getByRole("button", { name: "Create Source" }).click(); + await dialog.waitFor({ state: "hidden" }); + const sourceId = sql(`select id from sources where title = '${title}'`); + expect(sourceId, "source row"); + + await page.goto(`/library/${sourceId}`); + await page.getByRole("button", { name: "Choose File" }).waitFor(); + await shot("before-upload"); + const uploaded = page.waitForResponse( + (r) => r.url().includes(`/sources/${sourceId}/pdf`) && r.request().method() !== "GET" + ); + await page.locator("input[type=file][accept='application/pdf']").setInputFiles({ + name: "verify.pdf", + mimeType: "application/pdf", + buffer: makePdf("Verify PDF upload"), + }); + const res = await uploaded; + expect(res.ok(), `upload responded ${res.status()}`); + await page.waitForTimeout(1000); + await shot("after-upload"); + + // Side effects: key on the row, object in the S3 stand-in. + const key = sql(`select pdf_object_key from sources where id = ${sourceId}`); + expect(key, "sources.pdf_object_key set"); + // Objects are private (unsigned GET/HEAD → 403); the bucket listing is open. + const listing = await (await fetch(`${state.S3_URL}/root-verify?list-type=2&prefix=${encodeURIComponent(key)}`)).text(); + const size = listing.match(/<Size>(\d+)<\/Size>/)?.[1]; + expect(listing.includes(`<Key>${key}</Key>`) && Number(size) > 0, `object ${key} in S3 stand-in`); + + // Read path: the API hands out a presigned URL (what the viewer and "open in + // new tab" use); fetching it returns the same bytes. + const url = await page.evaluate(async (id) => { + const { token } = await (await fetch("/api/auth/token")).json(); + const res = await fetch(`/rag-api/sources/${id}/pdf/url`, { headers: { Authorization: `Bearer ${token}` } }); + return (await res.json()).url; + }, Number(sourceId)); + expect(url?.includes(key), `presigned URL for ${key} (got ${url})`); + const pdf = await page.request.get(url); // not window.fetch: the bucket sends no CORS headers + const body = await pdf.body(); + expect(pdf.ok() && body.subarray(0, 5).toString() === "%PDF-" && body.length === Number(size), "presigned URL serves the uploaded PDF"); + + const pageCount = sql(`select metadata->>'page_count' from sources where id = ${sourceId}`); + expect(pageCount === "1", `metadata.page_count stored (got ${pageCount})`); + + // Viewer: opens, fetches the presigned URL and renders the page. + const pdfFetched = page.waitForResponse((r) => r.url().includes(key) && r.ok(), { timeout: 20000 }); + await page.getByRole("button", { name: /^PDF/ }).click(); + await page.getByText("PDF Viewer").waitFor(); + await page.getByText("1 pages").waitFor({ timeout: 10000 }); + await pdfFetched; + await page.getByText("Verify PDF upload").first().waitFor({ timeout: 15000 }); // pdf.js text layer + await shot("viewer"); + + // Rows uploaded before page_count was stored have only size_bytes: the + // viewer must still open them. + sql(`update sources set metadata = metadata - 'page_count' where id = ${sourceId}`); + await page.goto(`/library/${sourceId}`); + await page.getByRole("button", { name: /^PDF/ }).click(); + await page.getByText("Verify PDF upload").first().waitFor({ timeout: 15000 }); + await shot("viewer-legacy-row"); + return { source_id: Number(sourceId), pdf_object_key: key, object_size: Number(size), page_count: Number(pageCount) }; +}; diff --git a/.claude/skills/verify-root/harness/scenarios/quote-embed-ask.mjs b/.claude/skills/verify-root/harness/scenarios/quote-embed-ask.mjs new file mode 100644 index 0000000..26d4a34 --- /dev/null +++ b/.claude/skills/verify-root/harness/scenarios/quote-embed-ask.mjs @@ -0,0 +1,81 @@ +// Feature: highlights → embeddings → Ask. Add a quote to a new source, prove the +// background task embedded it (rag_embeddings row + fake Voyage call), then ask a +// question in /ask and see the answer stream back. +// LLM_MODE=fake (default): FakeLLMClient calls the real search tool once, then +// answers "[fake-llm] ... Tool results: 1 ...". +// LLM_MODE=http: live Gemini client → fake_providers.py, answer "[stub-llm] ...". +import fs from "node:fs"; +import path from "node:path"; + +const poll = async (fn, ms = 15000) => { + const end = Date.now() + ms; + for (;;) { + const v = fn(); + if (v) return v; + if (Date.now() > end) return v; + await new Promise((r) => setTimeout(r, 500)); + } +}; + +export default async ({ page, shot, sql, state, expect }) => { + const stamp = Date.now(); + const title = `Verify Quotes ${stamp}`; + const quote = `Compounding curiosity turns small daily reading into durable insight ${stamp}`; + const logFile = path.join(state.RUN_DIR, "fake-providers.jsonl"); + const embedCallsBefore = fs.existsSync(logFile) ? fs.readFileSync(logFile, "utf8").split("\n").filter((l) => l.includes('"embed"')).length : 0; + + // Source to hang the quote on. + await page.goto("/library"); + await page.getByRole("button", { name: "Add Source" }).click(); + const addSource = page.getByRole("dialog", { name: "Add Source" }); + await addSource.getByRole("textbox", { name: "Title *" }).fill(title); + await addSource.getByRole("button", { name: "Create Source" }).click(); + await addSource.waitFor({ state: "hidden" }); + const sourceId = await poll(() => sql(`select id from sources where title = '${title}'`)); + expect(sourceId, "source row"); + + // Quote via the source page's Quote button. + await page.goto(`/library/${sourceId}`); + await page.getByRole("button", { name: "Quote" }).click(); + const dlg = page.getByRole("dialog", { name: "Add Citation" }); + await dlg.getByRole("textbox", { name: "Text *" }).fill(quote); + await shot("quote-filled"); + await dlg.getByRole("button", { name: "Create Citation" }).click(); + await dlg.waitFor({ state: "hidden" }); + + await page.goto(`/library/${sourceId}/highlights`); + await page.getByText(quote).first().waitFor(); + await shot("highlights"); + + // Side effect: background embedding task wrote a vector for the citation. + const emb = await poll(() => + sql(`select e.model, vector_dims(e.embedding) from rag_embeddings e join citations c on c.id = e.citation_id where c.text = '${quote}'`) + ); + const embedCallsAfter = fs.existsSync(logFile) ? fs.readFileSync(logFile, "utf8").split("\n").filter((l) => l.includes('"embed"')).length : 0; + // Checked at the end so the Ask half still runs (and records evidence) when embedding is broken. + + // Ask. + await page.goto("/ask"); + await page.getByRole("textbox", { name: "Ask anything..." }).fill("What does compounding curiosity do for reading?"); + await page.getByRole("textbox", { name: "Ask anything..." }).press("Enter"); + const fakeMode = (state.LLM_MODE ?? "fake") === "fake"; + const answer = page.getByText(fakeMode ? "[fake-llm] Stubbed answer" : "[stub-llm]").first(); + await answer.waitFor({ timeout: 30000 }); + await page.waitForTimeout(1000); + await shot("ask-answer"); + + const answerText = await answer.textContent(); + const log = fs.readFileSync(logFile, "utf8").split("\n"); + const geminiCalls = log.filter((l) => l.includes('"gemini"')).length; + const queryEmbeds = log.filter((l) => l.includes('"input_type": "query"')).length; + if (fakeMode) { + // The fake called the real search tool: query embedding went to Voyage (fake). + expect(answerText.includes("Tool results: 1"), `answer used search results (got: ${answerText})`); + expect(queryEmbeds > 0, "search embedded the query via the Embedder"); + } else { + expect(geminiCalls > 0, "fake Gemini received a call"); + } + expect(embedCallsAfter > embedCallsBefore, "fake Voyage received an embed call for the new citation"); + expect(emb, "rag_embeddings row for the new citation"); + return { source_id: Number(sourceId), embedding: emb, llm_mode: state.LLM_MODE, answer: answerText, query_embeds: queryEmbeds, gemini_calls: geminiCalls }; +}; diff --git a/.claude/skills/verify-root/harness/scenarios/reflect-followups.mjs b/.claude/skills/verify-root/harness/scenarios/reflect-followups.mjs new file mode 100644 index 0000000..049b965 --- /dev/null +++ b/.claude/skills/verify-root/harness/scenarios/reflect-followups.mjs @@ -0,0 +1,47 @@ +// Feature: Reflect on a source → streamed answer → follow-up chips → click a chip. +// LLM_MODE=fake: FakeLLMClient; answer and chips start with "[fake-llm]". +// LLM_MODE=http: live Jetflow Gemini client → fake_providers.py, which answers +// "[stub-llm] ..." and returns a forced FollowUpPrompts function call. +export default async ({ page, shot, sql, state, expect }) => { + const tag = (state.LLM_MODE ?? "fake") === "fake" ? "[fake-llm]" : "[stub-llm]"; + const title = `Verify Reflect ${Date.now()}`; + + await page.goto("/library"); + await page.getByRole("button", { name: "Add Source" }).click(); + const addSource = page.getByRole("dialog", { name: "Add Source" }); + await addSource.getByRole("textbox", { name: "Title *" }).fill(title); + await addSource.getByRole("button", { name: "Create Source" }).click(); + await addSource.waitFor({ state: "hidden" }); + const sourceId = sql(`select id from sources where title = '${title}'`); + expect(sourceId, "source row"); + + await page.goto(`/library/${sourceId}/reflect`); + await page.getByRole("heading", { name: "Reflect on this source" }).waitFor(); + const box = page.getByRole("textbox", { name: "Ask anything..." }); + await box.fill("What stood out to me here?"); + await shot("reflect-question"); + await box.press("Enter"); + + await page.getByText(`${tag} Stubbed answer`).first().waitFor({ timeout: 30000 }); + // Chips arrive after the answer (separate follow-up agent call). + const chipText = `${tag} Tell me more`; + const chip = page.getByRole("button", { name: chipText }); + let chips = []; + try { + await chip.waitFor({ timeout: 15000 }); + chips = await page.getByRole("button", { name: new RegExp(`^\\${tag.slice(0, -1)}\\]`) }).allTextContents(); + } finally { + await shot("answer-with-followups"); + } + expect(chips.length === 2, `two follow-up chips (got ${JSON.stringify(chips)})`); + + // Clicking a chip submits it as the next question (chip + user bubble). + await chip.click(); + const deadline = Date.now() + 30000; + while ((await page.getByText(chipText).count()) < 2 && Date.now() < deadline) { + await page.waitForTimeout(250); + } + await page.getByText(`${tag} Stubbed answer`).nth(1).waitFor({ timeout: 30000 }); + await shot("chip-followed"); + return { source_id: Number(sourceId), llm_mode: state.LLM_MODE, chips }; +}; diff --git a/.claude/skills/verify-root/scripts/common.sh b/.claude/skills/verify-root/scripts/common.sh new file mode 100755 index 0000000..bfadd22 --- /dev/null +++ b/.claude/skills/verify-root/scripts/common.sh @@ -0,0 +1,73 @@ +# Shared config for verify-root scripts. Sourced, not executed. +# All ports derive from VERIFY_PORT_OFFSET (steps of 10) so instances (e.g. main +# vs branch worktrees) can run side by side without colliding. + +set -euo pipefail + +SKILL_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +REPO_ROOT="$(cd "$SKILL_DIR/../../.." && pwd)" +# App source to run. Defaults to this checkout; compare.sh points it at a +# worktree of another ref. State/evidence always live under REPO_ROOT/.verify. +APP_ROOT="${VERIFY_APP_ROOT:-$REPO_ROOT}" + +OFFSET="${VERIFY_PORT_OFFSET:-0}" +INSTANCE="i${OFFSET}" + +PG_PORT=$((55432 + OFFSET * 10)) +API_PORT=$((18081 + OFFSET * 10)) +AUTH_PORT=$((18082 + OFFSET * 10)) +FAKE_PORT=$((18090 + OFFSET * 10)) +S3_PORT=$((19000 + OFFSET * 10)) +WEB_PORT=$((13000 + OFFSET * 10)) + +# Instance state lives under the checkout; evidence lives beside it and is never +# touched by down.sh. Both are gitignored (.verify/). +VERIFY_HOME="$REPO_ROOT/.verify" +RUN_DIR="$VERIFY_HOME/run/$INSTANCE" +EVIDENCE_ROOT="$VERIFY_HOME/evidence" + +PG_CONTAINER="root-verify-pg-$INSTANCE" +PG_IMAGE="paradedb/paradedb:0.20.5" # same image as CI integration tests +MIGRATE_IMAGE="migrate/migrate:v4.19.0" # same as CI + +# Local-only DB. Scripts refuse to run against anything else. +DATABASE_URL="postgres://postgres:postgres@127.0.0.1:${PG_PORT}/root?sslmode=disable" +WEB_URL="http://localhost:${WEB_PORT}" + +VERIFY_EMAIL="verify@example.com" +VERIFY_PASSWORD="verify-password-123" +VERIFY_NAME="Verify Bot" + +log() { printf '[verify-root:%s] %s\n' "$INSTANCE" "$*" >&2; } +die() { log "ERROR: $*"; exit 1; } + +assert_local_db() { + case "$1" in + *@127.0.0.1:*|*@localhost:*) ;; + *) die "refusing: DATABASE_URL is not local ($1)";; + esac +} + +# Minimal, explicit environment for every service we launch: nothing from the +# caller's shell or Doppler (DATABASE_URL, LOGFIRE_TOKEN, real API keys) leaks in. +base_env() { + local v + printf '%s\n' "PATH=$PATH" "HOME=$HOME" + for v in HTTPS_PROXY HTTP_PROXY NO_PROXY https_proxy http_proxy no_proxy \ + SSL_CERT_FILE REQUESTS_CA_BUNDLE NODE_EXTRA_CA_CERTS \ + PLAYWRIGHT_BROWSERS_PATH UV_CACHE_DIR; do + [ -n "${!v:-}" ] && echo "$v=${!v}" + done + return 0 +} + +pid_alive() { [ -f "$RUN_DIR/$1.pid" ] && kill -0 "$(cat "$RUN_DIR/$1.pid")" 2>/dev/null; } + +wait_http() { # wait_http <name> <url> <timeout_s> + local i + for ((i = 0; i < $3; i++)); do + curl -fsS -o /dev/null --max-time 2 "$2" 2>/dev/null && return 0 + sleep 1 + done + die "$1 not ready at $2 after $3s (log: $RUN_DIR/$1.log)" +} diff --git a/.claude/skills/verify-root/scripts/compare.sh b/.claude/skills/verify-root/scripts/compare.sh new file mode 100755 index 0000000..f4746af --- /dev/null +++ b/.claude/skills/verify-root/scripts/compare.sh @@ -0,0 +1,76 @@ +#!/usr/bin/env bash +# Before/after proof: run one scenario against <base-ref> and against this +# checkout, side by side, and write a compare.html with both videos + screenshots. +# +# Usage: compare.sh <base-ref> <scenario> [--keep] +# e.g. compare.sh origin/main library-add-source +# Base runs as instance i1 (ports +10) from a temporary git worktree; head uses +# instance i0 (started if not already up). --keep leaves the base instance and +# worktree running. Prints the compare directory. + +source "$(dirname "$0")/common.sh" + +BASE_REF="${1:?usage: compare.sh <base-ref> <scenario> [--keep]}" +SCENARIO="${2:?usage: compare.sh <base-ref> <scenario> [--keep]}" +KEEP="${3:-}" +SCRIPTS="$SKILL_DIR/scripts" +HARNESS="$SKILL_DIR/harness" + +BASE_SHA=$(git -C "$REPO_ROOT" rev-parse --short "$BASE_REF") +WT="$VERIFY_HOME/worktrees/$BASE_SHA" +if [ ! -d "$WT" ]; then + log "worktree for $BASE_REF ($BASE_SHA) at $WT" + git -C "$REPO_ROOT" worktree add --detach "$WT" "$BASE_SHA" >/dev/null 2>&1 +fi + +cleanup_base() { + [ "$KEEP" = "--keep" ] && return 0 + VERIFY_PORT_OFFSET=1 "$SCRIPTS/down.sh" || true + git -C "$REPO_ROOT" worktree remove --force "$WT" 2>/dev/null || true +} +trap cleanup_base EXIT + +log "base instance (i1) from $BASE_SHA" +VERIFY_PORT_OFFSET=1 VERIFY_APP_ROOT="$WT" "$SCRIPTS/up.sh" >/dev/null +log "head instance (i0) from this checkout" +VERIFY_PORT_OFFSET=0 "$SCRIPTS/up.sh" >/dev/null + +run_side() { # run_side <offset> -> prints evidence dir + local out + out=$(cd "$HARNESS" && VERIFY_PORT_OFFSET="$1" node run.mjs "$SCENARIO" || true) + python3 -c 'import json,sys; print(json.loads(sys.stdin.read())["evidence"])' <<<"$out" +} +BASE_DIR=$(run_side 1) +HEAD_DIR=$(run_side 0) + +OUT="$EVIDENCE_ROOT/$(date -u +%Y-%m-%dT%H-%M-%SZ)-compare-$SCENARIO" +mkdir -p "$OUT" +cp -r "$BASE_DIR" "$OUT/base" +cp -r "$HEAD_DIR" "$OUT/head" +python3 - "$OUT" "$BASE_REF" <<'PY' +import html, json, os, sys +out, base_ref = sys.argv[1], sys.argv[2] +def side(name): + d = os.path.join(out, name) + res = json.load(open(os.path.join(d, "result.json"))) + shots = sorted(f for f in os.listdir(d) if f.endswith(".png")) + return res, shots +(bres, bshots), (hres, hshots) = side("base"), side("head") +def badge(r): return f'<b style="color:{"#1a7f37" if r.get("ok") else "#cf222e"}">{"PASS" if r.get("ok") else "FAIL"}</b>' +rows = "".join( + f'<tr><td>{f"<img src=base/{b}>" if b else ""}<div>{html.escape(b or "")}</div></td>' + f'<td>{f"<img src=head/{h}>" if h else ""}<div>{html.escape(h or "")}</div></td></tr>' + for b, h in __import__("itertools").zip_longest(bshots, hshots) +) +open(os.path.join(out, "compare.html"), "w").write(f"""<!doctype html><meta charset=utf-8> +<title>compare {html.escape(hres.get('label',''))} + +

{html.escape(hres.get('label',''))}: base vs head

+ + + +{rows}
base: {html.escape(base_ref)} @ {bres.get('git_head')} {badge(bres)}head: {hres.get('git_head')} {badge(hres)}
{html.escape(json.dumps(bres, indent=2))}
{html.escape(json.dumps(hres, indent=2))}
""") +PY +log "compare written: $OUT/compare.html" +echo "$OUT" diff --git a/.claude/skills/verify-root/scripts/db.sh b/.claude/skills/verify-root/scripts/db.sh new file mode 100755 index 0000000..e91128e --- /dev/null +++ b/.claude/skills/verify-root/scripts/db.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +# Run SQL against this instance's local database (read side-effects as evidence). +# Usage: db.sh "select id, title from sources order by created_at desc limit 5" +source "$(dirname "$0")/common.sh" +[ -f "$RUN_DIR/state.env" ] || die "instance not up" +docker exec -i "$PG_CONTAINER" psql -U postgres -d root -P pager=off -c "$1" diff --git a/.claude/skills/verify-root/scripts/doctor.sh b/.claude/skills/verify-root/scripts/doctor.sh new file mode 100755 index 0000000..6408390 --- /dev/null +++ b/.claude/skills/verify-root/scripts/doctor.sh @@ -0,0 +1,37 @@ +#!/usr/bin/env bash +# Read-only health check: "is this instance worth driving?" +# Exit 0 = every check passed. Run before the first drive and after any +# failed or surprising drive. + +source "$(dirname "$0")/common.sh" +set +e + +fail=0 +check() { # check