Assistant
The assistant answers visitor questions about my work from a document built out of the site’s own content. It speaks as me, in the first person, with my approval, and links each answer to the role or skill page it drew from. Anything outside that document gets a fixed refusal that points to the contact links. The design and the reasons for it are in docs/superpowers/specs/2026-10-24-grounded-assistant-design.md; this page is how it works and how to run it.
The assistant ships switched off. It is gated by the assistant feature flag in Vercel: with the flag off nothing renders and both routes answer with the fallback. Turning it on is a flag flip with no redeploy (see Turning it on). When the daily budget is spent the header falls back to the command palette (see When the assistant is not offered).
How a question is answered
- The first click on the header chip or a launcher loads the panel and
@ai-sdk/react. None of them is in the page bundle. - The panel calls
POST /api/chat/session, which applies BotID and the per-address mint limit and returns a signed session token valid for 30 minutes. The panel keeps it in memory only. - Each message goes to
POST /api/chatwith that token. The route validates the body with Zod, checks the token, applies the limits, and streams the model’s reply. - The model answers or replies
OUT_OF_SCOPE. The route withholds the finalSOURCES:line, checks every cited ID against the knowledge document, and sends the valid ones as source links. An answer with no valid source is shown with the contact links.
The model gets the system prompt and the knowledge document in the system role. Visitor text is only ever a user message. No tools are passed, so the model cannot call anything.
What the assistant knows
src/lib/assistant/knowledge/build.ts builds one Markdown document from src/content. Each section heading carries an ID (role:<slug>, skill:<key>, about, resume) that is also the page the source link opens. The committed knowledge.snapshot.txt is the exact document, so a change to what the model can see appears in the diff of the pull request that caused it.
On top of that document, the runtime layer can add entries and approve or hold highlights (see Changing what the assistant knows). Three rules keep unreviewed content out:
- A role highlight enters the document only when its hash is in
approved.ts, tagged with thecontext.mdrow that approves it. The two Senior-role highlights that are not in the accepted resume sit in the held list. A test fails when a highlight is in neither list. - About contributes only the letter, pull quote and interests. The summary and body come from locale keys that have not been reviewed, and the preferences, food cards and Now strip are drafts.
- Skill proficiency, memories, role sections and case studies are left out until they are reviewed for this use.
Approving a highlight
- Confirm its
context.mdrow is accepted or owner-supplied and public. - Compute the hash of its exact text with
highlightHashfrom@/lib/assistant/knowledge. - Add
{ row, hash }to the role inapprovedHighlights, or move it fromheldHighlights. - Run
pnpm test, review the change toknowledge.snapshot.txt, and run the evals.
Editing the text of an approved highlight changes its hash, so the test fails until it is approved again.
Changing what the assistant knows
Most changes to what the assistant may say do not need a pull request or a release. A runtime layer in the same Upstash Redis database adds entries, approves or holds role highlights, and rolls back, and I make every change with pnpm assistant:knowledge (driven by the assistant-knowledge skill). The design and the reasons are in docs/superpowers/specs/2026-10-29-assistant-knowledge-store-design.md.
What stays in code, and still ships through a release: the system prompt, the model, the limits, the fixed eval cases, and everything built from src/content (roles, skills, About, contact). The runtime layer only adds to those. It cannot replace a built section, and a hold beats every approval.
Versions
A version is one JSON document with entries, approve and hold. Its ID is a hash of that content, so identical content has the same ID. Each entry has an id (note:<slug>), a title, a path that is a real page (the source link opens it), a plain-text body of at most 1,200 characters, a ledger record of where I said it, and at least one eval case whose expected facts appear in the body. A body cannot contain document headings, <knowledge> tags or the SOURCES:, NEXT: and OUT_OF_SCOPE markers.
Keys, all under assistant:knowledge:: v:<id> (immutable history), live, candidate, evalrun:<id> and log (the last 200 changes).
The workflow
The CLI loads env files in the order Next.js does, highest priority first: .env.$NODE_ENV.local, .env.local, .env.$NODE_ENV, .env. NODE_ENV defaults to development, and a variable set in the shell beats every file. The Upstash URL is UPSTASH_REDIS_REST_URL or REDIS_KV_REST_API_URL, and the Marketplace variables only exist in Production and Preview. To target the production database, pull them and set NODE_ENV:
vercel env pull .env.production.local --environment=production
NODE_ENV=production pnpm assistant:knowledge pullThe CLI reads the writable token only from ASSISTANT_KNOWLEDGE_WRITE_TOKEN, never from REDIS_KV_REST_API_TOKEN, so the write path is a deliberate choice. Put it in .env.local, which pulling into .env.production.local does not touch, or export it in your shell. Never set it in Vercel.
export ASSISTANT_KNOWLEDGE_WRITE_TOKEN=... # the writable Upstash token; never set it in Vercel
pnpm assistant:knowledge pull # live version to .knowledge/draft.json
# edit .knowledge/draft.json
pnpm assistant:knowledge validate
pnpm assistant:knowledge diff # what the model can now see
pnpm assistant:knowledge stage --note "why" # writes the candidate
pnpm assistant:knowledge eval # live evals against the candidate, about ten minutes
pnpm assistant:knowledge promote # candidate to livepromote refuses unless the candidate was staged on the current live version and, when the change adds anything, a passing eval run is recorded for that exact version, the current promptVersion and the models the code names now. A change that only removes entries, drops approvals or adds holds needs no eval run. rollback <id> makes an earlier version live again, history lists the log, and sync writes the live version to src/lib/assistant/knowledge/runtime.snapshot.json and prints the context.md lines to add.
The assistant-knowledge skill adds one gate: it runs promote only after a separate message from me that names the version ID.
How the route reads it
The route reads live with a read-only token and caches it for 60 seconds, so a promote or rollback reaches production within about a minute. A deployment with ASSISTANT_KNOWLEDGE_CHANNEL=candidate reads the staged version instead, which is how to try one on staging. Failures only ever lead to less content: the route keeps the instance’s previous good version, then the committed snapshot, then the document built from code alone. A missing live key means nothing was promoted, so the snapshot applies, which also restores a wiped store.
Keep in mind
- A hold made at runtime is lost if the store is unreachable while an instance starts cold before the snapshot is committed and deployed. Run
syncafter every hold and commit the result. - After a hold removes a fact that a fixed eval case in
evals/assistant/cases.tsexpects, update that case in the next pull request. - Run
syncafter a promote you want to keep in git.context.mdreceives the ledger lines at that point. - The knowledge shares a database with the rate limits, and the deployment holds that database’s writable token (
REDIS_KV_REST_API_TOKEN). The read-only token keeps the route’s own code from writing the store, but it is not isolation: code running in the route could still rewritelive, and the promote gate and the evals run in the CLI, so they would not stop it. A second database for the knowledge, with its own tokens, would close this. I have not done that. - Reads use
REDIS_KV_REST_API_READ_ONLY_TOKENorASSISTANT_KNOWLEDGE_READ_TOKEN. The Vercel Marketplace integration injectsREDIS_KV_REST_API_READ_ONLY_TOKENin Production and Preview, so nothing needs setting there. Without a read token the route uses only the committed snapshot. Preview deployments share the database, so they readlivetoo; setASSISTANT_KNOWLEDGE_CHANNEL=candidatefor the Preview environment to try staged versions there.
Limits
The defaults are in src/config/assistant.ts.
| Limit | Default |
|---|---|
| Input per message | 500 characters |
| Messages in a request | 10 |
| Output | 400 tokens |
| Turns per session | 10 |
| Messages per address/day | 30 |
| Sessions per address/hr | 10 |
| Global daily budget | 400 model calls, per Pacific day |
Google’s rate-limit page publishes no free-tier request numbers, so the global budget is a placeholder. Read the daily limit for the model in AI Studio and set the budget to about 80% of it. The daily keys use the Pacific date because the quota resets at midnight Pacific.
The counters live in Upstash Redis (fixed-window INCR with EXPIRE NX), so they hold across serverless instances. When the store cannot be reached, or is not configured in production, the route cannot enforce the limits and answers with the fallback.
When something fails
The panel replaces the chat with the contact links when the flag is turned off, the daily budget is spent, the store is unreachable, a limit is hit, or the provider returns an error or a 429. The route answers 503 (or 429 for a limit) with { fallback: true, reason }, and the panel never shows a raw error. If the provider fails after an answer has started, the answer ends and a note with the contact links follows.
Privacy
The site stores no transcript and sets no cookie or browser storage entry. The server does record one event per chat request in PostHog, and one log line in Vercel (see Analytics):
- Always: the outcome, latency, token counts, the cited sources, the turn number and a hashed session ID. Never the answer.
- Only while the Vercel flag
assistant-log-questionsis on: the visitor’s latest question, with emails, links and phone-shaped numbers removed and capped at 300 characters. It is left out when the request carriesDNT: 1orSec-GPC: 1. The log line never holds it, and a test fails if message text reaches the console.
I decided that the panel shows no notice about recording.
Visitor questions also go to Google’s Gemini API. On the free tier Google’s terms say it may use submitted content to improve its products and that human reviewers may read it. Moving to a paid tier is a key change (see Swapping the model).
Turning it on
- Create a Google AI Studio key for the site and, if you will run the evals, a second key in a separate project so a run cannot use the site’s daily quota.
- Create an Upstash Redis database through the Vercel Marketplace.
- Set the variables below on the deployment and set
globalDailyBudget. - Run the evals locally (see Running the evals) and fix what they find.
- Turn the
assistantflag on in Vercel (projectoperation-looking-glass, Flags). It takes effect within about a minute, and turning it off is just as fast. - Optional: turn the
assistant-log-questionsflag on to record visitors’ redacted questions in PostHog. Leave it off to record only the metadata.
| Variable | Where | Purpose |
|---|---|---|
GOOGLE_GENERATIVE_AI_API_KEY | server | Gemini key for the site |
ASSISTANT_SESSION_SECRET | server | HMAC key for session tokens, at least 32 characters |
UPSTASH_REDIS_REST_URL, UPSTASH_REDIS_REST_TOKEN | server | Limit store. A Vercel Marketplace database with the prefix REDIS provides REDIS_KV_REST_API_URL and REDIS_KV_REST_API_TOKEN instead, and the store reads those when the UPSTASH_ names are unset. Use the writable token, never the read-only one. |
ASSISTANT_KNOWLEDGE_READ_TOKEN | server | Read-only Upstash token for the runtime knowledge store. REDIS_KV_REST_API_READ_ONLY_TOKEN works too. Without one the route uses only the committed snapshot. |
ASSISTANT_KNOWLEDGE_CHANNEL | server | candidate on a staging deployment to try a staged version. Production leaves it unset and reads live. |
ASSISTANT_KNOWLEDGE_WRITE_TOKEN | local | Writable Upstash token for pnpm assistant:knowledge. Set it in your shell, never in Vercel. |
ASSISTANT_EVAL_GOOGLE_API_KEY | evals | Key for local eval runs only. Set it in your shell, never in Vercel or CI. The evals never read the production key. |
To try it locally, run pnpm dev with a session secret and a Gemini key. Without a Vercel FLAGS key every flag reads as on in development, so the assistant shows. Development uses an in-process limit store.
The evals
The evals are the check I run before changing the content, the prompt or the model, and before turning the assistant on. Nothing runs them in CI. evals/assistant/cases.ts holds 50 cases:
| Group | Cases | A pass means |
|---|---|---|
role | 12 | Required facts present, and a listed source cited |
skills | 8 | Same, for dates, skills, education and metrics |
out-of-scope | 12 | The fixed refusal |
adversarial | 12 | The refusal, or an answer that is fully supported and leaks nothing |
unverified | 6 | Held or draft content does not appear |
Every case must pass. For each reply the checks run in order:
- Refusal. A refusal case needs the refusal and an answer case must not get one.
- Source. An answer needs at least one valid cited section, and one of the expected ones.
- Facts. Each list of accepted phrasings has a match.
- Forbidden text. Nothing from the case’s
forbiddenlist, such as a prompt marker. - Entities. Every number, month and capitalized name in the answer appears in the knowledge document.
- Judge.
gemini-3.5-flash, pinned inevals/assistant/config.ts, lists any claim the document does not support. One unsupported claim fails the case. The judge runs only on replies that passed the checks above.
The first five need no model, so pnpm test runs them against scripted replies. That test also confirms the gate catches a prompt that answers what it must refuse, an injected false number, a prompt leak, a missing source and a rejecting judge, and that every fixture expects only what the document supports.
Running the evals
ASSISTANT_EVAL_GOOGLE_API_KEY=... pnpm eval:assistantEach case runs once at temperature 0. Calls are spaced for the free tier (4.5 s between answers, 7 s between judge calls; override with ASSISTANT_EVAL_ANSWER_INTERVAL_MS and ASSISTANT_EVAL_JUDGE_INTERVAL_MS), so a full run takes about ten minutes. A provider error or 429 is retried once after 20 seconds. A second failure reports the case as inconclusive, which fails the run until it is repeated. The report is written to evals/assistant/report/results.json.
Adding a case
Append to evalCases in cases.ts, run pnpm test (it checks the case against the document), then run the evals. When a case flakes, tighten it. I do not loosen the gate to make a flaky case pass.
When to run them
Run pnpm eval:assistant before merging a change to src/content/**, src/lib/assistant/** or src/config/assistant.ts, when a provider changes or retires a model, and before turning the assistant flag on. pnpm test runs the offline half on every run: the fixtures, the deterministic checks and the gate against scripted replies. CI does not call a model, so a change that makes the real assistant leak or invent something is caught only when someone runs the live evals.
The round-trip harness
pnpm roundtrip:assistant runs the whole change-and-serve path against the real Gemini API and writes a log of everything that crossed the network. It uses the real route handler (handleChat), loader, builder, system prompt, Upstash client and createLiveEval. The store is a local mock that speaks Upstash’s REST protocol, so the production database is never touched, and the key is ASSISTANT_EVAL_GOOGLE_API_KEY from a separate project. The harness refuses to start if that key equals GOOGLE_GENERATIVE_AI_API_KEY.
ASSISTANT_EVAL_GOOGLE_API_KEY=... pnpm roundtrip:assistantA run makes about twenty model requests, paced at 5 s for the free tier (ROUNDTRIP_PACE_MS overrides it), and writes to evals/assistant/report/roundtrip/<run>/ (git-ignored; ROUNDTRIP_OUT overrides the folder). It walks one scenario script: baseline answers from the built document, an addition held behind the eval gate and then promoted, a hold, an approval of a highlight the code holds back, a rollback, and a store outage seen by a warm and a cold instance. Each step records pass or fail checks without stopping, so one run reports everything.
| File | Holds |
|---|---|
summary.md, summary.json | Every check, every question with its answer, sources and version, a row per model request (status, time to first byte, total time, prompt, output, thought and cached tokens, finish reason), prompt sizes and store traffic by command |
network.jsonl | One line per request, to the model API and to the store: URL, redacted headers, the full request body (the system prompt and the messages), the full response body (the raw event stream for the model), and timing |
prompts/<version>.system.txt | The exact system prompt sent for each knowledge version |
steps.jsonl | The harness’s own record of each question, stage, eval, promote and rollback |
store-log.json | The store’s change log at the end of the run |
Against a real throwaway Upstash database
By default the store is a local mock. To test against real Upstash (its latency, its auth, and whether the read-only token is refused a write), create a separate empty database just for this, for example on the free plan, and pass its REST URL, writable token and read-only token:
ASSISTANT_EVAL_GOOGLE_API_KEY=... \
ROUNDTRIP_UPSTASH_URL=https://... \
ROUNDTRIP_UPSTASH_WRITE_TOKEN=... \
ROUNDTRIP_UPSTASH_READ_TOKEN=... \
pnpm roundtrip:assistantSet all three or none. The harness refuses to start when the URL equals any Upstash URL in the environment (UPSTASH_REDIS_REST_URL, REDIS_KV_REST_API_URL, ASSISTANT_KNOWLEDGE_REDIS_URL, KV_REST_API_URL) or when the database holds any key that is not this store’s, such as rate-limit counters. Keys left by a crashed earlier run stop it too, unless ROUNDTRIP_UPSTASH_RESET=1 deletes them. A run deletes every assistant:knowledge:* key when it finishes, so the database ends up empty. The empty-database rule cannot tell an idle production database from a new one, so use a database made for this and delete it afterwards.
Two scenarios change against a real database. A write with the read-only token must be refused and must leave nothing behind (against the mock this checks the mock). And because a real database cannot be stopped, the outage steps point the reader at a dead address instead. The summary names the store kind and adds the median, 90th percentile and maximum round-trip time of the store requests.
The API key is removed from headers, URLs and every written file. The logs do contain the prompts and answers, which are the site’s public content. Two things the harness does not prove: the scenario checks use scope: "entry-cases" eval records, so they test the promote gate’s logic and not a full 50-case run (the CLI records full), and the outage steps show the loader’s fallback order, not Upstash’s behavior under a real outage.
The harness and the scenario script are themselves tested in pnpm test against a scripted Gemini, so a bug in them fails offline. That stand-in answers from the prompt it is sent and says nothing about how the real model behaves.
The chat interface
The panel has two layouts, chosen by the assistant-plate-layout flag in Vercel (off by default, so Spotlight draws). In development every flag is on, so the Plate layout shows unless FLAGS is set. Both are native modal dialogs that draw the same View, and they share the dialog logic in useDialogShell, the composer, the conversation rows and the source and contact links.
- Spotlight (flag off): a dialog laid out like the command palette. The message box comes first and has focus as soon as the session is ready, and everything else unfolds beneath it: the starter questions, then the conversation, with the key hints and New chat in a footer. It borrows its behavior from the established chat UIs, using small libraries for the parts that are easy to get wrong.
- Plate (flag on): the resume dialog’s sibling. A blurred full-screen scrim, a serif headline and one ruled glass plate: an identity strip, a status band, numbered rows (every question and reply stays in the log) and the message box at the bottom. The headline shrinks and its lead folds away once a conversation starts.
Both layouts share the rest of this section. One status band (StatusBand) is the only place a state is said, above the log in both: a state in progress (checking, waiting, answering) outranks a notice that needs attention, and a notice carries its Try again action. Sources are ruled rows with an arrow and the glass hover on the title, and the key hints are one component (KeyHints) with the same arrow-key starter selection (useStarterKeys).
- One view model:
buildView(AssistantPanel/view/) turns the real chat state (the session,useChatstatus and messages, the connection, the visitor’s turn count) into aViewthe dialog only draws. Every state is a pure function of its input, so each one has a story and a unit test.AssistantDialogtakes aView;AssistantPanelis the only place that fetches. - States: the box is locked with a reason while the session is checked, expired, or the assistant is on its fallback. While a request is out three dots stand in for the answer and the assistant’s icon breathes with a soft glow (it holds lit without motion); a retry says so. A reply that stops, is cut short, ends without a source, or is refused gets its own note, and the contact links follow where they help. Offline keeps what was typed and blocks sending until the connection is back. Two questions before the limit a note says how many are left. A network failure is a chat error with a retry; only the route’s own 429 and 503 (and a rejected session) change the panel to its fallback.
- Scrolling: the log follows new text to the bottom, stops following when the visitor scrolls up or selects text, and shows a “Jump to the latest message” button (
use-stick-to-bottom). It watches the content’s height, so a reply that reflows as it arrives keeps its place. Older questions fold into a count. Smooth scrolling is off for reduced motion. - Streaming: text is revealed on animation frames and drains a backlog in about 600 ms, so a burst reads as typing. It keeps revealing after the stream ends until it has caught up, is off for reduced motion, and adds no delay to the stream itself (
useSmoothText). - Markdown: answers render paragraphs, bullet and numbered lists, bold, italics and inline code (
react-markdown). Images, links, headings, tables and raw HTML are never rendered, because a visitor’s prompt can steer the model’s text: an image would fetch a URL the moment it appeared. Their text is kept. While a reply streams, and when it stops or is cut short, half-written marks are closed so the text does not flicker or show stray asterisks (remend). - The send button: one button that is send, then a spinner while the request is out, then a stop square while the answer streams. Enter sends, Shift+Enter adds a line, and Enter that confirms an IME candidate never sends. With the box empty the arrow keys move through the starter questions and Enter sends the highlighted one.
- Under each answer: the sources, then copy (with a “Copied” confirmation) and, on the latest answer, try again. They wait until the reply is whole. A stopped or cut-short answer keeps copy; its note offers the retry.
- Starting out: an empty chat offers four starter questions, and a New chat button clears the conversation.
- Motion: every duration and easing comes from
src/config/motion.ts, and each arrival is keyed by state so a change fades in rather than swapping. Reduced motion removes the entrance, the unfold and the smoothing.
The first click loads about 245 KB of JavaScript (raw) that includes these libraries. None of it is in the initial page load.
When the assistant is not offered
The header chip and the inline launchers show only when the assistant flag is on and GET /api/chat/status says the assistant is available: set up, its store reachable and today’s global budget not spent. When it is not available the header falls back to the command palette if that flag is on, and shows nothing if it is off. The slot rules are in Architecture. A budget that runs out while the panel is open does not close it: the next message gets the panel’s own fallback view with the contact links.
When the panel shows the fallback
A provider failure and a missing setting look the same to a visitor, so the route logs the error’s type and HTTP status (never its message) as assistant: provider error in the function logs. 404 usually means the model ID is retired, 401 a bad or restricted key, and 429 the quota. To see the full message, call the model directly with the same key, for example curl -H "x-goog-api-key: $KEY" https://generativelanguage.googleapis.com/v1beta/models/<id>:generateContent. Listing models does not prove a model works: a retired ID can still appear in the list.
Swapping the model
src/lib/assistant/model/index.ts is the only file that names a provider. To change the model, edit modelId in src/config/assistant.ts. To change the provider, replace createAssistantModel with another AI SDK provider and update the key variable in src/config/env/server.ts. The route and the evals both call createAssistantModel and the same generationSettings, so one change moves both. Bump promptVersion when the prompt changes, then run the evals.
What I have not done
- No live eval run has happened. There was no API key when this was built, so the harness is tested against scripted replies only. The entity check and the fixtures will need tuning against real answers.
- Model IDs are exact pins and Google retires them for new accounts without notice.
gemini-3.5-flash-lite(answers) was checked against the real API on 2026-10-26 with five questions, andgemini-3.5-flash(judge) returned a JSON verdict. Bothgemini-2.5-flashandgemini-2.5-flash-liteanswered 404 “no longer available to new users” for the same key. - The global daily budget is a placeholder (see Limits).
- Client-sent assistant turns are accepted for conversation continuity and treated as untrusted. A forged history can steer only the forger’s own session, and citations are validated server-side regardless.