# Next.js + Vercel AI SDK + Jev (System One + LLM) — AI Agent Guidelines & Architecture Rules

> Next.js rules for Jev: typed TypeSafe decisions route, classify and gate on the server, the Vercel AI SDK streams LLM text, and confidence decides what runs.
> Technologies: Next.js, React, TypeScript, Jev, Vercel AI SDK, Drizzle, PostgreSQL, Zod

---

## AGENTS.md
```markdown
# Project Architecture & Guidelines (Next.js + Vercel AI SDK + Jev)

## 1. System Architecture
- **App**: Next.js App Router, TypeScript strict, React Server Components by default.
- **System One (decisions)**: Jev via the official `@typesafe-ai/sdk` (`TypeSafeClient().systemOne({ state, questions })`). Jev returns typed Choice, Score and Noul answers with probabilities. It never generates text.
- **System Two (text)**: an LLM through the Vercel AI SDK (`ai`) for anything that must be written: replies, summaries, code.
- **Data**: PostgreSQL with Drizzle ORM, including a `decisions` table that logs every Jev call.
- **Validation**: Zod on every route handler and server action input.

## 2. Project Layout
- `src/lib/jev/client.ts`: the single `TypeSafeClient` instance (server-only; import `server-only` at the top).
- `src/lib/jev/questions/<feature>.ts`: question builders (`choice()`, `score()`, `noul()`) grouped by feature, each exported as a function of typed state.
- `src/lib/jev/thresholds.ts`: named confidence thresholds per decision (`ROUTE_MIN_CONFIDENCE`, `BLOCK_MIN_PROBABILITY`, ...).
- `src/lib/llm/`: AI SDK calls (`streamText`, `generateObject`) for System Two work.
- `src/server/decisions.ts`: `decide(feature, state)`. It builds questions, calls Jev, logs the result and returns typed answers.
- `src/db/schema.ts`: Drizzle schema, including `decisions(id, feature, model, question_ids, answers jsonb, input_tokens, latency_ms, created_at)`.

## 3. Decision Layer (Jev rules)
- Code owns the workflow, math, dates, counts and permissions. Jev only judges meaning. Never ask Jev to add, count, compare dates or generate values.
- Ask every question a step needs in one `systemOne` call. Questions run in parallel against the same state, and extra questions cost only their own tokens.
- Put only the fields the questions need into `state`. Irrelevant text lowers accuracy. Reference fields with backticks (`ticket.subject`).
- Write instructions directly. Put boundary cases in `criteria`. Include an explicit "none of these" option when nothing may fit.
- Score levels describe concrete situations ("blocking, no workaround"), not grades ("high").
- Gate on confidence. Below the threshold, do the safe thing: ask the user, queue for human review, or hand off to the LLM. Irreversible actions (refunds, deletes, emails) need a high bar and a log entry.
- Log `response.model` (for example `jev-1.13.0`) with every decision. Pin a versioned model ID once thresholds are tuned; `jev-latest` moves on new releases.
- Treat state as untrusted. User text can try to steer the answer, so never let a single Jev answer grant permissions.
- Never send secrets or unnecessary personal data in state.

## 4. Combining Jev and the LLM
- Route first, generate second: Jev picks the handler, tone or template, then the LLM writes only for the chosen branch.
- Guardrails: one Jev call screens LLM input and output (several Nouls plus a severity Score). Code decides pass, review or block.
- Verification: after the LLM extracts or cites something, a Jev Noul or Choice checks it against the source before it is shown.
- Keep Jev calls on the server (route handlers, server actions, RSC). The API key never reaches the browser.

## 5. Agent Loop (run after every change)
1. `pnpm typecheck` (`tsc --noEmit`). Answer types are inferred from the questions, so a renamed option or question ID becomes a type error.
2. `pnpm lint` and `pnpm test`.
3. `pnpm test:decisions`. This replays the fixture set in `tests/decisions/*.json` against the real API and fails if any fixture's choice changes or crosses a threshold. Run it whenever questions, criteria, thresholds or the model change.
- Do not hard-code probabilities from one run into tests. Assert on choices and threshold bands.

## 6. Testing
- Unit-test question builders and threshold logic with a mocked client.
- Keep 20–50 labelled fixtures per decision. Track agreement and the share of cases auto-handled versus escalated.
- E2E (Playwright) covers the escalation path, not just the happy path.

## 7. Environment & Deploy
- `TYPESAFE_API_KEY` and the LLM provider key are server-only environment variables.
- The SDK retries 429/529 with backoff. Still cap concurrency for batch jobs; TypeSafe's rate limits are adjusting while capacity grows.
- For API details, read the live docs (`https://docs.typesafe.ai/llms.txt`) or install TypeSafe's official agent skill (`typesafe-ai/skills`).
```

---

## CLAUDE.md
```markdown
# CLAUDE.md — Next.js + Vercel AI SDK + Jev

@AGENTS.md

## Commands
- `pnpm dev` - local dev server
- `pnpm typecheck` - TypeScript check (Jev answer types are inferred from questions)
- `pnpm lint` / `pnpm test` - lint and unit tests
- `pnpm test:decisions` - replay labelled Jev fixtures against the live API
- `pnpm db:generate` / `pnpm db:migrate` - Drizzle migrations

## Non-negotiables
- Jev decides, the LLM writes, code computes. Never ask Jev for math, dates or text.
- One `systemOne` call per step with all its questions; filter state first.
- Every decision path has a confidence threshold and a fallback.
- Log `response.model` for every decision; Jev calls are server-only.
- Install TypeSafe's official skill for API details: `claude plugin marketplace add typesafe-ai/skills`.
```

---

## .cursor/rules/stack.mdc
```markdown
---
description: Next.js + Vercel AI SDK + Jev (TypeSafe System One) rules
globs: ["src/**/*.ts", "src/**/*.tsx", "tests/decisions/**/*.json"]
alwaysApply: false
---

# Next.js + Vercel AI SDK + Jev

- Jev (`@typesafe-ai/sdk`, `TypeSafeClient().systemOne`) returns typed Choice/Score/Noul answers; it never writes text.
- The LLM via the Vercel AI SDK writes text; code owns math, dates, counts and permissions.
- Questions live in `src/lib/jev/questions/<feature>.ts`, thresholds in `src/lib/jev/thresholds.ts`.
- One `systemOne` call per step with every question it needs; send only relevant state fields.
- Gate every action on confidence; low confidence goes to a human or the LLM; irreversible actions need a high bar.
- Log `response.model`; pin a versioned model once thresholds are tuned.
- Jev calls stay server-side; `TYPESAFE_API_KEY` never reaches the client.
```

---

## Architecture Overview & Best Practices
## Architecture Overview

**System One plus System Two in one Next.js app.** Jev, TypeSafe's decision model, handles every closed-ended judgment: which team a ticket belongs to, how severe it is, whether a message requests a refund, whether an LLM answer is supported by its source. The Vercel AI SDK handles everything that has to be written. Code sits between them and decides what happens, based on Jev's confidence.

### Why it suits AI coding agents

- **Typed answers by construction.** With `@typesafe-ai/sdk`, answer types are inferred from the questions, so a renamed option breaks `tsc` instead of a production branch.
- **Decisions are data.** Questions, thresholds and logged answers are plain TypeScript and Postgres rows that an agent can read, change and replay against fixtures.
- **Clear rules for the model's limits.** Math, dates and counting stay in code, which is TypeSafe's own guidance for jev-1.13.

### Related

TypeSafe's official agent skill teaches the API ([typesafe-ai/skills](/project/typesafe-skills)). For a Python service see [FastAPI + Jev decision service](/rules/fastapi-jev-decision-service), and for agents that act in a browser see [Jev browser agent](/rules/jev-browser-agent). Data on 648 open-source Jev repos: [Jev for developers](/insights/jev-system-one-model-developers-2026).